【问题标题】:What is the equivalent of this objective-c code in swift?swift中这个objective-c代码的等价物是什么?
【发布时间】:2015-08-15 15:06:26
【问题描述】:

此代码的 swift 替代代码是什么?

static inline CGFloat randomInRangeScale(CGFloat scale)
{
    CGFloat value = arc4random_uniform(INT16_MAX);
    return value * 0.000015 + 0.8 ;
}

我试过了:

func randomInRangeScale(scale : CGFloat) -> CGFloat
{
    let value : CGFloat = arc4random_uniform(UInt16);
    return value * 0.000015 + 0.8 ;
}

但它给了我一个错误"Cannot invoke 'arc4random_uniform' with an argument list of type '((UInt16).Type)"

【问题讨论】:

  • 你应该发布你尝试过的东西。
  • inline in swift 可以像@inline 一样使用 UInt16.max
  • 如果你想要 INT16_MAX 的等价物,显然是 Int16.max。

标签: ios objective-c swift


【解决方案1】:

这应该可以完成工作

func randomInRangeScale(scale : CGFloat) -> CGFloat {
    let random = arc4random_uniform(UInt32(UInt16.max))
    let randomCGFloat = CGFloat(random)
    return randomCGFloat * 0.000015 + 0.8
}

【讨论】:

  • @Avt 此答案修复了您的答案存在的编译错误。 arc4random_uniform 的返回值是UInt32,而不是CGFloat
  • @Avt:您将UInt16 作为参数传递给arc4random_uniform。您的代码不起作用。然后你编辑了你的问题。
【解决方案2】:

arc4random_uniform的参数类型为UInt32,所以你必须将UINT16_MAX转换为UInt32,并将值转换为CGFloat

试试这个:

func randomInRangeScale(scale : CGFloat) -> CGFloat {
    let value = arc4random_uniform(UInt32(UINT16_MAX));
    return CGFloat(value) * 0.000015 + 0.8;
}

【讨论】:

    【解决方案3】:

    尝试将其作为 CGFloat 的扩展,例如 -

    extension CGFloat {
    static func randomFloat() -> CGFloat {
        return CGFloat(arc4random_uniform(UInt32(UInt16.max))) * 0.000015 + 0.8
         }
    }
    

    并使用 -

    调用它
    CGFloat.randomFloat()
    

    在运行一些涉及在主线程上循环调用它 1 亿次的测试之后,它似乎比将相同的函数实现为方法更快。

    这是测试-

    let loopIterationCount = 100000000
        var timestamp = NSDate()
        for var k = 0 ; k < loopIterationCount ; k++ {
            let x = CGFloat.randomFloat()
        }
        var timeStampEnd = NSDate()
        println("CGFloat extension took \(self.timeDifference(timestamp, endTime: timeStampEnd)) seconds.")
    
        timestamp = NSDate()
        for var k = 0 ; k < loopIterationCount ; k++ {
            let x = self.randomFloat()
        }
        timeStampEnd = NSDate()
        println("function took \(self.timeDifference(timestamp, endTime: timeStampEnd)) seconds.")
    
    func randomFloat() -> CGFloat {
        return CGFloat(arc4random_uniform(UInt32(UInt16.max))) * 0.000015 + 0.8
    }
    
    func timeDifference(startTime: NSDate, endTime: NSDate) -> NSTimeInterval {
        return endTime.timeIntervalSinceDate(startTime)
    }
    

    结果

    CGFloat 扩展耗时 3.19389200210571 秒。

    函数耗时 5.25490999221802 秒。

    【讨论】:

      猜你喜欢
      • 2014-07-28
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      相关资源
      最近更新 更多