【问题标题】:Swift - Computed Property ReturnSwift - 计算属性返回
【发布时间】:2019-02-14 18:54:22
【问题描述】:

我有一组字典,我将用于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]
}()

有没有办法不写每个 var 作为回报?

如何一次返回所有变量?

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

在此先感谢 :)

【问题讨论】:

  • 为什么suggestions 是一个数组?还有其他变量在哪里,我只看到一个?
  • 这是一个闭包,不是计算属性
  • 如果是常数,为什么还要计算呢?计算属性充当观察者。他们每次都可以改变。考虑使用let
  • 您能否更新您的问题并说明suggestions 的目的?我们可以通过这种方式提供更好的帮助。
  • 看我的回答,你可以在你的结构中将颜色设置为常量,然后使用默认构造函数来启动一个常量collectionViewData

标签: ios swift computed-properties


【解决方案1】:

如果建议数据永远不会改变,只需使用以下结构:

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

【讨论】:

  • 每个单元格的颜色都不同,但是是的,我认为这种方式要好得多,谢谢! :)
【解决方案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
    }
}

【讨论】:

    猜你喜欢
    • 2018-02-03
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 2018-07-15
    • 2018-06-30
    • 2016-09-04
    • 2018-10-13
    • 2016-04-22
    相关资源
    最近更新 更多