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

已有代码:

    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)))
    }


发表评论

电子邮件地址不会被公开。 必填项已用*标注

无觅相关文章插件,快速提升流量