Swift 转换不符合预期

Swift Casting doesn't work as Expected

我已经创建了一个自定义协议,我打算用它来代替 Any

但是当我尝试从 JSONSerialization.jsonObject

投射它时我不工作

这是我的自定义协议

public protocol StringOrNumber {}

extension String:StringOrNumber {}
extension NSNumber:StringOrNumber {}
extension Bool:StringOrNumber {}
extension Float:StringOrNumber {}
extension CGFloat:StringOrNumber {}
extension Int32:StringOrNumber {}
extension Int64:StringOrNumber {}
extension Int:StringOrNumber {}
extension Double:StringOrNumber {}
extension Dictionary:StringOrNumber {}
extension Array:StringOrNumber {}
extension NSDictionary:StringOrNumber {}
extension NSArray:StringOrNumber {}
extension NSString:StringOrNumber {}
extension NSNull:StringOrNumber {}

这是我希望能工作但没有工作的代码

let json = try JSONSerialization.jsonObject(with: data, options: [])
           if let object = json as? [String: StringOrNumber] {
               // json is a dictionary
               print(object)
           }

但是,如果我尝试分两步转换它,它的工作原理如下

let json = try JSONSerialization.jsonObject(with: data, options: [])
if let object = json as? [String: Any] {
    // json is a dictionary
    print(object)

    if let newObject:[String:StringOrNumber] = object as? [String:StringOrNumber] {
        // json is a newer dictionary
        print(newObject)
    }


}

这是我正在从文件中读取的示例 JSON。(没关系,你也可以尝试自己的

{
     "firstName": "John",
}

我不明白为什么第一段代码不起作用而第二段代码却能...

谢谢

它不是 Swift(语言)特定的,它是 Apple 特定的...

如果将数据更改为

,情况会更糟
let d = ["first":"john", "last":"doe", "test int": 0, "test null": NSNull()] as [String:Any]

linux 版本按预期工作,

["test null": <NSNull: 0x0000000000825560>, "last": "doe", "first": "john", "test int": 0]
["test null": <NSNull: 0x0000000000825560>, "last": "doe", "first": "john", "test int": 0]
["test int": 0, "last": "doe", "first": "john", "test null": <NSNull: 0x0000000000825560>]

但苹果打印

[:]
[:]
{
    first = john;
    last = doe;
    "test int" = 0;
    "test null" = "<null>";
}

看起来很奇怪。下一个代码片段解释原因

import Foundation

public protocol P {}

extension String:P {}
extension Int:P {}
extension NSNull:P {}

let d = ["first":"john", "last":"doe", "test null": NSNull(), "test int": 10] as [String:Any]
print("A)",d, type(of: d))

let d1 = d as? [String:P] ?? [:]
print("B)",d1, type(of: d1))
print()

if let data = try? JSONSerialization.data(withJSONObject: d, options: []) {

    if let jobject = try? JSONSerialization.jsonObject(with: data, options: []) {

        let o = jobject as? [String:Any] ?? [:]
        print("1)",o, type(of: o))

        var o2 = o as? [String:P] ?? [:]
        print("2)",o2, type(of: o2), "is it empty?: \(o2.isEmpty)")
        print()

        if o2.isEmpty {
            o.forEach({ (t) in
                let v = t.value as? P
                print("-",t.value, type(of: t.value),"as? P", v as Any)
                o2[t.key] = t.value as? P ?? 0
            })
        }
        print()
        print("3)",o2)
    }
}

在苹果上打印

A) ["test null": <null>, "test int": 10, "first": "john", "last": "doe"] Dictionary<String, Any>
B) ["test null": <null>, "test int": 10, "first": "john", "last": "doe"] Dictionary<String, P>

1) ["test null": <null>, "test int": 10, "first": john, "last": doe] Dictionary<String, Any>
2) [:] Dictionary<String, P> is it empty?: true

- <null> NSNull as? P Optional(<null>)
- 10 __NSCFNumber as? P nil
- john NSTaggedPointerString as? P nil
- doe NSTaggedPointerString as? P nil

3) ["test null": <null>, "test int": 0, "first": 0, "last": 0]

在 linux 上它打印

A) ["test int": 10, "last": "doe", "first": "john", "test null": <NSNull: 0x00000000019d8c40>] Dictionary<String, Any>
B) ["test int": 10, "last": "doe", "first": "john", "test null": <NSNull: 0x00000000019d8c40>] Dictionary<String, P>

1) ["test int": 10, "last": "doe", "first": "john", "test null": <NSNull: 0x00000000019ec550>] Dictionary<String, Any>
2) ["test int": 10, "last": "doe", "first": "john", "test null": <NSNull: 0x00000000019ec550>] Dictionary<String, P> is it empty?: false

3) ["test int": 10, "last": "doe", "first": "john", "test null": <NSNull: 0x00000000019ec550>]

最后,我使用了来自开源发行版的 JSONSerialization 的稍微修改的源代码(为了避免与 apple Foundation 冲突,我将 class 重命名为 _JSONSerialization :-)并按照它在我的游乐场中工作的方式更改代码,没有任何警告和错误,并且...... 它打印出预期的结果:)

为什么现在可以了?关键是

/* A class for converting JSON to Foundation/Swift objects and converting Foundation/Swift objects to JSON.    An object that may be converted to JSON must have the following properties:
 - Top level object is a `Swift.Array` or `Swift.Dictionary`
 - All objects are `Swift.String`, `Foundation.NSNumber`, `Swift.Array`, `Swift.Dictionary`,  or `Foundation.NSNull`
 - All dictionary keys are `Swift.String`s
 - `NSNumber`s are not NaN or infinity  */

现在,将所有可能的值有条件地向下转换为 P 可以按预期工作

老实说,在 linux :-) 和苹果上试试这个片段。

let d3 = [1.0, 1.0E+20]
if let data = try? JSONSerialization.data(withJSONObject: d3, options: []) {
    if let jobject = try? JSONSerialization.jsonObject(with: data, options: []) as? [Double] ?? [] {
        print(jobject)
    }
}

苹果版画

[1.0, 1e+20]

同时 linux

[]

并且具有非常大的价值会崩溃。这个错误来自(在开源 JSONSerialization 中)

if doubleResult == doubleResult.rounded() {
        return (Int(doubleResult), doubleDistance)
}

替换为

if doubleResult == doubleResult.rounded() {
         if doubleResult < Double(Int.max) && doubleResult > Double(Int.min) {
                 return (Int(doubleResult), doubleDistance)
         }
 }

和'deserialization'按预期工作(序列化有其他错误......)

如果您只想检查协议一致性:

使用is代替as

if json is [String : StringOrNumber] {

    print("valid")
}
else {
    print("invalid")
}

如果要使用转换后的类型:

if let object = (json as? [String: Any]) as? [String : StringOrNumber] {

    print("valid object = \(object)")
}
else {
    print("invalid")
}