<ぴよぴよ辞書>超画期的日中フレーズ集共同編集(快速検索)

【SWIFT】ランダムパスワード生成の演習(#46)

Udemy SWIFT by Angela – Code Exercise 4

ここ数日間、Udemy Swiftコースのレッスン46を終えた後の演習4と格闘しています。とりあえず7割くらいは理解したので、次に進もうと思います。

演習4:アルファベット26文字を元にランダムに6文字のパスワードを生成する。

いろんな書き方があるので、まとめていきます。初級的な書き方(長いコード)から上級的な書き方(短いコード)の順番になっています。

方法1:直感的な書き方(10行)

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"]
    
let p1 = alphabet [Int.random(in: 0 ... 25)]
let p2 = alphabet [Int.random(in: 0 ... 25)]
let p3 = alphabet [Int.random(in: 0 ... 25)]
let p4 = alphabet [Int.random(in: 0 ... 25)]
let p5 = alphabet [Int.random(in: 0 ... 25)]
let p6 = alphabet [Int.random(in: 0 ... 25)]
    
var password = p1 + p2 + p3 + p4 + p5 + p6
print (password)

 

方法2:randomElementを使う(10行)

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"]
        
var p1 = alphabet.randomElement()!
var p2 = alphabet.randomElement()!
var p3 = alphabet.randomElement()!
var p4 = alphabet.randomElement()!
var p5 = alphabet.randomElement()!
var p6 = alphabet.randomElement()!

var password = p1 + p2 + p3 + p4 + p5 + p6
print(password)

 

メリット:配列の値の数量を気にしなくてよい

注意点:最後に「!」マークが必要。これがないと6つとも同じ文字になる。

方法3:randomElement + 複合演算子(7行)

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"]
    
var password = ""
while password.count < 6 {
password += alphabet.randomElement()!
}
print(password)

 

関連記事:+= の意味

複合演算子は数字に使いますが、Stringにも使えます。

ただし、1+2=3のにたいして、”a”+”b”=”ab”になります。

方法4:randomElement + for + terminator(5行)

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"]

for _ in 1...6 {
print(alphabet.randomElement()!, terminator: "");
}

 

これは46レッスンまでしか学んでない私にとっては難解ですが、ちゃんと作動しました。

説明できるようになったら、また戻ってきて解説を追記します。

Udemyオフィシャルの答えとみんなの討論はこちら

ではまた。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です