How to add an optional string extension?

后端 未结 9 573
佛祖请我去吃肉
佛祖请我去吃肉 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:11

    Update: For a workaround that works with Swift 2 and above, see Daniel Shin’s answer


    An optional String isn't in and of itself a type, and so you cannot create an extension on an optional type. In Swift, an Optional is just an enum (plus a bit of syntactic sugar) which can either be None, or Some that wraps a value. To use your String method, you need to unwrap your optionalString. You can easily use optional chaining to achieve this:

    optionalString?.someFunc()
    

    If optionalString is not nil, someFunc will be called on it. An alternative (less concise) way of doing this is to use optional binding to establish whether or not optionalString has a value before trying to call the method:

    if let string = optionalString {
        string.someFunc()    // `string` is now of type `String` (not `String?`)
    }
    

    In your example from the comments below, you needn't nest multiple if statements, you can check if the optional string is an empty string in a single if:

    if optionalString?.isEmpty == true {
        doSomething()
    }
    

    This works because the expression optionalString?.isEmpty returns an optional Bool (i.e. true, false or nil). So doSomething() will only be called if optionalString is not nil, and if that string is empty.

    Another alternative would be:

    if let string = optionalString where string.isEmpty {
        doSomethingWithEmptyString(string)
    }
    

提交回复
热议问题