How to add an optional string extension?

后端 未结 9 521
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 23:44

You can create a String extension like so:

extension String {
   func someFunc -> Bool { ... }
}

but what if you want it to apply to opt

相关标签:
9条回答
  • 2020-12-14 00:23

    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
      }
    }
    
    0 讨论(0)
  • 2020-12-14 00:24

    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.

    0 讨论(0)
  • 2020-12-14 00:24

    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
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题