我創建兩個單獨的文件[Page.swift
和PageTableViewController.swift
]什麼是在Swift中創建對象數組的正確語法?
在Page.swift:
class Page {
// MARK: Properties
var chapter: Int
var verse: Int
var sanskrit: String?
// MARK: Initialization
init?(chapter: Int, verse: Int, sanskrit: String?) {
// Initialize stored properties.
self.chapter = chapter
self.verse = verse
self.sanskrit = sanskrit
}
}
在我PageTableViewController.swift:
import UIKit
class PageTableViewController: UITableViewController {
// MARK: Properties
var pages = [Page]()
override func viewDidLoad() {
super.viewDidLoad()
createPages()
}
func createPages() {
let page1 = Page(chapter: 1, verse: 1, sanskrit: "अथ योगानुशासनम्")
let page2 = Page(chapter: 1, verse: 2, sanskrit: "योगश्चित्तवृत्तिनिरोधः")
pages += [page1, page2] // ERROR appears here as noted below..
}
}
但error
出現在那裏,我得到:
Binary operator '+=' cannot be applied to operands of type '[Page]' and '[Page?]'
爲什麼會這樣?
我認爲這是因爲你的init?初始化器創建一個可選的而不是一個頁面。 –