最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]swift获取随机数值

Swift crifan 2558浏览 0评论

已有代码:

    func getRandomHeaderColor(){
let headerColorHexStrArr = [
“#55c1d8”,
“#89c997”,
“#f6b37f”,
“f19ec2”,
“#84ccc9”,
“#f29c9f”,
“#c490bf”,
“#32b16c”,
“#ea68a2”,
]letrandomColorHexStr = headerColorHexStrArr[]
    }
希望获得随机数,以便于取得对应的hex值
此处是:
希望传递进入随机数范围,然后获得一个随机的整形数值,即可。
[解决过程]
1.搜:
swift random int number
参考:
    func getRandomInRange(lower:Int, upper:Int) -> Int {
        return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
    }

        let headerColorHexStrArr:[String] = [
            "#55c1d8",
            "#89c997",
            "#f6b37f",
            "f19ec2",
            "#84ccc9",
            "#f29c9f",
            "#c490bf",
            "#32b16c",
            "#ea68a2",
            ]

        let lower = 0
        let upper = headerColorHexStrArr.count - 1 // 8
        var randomIndex:Int = getRandomInRange(lower, upper: upper)
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")
        randomIndex = getRandomInRange(lower, upper: upper)
        print("randomIndex=\(randomIndex)")

输入结果是:

randomIndex=5
randomIndex=4
randomIndex=1
randomIndex=8
randomIndex=3
randomIndex=7
randomIndex=0
randomIndex=0
randomIndex=4
randomIndex=7
randomIndex=7
randomIndex=2
randomIndex=6
randomIndex=0
 [总结]
swift生成随机数,可以用:
    func getRandomInRange(lower:Int, upper:Int) -> Int {
        return lower + Int(arc4random_uniform(UInt32(upper - lower + 1)))
    }

转载请注明:在路上 » [已解决]swift获取随机数值

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.206 seconds, using 22.09MB memory