【问题标题】:Cannot invoke 'stride' with an argument list of type '(from: T, to: T, by: T)' Swift不能使用类型为“(从:T,到:T,by:T)”Swift 的参数列表调用“步幅”
【发布时间】:2020-08-23 14:16:55
【问题描述】:

我正在尝试创建一个适用于 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】:

    必须是 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-23
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      • 1970-01-01
      相关资源
      最近更新 更多