关于ios:在这种情况下,’JSONEncoder’/’JSONDecoder’对于类型查找是模棱两可的

'JSONEncoder' / 'JSONDecoder' is ambiguous for type lookup in this context

我正在关注错误

enter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import Foundation
import JSONCodable

extension JSONEncoder {
    func encode(_ value: CGAffineTransform, key: String) {
        object[key] = NSValue(cgAffineTransform: value)
    }

    func encode(_ value: CGRect, key: String) {
        object[key] = NSValue(cgRect: value)
    }

    func encode(_ value: CGPoint, key: String) {
        object[key] = NSValue(cgPoint: value)
    }
}

extension JSONDecoder {

    func decode(_ key: String, type: Any.Type) throws -> NSValue {
        guard let value = get(key) else {
            throw JSONDecodableError.missingTypeError(key: key)
        }
        guard let compatible = value as? NSValue else {
            throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: NSValue.self)
        }
        guard let objcType = String(validatingUTF8: compatible.objCType), objcType.contains("\\(type)") else {
            throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: type)
        }
        return compatible
    }

    func decode(_ key: String) throws -> CGAffineTransform {
        return try decode(key, type: CGAffineTransform.self).cgAffineTransformValue
    }

    func decode(_ key: String) throws -> CGRect {
        return try decode(key, type: CGRect.self).cgRectValue
    }

    func decode(_ key: String) throws -> CGPoint {
        return try decode(key, type: CGPoint.self).cgPointValue
    }
}


JSONCodable还声明了JSONEncoder / JSONDecoder类,因此编译器不知道您要扩展的类:标准类还是库中的那些。

使用模块名称作为前缀,以提示编译器扩展哪个类。

1
2
3
4
5
6
7
8
9
10
import Foundation
import JSONCodable

extension JSONCodable.JSONEncoder {
    // extension code
}

extension JSONCodable.JSONDecoder {
    // extension code
}

但是不适用于该特定库,因为该库声明了具有相同名称(JSONCodable)的协议。因此,您只需要显式地从模块中导入两个类(有关更多详细信息,请参见此SO帖子):

1
2
3
4
5
6
7
8
9
10
11
import Foundation
import class JSONCodable.JSONEncoder
import class JSONCodable.JSONDecoder

extension JSONCodable.JSONEncoder {
    // your code
}

extension JSONCodable.JSONDecoder {
    // your code
}