mercredi 3 avril 2019

Creating an array of struct without duplicates

Recently started learning Swift and is now faced with the problem (code below will insert):

I create an array of structure from 3 arrays. When creating an instance of the structure, I need to do it by random (randomElement as I understood) - all 3 parameters must be unique. How do I check for uniqueness in the function?

arrayOfHumans = createRandomHuman()

struct Human {
    let name: String
    let surname: String
    let age: String
    var email: String
}

var arrayOfHumans = [Human] () 
var humans: [Human] = []

let nameA  = ["Tim", "Mike", "Stan"]
let surnameA = ["Burk", "Sims", "Stoch"]
let ageA = ["12", "30", "25"]
let emailA = ["one@live.com", "two@gmail.com", "three@outlook.com"]

func createRandomHuman() -> [Human] {
    for _ in 1...3 {
        if nameA.isEmpty == false {
            let human = Human(name: nameA.randomElement()!,
                            surname: surnameA.randomElement()!,
                            age: ageA.randomElement()!,
                            email: emailA.randomElement()!)
            humans.append(human)
        }
    }
    return humans
}

Actual result:

first Struct {
    name: Tim
    surname: Sims
    age: 12
    email: three@outlook.com
}

second Struct {
    name: Mike
    surname: Stoch
    age: 25
    email: one@live.com
}

third Struct {
    name: Stan
    surname: Burk
    age: 30
    email: two@gmail.com
}




Aucun commentaire:

Enregistrer un commentaire