2015-10-01 39 views
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 
    } 
} 

感谢您的投入。

回答

1

UPDATE

如果你想不保持decode<U>作为通用的功能,那么你应该约束添加到该说U必须有一个不带参数初始化泛型参数U

protocol HasInitializer { 
    init() 
} 

protocol EntityDecoder { 
    func decode<U: HasInitializer>(json: [String:AnyObject], index: Int) -> U 
} 

struct FirmDecoder : EntityDecoder { 
    func decode<Firm: HasInitializer>(json: [String : AnyObject], index: Int) -> Firm { 
     return Firm() 
    } 
} 

,做泛型参数和结构不使用相同的名称Firm。这很混乱。

原来的答案

EntityDecoderFirmDecoder定义是无效的,这是正确的方式:

import UIKit 
protocol EntityDecoder { 
    typealias U 
    func decode(json: [String:AnyObject], index: Int) -> U 
} 

public struct Firm { 
    public init() {} 
} 

struct FirmDecoder : EntityDecoder { 
    func decode(json: [String : AnyObject], index: Int) -> Firm { 
     return Firm() 
    } 
} 
+0

要添加一些解释,在这个问题:'解码'声明泛型函数和“公司”在这里被用作任何类型的占位符,而不是实际的'struct Firm' – JeremyP

+0

@JeremyP我更新了我的答案,但我不明白你为什么使'FirmDecoder.decode()'方法是通用的,你为什么期待那'坚强'泛型pa rameter将有没有参数的初始化器。 – mixel

+0

@Entan对不起,我把你和JeremyP混淆:)如果一切都好,请接受我的答案。 – mixel