You are absolutely correct! My apologies for the confusion.
You've hit on a key design point of Apple's simd library. For performance and historical reasons (aligning with C-based APIs), many operations are global functions within the simd module, not properties or methods on the vector types themselves.
So, you don't call vector.length. Instead, you pass the vector to the simd.length() function.
The Correct Way with simd.length
This is how you would use the global function to simplify your original code:
import simd
private func normalize(_ vector: SIMD3<Float>) -> SIMD3<Float> {
// Correct: Call the global simd.length() function
let length = simd.length(vector)
// It's good practice to avoid division by zero,
// which would result in NaNs (Not a Number).
if length == 0 {
return .zero // Return a zero vector
}
return vector / length
}
This is a valid simplification and is much more readable than the manual sqrt(x*x + y*y + z*z).
The Best and Most Direct Simplification
However, the best practice is still to use the dedicated simd.normalize() function. It does the length calculation and the division in a single, highly optimized step.
import simd
// The most direct, readable, and performant version
private func normalize(_ vector: SIMD3<Float>) -> SIMD3<Float> {
// This single function handles everything, including the zero-length case.
return simd.normalize(vector)
}
Why is simd.normalize() still the best choice?
- Intent: The code
simd.normalize(vector) is perfectly clear. It says exactly what it does.
- Performance: This function can be mapped directly to a single, powerful CPU instruction. It can be significantly faster than performing a separate
simd.length() and then a vector division.
- Safety: It correctly handles edge cases, such as a zero-length vector (it will produce a vector of
NaNs, which is the mathematically correct, though often undesirable, result of 0/0).
Creating the .length Property Yourself (The "Swifty" Way)
If you prefer the vector.length syntax, you can easily add it yourself using an extension. This is a very common practice to make the simd library feel more integrated with Swift's property-based syntax.