Home > Software design >  Get a specific value from an array in swift ios
Get a specific value from an array in swift ios

Time:06-29

I have a testModel object. How can I get an array containing only the id field from testModel to store in nameID

Below is my code

struct Model {
    let id: Int
    let name: String
}

ViewController

  let nameID = [Int]()

  let testModel = [Model(id: 1, name: ""), Model(id: 2, name: ""), Model(id: 3, name: "")]

  override func viewDidLoad() {
        super.viewDidLoad()

   let people = testModel.map { item in
          print(item.id)
         self.nameID = item.id
    }
}

CodePudding user response:

You should never have side effects (mutating state) inside the closure of a map. instead, you simply need to return item.id and then assign people to hairstyleID.

let ids = testModel.map { item in item.id }
self.hairstyleID = ids

You can also simplify the map using KeyPaths testModel.map(\.id).

CodePudding user response:

You can try

hairstyleID = testModel.map { $0.id }

CodePudding user response:

The simplest way to get an array containing only the id field from testModel to store in nameID is to use map:

let nameID:[Int] = []
let testModel = [Model(id: 1, name: ""), Model(id: 2, name: ""), Model(id: 3, name: "")]

override func viewDidLoad() {
    super.viewDidLoad()
    nameID = testModel.map{ $0.id }
}

CodePudding user response:

Here is how to get all id's and a simple filter example to get some model from the list:

struct Model {
    let id: Int
    let name: String
}

func workWithModel() {
    let modelList = [Model(id: 1, name: "Home"), Model(id: 2, name: "Work"), Model(id: 3, name: "Other place")]
    // Get all id's
    let nameIDs = modelList.map { $0.id }
        
    print("Name IDs: \(nameIDs)")
        
    // Filter some model
    guard let whereAreYou = modelList.first(where: {
        $0.name == "Work" || $0.name.contains("w")
    }) else { return }
        
    print("Just now you are in: \(whereAreYou)")
}

The output is:

Name IDs: [1, 2, 3]
Just now you are in: Model(id: 2, name: "Work")
  • Related