使用基于元组的值将基于变量的元组直接传递给枚举会导致编译错误。例如:
我有一个枚举如下:
enum AnswerType {
case Objective(Int)
case Subjective(question: Int, answer: String)
}
var stAnswer = (question: 1, answer: "Student's Answer")
let answerType = AnswerType.Subjective(stAnswer) //Compilation error here - "Missing argument for parameter answer in call"
这给Swift 2.1带来了编译错误。但是当我将stAnswer
更改为常量时,让它工作正常。任何有想法的人都会在这里造成编译错误吗?
答案 0 :(得分:2)
Swift无法以这种方式处理var
。它只能传递一个常量元组来初始化相关数据。这很可能只是编译器中未实现的功能,我建议打开雷达(bugreport.apple.com)。
最简单的解决方案是将元组声明为常量:
let stAnswer = (question: 1, answer: "Student's Answer")
let answerType = AnswerType.Subjective(stAnswer)
如果这不实用,那么在传递之前制作一个常量副本(这是编译器应该能够自动完成的)。
var stAnswer = (question: 1, answer: "Student's Answer")
let values = stAnswer
let answerType = AnswerType.Subjective(values)
您也可以使用封闭来强制复制。这对我来说有点过于棘手,但有些人可能更喜欢它:
let answerType = AnswerType.Subjective({stAnswer}())
你也可以使用@ Rob的评论解决方案(这里为未来的读者复制),这是很好的IMO:
let answerType = AnswerType.Subjective(question: stAnswer.question, answer: stAnswer.answer)
答案 1 :(得分:2)
typealias
并没有遭受这种奇怪的行为:
typealias SubjectiveType = (question: Int, answer: String)
enum AnswerType {
case Objective(Int)
case Subjective(SubjectiveType)
}
var stAnswer = SubjectiveType(question: 1, answer: "Student's Answer")
stAnswer.answer = "Student's revised answer"
let answerType = AnswerType.Subjective(stAnswer)
或者您也可以struct
使用SubjectiveType
,并完成非常相似的事情。
答案 2 :(得分:1)
要使用元组作为枚举值,请对元组进行双重支撑,因此:
enum AnswerType {
case Objective(Int)
case Subjective((question: Int, answer: String))
// One tuple value, rather than two non-tuple values
}
var stAnswer = (question: 1, answer: "Student's Answer")
let answerType = AnswerType.Subjective(stAnswer) // No error now...