Swift-计算属性返回

时间:2018-09-10 10:44:22

标签: ios swift computed-properties

我有一系列字典,将用于collectionView中的单元格。我是新手,所以我尝试找到最佳的存储方式。

现在我使用此代码:

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]
}()

有没有一种方法不写每个var作为回报?

如何一次返回所有变量?

或者也许有更好的方法来存储这些数据?

先谢谢了:)

2 个答案:

答案 0 :(得分:2)

要实现此目的,您可以使用私有属性,然后将其返回,例如:

    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
    }
}

答案 1 :(得分:2)

如果建议数据从未更改,则只需使用以下结构:

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")]