首页 文章

带约束的类型Array的扩展不能有继承子句 - swift 2 [duplicate]

提问于
浏览
21

这个问题在这里已有答案:

在swift 2中我想扩展Array类型 . 我有一个 JSONDecodable 协议 . 如果 Array 的元素也是 JSONDecodable ,我想对编译器说的是 Array 符合协议 JSONDecodable . 这是代码:

public protocol JSONDecodable {
    static func createFromJSON(json: [String: AnyObject]) throws -> Self
}

extension Array: JSONDecodable where Element: JSONDecodable {

}

但是编译器给出了错误:“带有约束的类型数组的扩展不能有继承子句”

那么还有其他方法可以实现这种行为吗?

2 回答

  • 7

    小型擦除怎么样?它应该打勾

    protocol JSONDecodable {
        init(json: JSON) throws
    }
    

    虽然Swift 3不允许做扩展

    extension Array: JSONDecodable where Element: JSONDecodable
    

    但它可能做到:

    extension Array: JSONDecodable {
        init(json: JSON) throws {
            guard let jsonArray = json.array,
                let decodable = Element.self as? JSONDecodable.Type else {
                    throw JSONDecodableError.undecodable
            } 
    
            self = jsonArray.flatMap { json in
                let result: Element? = (try? decodable.init(json: json)) as? Element
                return result
            }
        }
    }
    
  • 0

    我认为你在推特上找到的the hint意味着:

    protocol X {
        var xxx: String { get }
    }
    
    // This is a wrapper struct
    struct XArray: X {
    
        let array: Array<X>
    
        var xxx: String {
            return "[\(array.map({ $0.xxx }).joinWithSeparator(", "))]"
        }
    
    }
    
    // Just for this demo
    extension String: X {
        var xxx: String {
            return "x\(self)"
        }
    }
    
    let xs = XArray(array: ["a", "b", "c"])
    print(xs.array) // ["a", "b", "c"]
    print(xs.xxx) // [xa, xb, xc]
    

相关问题