Swift 3 - 声明的变量给我 'unresolved identifier error'

标签 swift

我试图在 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/

相关文章:

ios - MVP 架构模式示例。 swift

ios - 前一天凌晨 4 点的日期

swift - 需要使用 UICollectionViewLayout 进行 UICollectionViewCell 填充

xcode - swift Xcode 6 : How do I use multiple functions in one statement?

ios - 在 swiftUI 中捕获 onLongPressGesture 的触摸位置?

iOs:(Swift 3)我用 var 变量初始化:[[Any]] = [],但出现错误消息 [type 'Any' has no subscript members]

ios - 点击 swift 时 tableviewcell 打开 url

ios - Swift Extension 获取框架右侧的坐标位置

ios - Swift 无法从 JSON api 读取普通话?

ios - Alamofire - 多部分表单数据 key :value