我真的很想考虑使用快捷方式将工作区作为小菜一碟而且不是Swift的专家,所以下面的代码/方案有任何快捷方式
let Item1 = MenuItem()
Item1.titleEn = "item 1"
let Item2 = MenuItem()
Item2.titleEn = "item 2"
let Item3 = MenuItem()
Item3.titleEn = "item 3"
let Item4 = MenuItem()
Item4.titleEn = "item 4"
let Item5 = MenuItem()
Item5.titleEn = "item 5"
let Item6 = MenuItem()
Item6.titleEn = "item 6"
self.items.append(Item1)
self.items.append(Item2)
self.items.append(Item3)
self.items.append(Item4)
self.items.append(Item5)
self.items.append(Item6)
答案 0 :(得分:3)
向MenuItem
添加初始值设定项以传递标题
class MenuItem {
let title : String
init(title: String) { self.title = title }
}
然后使用标题数组并映射它们
var items = [MenuItem]()
let titles = ["item 1", "item 2", "item 3", "item 4", "item 5", "item 6"]
let menuItems = titles.map { MenuItem(title: $0) }
items.append(contentsOf: menuItems)
对于两个项目使用元组
class MenuItem {
let title : String
let icon : String
init(title: String, icon: String) { self.title = title; self.icon = icon }
}
var items = [MenuItem]()
let titles = [("item 1", "icon 1"), ("item 2", "icon 2"), ("item 3", "icon 3"), ("item 4", "icon 4"), ("item 5", "icon 5"), ("item 6", "icon 6")]
let menuItems = titles.map { MenuItem(title: $0.0, icon: $0.1) }
items.append(contentsOf: menuItems)
注意:
在大多数情况下,使用结构就足够了。好处是您可以免费获得初始化程序
struct MenuItem {
let title : String
let icon : String
}
答案 1 :(得分:0)
简单地说,在for in
循环中执行:
func appendItem(_ title: String) {
var item = MenuItem()
item.titleEn = title
items.append(item)
}
var items = [MenuItem]()
for i in 0...5 {
appendItem("Item \(i+1)")
}
dump(items)
/*
6 elements
▿ __lldb_expr_48.MenuItem
▿ titleEn: Optional("Item 1")
- some: "Item 1"
▿ __lldb_expr_48.MenuItem
▿ titleEn: Optional("Item 2")
- some: "Item 2"
▿ __lldb_expr_48.MenuItem
▿ titleEn: Optional("Item 3")
- some: "Item 3"
▿ __lldb_expr_48.MenuItem
▿ titleEn: Optional("Item 4")
- some: "Item 4"
▿ __lldb_expr_48.MenuItem
▿ titleEn: Optional("Item 5")
- some: "Item 5"
▿ __lldb_expr_48.MenuItem
▿ titleEn: Optional("Item 6")
- some: "Item 6"
*/