參考您定的代碼片段,爲實現MVC,你應該創建爲教訓哪位包含所需的屬性 - ,這樣的模型,mylessons
數組應該包含教訓的對象。
如果你想層在不同的文件中分離(這是一個好主意),你可能希望創建一個文件 - Lesson.swift
的示例 - ,其中包含你的模型,如下所示:
課。 SWIFT:
// Note that I decalred it as 'struct'
// instead of 'class' do what is suitable
// for your requirements...
struct Lesson {
var title:String?
var subtitle: String?
var bgImage: String?
var lesImage: String?
var lesTitle: String?
}
的ViewController:
// note that myLessons data type is: '[Lesson]'
var myLessons = [Lesson(title: "Posture",
subtitle: "Set up your body",
bgImage: "Ln1",
lesImage: "Posture_pic",
lesTitle: "So starting from the head and moving down",
lesContent: "1) The top back part of your head should be pointing up..")]
注:如果要實現tableView:cellForRowAtIndexPath:
,你應該訪問的教訓每一行是這樣的:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//....
let currentLesson = myLessons[indexPath.row]
// ...
}
另外:
,如果你能轉換這將是很好給定字典的課程對象,實際上它是可能的,通過將以下字典擴展:
extension Dictionary where Key: ExpressibleByStringLiteral, Value: ExpressibleByStringLiteral {
func toLesson() -> Lesson {
var lessonToRetrun = Lesson()
if let title = self["title"] as? String {
lessonToRetrun.title = title
}
if let subtitle = self["subtitle"] as? String {
lessonToRetrun.subtitle = subtitle
}
if let bgimage = self["bgimage"] as? String {
lessonToRetrun.bgImage = bgimage
}
if let lesimage = self["lesimage"] as? String {
lessonToRetrun.lesImage = lesimage
}
if let lestitle = self["lestitle"] as? String {
lessonToRetrun.lesTitle = lestitle
}
if let lescontent = self["lescontent"] as? String {
lessonToRetrun.lesContent = lescontent
}
return lessonToRetrun
}
}
,你將能夠做到:
let lessonDict = ["title":"Posture",
"subtitle":"Set up your body",
"bgimage":"Ln1", "lesimage":"Posture_pic",
"lestitle":"So starting from the head and moving down:",
"lescontent":"1) The top back part of your head should be pointing up.."]
let convertedLesson = lessonDict.toLesson()
print(convertedLesson)
// Lesson(title: Optional("Posture"), subtitle: Optional("Set up your body"), bgImage: Optional("Ln1"), lesImage: Optional("Posture_pic"), lesTitle: Optional("So starting from the head and moving down:"), lesContent: Optional("1) The top back part of your head should be pointing up.."))
,但你必須要相當肯定的keys
是相同的。
希望這有助於。
什麼是努力實現?即沒有分離的目的? –
由於變量太長,所以我想打開一個新文件來存儲它並訪問它。無論新文件是.swift還是.json。謝謝 –
我建議創建一個*模型*給定對象,你的數組應該包含此模型,而不是'[字符串:字符串]對象'。 –