mercredi 23 octobre 2019

Swift Array - Difference between "Int.random(in: 0...25)" and "randomElement()"

I recently started learning swift via an online course.

I was given the Task to generate a passwort out of a given Array containing characters. We learned mainly two code examples to randomly choose one.

  1. variable[Int.random(in: 0...25)]
  2. variable.randomElement()

Both work just fine when pulling out one single element out of an array but only "variable[Int.random(in: 0...25)" when combined multiple times with a plus (+).

Why is that?


I looked up the documentation but couldn't find an answer

https://developer.apple.com/documentation/swift/array/2994747-randomelement


Explanation:

This code works:

let alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

//The number of letters in alphabet equals 26
var password = alphabet[Int.random(in: 0...25)] + alphabet[Int.random(in: 0...25)] + alphabet[Int.random(in: 0...25)] + alphabet[Int.random(in: 0...25)] + alphabet[Int.random(in: 0...25)] + alphabet[Int.random(in: 0...25)]  

print(password)

This code does not work, because "randomElement()" gets grey after combining multiple with plus (why?)

let alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

//The number of letters in alphabet equals 26
var password = alphabet.randomElement() + alphabet.randomElement() + alphabet.randomElement() + alphabet.randomElement() + alphabet.randomElement() + alphabet.randomElement()  

print(password)



Aucun commentaire:

Enregistrer un commentaire