我有一個類Question
嵌套結構MultipleChoiceAnswers
。當初始化Question
時,我也初始化了MultipleChoiceAnswers
,並給它一個Question
實例的參考。然後我想將MultipleChoiceAnswers
實例分配給Question
實例的屬性answers
。如何解決此循環參考初始化錯誤?
這裏是一個概述:
struct Answer {
let value:Double;
let isCorrect:Bool;
}
class Question {
struct MultipleChoiceAnswers {
let question:Question;
let answers:[Answer];
}
let answers:MultipleChoiceAnswers;
init(possibleAnswersCount:UInt) {
let answers:[Answer];
/*
here I generate some Answer instances
that get appended to the answers Array
*/
self.answers = MultipleChoiceAnswers(question: self, answers: answers); // <-- error
}
}
然而,這導致錯誤:
Variable 'self.answers' used before being initalized
這是有道理的。不管怎樣,我能不能解決這個錯誤?我想用weak
或unowned
解決這個的(最好是後者,因爲它應該是一個
強
保證非nil
參考),但我不認爲我完全理解其中的邏輯,但因爲改變MultipleChoiceAnswers
到:
struct MultipleChoiceAnswers {
unowned let question:Question;
let answers:[Answer];
}
...不能解決錯誤。
如何解決此錯誤,同時保留
強
保證非nil
循環參考?
P.S:說實話,我甚至完全肯定但我是否真的需要這循環引用來開始的,但由於這試探性的實施提出了這個錯誤,我得到了好奇可能的解決方案呢。
確實有效。謝謝。所以,(這個問題是由我爲這個問題得到的)決定的,這是否意味着「弱」和/或「無主」與我的情況完全不相干?那些僅僅是用來防止內存泄漏,也許呢?無主的 – Codifier 2014-09-28 22:49:09
在這裏是一個不錯的選擇。我不知道你爲什麼被拒絕。 – 2014-09-29 01:05:58
對。再次感謝。 – Codifier 2014-09-29 16:26:33