我遇到了以下错误
我不知道为什么会出现这个问题,我该如何解决? 请帮忙!
注意:我使用的是 Xcode 版本 9.3.1 和 Swift4, 我曾尝试使用 JSONCodable.JSONEncoder 和 JSONCodable.JSONDecoder 但它不起作用。
代码如下:
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
类,因此编译器不知道您要扩展哪些:标准类,或图书馆的那些。
通过在类前加上模块名称来告诉编译器要扩展哪个类,应该可以消除歧义。
import Foundation
import JSONCodable
extension JSONCodable.JSONEncoder {
// extension code
}
extension JSONCodable.JSONDecoder {
// extension code
}
然而,这对这个特定的库不起作用,因为该库声明了一个具有相同名称的协议(protocol) (JSONCodable
)。因此,您只需要从模块中显式导入两个类(有关更多详细信息,请参阅 this SO post):
import Foundation
import class JSONCodable.JSONEncoder
import class JSONCodable.JSONDecoder
extension JSONCodable.JSONEncoder {
// your code
}
extension JSONCodable.JSONDecoder {
// your code
}
关于ios - 'JSONEncoder'/'JSONDecoder' 在此上下文中对于类型查找不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51759671/