2016-11-10 85 views
0

雖然編碼JSON,I'm展開的東西與if let聲明,但我想使全局可用使從if語句的變量全球

do { 
    if 
    let json = try JSONSerialization.jsonObject(with: data) as? [String: String], 
    let jsonIsExistant = json["isExistant"] 
    { 
    // Here I would like to make jsonIsExistant globally available 
    } 

這甚至可能一個變量?如果不是這樣,我可以在這個內部做一個if聲明,但我認爲這不是很聰明,甚至不可能。

回答

1

delclare jsonIsExistant在你想要的地方。如果你正在一個iOS應用,除了上述viewDidLoad()創建變量

var jsonIsExistant: String? 

那麼在這一點上使用它

do { 
    if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], 
    let tempJsonIsExistant = json["isExistant"] { 
     jsonIsExistant = tempJsonIsExistant 
    } 
} 

這可能像這樣雖然

do { 
    if let json = try JSONSerialization.jsonObject(with: data) as? [String: String] { 
     jsonIsExistant = json["isExistant"] 
    } 
} catch { 
    //handle error 
} 

改寫如果處理第二種方法,那麼你必須在使用之前檢查jsonIsExistant是否爲零,或者你可以立即使用!如果你確定每次成功成爲json時都會有一個「isExistant」字段。

1

這是沒有意義的變量暴露給if let聲明外:


if let json = ... { 
    //This code will only run if json is non-nil. 
    //That means json is guaranteed to be non-nil here. 
} 
//This code will run whether or not json is nil. 
//There is not a guarantee json is non-nil. 

您有其他幾個選項,這取決於你想要做什麼:


您可以將需要json的其餘代碼放在if的內部。你說你不知道嵌套if陳述是「聰明的還是可能的」。它們是可能的,程序員經常使用它們。你也可以將其解壓縮到另一個功能:

func doStuff(json: String) { 
    //do stuff with json 
} 

//... 
if let json = ... { 
    doStuff(json: json) 
} 

如果您知道是JSON不應該永遠是nil,用!可以強制解開它:

let json = ...! 

您可以使用guard語句使變量全局。 guard內部的代碼將僅在jsonnil時運行。

//throw an error 
do { 
    guard let json = ... else { 
     throw SomeError 
    } 
    //do stuff with json -- it's guaranteed to be non-nil here. 
} 



//return from the function 
guard let json = ... else { 
    return 
} 
//do stuff with json -- it's guaranteed to be non-nil here. 



//labeled break 
doStuff: do { 
    guard let json = ... else { 
     break doStuff 
    } 
    //do stuff with json -- it's guaranteed to be non-nil here. 
} 
:一個 guard語句 必須出口封閉範圍,例如通過引發錯誤,通過從函數返回,或用標記的斷裂的主體