vol7ron vol7ron - 2 years ago 236
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 Source

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:


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 {

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 {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download