저는 Floft, Double 및 Int의 세 가지 유형으로 Swift에서 일반 벡터 클래스를 작성합니다. 지금까지 작동하지만 벡터의 길이를 계산하려고하면 문제가 발생합니다.Swift의 일반 제곱근
벡터 길이의 공식은 (x² + y²)의 제곱근입니다. 그러나 내 벡터에 제네릭 클래스를 사용하기 때문에 x와 y의 값을 T라고합니다.
Swift의 sqrt 함수는 Double을 인수로 받아 들일 수 있지만 일반 인수는 허용하지 않습니다.
제네릭 매개 변수와 함께 sqrt 함수를 사용할 수있는 방법이 있습니까?
protocol ArithmeticType {
func + (left: Self, right: Self) -> Self
func - (left: Self, right: Self) -> Self
func * (left: Self, right: Self) -> Self
func/(left: Self, right: Self) -> Self
prefix func - (left: Self) -> Self
func toDouble() -> Double
}
extension Double: ArithmeticType {
func toDouble() -> Double {
return Double(self)
}
}
extension Float: ArithmeticType {
func toDouble() -> Double {
return Double(self)
}
}
extension Int: ArithmeticType {
func toDouble() -> Double {
return Double(self)
}
}
class Vector<T where T: ArithmeticType, T: Comparable> {
var length: T { return sqrt((self ⋅ self).toDouble()) }
}
infix operator ⋅ { associativity left }
func ⋅<T: ArithmeticType> (left: Vector<T>, right: Vector<T>) -> T {
var result: T? = nil
for (index, value) in enumerate(left.values) {
let additive = value * right.values[index]
if result == nil {
result = additive
} else if let oldResult = result {
result = oldResult + additive
}
}
if let unwrappedResult = result {
return unwrappedResult
}
}
길이가 부동 소수점 수 (예 : length ([1, 1] = sqrt (2))이기 때문에 일반적으로 Double으로 변환 할 수 있습니다. - Btw, ArithmeticType'이 정의 되었습니까? –
당신은 sqrt 함수를 작성하지 않으시겠습니까? 이것은 c11 기능과 같은 것을 얻으려고 부풀어 오른 많은 코드처럼 보입니다. 그런 다음 정수를 사용자 정의하여 ceil, floor 등을 수행 할 수 있습니다. 또는 임의의 정밀도 라이브러리 사용 –