Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
967 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...