最近开始学习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 = ["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
}
实际结果:
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
}
答案 0 :(得分:0)
一种解决方案是分别shuffle
的姓氏,年龄和电子邮件地址以获取随机但唯一的顺序。
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] {
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
}
答案 1 :(得分:0)
如果我理解的正确,那么您想确保所有随机创建的人类都是不同的。
如果是这样,问题是两个人何时不同。这取决于您的问题。因此,您作为程序员必须定义它。
您可以采用Equatable
protocol。
一旦您的结构符合此协议,就可以遍历所有先前启动的人类,并检查新随机创建的人类是否等于其中之一。如果是这样,请创建一个新的。