在某些情况下,当作为数组传递时,Swift无法隐式推断Enum的协议一致性

时间:2016-08-08 12:51:21

标签: swift enums swift2 protocols swift-protocols

在Enum all中使用变量MotorVehicle以传递所有枚举案例时,代码无法编译。但是在使用所述变量的情况下做同样的事情。为什么是这样?我想让Enum"意识到"在所有情况下,不必在任何地方创建它的数组,或者必须使用" map"。使用变量allAsProtocol(由版本7使用)的解决方案只是简单丑陋的恕我直言。有什么想法吗?

Swift 2.2代码(只需将以下代码粘贴到Playground中)

    protocol Motorized {
        func startEngine()
    }

    enum MotorVehicle: String, Motorized {
        case Car
        case MotorCycle

        static var all: [MotorVehicle] {
            return [.Car, .MotorCycle]
        }

        static var allAsProtocol: [Motorized] {
            return [MotorVehicle.Car, MotorVehicle.MotorCycle]
        }

        func startEngine() {
            print("Starting \(self.rawValue)")
        }
    }

    func start(motorized motorized: [Motorized]) {
        for motor in motorized {
            start(motorized: motor)
        }
    }

    func start(motorized motorized: Motorized) {
        motorized.startEngine()
    }

    // VERSION 1
    start(motorized: MotorVehicle.Car) //works

    // VERSION 2
    start(motorized: [MotorVehicle.Car, MotorVehicle.MotorCycle]) //works

    // VERSION 3
    /* In my opinion, this is logically identical to the code at the previous line...  */
    start(motorized: MotorVehicle.all) //Compilation Error - Cannot convert value of type ‘[MotorVehicle]’ to expected argument type ‘[Motorized]'

    // VERSION 4
    start(motorized: (MotorVehicle.all as! [Motorized])) //Compilation Error - 'Motorized' is not a subtype of 'MotorVehicle'

    // VERSION 5
    start(motorized: (MotorVehicle.all as [Motorized])) //Compilation Error - cannot convert value of type [MotorVehicle] to type [Motorized] in coercion

    // VERSION 6
    start(motorized: (MotorVehicle.all.map { return $0 as Motorized } )) //works

    // VERSION 7
    start(motorized: MotorVehicle.allAsProtocol) //works

0 个答案:

没有答案