2017-01-13 25 views
1

我有一个plist中包含2个整数值的数组。我可以读取第一个值使用此代码没有问题检查数组是否包含索引值Swift

let mdic = dict["m_indices"] as? [[String:Any]] 
var mdicp = mdic?[0]["powers"] as? [Any] 
self.init(
    power: mdicp?[0] as? Int ?? 0 
) 

不幸的是,一些plists没有第二个索引值。所以打电话给这个

power: mdicp?[1] as? Int ?? 0 

return nil。我如何检查是否有索引,因此只有当值存在时才抓取值?我试图把它包装在一个if-let声明中

 if let mdicp1 = mdic?[0]["powers"] as? [Any]?, !(mdicp1?.isEmpty)! { 
     if let mdicp2 = mdicp1?[1] as! Int?, !mdicp2.isEmpty { 
      mdicp2 = 1 
     } 
    } else { 
     mdicp2 = 0 
    } 

但我迄今为止的尝试都让多个控制台错误。

回答

0

如果你处理的整数数组,并且只担心前两个项目,你可以这样做:

let items: [Int] = [42, 27] 
let firstItem = items.first ?? 0 
let secondItem = items.dropFirst().first ?? 0 

无论您是否真的想要使用零合并运算符??来将缺失值评估为0或仅将它们作为可选项,取决于您。

或者你可以这样做:

let firstItem = array.count > 0 ? array[0] : 0 
let secondItem = array.count > 1 ? array[1] : 0 
0

试试这个

if mdicp.count > 1, 
    let mdicpAtIndex1 = mdicp[1] { 
    /// your code 
} 

mdicp可能包含可选值元素的数量“N”,那么你要做的可选结合之前拆开包装,以避免崩溃。

例如,如果我intialize阵列容量5

var arr = [String?](repeating: nil, count: 5) 

print(arr.count) /// it will print 5 
if arr.count > 2 { 
     print("yes") /// it will print 
} 

if arr.count > 2, 
    let test = arr[2] { // it won't go inside 
    print(test) 
} 

///if I unwrap it 
print(arr[2]!) /// it will crash 
+1

如果'mdicp'只有一个项目,这将崩溃。数组不是像字典,如果没有找到键,它将返回'nil'。对于数组,如果索引超出边界,则会崩溃。 – Rob

相关问题