2017-09-19 7 views
0

Swift enumの1つのケースと、プロトコルに基づいた関連する値を一致させたいと思います。具体的には、関連する値の実際の型に大文字小文字を限定したいのですが、それが可能なのかどうかは分かりません。Swiftの実際のタイプでスイッチケースを制限する方法

protocol MyProtocol {} 

extension Int:MyProtocol {} 
extension Double:MyProtocol {} 

enum MyEnum { 
    case something(MyProtocol) 
    case nothing 
} 

let somethingInt = .something(10) 
let somethingDouble = .something(10.0) 

switch somethingInt { 
    case .something(let aValueInt): 
    !!! I want to figure out how to limit this case to a double or an int 
    case .something(let aValueDouble): 
    !!! I want to figure out how to limit this case to a double or an int 
    case .nothing: 
    break 
} 

答えて

0

ここでコンパイルし、正常に動作する例を示します

protocol MyProtocol {} 

    extension Int:MyProtocol {} 
    extension Double:MyProtocol {} 

    enum MyEnum { 
     case something(MyProtocol) 
     case nothing 
    } 

    let somethingInt = MyEnum.something(10) 
    let somethingDouble = MyEnum.something(11.0) 

    switch somethingInt { // and try it with somethingDouble instead 
    case .something(let aValueInt as Int): print(aValueInt) 
    case .something(let aValueDouble as Double): print(aValueDouble) 
    case .something(_): break 
    case .nothing: break 
    } 
関連する問題