본문 바로가기
App

Swift(iOS) Random 랜덤 숫자, 범위 설정, 배열 원소 랜덤 선택

by 푸드듥 2022. 6. 29.
반응형

 

자료형.random(in: lower ... upper)

1. 자료형 설정

임의의 정수: Int.random(in: lower ... upper)

- 예: Int.random(in: 1 ... 5)

임의의 실수: Float.random(in: lower ... upper)
임의의 불리언: Bool.random()

 

2. 랜덤 범위 설정

Int.random(in: 1 ... 5)

→ 1,2,3,4,5 중 하나
Int.random(in: 1 ..< 5)

→ 1,2,3,4 중 하나

 

3. 배열에서 임의의 원소 선택하기
array[Int.random(in: 1...5)]
array.randomElement()

*배열 원소를 섞는 방법

array.shuffle()

반응형

댓글