Swift: Testing optionals for nil

前端 未结 14 652
攒了一身酷
攒了一身酷 2020-12-08 08:51

I\'m using Xcode 6 Beta 4. I have this weird situation where I cannot figure out how to appropriately test for optionals.

If I have an optional xyz, is the correct w

14条回答
  •  粉色の甜心
    2020-12-08 09:32

    Another approach besides using if or guard statements to do the optional binding is to extend Optional with:

    extension Optional {
    
        func ifValue(_ valueHandler: (Wrapped) -> Void) {
            switch self {
            case .some(let wrapped): valueHandler(wrapped)
            default: break
            }
        }
    
    }
    

    ifValue receives a closure and calls it with the value as an argument when the optional is not nil. It is used this way:

    var helloString: String? = "Hello, World!"
    
    helloString.ifValue {
        print($0) // prints "Hello, World!"
    }
    
    helloString = nil
    
    helloString.ifValue {
        print($0) // This code never runs
    }
    

    You should probably use an if or guard however as those are the most conventional (thus familiar) approaches used by Swift programmers.

提交回复
热议问题