【问题标题】:Is there a way to shorten if statements with arc4random_uniform( ) inside them?有没有办法缩短其中带有 arc4random_uniform( ) 的 if 语句?
【发布时间】:2015-03-10 00:05:57
【问题描述】:

我在处理一些 if 语句时遇到了一些问题。我试图弄清楚如何缩短带有arc4random_uniform 的if 语句。这是我的代码:

func firstCustomNumberRange(sender : AnyObject){

    if (firstCustomNumberRangeLabel == 1 )
    {
        var randomNumber = 1
    }


    if (firstCustomNumberRangeLabel == 2 )
    {
        var randomNumber = arc4random_uniform( 2) + 1
    }


    if (firstCustomNumberRangeLabel == 3 )
    {
        var randomNumber = arc4random_uniform( 3) + 1
    }


    if (firstCustomNumberRangeLabel == 4 )
    {
        var randomNumber = arc4random_uniform( 4) + 1
    }
     ...}

(我重复了最多 20 个模式)。这是一个非常耗时的过程,仅编写这些简单的 if 语句就花了我大约 30 分钟。

是否可以缩短带有自定义 arc4random_uniform( ) 的 if 语句。

提前致谢。

【问题讨论】:

    标签: swift if-statement ibaction arc4random


    【解决方案1】:

    只需将firstCustomNumberRangeLabel 的值直接传递给arc4random_uniform()

    func firstCustomNumberRange(sender : AnyObject){
        if let numberRange = NSNumberFormatter().numberFromString(firstCustomNumberRangeLabel.text!) {
            let randomNumber = arc4random_uniform(UInt32(numberRange.unsignedIntegerValue)) + 1
        }
    }
    

    【讨论】:

    • 你为什么说var randomNumber: Double。我只是想知道以供将来参考。
    • 哦,我不熟悉arc4random_uniform 函数,所以我只是猜测它的返回类型。它应该将randomNumber 的类型设置为arc4random_uniform 返回的任何类型-我想实际上可能是Int
    • 出现错误提示:'UILabel' not convertible to a 'UInt32' on the 6th line
    • 啊,好的。您需要使用NSNumberFormatter 将您的标签(我假设是文本?)转换为UInt32
    • 查看我的编辑。如果有其他问题,您可能需要重新提出问题或提出新问题。
    猜你喜欢
    • 1970-01-01
    • 2021-07-30
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    相关资源
    最近更新 更多