【问题标题】:Swift Generics, Stucts and Protocol: No accessible initializersSwift 泛型、结构和协议:没有可访问的初始化器
【发布时间】: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


    【解决方案1】:

    更新

    如果您想将decode&lt;U&gt; 保留为泛型函数,那么您应该向泛型参数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()
        }
    }
    

    【讨论】:

    • 补充一点解释,在问题中:decode&lt;Firm&gt; 声明了一个泛型函数,这里的“Firm”用作任何类型的占位符,而不是实际的struct Firm
    • @JeremyP 我更新了我的答案,但我不明白您为什么将 FirmDecoder.decode() 方法设为通用以及您为什么期望 Firm 通用参数将具有没有参数的初始化程序。
    • @Eternam 对不起,我把你和 JeremyP 弄混了 :) 如果一切正常,请接受我的回答。
    猜你喜欢
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 2020-03-05
    • 2016-04-11
    • 1970-01-01
    • 2016-07-06
    • 2020-02-07
    • 1970-01-01
    相关资源
    最近更新 更多