Swift 语法更新? 类 协议中不允许。无法填充 SKTexture

Swift Syntax Update? Classes not allowed in protocol. Can't fill SKTexture

我目前正在编写一个教程来创建 iOS 等距游戏。你可以找到 this one here.

我刚开始编码 Swift 因为有很多语法错误 在使用 3 个月前的教程时出现 我问自己最近 Swift 是否有一些主要更新。

直到现在,我自己或 XCode 自己设法解决了这些小问题,但是 我无法帮助自己:

protocol TextureObject {
    class var sharedInstance: TextureDroid {get}
    var texturesIso:[[SKTexture]?] {get}
    var textures2D:[[SKTexture]?] {get}
}

这是我要设置的协议(与教程中的完全一样),但 XCode 不允许我定义 class 变量。错误代码如下:

"Class properties are only allowed within classes: 
use static to declare a static property"

将 "class" 替换为 "static" (这对我来说没有逻辑意义)和 删除协议(并定义应在不使用协议的情况下继承的 class)导致此代码中的另一个错误:

class TextureDroid: TextureObject  {

class var sharedInstance: TextureDroid {
    return textureDroid
}

let texturesIso:[[SKTexture]?]
let textures2D:[[SKTexture]?]

init() {

    texturesIso = [[SKTexture]?](count: 2, repeatedValue: nil)
    textures2D = [[SKTexture]?](count: 2, repeatedValue: nil)

    //Idle
    texturesIso[Action.Idle.rawValue] = [
        SKTexture(imageNamed: "iso_3d_"+textureImage(Tile.Droid, Direction.N, Action.Idle)),
        SKTexture(imageNamed: "iso_3d_"+textureImage(Tile.Droid, Direction.NE, Action.Idle)),
        SKTexture(imageNamed: "iso_3d_"+textureImage(Tile.Droid, Direction.E, Action.Idle)),
        SKTexture(imageNamed: "iso_3d_"+textureImage(Tile.Droid, Direction.SE, Action.Idle)),
        SKTexture(imageNamed: "iso_3d_"+textureImage(Tile.Droid, Direction.S, Action.Idle)),
        SKTexture(imageNamed: "iso_3d_"+textureImage(Tile.Droid, Direction.SW, Action.Idle)),
        SKTexture(imageNamed: "iso_3d_"+textureImage(Tile.Droid, Direction.W, Action.Idle)),
        SKTexture(imageNamed: "iso_3d_"+textureImage(Tile.Droid, Direction.NW, Action.Idle)),
    ]

这个错误出现在我要填充texturesIso的所有行中

Immutable value 'self.texturesIso' may not be assigned to

这是我的问题:

  1. 如何修复第一个错误?有没有一种在协议中定义 classes 的新方法?

  2. 这两个错误是相互关联的,还是第二个刚刚出现,因为我设法消除了第一个?

  3. 如何正确填充SKTexture? texturesIso.append 也不行。

  4. 我对 Swift 更新是否正确?如果是,是否有对 Swift 所有突然更改的概述,因为我找不到。

非常感谢任何人的帮助,在此先感谢。

本教程似乎使用了 swift 的旧版本。您可以使用使用早期 swift 编译器的旧版本 xcode 或更新代码。我将尝试帮助您更新代码。

  1. "Protocol declarations can’t contain class, structure, enumeration, or other protocol declarations. The protocol member declarations are discussed in detail below." - 关于 swift 协议声明的 Apple 文档

只需将 class 变量更改为静态。这不会导致第二个错误,只是编译器在第一个错误之后停止,所以第二个错误没有显示。

  1. 不可变值 'self.texturesIso' 不能分配给

    var texturesIso:[[SKTexture]?] {get}

定义了getter但没有setter,所以你没办法设置self.texturesIso属性。将其更改为 {get set},并且对 textures2d 属性 执行相同的操作也可能是必要的,并将它们更改为 class 中的 vars。

  1. 有 swift 更新是的。新版本是 Swift 1.2

除了回答这个具体问题之外,当我下载教程代码时,为了编译它,我还需要更改 touchesEnded 以使用 Set 而不是 NSSet,这会破坏 touches.anyObject,所以我使用 touches.first 代替。此外,它试图更改 gameScene 中的不可变图块,所以我将其更改为 var.

注意:我刚刚下载了代码并对其进行了编译 运行,我不确定它应该如何 运行,但对我来说似乎没问题。 Does swift have class level static variables? 也有一些关于计算 class 变量与静态变量的有用信息,尽管它没有讨论问题的协议位