2017-09-14 240 views
0

是否有可能有專門的通用協議的協議?我想是這樣的:Swift協議專用通用協議

protocol Protocol: RawRepresentable { 
    typealias RawValue = Int 
    ... 
} 

這並不編譯,但是當我嘗試從一個協議實例訪問initrawValue,其型號爲RawValue,而不是Int

+0

你想創建一個協議,這是隻適用於枚舉與'詮釋'原始價值? –

+1

你不能爲你的協議找到一個更好的名字嗎? –

回答

2

在斯威夫特4,你可以添加約束到您的協議:

protocol MyProtocol: RawRepresentable where RawValue == Int { 
} 

而現在MyProtocol定義的所有方法都會有一個Int rawValue。例如:是採用RawRepresentable

extension MyProtocol { 
    var asInt: Int { 
     return rawValue 
    } 
} 

enum Number: Int, MyProtocol { 
    case zero 
    case one 
    case two 
} 

print(Number.one.asInt) 
// prints 1 

類型,但其RawValue不誠信不能採納你的約束協議:

enum Names: String { 
    case arthur 
    case barbara 
    case craig 
} 

// Compiler error 
extension Names : MyProtocol { }