LoginSignup
2
1

More than 5 years have passed since last update.

JKはSwiftで配列からランダムに要素を抽出したい

Posted at

今回作りたいもの

名前の入った配列からランダムに一つ要素を抽出して表示します。
元はといえば配列に友達の名前を入れて罰ゲームルーレットを作るつもりでちょっと不満があったので一応書いておく。

コード

ViewContoller.swift
nameLabel.text = nameArray[Int(arc4random()) % nameArray.count]

UILabelに名前の入った配列から一つランダムに代入するだけです。

補足

最初は
arc4random() % nameArray.count
だけで済むと思ったんですけど

Binary operator '%' cannot be applied to operands of type 'UInt32' and 'Int'

とかなんとか出てきた。

型が違うから%使えねえぞと

ということ。

なんで知らないけどこいつの戻り値はUint32で返ってくるらしい。
この別にただIntで囲めばいいんだけどなんとなーくめんどくさい。

GameplayKit内のnextInt()というものがあると聞いたけどちょっとよくわかんなかったので暫定的にこんな感じで。

いい感じに一発で出せるような方法あれば教えてください。

2
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1