Koichi Adachi

smart phone app development tips

Swift convert Dictionary<Int,AnyObject> to Dictionary<HogeType,AnyObject>

@objc public enum HogeType:Int{
  case unknown
  case hoge1
  case hoge2
  case hoge3
  case hoge4
  case hoge5
}

class A{  
}

bucket brigade

let convertedDict = [1:A(), 2:A(), 100:A()].reduce([HogeType:A]()){
  
  guard let controlType = HogeType(rawValue: $1.key) else {
    return $0
  }
  var bucket = $0
  bucket.updateValue($1.value, forKey: controlType)
  return bucket
}

remove complex code

let convertedDict = [1:A(), 2:A(), 100:A()].map {(HogeType(rawValue:$0.key),$0.value)}.filter{(($0.0) != nil)}