How to add an optional string extension?

vol7ron picture vol7ron · Apr 6, 2015 · Viewed 21.6k times · Source

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

Answer

Vladyslav Zavalykhatko picture Vladyslav Zavalykhatko · Mar 28, 2017

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