Swift - 计算 属性 Return
Swift - Computed Property Return
我有一组字典,我将用于 collectionView 中的单元格。我是 swift 的新手,所以我尝试找到最好的存储方式。
现在我使用这个代码:
var collectionViewData: [collectionViewStruct] = {
var cell_1 = collectionViewStruct()
cell_1.title = "..."
cell_1.text = "..."
cell_1.firstColor = "C68CF2"
cell_1.secondColor = "EFA8CA"
var cell_2 = collectionViewStruct()
cell_2.title = "..."
cell_2.text = "..."
cell_2.firstColor = "C68CF2"
cell_2.secondColor = "EFA8CA"
return [cell_1, cell_2]
}()
有没有办法不在 return 中写入每个变量?
如何一次性return所有变量?
或者也许有更好的方法来存储这些数据?
提前致谢:)
为了实现这一点,您可以使用私有 属性 和 return,而不是像:
private var _suggestions: [suggestionsStruct] = [suggestionsStruct]()
var suggestions: [suggestionsStruct] {
get{
if _suggestions.count > 0{
var suggestion_1 = suggestionsStruct()
suggestion_1.title = "..."
suggestion_1.text = "..."
suggestion_1.firstColor = "C68CF2"
suggestion_1.secondColor = "EFA8CA"
_suggestions.append(suggestion_1)
}else{
var suggestion_1 = suggestionsStruct()
suggestion_1.title = "..."
suggestion_1.text = "..."
suggestion_1.firstColor = "C68CF2"
suggestion_1.secondColor = "EFA8CA"
_suggestions = [suggestion_1]
}
return _suggestions
}
}
如果建议数据永远不变,只需使用以下结构:
struct collectinView {
let title: String
let text: String
let firstColor = "C68CF2"
let secondColor = "EFA8CA"
}
let collectionViewData = [
collectionView(title: "...", text: "..."),
collectionView(title: "other Title", text: "Other text")]
我有一组字典,我将用于 collectionView 中的单元格。我是 swift 的新手,所以我尝试找到最好的存储方式。
现在我使用这个代码:
var collectionViewData: [collectionViewStruct] = {
var cell_1 = collectionViewStruct()
cell_1.title = "..."
cell_1.text = "..."
cell_1.firstColor = "C68CF2"
cell_1.secondColor = "EFA8CA"
var cell_2 = collectionViewStruct()
cell_2.title = "..."
cell_2.text = "..."
cell_2.firstColor = "C68CF2"
cell_2.secondColor = "EFA8CA"
return [cell_1, cell_2]
}()
有没有办法不在 return 中写入每个变量?
如何一次性return所有变量?
或者也许有更好的方法来存储这些数据?
提前致谢:)
为了实现这一点,您可以使用私有 属性 和 return,而不是像:
private var _suggestions: [suggestionsStruct] = [suggestionsStruct]()
var suggestions: [suggestionsStruct] {
get{
if _suggestions.count > 0{
var suggestion_1 = suggestionsStruct()
suggestion_1.title = "..."
suggestion_1.text = "..."
suggestion_1.firstColor = "C68CF2"
suggestion_1.secondColor = "EFA8CA"
_suggestions.append(suggestion_1)
}else{
var suggestion_1 = suggestionsStruct()
suggestion_1.title = "..."
suggestion_1.text = "..."
suggestion_1.firstColor = "C68CF2"
suggestion_1.secondColor = "EFA8CA"
_suggestions = [suggestion_1]
}
return _suggestions
}
}
如果建议数据永远不变,只需使用以下结构:
struct collectinView {
let title: String
let text: String
let firstColor = "C68CF2"
let secondColor = "EFA8CA"
}
let collectionViewData = [
collectionView(title: "...", text: "..."),
collectionView(title: "other Title", text: "Other text")]