Determining if Swift dictionary contains key and obtaining any of its values

前端 未结 7 1557
离开以前
离开以前 2020-11-30 17:04

I am currently using the following (clumsy) pieces of code for determining if a (non-empty) Swift dictionary contains a given key and for obtaining one (any) value from the

相关标签:
7条回答
  • 2020-11-30 18:10

    The accepted answer let keyExists = dict[key] != nil will not work if the Dictionary contains the key but has a value of nil.

    If you want to be sure the Dictionary does not contain the key at all use this (tested in Swift 4).

    if dict.keys.contains(key) {
      // contains key
    } else { 
      // does not contain key
    }
    
    0 讨论(0)
提交回复
热议问题