본문 바로가기
iOS/애플 개발자 공식 문서

[Swift] stride()로 숫자를 단계적으로 다루기

by Dev.Andy 2023. 3. 18.

Swift로 팩토리얼 문제를 반복적으로(iteratively) 풀어 보면서 stride() 메서드를 알게 되었다. 이를 보다 더 자세히 알고 싶어서 포스팅을 했다.

 

[백준] (Swift) 10872번: 팩토리얼 (재귀 vs 반복)

📌 문제 10872번: 팩토리얼 📌 풀이 개요 N에서 1까지 차례로 곱하는 팩토리얼은 크게 2가지 경우로 풀어 볼 수 있다. 재귀적으로(recursively) 푸는 방식이거나, 반복적으로(iteratively) 푸는 방식이다.

andy-archive.tistory.com

 

📌 공식 문서 링크

 

계단을 올라가는 사람의 발 사진. stride는 성큼성큼 걷다, 걸음이라는 뜻의 영단어이다.

stride는 (1) 동사로는 '성큼성큼 걷다', (2) 명사로는 '(성큼성큼 걷는) 걸음[발(걸음)]' 라는 뜻의 영단어이다.

 

📌 개요

stride()는 크게 2가지로 나뉜다. stride(from:to:by:)stride(from:to:through:)이다.

 

둘의 차이점은 아래와 같다.

  1. to는 끝 값(end)을 포함하지 않는다.
  2. through는 끝 값을 포함한다.

 

(1) stride(from:to:by:)

stride(from:to:by:)
Returns a sequence from a starting value to, but not including, an end value, stepping by the specified amount.
시작 값에서부터 끝 값을 포함하지 않는 직전까지, 명시된 양만큼 단계를 밟는 시퀀스를 반환한다.

 

(2) stride(from:through:by:)

stride(from:through:by:)
Returns a sequence from a starting value toward, and possibly including, an end value, stepping by the specified amount.
시작 값에서부터 끝 값을 포함하여, 명시된 양만큼 단계를 밟는 시퀀스를 반환한다.

 

📌 선언

두 가지 메서드 모두 각각 3가지의 매개변수(parameter)를 받으며 매개변수의 이름에 맞게 적으면 된다.

(1) stride(from:to:by:)

func stride<T>(
    from start: T,
    to end: T,
    by stride: T.Stride
) -> StrideTo<T> where T : Strideable

 

(2) stride(from:to:through:)

func stride<T>(
    from start: T,
    through end: T,
    by stride: T.Stride
) -> StrideThrough<T> where T : Strideable

 

📌 매개변수

(1) stride(from:to:by:)

start
The starting value to use for the sequence. If the sequence contains any values, the first one is start.
(함수의) 순서에서 시작 값에 이용된다. 만약 과정이 어느 값을 갖고 있으면, 그중 첫 번째가 시작(start)이다.

end
An end value to limit the sequence. end is never an element of the resulting sequence.
과정을 제한하는 끝 값이다. 끝(end)은 절대로 과정의 요소가 될 수 없다.

stride
The amount to step by with each iteration. A positive stride iterates upward; a negative stride iterates downward.
각각의 반복에서 단계별로 수행할 양이다. 양의 걸음(stride)은 오름차순으로, 음의 걸음(stride)는 내림차순으로 반복한다.

여기서 주목할 부분은 끝 값은 절대로 포함하지 않는다는 점이다.

 

 

📌 반환값

A sequence from start toward, but not including, end. Each value in the sequence steps by stride.
시작(start)부터 끝(end)을 포함하지 않는 범위까지의 시퀀스다. 걸음(stride)에 의한 시퀀스 단계에서 각각의 값을 의미한다.

 

📌 실제 사용

stride()를 통해 내림차순을 손쉽게 이용할 수 있다. 시작을 큰 수로, 끝을 작은 수로 입력한 다음에 bythrough에서 $-1$을 넣어주면 된다.

 

 

📌 논의

(추후 업데이트 예정)

댓글