创建一个没有重复的struct数组

问题描述 投票:-1回答:2

最近开始学习Swift并且现在面临问题(下面的代码将插入):

我从3个数组创建一个结构数组。在创建结构的实例时,我需要通过随机(我理解的randomElement)来做 - 所有3个参数必须是唯一的。如何检查函数的唯一性?

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 = ["[email protected]", "[email protected]", "[email protected]"]

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
}

实际结果:

first Struct {
    name: Tim
    surname: Sims
    age: 12
    email: [email protected]
}

second Struct {
    name: Mike
    surname: Stoch
    age: 25
    email: [email protected]
}

third Struct {
    name: Stan
    surname: Burk
    age: 30
    email: [email protected]
}
arrays swift random struct
2个回答
0
投票

一个解决方案是shuffle姓氏,年龄和电子邮件数组分别得到一个随机但唯一的顺序。

let nameA  = ["Tim", "Mike", "Stan"]
let surnameA = ["Burk", "Sims", "Stoch"]
let ageA = ["12", "30", "25"]
let emailA = ["[email protected]", "[email protected]", "[email protected]"]

func createRandomHuman() -> [Human] {
    let shuffledSurnameA = surnameA.shuffled()
    let shuffledAgeA = ageA.shuffled()
    let shuffledEmailA = emailA.shuffled()
    var humans: [Human] = []
    for i in 0..<nameA.count {
        let human = Human(name: nameA[i],
                          surname: shuffledSurnameA[i],
                          age: shuffledAgeA[i],
                          email: shuffledEmailA[i])
            humans.append(human)
    }
    return humans
}

let arrayOfHumans = createRandomHuman()

另一种方法是改变指数

func createRandomHuman() -> [Human] {
    let indices = nameA.indices
    let shuffledIndices = (0..<3).map{ _ in indices.shuffled()}
    var humans: [Human] = []
    for i in 0..<nameA.count {
        let human = Human(name: nameA[i],
                          surname: surnameA[shuffledIndices[0][i]],
                          age: ageA[shuffledIndices[1][i]],
                          email: emailA[shuffledIndices[2][i]])
        humans.append(human)
    }
    return humans
}

0
投票

如果我理解你的话,你要确保所有随机创造的人都不同。 如果是这样,问题是两个人何时不同。这取决于您的问题。因此,您作为程序员必须定义它。 你可以采用Equatable protocol来做到这一点。 一旦你的结构符合这个协议,你就可以遍历所有先前发起的人类,并检查新的随机创建的人是否等于其中一个。如果是这样,请创建一个新的。

© www.soinside.com 2019 - 2024. All rights reserved.