gpt4 book ai didi

swift - 在 swift 中,为什么我不能实例化一个有初始化器的协议(protocol)?

转载 作者:可可西里 更新时间:2023-11-01 00:20:03 25 4
gpt4 key购买 nike

我知道通常我无法实例化协议(protocol)。但是,如果我在协议(protocol)中包含一个初始化程序,那么编译器肯定知道当协议(protocol)稍后被结构或类使用时,它会有一个可以使用的初始化程序?我的代码如下和行:

protocol Solution {
var answer: String { get }
}

protocol Problem {
var pose: String { get }
}

protocol SolvableProblem: Problem {
func solve() -> Solution?
}

protocol ProblemGenerator {
func next() -> SolvableProblem
}

protocol Puzzle {
var problem: Problem { get }
var solution: Solution { get }

init(problem: Problem, solution: Solution)
}

protocol PuzzleGenerator {
func next() -> Puzzle
}

protocol FindBySolvePuzzleGenerator: PuzzleGenerator {
var problemGenerator: ProblemGenerator { get }
}

extension FindBySolvePuzzleGenerator {
func next() -> Puzzle {
while true {
let problem = problemGenerator.next()
if let solution = problem.solve() {
return Puzzle(problem: problem, solution: solution)
}
}
}
}

行:

return Puzzle(problem: problem, solution: solution)

给出错误:无法实例化协议(protocol)类型“Puzzle”

最佳答案

想象协议(protocol)是形容词。 Movable 说你可以移动它,Red 说它有color = "red"...但是他们没有'说出 是什么。你需要一个名词。一辆红色的可移动汽车。您可以实例化一辆汽车,即使细节不多。您不能实例化红色。

关于swift - 在 swift 中,为什么我不能实例化一个有初始化器的协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51018241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com