我试图在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)
}
}
答案 0 :(得分:1)
您需要阅读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))")
}
答案 1 :(得分:0)
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)
}
}
}
或者在会话外声明变量。