mono0926
9/30/2016 - 11:37 AM

dictionary.unwrap.swift

private func unwrapIfCan(value: Any) -> Any {
    let m = Mirror(reflecting: value)
    guard let displayStyle = m.displayStyle else {
        return value
    }
    switch displayStyle {
    case .optional:
        break
    default:
        return value
    }
    guard let first = m.children.first else {
        return NSNull()
    }
    return first.value
}

extension Dictionary
{
    public func unwrappingValues() -> [Key: Any]
    {
        return reduce([Key: Any]()) { sum, e -> [Key: Any] in
            var sum = sum
            let value = unwrapIfCan(value: e.value)
            if !(value is NSNull) {
                print(value)
                sum[e.key] = value
            }
            return sum
        }
    }
}

// これがやりたい
var d1: [String: Any?] = ["a": 1, "b": nil]
d1.unwrappingValues() // → ["a": 1]
// これは、unwrapValuesが、OptionalなValueしか受け付けないなら実行出来ずでOK
var d2: [String: Int] = ["a": 1]
d2.unwrappingValues() // → ["a": 1]