我试图在 if 语句中使用 securityCode
变量,但它说它是一个“未解析的标识符”,知道为什么吗?
这是我的代码:
func loginAction (sender: UIButton!){
guard let url = URL(string: "myurl") else{ return }
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
print(data)
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let securityCode = parseJSON["security"] as? Bool
print("security code bool: \(String(describing: securityCode))")
}
} catch {
print(error)
}
}
}.resume()
if securityCode! == true {
let layout = UICollectionViewFlowLayout()
let mainScreen = MainController(collectionViewLayout: layout)
present(mainScreen, animated: true, completion: nil)
}
}
最佳答案
您需要阅读 Swift 中的作用域。
securityCode
在此 if
语句中声明:
if let parseJSON = json {
let securityCode = parseJSON["security"] as? Bool
print("security code bool: \(String(describing: securityCode))")
}
因此,只有在 if
语句范围内的代码才会知道 securityCode
。
如果您希望此 if
语句之后的代码知道 securityCode
,您需要在该范围之外进行声明,这可以通过以下方式实现:
var securityCode: Bool?
if let parseJSON = json {
securityCode = parseJSON["security"] as? Bool
print("security code bool: \(String(describing: securityCode))")
}
关于Swift 3 - 声明的变量给我 'unresolved identifier error',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45091744/