无法使用类型为'(from:T,to:T,by:T)'的参数列表调用'stride'Swift

问题描述 投票:0回答:1

我正在尝试创建一个对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
    }
ios swift iphone xcode swift3
1个回答
1
投票

步骤类型必须为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
}
© www.soinside.com 2019 - 2024. All rights reserved.