Swift String Interpolation displaying optional?

前端 未结 4 1522
感情败类
感情败类 2020-12-10 12:25

When i use the following code and have nameTextField be \"Jeffrey\" (or any other name)

@IBAction func helloWorldAction(nameTextField: UITextField) {

    na         


        
4条回答
  •  感情败类
    2020-12-10 12:48

    You can also use optional map.
    This is where I learned of how to use it.

    Basically, map will take an optional and return a value if there's a value and return nil if there's no value. It think this makes more sense in code, so here's the code I found useful:

    func getUserAge() -> Int? {  
        return 38  
    }
    
    let age = getUserAge()
    
    let ageString = age.map { "Your age is \($0)" }
    print(ageString ?? "We don't know your age.")
    

    I guess this may not be super helpful in the case where you're passing in an optional string, (nil coalescing works just fine in that case), but this is super helpful for when you need to use some value that isn't a string.
    It's even more useful when you want to run logic on the given value since map is a closure and you can use $0 multiple times.

提交回复
热议问题