How does one generate a random number in Apple's Swift language?

后端 未结 25 1603
有刺的猬
有刺的猬 2020-11-22 09:51

I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation in one\'s own program? Or is t

25条回答
  •  -上瘾入骨i
    2020-11-22 10:30

    Swift 4.2

    Bye bye to import Foundation C lib arc4random_uniform()

    // 1  
    let digit = Int.random(in: 0..<10)
    
    // 2
    if let anotherDigit = (0..<10).randomElement() {
      print(anotherDigit)
    } else {
      print("Empty range.")
    }
    
    // 3
    let double = Double.random(in: 0..<1)
    let float = Float.random(in: 0..<1)
    let cgFloat = CGFloat.random(in: 0..<1)
    let bool = Bool.random()
    
    1. You use random(in:) to generate random digits from ranges.
    2. randomElement() returns nil if the range is empty, so you unwrap the returned Int? with if let.
    3. You use random(in:) to generate a random Double, Float or CGFloat and random() to return a random Bool.

    More @ Official

提交回复
热议问题