Join string array with separator “, ” and add “, and ” to join the last element in Swift

前端 未结 2 327
余生分开走
余生分开走 2021-01-13 01:24

I\'m messing around with parsing JSON with SwiftyJSON on a swift playground. My code is as follows:

import UIKit
import SwiftyJSON

var partyList: [String] =         


        
相关标签:
2条回答
  • 2021-01-13 02:08

    Since iOS 13.0+ / macOS 10.15+ Apple provides the ListFormatter. See also here for details.

    Arrays can be formatted as easy as:

    let elements = ["a", "b", "c"]
    result = ListFormatter.localizedString(byJoining: elements)
    

    As the function name suggests, you also get the localization for free.

    0 讨论(0)
  • 2021-01-13 02:15

    Add a condition to check if your String collection has less than or is equal to 2 elements, if true just return the two elements joined by " and " otherwise drop the last element of your collection, join the elements with a separator ", " then re add the last element with the final separator ", and ".

    You can extend BidirectionalCollection protocol constraining its elements to the StringProtocol:

    Bidirectional collections offer traversal backward from any valid index, not including a collection’s startIndex. Bidirectional collections can therefore offer additional operations, such as a last property that provides efficient access to the last element and a reversed() method that presents the elements in reverse order.

    Xcode 11.4 • Swift 5.2 or later

    extension BidirectionalCollection where Element: StringProtocol {
        var sentence: String {
            count <= 2 ?
                joined(separator: " and ") :
                dropLast().joined(separator: ", ") + ", and " + last!
        }
    }
    

    let elements = ["a", "b", "c"]
    let sentenceFromElements = elements.sentence   // "a, b, and c"
    
    0 讨论(0)
提交回复
热议问题