Receive only one data from filters to struct

2019-09-07 03:38发布

问题:

Short question, I have the following structure, which I store in "Salas"

struct SalasMaster {
    let id: Int
    let nombre: String
    let latitud: String
    let longitud: String
    let piso: String
    let observaciones: String
    let pabellon: String
}

var Salas = [SalasMaster]()

...receiving data...
...dump(Salas)
        example -> SalasMaster
                   - id: 307
                   - nombre: "SALA DE PROYECTOS "
                   - latitud: "-29.96429300"
                   - longitud: "-71.34937300"
                   - piso: "1"
                   - observaciones: ""
                   - pabellon: "X - Escuela de Ingeniería"

And finally what I want is to filter the example id, at this moment I get an array where it is, along with all other corresponding data

...filter data...

var arrayFiltered = Salas.filter{$0.id == 307}

Print(arrayFiltered) -> [SalasMaster(id: 307, nombre: "SALA DE PROYECTOS ", latitud: "-29.96429300", longitud: "-71.34937300", piso: "1", observaciones: "", pabellon: "X - Escuela de Ingeniería")]

But I can't find the way to return only one data that I'm interested in retrieving from "id", in this case I want to capture only "latitud", although in another case I might need another one.

回答1:

You can use first(where:) for that because it will give you first matching record and stop searching after it.

if let sale = Salas.first(where: { $0.id == 307 }) {
    print(sale.latitud)
}


回答2:

This will map through Salas and return an array of latituds.

Salas.flatMap { $0.id == 307 ? $0.latitud : nil }

For example

var arrayFiltered = Salas.flatMap { $0.id == 307 ? $0.latitud : nil }

Print(arrayFiltered) -> ["-29.96429300"]


回答3:

struct SalasMaster {
  let id: Int
  let nombre: String
  let latitud: String
}

// creating the array
let sala1 = SalasMaster(id: 1, nombre: "Sala1", latitud: "123")
let sala2 = SalasMaster(id: 2, nombre: "Sala2", latitud: "321")
let salas = [sala1, sala2]

let idToFind = 1
let latitudFound = salas
                        .first { $0.id == idToFind } // returns the object found
                        .map   { $0.latitud } // we transform the object

if let latitudFound = latitudFound {
  print(latitudFound) // 123
}

or if you want to get more than one field that interests you, you could use tuples:

let idToFind = 1
let salaFound = salas
                     .first { $0.id == idToFind } // returns the object found
                     .map   { (latitud: $0.id, nombre: $0.nombre) } // returns a tuple

if let sala = salaFound {
  print(sala.latitud) // 123
  print(sala.nombre) // Sala1
  //print(sala.id) // (latitud: Int, nombre: String) has no member 'id'
}