2017-01-06 1 views
0

私はSwiftの初心者であり、Swift 3.0を使用しています。 私はセットアップを次ています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 
    ] 
] 

私の質問は、私はこの配列を繰り返し処理し、「操作」のインデックスの値をチェックしますかどのようにでしょうか?

答えて

0

このような意味ですか? (キーが存在しない場合nil

for dict in profileArray { 

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

Aスウィフト辞書はOptional値を返しますので、値をチェックするには、オプションのバインディングを使用することができます。

1

各辞書にキー"operation"にアクセスしようと、辞書の配列にflatMap操作を呼び出す:あなたは本当にAnyObject値の辞書を使用したい場合は

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

また、考慮してください。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] 
:例えば、辞書ではなく、使用するカスタム型を構築検討するかもしれません
関連する問題