本文介绍了Swift3随机扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此扩展方法生成一个随机数:

I was using this extension method to generate a random number:

func Rand(_ range: Range<UInt32>) -> Int {
        return Int(range.lowerBound + arc4random_uniform(range.upperBound - range.lowerBound + 1))
    }

我喜欢它b / c这不是废话,你只是这样叫:

I liked it b/c it was no nonsense, you just called it like this:

 let test = Rand(1...5) //generates a random number between 1 and 5



I honestly don't know why things need to be so complicated in Swift but I digress..

所以我现在收到Swift3中的错误

So i'm receiving an error now in Swift3

No '...' candidates produce the expected contextual result type 'Range<UInt32>'

有谁知道这意味着什么,或者我怎么能让我真棒的兰德功能再次运作?我猜x ... y不再创建Ranges或x..y必须明确定义为UInt32?我有什么建议让事情变得更容易吗?

Would anyone know what this means or how I could get my awesome Rand function working again? I guess x...y no longer creates Ranges or x..y must be explicitly defined as UInt32? Any advice for me to make things a tad easier?

非常感谢,感谢你的时间!

Thanks so much, appreciate your time!

推荐答案

在Swift 3中有四种Range结构:

In Swift 3 there are four Range structures:


  • x。 < y范围< T>

  • x.. 。y ClosedRange< T>

  • 1 ..< ; 5 CountableRange< T>

  • 1 ... 5 CountableClosedRange< T>

  • "x" ..< "y"Range<T>
  • "x" ... "y"ClosedRange<T>
  • 1 ..< 5CountableRange<T>
  • 1 ... 5CountableClosedRange<T>

(运营商 ..< ... 重载,以便元素具有可争分性(随机访问迭代器,例如数字和指针),将返回一个可数范围。但是这些运算符仍然可以返回普通范围来满足类型检查器。)

(The operators ..< and ... are overloaded so that if the elements are stridable (random-access iterators e.g. numbers and pointers), a Countable Range will be returned. But these operators can still return plain Ranges to satisfy the type checker.)

由于Range和ClosedRange是不同的结构,你不能隐式地将它们相互转换,从而错误地转换它们。

Since Range and ClosedRange are different structures, you cannot implicitly convert a them with each other, and thus the error.

如果你想让Rand接受一个ClosedRange以及Range,你必须重载它:

If you want Rand to accept a ClosedRange as well as Range, you must overload it:

// accepts Rand(0 ..< 5)
func Rand(_ range: Range<UInt32>) -> Int {
    return Int(range.lowerBound + arc4random_uniform(range.upperBound - range.lowerBound))
}

// accepts Rand(1 ... 5)
func Rand(_ range: ClosedRange<UInt32>) -> Int {
    return Int(range.lowerBound + arc4random_uniform(range.upperBound + 1 - range.lowerBound))
}

这篇关于Swift3随机扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-15 09:59