Swift 3 - 声明的变量给我"未解决的标识符错误"



我试图在 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 中的 scope。

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))")
}
if securityCode! == true {
let layout = UICollectionViewFlowLayout()
let mainScreen = MainController(collectionViewLayout: layout)
present(mainScreen, animated: true, completion: nil)
}

这超出了范围。

要使其正常工作,您必须将函数嵌入到同一作用域中。例如

if let parseJSON = json {
let securityCode = parseJSON["security"] as? Bool
print("security code bool: (String(describing: securityCode))")
if let securityCode = securityCode{
if securityCode == true {
let layout = UICollectionViewFlowLayout()
let mainScreen = MainController(collectionViewLayout: layout)
self.present(mainScreen, animated: true, completion: nil)
}
}
}

或者在会话外部声明变量。

最新更新