【发布时间】:2018-12-03 17:17:17
【问题描述】:
我了解通常我无法实例化协议。 但是,如果我在协议中包含一个初始化程序,那么编译器肯定知道当协议稍后被结构或类使用时,它会有一个可以使用的 init? 我的代码如下和行:
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)
给出错误:协议类型“拼图”无法实例化
【问题讨论】:
-
如果没有办法解决实例化的问题,那么我还有其他方法可以从协议扩展中返回 Puzzle 吗?
-
"但是如果我在协议中包含一个初始化程序,那么编译器肯定知道该协议何时被结构或类使用",不;可能相关:stackoverflow.com/questions/41074354/…
标签: swift protocols instantiation