[英]What is the Objective-C equivalent of 'weak self' in a Swift closure?
[英]What is the equivalent of this objective-c code in swift?
这段代码中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)"
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;
}
这应该做的工作
func randomInRangeScale(scale : CGFloat) -> CGFloat {
let random = arc4random_uniform(UInt32(UInt16.max))
let randomCGFloat = CGFloat(random)
return randomCGFloat * 0.000015 + 0.8
}
尝试将它作为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秒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.