nhg*_*rif 16 generics value-type reference-type swift
我知道我们可以通过使用AnyObject以下方式指定我们的泛型是任何引用类型:
class Foo<T: AnyObject> {
// ...
}
Run Code Online (Sandbox Code Playgroud)
但有没有办法指定我们的泛型应该只是值类型,而不允许引用类型?
// some code for testing
class C { } // just a simple class as an example for a reference type
var c = C()
var d: Double = 0.9 // a value type
Run Code Online (Sandbox Code Playgroud)
extensionprotocol ValueType { }
extension Double : ValueType { }
extension Int : ValueType { }
// ... all value types to be added
func printT1 <T: ValueType> (input: T) {
println("\(input) is value")
}
printT1(d) // Does work
//printT1(c) // Does not work
Run Code Online (Sandbox Code Playgroud)
但是正如评论中提到的,它是有效的但不可行,因为用户定义的值类型必须实现这个协议。
func printT <T: AnyObject> (input: T) {
println("\(input) is reference")
}
func printT <T: Any> (input: T) {
println("\(input) is value")
}
Run Code Online (Sandbox Code Playgroud)
assert另一种解决方案可能是通过 assert
func printT <T: Any> (input: T) {
print("\(input) is " + ((T.self is AnyObject) ? "reference" : "value"))
}
Run Code Online (Sandbox Code Playgroud)
where子句我认为这将是最好的解决方案。不幸的是,这是不可能的
func printT <T: Any where T: ~AnyObject > (input: T) {
println("\(input) is value")
}
Run Code Online (Sandbox Code Playgroud)
或类似。也许在 Swift 的未来版本中可以实现。
| 归档时间: |
|
| 查看次数: |
1170 次 |
| 最近记录: |