Home > Net >  Is this really the proper way to check the count of an optional string in Swift?
Is this really the proper way to check the count of an optional string in Swift?

Time:06-17

I am scrolling through an array of many things in app. One of the items in the array is a string, and it is an optional. I've edited out everything else since my question is about the strings.

At one point I need to call some functions on the strings, if they exist.

Both of these appear to work

if newItem.item?.count ?? 0 > 0 { ...

and

if let current = newItem.item,
            current.count > 0 {

The top one is cleaner, but I can read the second one easier. The first looks like a cousin of a ternary conditional. I simply want to clarify that even if I am doing it correctly, if there is a more accepted way to do it.

CodePudding user response:

Comparing a default against a number is code stink. Deodorizing usually involves Optional.map

if newItem.item?.count.map { $0 > 0 } == true {

or better usage of properties.

if newItem.item?.isEmpty == false {
  • Related