2015-10-22 102 views
3

假設我們有以下的協議和類:檢查是否泛型類型的具體類型的內部類

protocol Numeric { } 
extension Float: Numeric {} 
extension Double: Numeric {} 
extension Int: Numeric {} 

class NumericProcessor<T:Numeric> { 
    var test:T 
    func processString(stringValue: String?) 
     if T is Double { 
      test = Double(stringValue) 
     } 
    } 
} 

我要的是字符串到spesific牛逼轉換:數字。

test = T(stringValue) 

將不起作用,雖然Double(stringValue),Float(stringValue)將工作。

if T is Double { 
    test = Double(stringValue) 
} 

不能工作,因爲T is Double不會被問到。 我怎麼可能在通用的Numeric類中處理這個問題?

回答

2

編輯

我是個白癡。您可以將初始化劑添加到協議

protocol Numeric 
{ 
    init?(_ s: String) 
} 

extension Float: Numeric{} 

class NumericProcessor<T:Numeric> 
{ 
    var test:T? 

    func processString(stringValue: String?) 
    { 
     test = T(stringValue!) 
    } 
} 

let n = NumericProcessor<Float>() 

n.processString("1.5") 
print("\(n.test)") // prints "Optional(1.5)" 

原來不是那麼好回答

您可以添加靜態功能的協議來執行轉換。

protocol Numeric 
{ 
    static func fromString(s: String) -> Self? 
} 

extension Float: Numeric 
{ 
    static func fromString(s: String) -> Float? 
    { 
     return Float(s) 
    } 
} 

// Same pattern for Int and Double 

class NumericProcessor<T:Numeric> 
{ 
    var test:T? 

    func processString(stringValue: String?) 
    { 
     test = T.fromString(stringValue!) 
    } 

} 

let n = NumericProcessor<Float>() 

n.processString("1.5") 
print("\(n.test)") // prints "Optional(1.5)" 
0

這個怎麼樣:

protocol Numeric { } 
extension Float: Numeric {} 
extension Double: Numeric {} 
extension Int: Numeric {} 

class NumericProcessor<T:Numeric> { 
    var test:T? 
    func processString(stringValue: String?) 
     if T.self == Swift.Double { 
      test = Double(stringValue) as? T 
     } else if T.self == Swift.Float { 
      test = Float(stringValue) as? T 
     } 
    } 
}