-1

我正在 swift 2.0 中初始化一组骰子。我已经声明了一个带有名称(:String),状态列表(:[String])和面(状态数组的索引)(:[Int])的类Die

根据GameplayKit Framework ReferenceErica Sadun 的这篇短文中的建议,我想删除 GKARC4RandomSource 的前 1024 个值以确保“真正的”随机性。

在我的 UIViewController 中,我设置了一个 init? 初始化我的骰子的函数

class IceDiceViewController: UIViewController {

    var Dice: [Die]
    var source : GKRandomSource

...

    required init?(coder aDecoder: NSCoder){
        Dice = [Die]()
        source = GKARC4RandomSource()

// call the init function to instantiate all variables
        super.init(coder: aDecoder)
//  now initialize two dice with states ["red","yellow","blue","black","green","multiple"]
        Dice.append(Die(name:"iceDie", states: ["red","yellow","blue","black","green","multiple"]))
        Dice.append(Die(name:"iceDie", states: ["big","med","small","bigmed","bigsmall","medsmall"]))
// and drop the first values of the ARC4 random source to ensure "true" randomness
        source.dropValuesWithCount(1024)

...

}

这甚至不会编译:最后一行返回错误:

Value of type GKRandomSource has no member dropValuesWithCount

我的代码在没有这一行的情况下工作,但我不确定我在这里做错了什么,除了上面引用的链接之外,我几乎找不到在网络上使用 Gameplay Kit 实现 Dice 的任何参考。

4

1 回答 1

0

这是声明类型的问题source

var source : GKRandomSource

由于您只告诉 Swift 它是 a GKRandomSource,因此它只会让您调用在该类上定义的方法(因此对所有子类都可用)。该dropValuesWithCount方法仅在其中一个子类上,因此您不能在静态类型不是该子类的变量上调用它。

即使当您调用该方法时变量实际上包含正确类型的对象,编译器也无法真正知道这一点——它只知道声明的(和推断的)类型。

因此,您可以简单地声明它source实际上是 a GKARC4RandomSource,而不仅仅是 a GKRandomSource

var source : GKARC4RandomSource

但是话又说回来,也许您希望代码的其他部分不知道它是哪个随机子类,以便您可以轻松切换随机数生成器而无需更改所有代码?好吧,有几种方法可以解决这个问题,但一种简单的方法可能是将它放在调用 ARC4 特定 API 的地方:

(source as! GKARC4RandomSource).dropValuesWithCount(1024)
于 2015-12-25T02:15:34.030 回答