【问题标题】:Check if array contains an index value in Swift检查数组是否包含 Swift 中的索引值
【发布时间】:2017-05-28 14:37:02
【问题描述】:

我在 plist 中有一个数组,其中包含 2 个整数值。我可以使用此代码读取第一个值没有问题

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

不幸的是,一些 plist 没有第二个索引值。所以调用这个

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

返回零。如何检查那里是否存在索引,以便仅在存在值时才获取值?我试图将它包装在 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
    }

但到目前为止,我的尝试已经导致多个控制台错误。

【问题讨论】:

    标签: ios arrays swift indexing nsarray


    【解决方案1】:

    试试这个

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

    mdicp 可能包含“n”个具有可选值的元素,因此您必须在解包之前进行可选绑定以避免崩溃。

    例如,如果我初始化容量为 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
    

    【讨论】:

    • 如果mdicp 只有一项,这将崩溃。数组不像字典,如果找不到键,则返回nil。使用数组,如果索引超出范围,就会崩溃。
    【解决方案2】:

    如果您正在处理整数数组并且只担心前两项,您可以执行以下操作:

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

    您是否真的想使用 nil 合并运算符 ?? 将缺失值评估为 0,或者只是将它们保留为可选项,这取决于您。

    或者你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2015-05-25
      • 2015-01-01
      • 2021-07-15
      • 1970-01-01
      相关资源
      最近更新 更多