Your alphabet is currently an [String]
(a.k.a. Array<String>
). You should probably change it to an [Character]
instead.
Even better, since randomElement
is defined on Collection
, and Collection
whose Element
is Character
would work. String
is a Collection
, and its Element
is Character
, so it fits the bill perfectly. The nicest way to do that is by breaking apart a string literal:
let alphabet = "abcdefghijklmnopqrstuvwxyz"
randomElement()
returns a T?
(in this case, String?
, a.k.a. Optional<String>
), not just a T
. Because if alphabet
were to be empty (it's not, but if it was), then there would be no elements to return. The only sane thing to do is return nil
instead.
Since in your case you can be certain that alphabet
is non-empty, and that randomElement()
will always return a valid non element, you're justified to force unwrap the result with the !
operator. Now don't make a bad habit of this. You have good reason to force unwrap here, but it's not to be used as a first-resort method of optional handling.
You're also repeating yourself a lot. You can improve this by using a loop of some kind or another.
In this case, you can use a neat little trick. Starting with a range like 0..<6
, which has 6 elements, you can call map
on it to transform its elements (which are 0
, 1
, ... 5
). In this case, you woudl transform each element by ignoring it, and just replacing it with a random element frmo the alphabet:
(0..<6).map { _ in alphabet.randomElement()! }
The result is an Array<Character>
. All you need is to turn it into a string. Final code:
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let password = String((0..<6).map { _ in alphabet.randomElement()! })