Engineering

Convert [String : Any?] to [String : Any]

This snippet convert [String : Any?] to [String : Any]. It would be helpful in building parameter for API Request.

extension Dictionary where Key == String, Value == Any? {

  func filterNil() -> Dictionary<String, Any> {

    var dic: [String : Any] = .init(minimumCapacity: self.count)

    for arg in self {
      guard let value = arg.value else {
        continue
      }
      dic[arg.key] = value
    }

    return dic
  }
}

SampleCode

let param: [String : Any?] = [
  "age" : nil,
  "name" : "muukii",
  "height" : nil,
  "weight" : 56,
]
print(param.filterNil())

Result

["name": "muukii", "weight": 56]