【发布时间】:2016-03-23 07:45:08
【问题描述】:
我可以在 IF 中使用 let obj = something 的多个条件
if let u = custom["u"] as? String || let url = custom["URL"] as? String
{
// Do something here
}
【问题讨论】:
我可以在 IF 中使用 let obj = something 的多个条件
if let u = custom["u"] as? String || let url = custom["URL"] as? String
{
// Do something here
}
【问题讨论】:
您可以添加多个条件,但前提是您使用 AND 条件。
如果您使用OR,您不知道您的哪个值设置正确,因此无法正确访问变量。
通过AND 测试,您可以确定这两个变量都已正确创建,因此您可以肯定地知道它们的类型。
您必须编写用逗号分隔的测试:
if let u = custom["u"],
let url = custom["URL"] {
// Do something here
}
此外,您可以在 if let 块之后直接添加一些条件,使用 where 关键字:
if let u = custom["u"] where u == "testValue",
let url = custom["URL"] {
// Do something here
}
【讨论】:
我假设您的收藏类型是Dictionary。
如果你真的想用OR:
if(custom.keys.contains("u") || custom.keys.contains["URL"]) { }
但是正如其他人已经写的那样,这并没有真正的意义,因为如果您需要这些键的值,您仍然必须编写两个单独的 if 语句。
if let u = custom["u"] {
print("Value for u: \(u!)");
}
if let url = custom["URL"] {
print("Value for URL: \(url!)");
}
【讨论】:
1) 它对 OR 没有意义 2) 用 AND 代替
if let u = custom["u"] as? String,
let url = custom["URL"] as? String {
// Do something here
}
【讨论】:
我同意 user3441734。你为什么要这样做?
if let u = custom["u"] as? String {
if let url = custom["URL"] as?
// Do something here
}
}
我会这样做。只有当上述条件为真或:
if let u = custom["u"] as? String {
// Call same method
}
if let url = custom["URL"] as?
// Call same method
}
这样会检查并执行这两个。
【讨论】: