2017-07-13 33 views
0

我試圖在if語句中使用securityCode變量,但它說它的'未解決的標識符',任何想法爲什麼?Swift 3 - 聲明的變量給我'未解決的標識符錯誤'

繼承人我的代碼:

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) 

    } 
} 

回答

1

您需要了解在斯威夫特範圍。

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))") 
} 
+0

不要將'securityCode'聲明爲隱式解包。使其成爲可選項或使其成爲非可選項並賦予其初始值。 – rmaddy

+0

@rmaddy你說得對,我更新了我的代碼。謝謝! –

+0

@Moe Abdul-Hameed謝謝!現在正常工作 – Jeamz

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) 
     } 
    } 
} 

或者在會話外聲明變量。

+0

不要強制解開'securityCode'。如果它是'nil',應用程序將崩潰。 – rmaddy

+0

哦,沒錯。謝謝 –

相關問題