Code Snippet: Random Strings
From Coder Merlin
Revision as of 00:17, 4 December 2018 by Chukwuemeka-tinashe (talk | contribs) (Created page with "== Select a Random String from an Array == <syntaxhighlight lang="swift"> // Select a random string from an array and print the result let verbs = ["walk", "jump", "run", "swi...")
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Select a Random String from an Array[edit]
// Select a random string from an array and print the result
let verbs = ["walk", "jump", "run", "swim", "dance"]
let verb = verbs[Int.random(in:0..<verbs.count)]
print(verb)
// Select a random string from an array and print the result (with syntactic sugar)
let verbs = ["walk", "jump", "run", "swim", "dance"]
if let verb = verbs.randomElement() {// Note: randomElement() returns an optional string
print(verb)
}
Shuffle an Array[edit]
let verbs = ["walk", "jump", "run", "swim", "dance"]
let shuffledVerbs = verbs.shuffled()
for verb in shuffledVerbs {
print(verb)
}