search

Home  >  Q&A  >  body text

objective-c - Swift 里 guard 的里面不能用变量吗 , 那我想修改怎么办。

//我想在guard 改变num2的值.可是报错了
func demoGuard() {

    let oNum: Int? =  nil
    
 guard var num2 = oNum else{
        num2 = 10
        return
    }    
    

}

高洛峰高洛峰2758 days ago515

reply all(2)I'll reply

  • 为情所困

    为情所困2017-05-02 09:26:41

    The scope of num2 is only after guard, but it returns when it goes to else. What is the meaning of changing the value of num2 at this time? I assume you want to change the value of oNum? In this case, you can change let oNum to var oNum in guard, but the same thing is meaningless. It may also make sense if the value you want to change is the value of an inout type parameter passed in during an external call.

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-02 09:26:41

    This requirement is very strange, it is better to use the ?? operator

    num2 = oNum ?? 10

    reply
    0
  • Cancelreply