【发布时间】:2018-02-07 17:53:47
【问题描述】:
我知道以前有人问过这个问题,但我不知道如何解决当前的问题。我已经定义了一个带有associatedtype 属性的协议MultipleChoiceQuestionable:
protocol Questionable {
var text: String {get set}
var givenAnswer: String? {get set}
}
protocol MultipleChoiceQuestionable: Questionable {
associatedtype Value
var answers: Value { get }
}
struct OpenQuestion: Questionable {
var text: String
var givenAnswer: String?
}
struct MultipleChoiceQuestion: MultipleChoiceQuestionable {
typealias Value = [String]
var text: String
var givenAnswer: String?
var answers: Value
}
struct NestedMultipleChoiceQuestion: MultipleChoiceQuestionable {
typealias Value = [MultipleChoiceQuestion]
var text: String
var answers: Value
var givenAnswer: String?
}
符合此协议的类型以Questionable 形式保存在数组中,如下所示:
// This array contains OpenQuestion, MultipleChoiceQuestion and NestedMultipleChoiceQuestion
private var questions: [Questionable] = QuestionBuilder.createQuestions()
在我的代码中某处我想做类似的事情:
let question = questions[index]
if let question = question as? MultipleChoiceQuestionable {
// Do something with the answers
question.answers = .....
}
这是不可能的,因为 Xcode 警告我:Protocol MultipleChoiceQuestionable 只能用作泛型约束。我一直在寻找如何解决这个问题,因为泛型对我来说很新。显然 Swift 在编译期间不知道 associatedtype 的类型,这就是引发此错误的原因。我读过有关使用类型擦除的信息,但我不知道这是否能解决我的问题。也许我应该改用通用属性,或者我的协议定义错误?
【问题讨论】:
标签: swift generics swift-protocols