How to add an optional string extension?

后端 未结 9 589
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 23:44

You can create a String extension like so:

extension String {
   func someFunc -> Bool { ... }
}

but what if you want it to apply to opt

9条回答
  •  鱼传尺愫
    2020-12-14 00:12

    Extensions on Optional that return a String

    As of Swift 3, you cannot directly constrain an extension method to an optional String. You can achieve the equivalent result with protocols as Daniel Shin's answer explains.

    You can however, create an extension method on an Optional of any type and I've found some useful methods that have a String return value. These extensions are helpful for logging values to the console. I've used asStringOrEmpty() on a String optional when I want to replace a possible nil with empty string.

    extension Optional {
        func asStringOrEmpty() -> String {
            switch self {
                case .some(let value):
                    return String(describing: value)
                case _:
                    return ""
            }
        }
    
        func asStringOrNilText() -> String {
            switch self {
                case .some(let value):
                    return String(describing: value)
                case _:
                    return "(nil)"
            }
        }
    }
    

    Example Use:

    var booleanValue: Bool?
    var stringValue: String?
    var intValue: Int?
    
    print("booleanValue: \(booleanValue.asStringOrNilText())")
    print("stringValue: \(stringValue.asStringOrNilText())")
    print("intValue: \(intValue.asStringOrNilText())")
    
    booleanValue = true
    stringValue = "text!"
    intValue = 41
    
    print("booleanValue: \(booleanValue.asStringOrNilText())")
    print("stringValue: \(stringValue.asStringOrNilText())")
    print("intValue: \(intValue.asStringOrNilText())")
    

    Console Output:

    booleanValue: (nil)
    stringValue: (nil)
    intValue: (nil)
    
    booleanValue: true
    stringValue: text!
    intValue: 41
    

     

    Optional different than nil pointer

    These extensions illustrate that an Optional is different that a nil pointer. An Optional is a enum of a specified type (Wrapped) which indicates that it does or does not contain a value. You can write an extension on the Optional "container" even though it may not contain a value.

    Excerpt from Swift Optional Declaration

    enum Optional : ExpressibleByNilLiteral {
    
        /// The absence of a value.
        case none
    
        /// The presence of a value, stored as `Wrapped`.
        case some(Wrapped)
    
        ...
    }
    

    In code, the absence of a value is typically written using the nil literal rather than the explicit .none enumeration case.

提交回复
热议问题