【发布时间】:2015-10-01 09:08:52
【问题描述】:
为什么这段代码不能编译?
编译错误在struct FirmDecoder“return Firm()”中。
错误消息是:“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
提前致谢。
更新 @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
}
}
感谢您的意见。
【问题讨论】:
标签: generics struct protocols swift2 xcode7