如何使用var扩展委托实现的现有协议?

时间:2016-03-13 20:50:23

标签: swift

我尝试了很多组合,问题仍然存在。我无法弄清楚为什么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
    }

1 个答案:

答案 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