Extension method for Optional of String

I came across an article about extension of Optional (https://useyourloaf.com/blog/empty-strings-in-swift/), but I cannot get it to work for the Optional extension.

extension Optional where Wrapped == String {
  var isBlank: Bool {
    return self?.isBlank ?? true
  }
}

    func testIsBlank() {
        for s in [nil, "", " ", "\t", "abc"] {
            print(s?.isBlank)
        }
    }

For nil value, the output is still nil. I see the article is quite old dated back in 2019. There must be some changes in the language specs. What's going on here?

Answered by Scott in 765425022

The code in that article is still correct. It’s this line in the test which is going wrong:

print(s?.isBlank)

This unwraps the optional s and then calls isBlank only if s was non-nil. If s was nil then the result of the entire expression is nil. Note this isBlank method is defined in an extension on String, which is given in the article but not shown here.

To test this correctly, the line should be this:

print(s.isBlank)

This calls the isBlank method which is defined in the extension on Optional<String>. It’s totally separate from the other isBlank.

Accepted Answer

The code in that article is still correct. It’s this line in the test which is going wrong:

print(s?.isBlank)

This unwraps the optional s and then calls isBlank only if s was non-nil. If s was nil then the result of the entire expression is nil. Note this isBlank method is defined in an extension on String, which is given in the article but not shown here.

To test this correctly, the line should be this:

print(s.isBlank)

This calls the isBlank method which is defined in the extension on Optional<String>. It’s totally separate from the other isBlank.

Extension method for Optional of String
 
 
Q