![](/img/trans.png)
[英]Can't create protocol that is restricted to Classes in Xcode 9.3 / Swift 4.1
[英]Swift Syntax Update? Classes not allowed in protocol. Can't fill SKTexture
我目前正在编写有关创建iOS等距游戏的教程。 你可以在这里找到这个 。
我刚刚开始对Swift进行编码,因为使用3个月以上的教程时会出现很多语法错误,所以我问自己最近Swift中是否有一些主要更新。
到目前为止,我自己或XCode本身都已设法解决了这些小问题,但是我对此无能为力:
protocol TextureObject {
class var sharedInstance: TextureDroid {get}
var texturesIso:[[SKTexture]?] {get}
var textures2D:[[SKTexture]?] {get}
}
这是我要设置的协议(与本教程中的完全一样),但是XCode不允许我定义类变量。 错误代码如下:
"Class properties are only allowed within classes:
use static to declare a static property"
将“类”替换为“静态”(这对我来说没有逻辑意义)并删除协议(并定义了不使用协议即可继承的类),这会导致此代码中的另一个错误:
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)),
]
该错误出现在我要填充纹理的所有行中
Immutable value 'self.texturesIso' may not be assigned to
这是我的问题:
如何解决第一个错误? 有没有一种在协议内定义类的新方法?
是因为我设法消除了第一个错误,所以连接了这两个错误,还是刚刚出现了第二个错误?
如何以正确的方式填充SKTexture? texturesIso.append也不起作用。
我对Swift Update正确吗? 如果是的话,是否有Swift突然变化的概述,因为我找不到。
非常感谢任何人的帮助,在此先感谢。
本教程似乎使用的是较早版本的swift。 您可以使用使用较早的swift编译器的旧版xcode,也可以更新代码。 我将尝试帮助您更新代码。
只需将var类更改为static。 这不会导致第二个错误,只是编译器在第一个错误之后停止,因此第二个错误不会显示出来。
不变值'self.texturesIso'可能未分配给
var texturesIso:[[SKTexture]?] {get}
定义了一个getter但没有setter,因此您无法设置self.texturesIso属性。 将其更改为{get set},并且也有必要对textures2d属性执行相同的操作,并将其更改为类中的vars。
除了回答这个特定问题外,当我下载教程代码以进行编译时,我还需要更改touchesEnded以使用Set而不是NSSet,它会破坏touches.anyObject,因此我改用touches.first。 另外,它试图更改gameScene中的不可变图块,因此我将其更改为var。
注意:我只是下载了代码,然后将其编译并运行,我不确定该如何运行,但是对我来说似乎还可以。 swift是否具有类级别的静态变量? 关于计算类变量和静态变量有一些很好的信息,尽管它没有讨论问题的协议部分
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.