vol7ron vol7ron - 6 months ago 75
Swift Question

How to add an optional string extension?

You can create a String extension like so:

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


but what if you want it to apply to optional string?

var optionalString :String? = ""
optionalString!.someFunc() /* String? does not have a member someFunc */

Answer

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)
}
Comments