简体   繁体   中英

How to get all “title” values from dictionary of array in swift 5

Swift 5

I want to get array of all values from " title " key

// Create variable
var arrSportsList:[[String:String]] = []

    // viewDidLoad code
    arrSportsList = [
        ["title":"Cricket"],
        ["title":"Soccer"],
        ["title":"American Football"],
        ["title":"Ice Hockey"],
        ["title":"Tennis"],
        ["title":"Baseball"],
        ["title":"Basketball"],
        ]

I want to use this title in picker view.

You can use compactMap :

let titleArr = arrSportsList.compactMap { $0["title"] }

It transforms each dictionary to the value associated with the key title , and removes the dictionaries which don't have a title key.

I also suggest you to create a class/struct to store these sports, instead of dictionaries:

struct Sport {
    let title: String
    // other properties
}

Use compactMap(_:) method to get the title value from all dictionaries. If any dictionary doesn't contain title key it will be ignored

var arrSportsList:[[String:String]] = []

// viewDidLoad code
arrSportsList = [
    ["title1":"anothergame"],
    ["title":"Cricket"],
    ["title":"Soccer"],
    ["title":"American Football"],
    ["title":"Ice Hockey"],
    ["title":"Tennis"],
    ["title":"Baseball"],
    ["title":"Basketball"],
    ]


let titleArr = arrSportsList.compactMap { $0["title"] }
print(titleArr)//Cricket,Soccer,American Football,Ice Hockey,Tennis,Baseball,Basketball

Easiest way

 let titleArr = arrSportsList.compactMap { $0["title"] }

Or you can loop through the dictionary array and can get the titles Like

 let titleArr = Array<String>();
    for dict in arrSportsList {
        if let title = dict["title"] {
             titleArr.append(title);
        }
    }

In case of understanding more, you can use

// Create variable

var arrSportsList:[[String:String]] = []

// viewDidLoad code
arrSportsList = [
    ["title":"Cricket"],
    ["title":"Soccer"],
    ["title":"American Football"],
    ["title":"Ice Hockey"],
    ["title":"Tennis"],
    ["title":"Baseball"],
    ["title":"Basketball"],
    ]

var titleArray: [String]
for (key, value) in arrSportsList {
    print (key) // "title"
    print (value) //Cricket, Soccer, American Football, Ice Hockey, Tennis, Baseball, Basketball
    titleArray.append(value)
}
print (titleArray) //Cricket, Soccer, American Football, Ice Hockey, Tennis, Baseball, Basketball

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