@objc协议中的swift可选var

时间:2015-07-29 05:55:28

标签: swift swift2

我是一个快速的初学者(我的背景是VBA,VB.NET)。我首先发现在UIApplicationDelegate(.window ??)对象上使用窗口变量时双重可选变量(??)令人困惑。经过一些研究后,我了解到一个变量可以在协议中声明为可选,也可以返回一个可选类型。

安全使用变量的一种方法是:

 if let checkHasVar = UIApplication.sharedApplication().delegate?.window {
        if let varIsSomething = checkHasVar {
            //window exists and is referencing an object
        }
    }

另一个是:

 guard let hasWindowVar = UIApplication.sharedApplication().delegate?.window,  window = hasWindowVar else {
        return
    }

两者都运作良好但我有兴趣了解这是否是处理双重期权的合理方法

2 个答案:

答案 0 :(得分:0)

guard let = if not let。条件简单,我建议你使用if let,否则使用guard let

答案 1 :(得分:0)

有很多方法。

if let ...

if let windowProperty = UIApplication.sharedApplication().delegate?.window {
  if let window = windowProperty {
    print(window)
  }
}

链式if let ...

if let windowProperty = UIApplication.sharedApplication().delegate?.window,
  window = windowProperty {
    print(window)
}

模式匹配......

if case .Some(let windowProperty) = UIApplication.sharedApplication().delegate?.window,
  case .Some(let window) = windowProperty {
    print(window)
}

guard ...

guard let windowProperty = UIApplication.sharedApplication().delegate?.window,
  window = windowProperty else {
    return
}
print(window)

你可以把它们结合起来......

if let windowProperty = UIApplication.sharedApplication().delegate?.window,
  case .Some(let window) = windowProperty {
    print(window)
}
  

两者都运作良好但我有兴趣了解这是否是处理双重期权的合理方法

明智?对你起作用吗?你的代码是否可读?你懂这个了吗?选择你想要的任何东西,你喜欢并使用它。

这种问题会导致自以为是的答案,但这并不好。很多方法可以做你想要选择的东西。没有人可以帮助你。

相关问题