通过Swift 3.0中的数组进行交互

时间:2017-01-06 23:34:53

标签: swift3

我是Swift的初学者,正在使用Swift 3.0。 我有以下设置:

var profileArray = [[String: AnyObject]]()

profileArray.append(["profile_name":profileName.text! as AnyObject,"wifi":wifiValue.isOn as AnyObject,"bluetooth":btoothValue.isOn as AnyObject,"airplane":airplaneValue.isOn as AnyObject,"mobile_data":mdataValue.isOn as AnyObject,"not_disturb":nodisturbValue.isOn as AnyObject,"loc_service":locationValue.isOn as AnyObject,"ring_vol":ringVolume as AnyObject,"operation":editOperation as AnyObject])

//Value stored in this array
Array:

[
    [
        "wifi": 1,
        "bluetooth": 1,
        "not_disturb": 1,
        "operation": 1,
        "airplane": 1,
        "profile_name": loud,
        "loc_service": 1,
        "ring_vol": 4,
        "mobile_data": 1
    ],
    [
        "wifi": 1,
        "bluetooth": 0,
        "not_disturb": 1,
        "operation": 0,
        "airplane": 1,
        "profile_name": quite,
        "loc_service": 0,
        "ring_vol": 1,
        "mobile_data": 1
    ] 
]

我的问题是如何迭代这个数组并检查“operation”索引的值?

2 个答案:

答案 0 :(得分:1)

在字典数组上调用flatMap操作,尝试访问每个字典中的键"operation"

let correspondingOperationValues = profileArray.flatMap { $0["operation"] }
print(correspondingOperationValues) // [1, 0]

另外,请考虑您是否真的想要使用AnyObject值的词典:Any 可以更合适,还可以使用Any代码等包装器是一个代码气味标记。

如果词典的键是“静态的”(在编译时已知),您可以考虑构建要使用的自定义类型而不是字典,例如:

struct CustomSettings {
    let wifi: Bool
    let bluetooth: Bool
    let not_disturb: Bool
    let operation: Bool
    let airplane: Bool
    let profile_name: String
    let loc_service: Bool
    let ring_vol: Int
    let mobile_data: Bool
}

let profileArray = [
    CustomSettings(
        wifi: true,
        bluetooth: true,
        not_disturb: true,
        operation: true,
        airplane: true,
        profile_name: "foo",
        loc_service: true,
        ring_vol: 4,
        mobile_data: true),
    CustomSettings(
        wifi: true,
        bluetooth: false,
        not_disturb: true,
        operation: false,
        airplane: true,
        profile_name: "foo",
        loc_service: false,
        ring_vol: 1,
        mobile_data: true)
]

let correspondingOperationValues = profileArray
    .map { $0.operation } // [true, false]

答案 1 :(得分:0)

你的意思是这样吗?

for dict in profileArray {

    if let value = dict["operation"] {
        print(value)   // or do something else with the value
    }
}

如果密钥不存在,Swift Dictionary会返回Optional值(nil),因此您可以使用可选绑定来检查值。