0
为什么这段代码没有编译?Swift的泛型,工具和协议:没有可访问的初始化器
编译错误在struct FirmDecoder“return Firm()”中。
错误消息是:'公司'不能构造,因为它没有可访问的初始化器。
//: Playground - noun: a place where people can play
import UIKit
protocol EntityDecoder {
func decode<U>(json: [String:AnyObject], index: Int) -> U
}
public struct Firm {
public init(){}
}
struct FirmDecoder : EntityDecoder {
func decode<Firm>(json: [String : AnyObject], index: Int) -> Firm {
return Firm()
}
}
//extension EntityDecoder {
// func decode<Firm>(json: [String : AnyObject], index: Int) -> Firm {
// return Firm()
// }
//}
http://i.stack.imgur.com/q6bAE.png
在此先感谢。
UPDATE @JeremyP @mixel我并不是故意将FirmDecoder.decode()声明为通用函数。所以你的“原始答案”就是我试图达到的目标。
我是否正确地想到,无需为FirmDecoder实现.decode,我可以制定扩展协议来提供默认实现,因此FirmDecoder只需实现您在更新后的答案中提出的HasInitializer。
喜欢的东西(我没有访问的XCode目前):
protocol HasJsonInitializer {
init(json: [String:AnyObject], index: Int)
}
protocol EntityDecoder {
func decode<U: HasJsonInitializer>(json: [String:AnyObject], index: Int) -> U
}
extension EntityDecoder {
func decode<U: HasJsonInitializer>(json: [String : AnyObject], index: Int) -> U {
return U(json, index: index)
}
}
struct FirmDecoder : EntityDecoder, HasJsonInitializer {
init(json: [String:AnyObject], index: Int) {
// json processing
}
}
感谢您的投入。
要添加一些解释,在这个问题:'解码'声明泛型函数和“公司”在这里被用作任何类型的占位符,而不是实际的'struct Firm' –
JeremyP
@JeremyP我更新了我的答案,但我不明白你为什么使'FirmDecoder.decode()'方法是通用的,你为什么期待那'坚强'泛型pa rameter将有没有参数的初始化器。 – mixel
@Entan对不起,我把你和JeremyP混淆:)如果一切都好,请接受我的答案。 – mixel