정의
vector는 정수, 실수 등의 숫자를 담을 수 있는 컨테이며, 'simd'라는 프레임워크에 의해 제공되는 데이터 구조체이다(data structure).
주로 컬러 값을 나타내거나(red, green, blue, alpha), 좌표값을 나타낼 때(x, y, ...) 사용된다.
최대로 담을 수 있는 양
- Double(=double-precision number) 8개
- 또는 Float(single-precision number) 16개
벡터 연산 - 요소에 개별적으로 적용 (Elementwise Operations)
아래 예시처럼 계산이 각 요소별로 수행된다.
let a = simd_float4(x: 2, y: 4, z: 5, w: 8)
let b = simd_float4(x: 5, y: 6, z: 7, w: 8)
let c = a + b // c = (7.0, 10.0, 12.0, 16.0)
활용 예시 [ 더보기 ] 클릭
Calculate Luminance
You can calculate the luminance of a color by multiplying each of its red, green, and blue color channels by a certain coefficient, and adding the three products together—creating a grayscale representation of the color. The following code uses the Rec. 709 luma coefficients for the color-to-grayscale conversion. Without the simd framework, you could implement this calculation using the following code:
func lumaForColor(red: Float, green: Float, blue: Float) -> Float {
let luma = (red * 0.2126) +
(green * 0.7152) +
(blue * 0.0722)
return luma
}
The simd framework simplifies this code by treating the color and the coefficients as vectors, and returning the dot product (the sum of the elementwise products) of the vectors:
let rec709Luma = simd_float3(0.2126, 0.7152, 0.0722)
func lumaForColor(red: Float, green: Float, blue: Float) -> Float {
let luma = simd_dot(rec709Luma,
simd_float3(red, green, blue))
return luma
}
Calculate Length and Distance
Calculating the distance between two points using the Pythagorean theorem is a common task in games and graphics programming. The simd framework provides functions for calculating length and distance in two, three, and four dimensions.
Calculate Length
The length functions, for example, simd_length(_:), return the length of a vector. The following illustration shows how the length of a vector, A, is calculated as the square root of the sum of the squares of its two values.

Calculate Distance
The distance functions, for example, simd_distance(_:_:), return the distance between two vectors:

The following code shows how the length function returns the same value as the distance function if one of the vectors contains all zeros:
let a = simd_float2(x: 3, y: 4)
let b = simd_float2(x: 0, y: 0)
// Both distance and length = 5
let dist = simd_distance(a, b)
let len = simd_length(a)
애플 공식 문서 (링크)에서 더 많은 예시를 확인할 수 있다.
'Swift > 문법' 카테고리의 다른 글
[Swift|문법] 클로저(Closure) (1) | 2024.02.19 |
---|---|
[Swift|문법] index 찾기 메소드 - enumerated(), firstIndex(of:), firstIndex(where:), lastIndex(of:), lastIndex(where) (0) | 2024.02.18 |
[Swift|문법] 조건문 - combining conditions(&&, ||), ternary operator(삼항 연산자), switch (0) | 2024.02.16 |
[Swift] 연산자 (operator) - arithmetic, overloading, compound, comparison (0) | 2024.02.16 |
[Swift] 옵셔널(Optional) 제거 방법 3가지 (0) | 2024.02.15 |