Reducing the number of brackets in Swift

后端 未结 7 1875
离开以前
离开以前 2021-02-01 19:53

Does anyone know if there is a way to use some kind shorthand in swift? more specifically, leaving out the braces in things like IF statements... eg

if num == 0
         


        
7条回答
  •  说谎
    说谎 (楼主)
    2021-02-01 20:17

    Swift 2.0 update Method 1:

    a != nil ? a! : b
    

    Method 2: Shorthand if

    b = a ?? ""
    

    Referance: Apple Docs: Ternary Conditional Operator

    and it does work,

    u.dob = (userInfo["dob"] as? String) != nil ? (userInfo["dob"] as! String):""
    

    I am replacing a json string with blank string if it is nil.

    Edit: Adding Gerardo Medina`s suggestion...we can always use shorthand If

    u.dob = userInfo["dob"] as? String ?? ""
    

提交回复
热议问题