Search code examples
swiftswift-extensions

How to add an optional string extension?


You can create a String extension like so:

extension String {
   func someFunc() -> Bool { return true }
}

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

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

Attempting to add extension String? { produces the error:

Constrained extension must be declared on the unspecialized generic type 'Optional' with constraints specified by a 'where' clause


Solution

  • In Swift 3.1 you can add an extension to optional values as well:

    extension Optional where Wrapped == String {
      var isBlank: Bool {
        return self?.isBlank ?? true
      }
    }