如何在swift中访问if语句之外的数据

时间:2017-05-28 12:17:46

标签: arrays json swift

我想在if语句之外使用变量或数组。在javascript中,您可以在if语句之外提升变量,但不确定如何在swift中执行此操作?我尝试过使用struct,但我不确定要进入哪个方向。我想在函数中使用num并在每个数组中递增。但是,需要能够通过文件访问变量。

let jsonWithArrayRoot = try? JSONSerialization.jsonObject(with: fileData, options: [])

var zone: Int
var sound: String
var distance: Int
var title: String
var duration: Int
var type: String
var color: Int
var num:Int

num=0

if let array = jsonWithArrayRoot as? [AnyObject] {
    let json = array[num]

    test = array

    zone = json["zone"] as? Int ?? 0
    sound = json["sound"] as? String ?? ""
    distance = json["distance"] as? Int ?? 0
    title = json["title"] as? String ?? ""
    duration = json["duration"] as? Int ?? 0
    type = json["type"] as? String ?? ""
    color = json["color"] as? Int ?? 0

    print(zone)

}


//I want to access variables and later on    
print(zone)
print(sound)
print(distance)
print(title)
print(type)
print(color)

2 个答案:

答案 0 :(得分:0)

您应该立即为变量提供默认值,然后根据JSON数据更改它们。您当前的代码将默认值置于 JSON解析块中,这意味着如果if let array = jsonWithArrayRoot...失败,变量将没有值。

就个人而言,我也会将as? Int ??行重构为更漂亮的东西,但这是另一个问题。

这里的代码包含一个应该运行良好的最小修补程序:

let jsonWithArrayRoot = try? JSONSerialization.jsonObject(with: fileData, options: [])

var zone = 0
var sound = ""
var distance = 0
var title = ""
var duration = 0
var type = ""
var color = 0
var num = 0

if let array = jsonWithArrayRoot as? [AnyObject] {
    let json = array[num]

    zone = json["zone"] as? Int ?? zone
    sound = json["sound"] as? String ?? sound
    distance = json["distance"] as? Int ?? distance
    title = json["title"] as? String ?? title
    duration = json["duration"] as? Int ?? duration
    type = json["type"] as? String ?? type
    color = json["color"] as? Int ?? color
}

答案 1 :(得分:0)

使用警卫。

guard let array = jsonWithArrayRoot as? [AnyObject] else {return}

让json = array [num]

zone = json["zone"] as? Int ?? zone
sound = json["sound"] as? String ?? sound
distance = json["distance"] as? Int ?? distance
title = json["title"] as? String ?? title
duration = json["duration"] as? Int ?? duration
type = json["type"] as? String ?? type
color = json["color"] as? Int ?? color

现在可以在任何地方使用数组变量。

相关问题