Swift .uppercaseString or .lowercaseString property replacement

前端 未结 5 1357
青春惊慌失措
青春惊慌失措 2021-02-01 12:39

Since Strings in Swift no longer have the .uppercaseString or .lowercaseString properties available, how would i go about performing that function?

If i have for example

5条回答
  •  天涯浪人
    2021-02-01 12:56

    Swift 4 & 5

    TL;DR

    The new names in Swift 3 use the -ed postfix to indicate that uppercased() and lowercased() return a copy rather than a modified original:

    import Foundation
    
    let title = "Castration: The Advantages and the Disadvantages" // Don't `var` unless you have to!
    title.uppercased() // "CASTRATION: THE ADVANTAGES AND THE DISADVANTAGES"
    title.lowercased() // "castration: the advantages and the disadvantages"
    title.capitalized  // "Castration: The Advantages And The Disadvantages"
    

    Inconsistencies: .method() vs .property

    Note the odd discrepancy where uppercased() and lowercased() are functions, while capitalized is a property. This seems like an oversight, in which case hopefully someone comfortable with the swift evolution process will make a correction before 3.0 leaves beta.

    If happen to know you're working with NSString, there is a property available for all three:

    NSString(string: "abcd").uppercased
    NSString(string: "ABCD").lowercased
    NSString(string: "abCd").capitalized
    

    Language is Hard

    The methods above hide a whole string of method delegations to NSString and CFString with a default Locale of nil. This works most of the time. At least, it does in English. The fact is, I don't really understand the rest of what I'm about to paste from my playground.

    let turkishI = "\u{0130} is not I"                  // "İ is not I"
    turkishI.uppercased()                               // "İ IS NOT I"
    turkishI.uppercased(with: Locale(identifier: "en")) // "İ IS NOT I"
    turkishI.uppercased(with: Locale(identifier: "tr")) // "İ İS NOT I"
    turkishI.lowercased()                               // "i̇ is not i"
    turkishI.capitalized                                // "İ Is Not I"
    turkishI.lowercased(with: Locale(identifier: "en")) // "i̇ is not i"
    turkishI.lowercased(with: Locale(identifier: "tr")) // "i is not ı"
    

    Swift 3

    The Locale initializer has a slightly longer parameter name in Swift 3…

    turkishI.uppercased(with: Locale(localeIdentifier: "en"))
    

    Light Humor

    "✈️".uppercased()  // 

提交回复
热议问题