2015-10-30 191 views
4

將基於變量的元組直接傳遞給使用基於元組值的枚舉會導致編譯錯誤。例如:將var元組傳遞給枚舉值

我有如下的枚舉:

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" 

這使編譯器錯誤與雨燕2.1。但是當我將stAnswer更改爲常量使用時,讓它正常工作。任何人有想法是什麼導致編譯器錯誤在這裏?

+1

好奇的小編譯器特質。我也遇到了奇怪的元組行爲。也許你應該提交一個[bug報告](http://bugreport.apple.com)。在短期內,如果你確實需要'var stAnswer'而不是'let stAnswer',那麼將'answerType'改爲'let answerType = AnswerType.Subjective(問題:stAnswer.question,answer:stAnswer.answer)'。 (我知道這是不雅的,但對我來說,它看起來不那麼冒犯。) – Rob

回答

2

斯威夫特不能處理傳遞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) 
0

要使用元組作爲枚舉的值,雙支柱的元組,即:

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... 
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) 

或者你可以使用structSubjectiveType,也有所作爲版本y類似。