I have created a label with a frame on the screen which displays the chosen text. I also have two different arrays for the first and last name.
let nameArray = ["Jacob", "Lenny", "George", "Linda", "Arthur"]
let lastNameArray = ["Shelby", "Knight", "Luiz", "Hamilton", "Dobson"]
when I use nameLabel.text = nameArray.randomElement()
it works fine, but I want it to display both a random first name and a random last name from the given arrays within the same label. How would I go about doing this?
Just do the same thing but twice
nameLabel.text = "\(nameArray.randomElement()!) \(lastNameArray.randomElement()!)"
You can zip both array and then use random.
Here is solution
let nameArray = ["Jacob", "Lenny", "George", "Linda", "Arthur"]
let lastNameArray = ["Shelby", "Knight", "Luiz", "Hamilton", "Dobson"]
let combine = Array(zip(nameArray, lastNameArray))
let randomName = combine.randomElement() ?? ("", "")
nameLabel.text = randomName.0 + " " + randomName.1
I recommend this way, randomPerson
even creates (5) unique full names and starts over when all names are expended.
let firstNames = ["Jacob", "Lenny", "George", "Linda", "Arthur"]
let lastNames = ["Shelby", "Knight", "Luiz", "Hamilton", "Dobson"]
var tempFirstNames = [String]()
var tempLastNames = [String]()
func randomPerson() -> String {
if tempLastNames.isEmpty {
tempLastNames = lastNames
tempFirstNames = firstNames
}
let firstName = tempFirstNames.remove(at: Int.random(in: 0..<tempFirstNames.count))
let lastName = tempLastNames.remove(at: Int.random(in: 0..<tempLastNames.count))
return "\(firstName) \(lastName)"
}
And use it
nameLabel.text = randomPerson()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.