简体   繁体   中英

Swift - Computed Property Return

I have array of dictionaries that I will use for cells in collectionView. I'm new to swift, so I try to find the best way to store that.

Now I use this code:

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

Is there a way not to write every var in return?

How to return all the variables at once?

Or maybe there is a better way to store this data?

Thanks in Advance :)

For achieving this you can use a private property and return that instead like:

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

If the suggestions data is never changing, just use the following struct:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM