我有一个 struct ,它可以接受值序列和标量值(数字/字符串/布尔值)作为其泛型类型.我希望它们由两个不同的函数来描述,而不必在运行时进行任何类型判断.我try 使用泛型,但效果不是很好:
import Foundation
struct Box<T>: CustomStringConvertible {
static func descriptor<T: Sequence>(box: Box<T>) -> String {
return "This is a vector Box"
}
static func descriptor<T>(box: Box<T>) -> String {
return "This is a scalar Box"
}
var description: String {
return Box<T>.descriptor(box: self)
}
}
let b = Box<Double>()
b.description // "This is a scalar Box"
let c = Box<[Double]>()
c.description // "This is a scalar Box"
预计第二次通话会得到"This is a vector Box"
分.
我还try 将第一个函数的泛型限制为Collection
类型,但得到了相同的结果.