2015-07-03 11 views
1

我正在使用SwiftyJSON調用一些API並獲取一些數據。 當我使用:如果讓變量 - 使用未解決的標識符

if let variable = json["response"]["fieldname"] { 
} else { 
    println("error") 
} 

我不能夠稍後使用可變的,例如爲值追加到一個數組。 例如:

if let variable1 = json["response"]["fieldname1"] { 
} else { 
    println("error") 
} 
if let variable2 = json["response"]["fieldname2"] { 
} else { 
    println("error") 
} 
var currentRecord = structure(variable1, variable2) ---> This line returns an error (use of unresolved identifier variable1) as not able to find variable1 or variable2 
myArray.append(currentRecord) 

我怎樣才能解決這個問題?

回答

3

if let的範圍括號內緊隨其後:

if let jo = joseph { 
    // Here, jo is in scope 
} else { 
    // Here, not in scope 
} 
// also not in scope 
// So, any code I have here that relies on jo will not work 

在斯威夫特2,一個新的語句, guard加入,這似乎恰好有你想要的那種行爲:

guard let jo = joseph else { // do something here } 
// jo is in scope 

如果你被困在斯威夫特1,雖然,一個簡單的辦法喲ü解開這些變量沒有末日的金字塔是:

if let variable1 = json["response"]["fieldname1"], variable2 = json["response"]["fieldname2"] { 
    var currentRecord = structure(variable1, variable2) 
    myArray.append(currentRecord) 
} else { 
    println("error") 
} 
+0

謝謝,我將使用Swift 1的解決方案。即使我認爲我不高興做到這一點,因爲有些變量可能需要爲空 – MeV

0

你的代碼檢查變量2總是變量1失敗。 但是導致(編輯!)不是的錯誤。

您可以在同一行中檢查並分配兩個變量。 「真」分支將只執行如果兩個變量不是零

let response = json["response"] 
if let variable1 = response["fieldname1"], variable2 = response["fieldname2"] { 
    let currentRecord = structure(variable1, variable2) 
    myArray.append(currentRecord) 
} else { 
    println("error") 
} 
+1

檢查變量2不會導致錯誤 - 沒有在那裏依靠變量1的檢查。它應該工作正常。錯誤是使用這兩個超出範圍的變量。 – oisdk

+0

同意@oisdk – MeV

+0

致歉,你是對的 – vadian

1

@oisdk已經解釋說,if let定義的變量的範圍僅僅是聲明的括號內。

這就是你想要的,因爲如果它if let語句失敗,變量是未定義的。如果讓我們安全地解開你的選擇,那麼在大括號裏面,你可以確定這個變量是有效的。

另一種解決問題的方法(以雨燕1.2)是使用多,如果讓說明:

if let variable1 = json["response"]["fieldname1"], 
    let variable2 = json["response"]["fieldname2"] 
{ 
    //This code will only run if both variable1 and variable 2 are valid. 
    var currentRecord = structure(variable1, variable2) 
    myArray.append(currentRecord)} 
else 
{ 
    println("error") 
} 
+0

謝謝,我是將使用oisdk聲明的解決方案,但仍然認爲有更好的解決方案,因爲某些變量可能需要爲空 – MeV

相關問題