0

I'm currently using a simple method to test my textfield text like :

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

Now if try my function on a concrete String, all is ok

let result = myString.test() //result is a Bool

But if I execute it on an Optional String ( like UITExtField.text ), the type becomes Optional<Bool>

let result = myOptionalString?.test() //result is a Optional<Bool>

Is there a way to provide a default value ( or implementation ) to avoid the test of the result when the caller is Optional.

I Know I can use some operators like ?? or do an if-else statement, but it's lot of code for nothing

Thanks!

CZ54
  • 5,488
  • 1
  • 24
  • 39
  • Extend `UITextField` to add a `string` property that returns `text ?? ""`. (`UITextField` is the most common causer of this problem, and adding this extension makes whole classes of problems go away. As a rule, returning `String?` is a mistake because `nil` and `""` are almost always equivalent.) – Rob Napier Mar 19 '18 at 14:26

2 Answers2

2

You can make extension for Optional String.

Example

extension Optional where Wrapped == String {
    func test() -> Bool {
        switch self {
        case .none: return false
        case .some(let string): return true
        }
    }
}

I hope it'll help you ;)

1

You could extend Optional<String> to return a default value if nil, or forward to test() if not.

extension Optional where Wrapped == String {
    func test() -> Bool {
        guard let value = self else { return false }
        return value.test()
    }
}
Marcel Tesch
  • 184
  • 3
  • 15