我尝试了很多组合,问题仍然存在。我无法弄清楚为什么Swift不会编译以下代码。我已经使用了多种变体(使用'where'来约束协议,在协议中移动setter和amp;等等......)仍然没有运气。你能看出问题出在哪里吗?
// GameScene.swift
import SpriteKit
extension SKSceneDelegate { // adding 'where Self: Game'
// causes err to moves somewhere else
var playerDirection: PlayerDirection { get set } // doesn't like this!
}
class GameScene: SKScene {
override func keyDown(theEvent: NSEvent) {
switch (theEvent.keyCode) {
case 123:
delegate!.playerDirection = .Left;
case 124:
delegate!.playerDirection = .Right;
default:
break
}
}
}
// SomeGame.swift
import Foundation
import SpriteKit
class Game: NSObject, SKSceneDelegate {
var _playerDirection: PlayerDirection = .None
// moving that code to the protocol, compiler can't find _playerDirection
var playerDirection: PlayerDirection {
set {
_playerDirection = newValue
}
get {
return _playerDirection
}
}
lazy var scene: GameScene = {
let scene = GameScene(size: CGSizeMake(CGFloat(100), CGFloat(100)))
scene.delegate = self
return scene
}()
func update(currentTime: NSTimeInterval, forScene scene: SKScene) {
}
}
// PlayerControlComponent.swift
import Foundation
enum PlayerDirection {
case None, Left, Right, Down, Up
}
答案 0 :(得分:1)
我认为你是从错误的角度接近你的问题。看起来您想要的是能够从playerDirection
中的keyDown()
功能访问GameScene
。您应该检查playerDirection
SKSceneDelegate
中的delegate
属性是否为GameScene
,而不是尝试将Game
作为delegate
协议的属性。 ,如果是,则将Game
投射到playerDirection
,以便if let
属性可供您使用。
您可以使用as?
和override func keyDown(theEvent: NSEvent) {
if let game = delegate as? Game {
switch (theEvent.keyCode) {
case 123:
game.playerDirection = .Left;
case 124:
game.playerDirection = .Right;
default:
break
}
}
}
运算符轻松完成此操作:
delegate
这是非常好的,因为现在您还在检查以确保delegate
在使用之前确实存在。像之前那样强行解包它可能会导致运行时异常,如果在调用该函数之前未设置profile
。