You can create a String extension like so:
extension String {
func someFunc -> Bool { ... }
}
but what if you want it to apply to opt
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
}
}
You can do it like this:
protocol OptionalType { typealias A; var opt: A? { get } }
extension Optional: OptionalType { var opt: A? { return self } }
protocol StringType { var get: String { get } }
extension String: StringType { var get: String { return self } }
extension Optional where Wrapped: StringType {
func getOrElse(s: String) -> String {
return self.opt?.get ?? s
}
}
And:
let optStr: String? = nil
optStr.getOrElse("hello world")
The reason that you cannot constrain Optional
or String
for that matter, is because they are struct
. By making pseudo-protocol for each, now we can constrain as we like.
I feel like swift has given up a lot of things just to make it easier for beginners to learn or maybe the language hasn't matured enough yet.
Since Xcode 9.3, you can use this slight modification of @Vladyslav's answer:
extension Optional where Wrapped == String {
var isEmpty: Bool {
return self?.isEmpty ?? true
}
}