您的自定義初始值設定項無法初始化不可變屬性。如果你希望它是不可變的,那麼不用創建一個自定義的初始化器,只需要在需要的或指定的初始化器之一中進行初始化。
這樣,
class AddBook: UIViewController {
@IBOutlet weak var bookAuthor: UITextField!
@IBOutlet weak var bookTitle: UITextField!
let bookStore: BookStore
required init(coder aDecoder: NSCoder) {
fatalError("Cannot be instantiated from storyboard")
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
bookStore = BookStore()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
@IBAction func saveNewBook(sender: AnyObject) {
let author = self.bookAuthor.text!
let title = self.bookTitle.text!
bookStore.addBook(author, title: title)
}
}
還是這個,
class AddBook: UIViewController {
@IBOutlet weak var bookAuthor: UITextField!
@IBOutlet weak var bookTitle: UITextField!
let bookStore: BookStore
required init(coder aDecoder: NSCoder) {
bookStore = BookStore()
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
fatalError("Cannot be instantiated from code")
}
@IBAction func saveNewBook(sender: AnyObject) {
let author = self.bookAuthor.text!
let title = self.bookTitle.text!
bookStore.addBook(author, title: title)
}
}
但是,你的情況,你要爲你使用讓書店它是不可變的:圖書城,但如果你是不使用故事板,您可以簡單地從所需的初始化程序中拋出致命異常並使用您自己的初始化程序,
class AddBook: UIViewController {
@IBOutlet weak var bookAuthor: UITextField!
@IBOutlet weak var bookTitle: UITextField!
let bookStore: BookStore
init(bookStore: BookStore) {
self.bookStore = bookStore
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("cannot be initialized from storyboard")
}
@IBAction func saveNewBook(sender: AnyObject) {
let author = self.bookAuthor.text!
let title = self.bookTitle.text!
bookStore.addBook(author, title: title)
}
}
let book = AddBook(bookStore: BookStore())
現在,你需要有必要的初始化,你必須做出財產可變的,這樣你可以從這樣的自定義初始化設置,
class AddBook: UIViewController {
@IBOutlet weak var bookAuthor: UITextField!
@IBOutlet weak var bookTitle: UITextField!
var bookStore: BookStore!
init(bookStore: BookStore) {
self.bookStore = bookStore
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@IBAction func saveNewBook(sender: AnyObject) {
let author = self.bookAuthor.text!
let title = self.bookTitle.text!
bookStore.addBook(author, title: title)
}
}
let book = ... // initialized from storyboard or using performSegueWithIdentifier:
book.bookStore = BookStore()
主要的理念在這裏,沒有兩個初始值設定初始化不可變屬性。只有一個可以做,所以要麼使用必需的初始化程序來實例化它,要麼使所需的初始化程序不可用,或者使該屬性可變,以便可以有兩個初始化程序,並且都可以初始化它。
你需要設置'self.bookStore'之前你調用'super.init' – dan
我不明白我應該設置什麼它也。 BookStore是一個包含所有書籍和添加/刪除等的方法的類。 – aamck