struct PickerRange<T: Comparable> {
    var start: T
    var end: T
    var step: T

    var length: T {
        // Binary operator '/' cannot be applied to two 'T' operands.
        return max(start, end) - min(start,end) / step
    }
}

创建计算属性时出错。如何修复?

最佳答案

只需指定一个Numeric协议。
对于浮点精度:

struct PickerRange<T:FloatingPoint> {
    var start: T
    var end: T
    var step: T

    var length: T {
        return max(start, end) -  (min(start,end) / step)
    }
}

SignedIntegerUnsignedInteger或其他Numeric协议也是一个选项。
//Comparable
这两者都不需要您另外指定Comparable,因此指定其中一个就足够了。
编辑:
如何使一个结构为int和double?
本质上,您可以通过指定signedNumeric:
struct PickerRange<T:SignedNumeric & Comparable> {
    var start: T
    var end: T
    var step: T
}

// Treated as PickerRange<Double>
let a = PickerRange(start: 1.0, end: 5.0, step: 1)

// Treated as PickerRange<Int>
let b = PickerRange(start: 1, end: 5, step: 1)

但是,您有专门的length属性,其中包括/不支持的SignedNumeric运算符。解决方法将包括类型检查/强制强制转换为已用以下方法初始化结构的类型:
struct PickerRange<T:SignedNumeric & Comparable> {
    var start: T
    var end: T
    var step: T

    var length: T {
        if T.self is Double.Type {
            return (max(start, end) as! Double) - ((min(start, end) as! Double) / (step as! Double)) as! T
        } else if T.self is Int.Type {
            return (max(start, end) as! Int) - ((min(start, end) as! Int) / (step as! Int)) as! T
        } else {
            return 0
        }
    }
}

let a = PickerRange(start: 1.0, end: 5.0, step: 1)
let b = PickerRange(start: 1, end: 10, step: 1)

print(a.length)
print(b.length)

10-08 17:02