我正在尝试创建一个对Integer和Double都适用的通用函数。但是有些错误消息Cannot invoke 'stride' with an argument list of type '(from: T, to: T, by: T)'
。下面是我的代码:
func generateList<T: SignedNumeric>(from: T, to: T, step: T, addLastValue: Bool = true) -> [T] where T: Comparable & Strideable {
var items = [T]()
if step == 0 || from == to {
return [from]
}
for i in stride(from: from, to: to, by: step) {
items.append(i)
}
if addLastValue && to > items.last ?? to {
items.append(to)
}
return items
}
步骤类型必须为T.Stride
func generateList<T: SignedNumeric>(from: T, to: T, step: T.Stride, addLastValue: Bool = true) -> [T] where T: Comparable & Strideable {
var items = [T]()
if step == 0 || from == to {
return [from]
}
for i in stride(from: from, to: to, by: step) {
items.append(i)
}
if addLastValue && to > items.last ?? to {
items.append(to)
}
return items
}