Home > OS >  How to get element in array Swift IOS
How to get element in array Swift IOS

Time:08-31

How can i get an array of Id from dataInfo when name or title is empty

My code

struct Data {
    let id: String
    let name: String
    let tilte: String
}

var dataID: [String]

let dataInfo = [ Data(id: "1", name: "", tilte: ""), Data(id: 2, name: "K", tilte: "A"), Data(id: 3, name: "", tilte: ""), Data(id: 4, name: "4", tilte: "")]

my expectations

dataID = [1, 3, 4]

CodePudding user response:

First of all, because of your data Info not map with your sturct.

Your data should look like this

let dataInfo = [ Data(id: "1", name: "", tilte: ""), Data(id: "2", name: "K", tilte: "A"), Data(id: "3", name: "", tilte: ""), Data(id: "4", name: "4", tilte: "")]

And for your question, it can divide into 2 step: Make a dataInfo when name or title is empty and get their id

Code will be like this

var dataID: [String]

let dataInfo = [ Data(id: "1", name: "", tilte: ""), Data(id: "2", name: "K", tilte: "A"), Data(id: "3", name: "", tilte: ""), Data(id: "4", name: "4", tilte: "")]

let dataInfoFilterEmpty = dataInfo.filter{($0.name.isEmpty || $0.tilte.isEmpty)}
dataID = dataInfoFilterEmpty.map{$0.id} // ["1", "3", "4"]
  • Related