dev._.note

[Swift] prefix 와 suffix 본문

Dev/SWIFT

[Swift] prefix 와 suffix

Laena 2023. 10. 27. 16:19

📌 prefix

4가지 종류

  • prefix(_ maxLength: Int)
  • prefix(upTo end: Int)
  • prefix(through position: Int)
  • prefix(while predicate: (Element) -> Bool)

 


⭐️ prefix(_ maxLength: Int)

 

prefix(_:) | Apple Developer Documentation

Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.

developer.apple.com

Collection에서 지정한 maxLength까지 앞에서 부터 하위 시퀀스를 리턴. (maxLength는 0 이상이어야함)

let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(2))
// Prints "[1, 2]"
print(numbers.prefix(10))
// Prints "[1, 2, 3, 4, 5]"

 

prefix(10)을 한다고 해서 에러가 나지않고 존재하는 범위내에서 보여줌.

배열의 prefix를 가져오는 거의 모든 케이스는 prefix(_ maxLength: Int) 메소드 사용.

 


 

⭐️ prefix(upTo end: Int)

 

prefix(upTo:) | Apple Developer Documentation

Returns a subsequence from the start of the collection up to, but not including, the specified position.

developer.apple.com

prefix(upTo: Int)는 Collection의 시작부터 지정된 위치까지(포함하지 않음)의 하위 시퀀스를 반환.

prefix(upTo: Int)는 이 Argument가 Index를 의미.

let numbers = [1, 2, 3, 4, 5]

print(numbers.prefix(upTo: 4))
// [1, 2, 3, 4]

startIndex를 사용 한 예제

let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(upTo: numbers.startIndex))
// []

startIndex는 0부터 시작이기때문에 0부터 0까지의 결과 없음.

 

🙅‍♀️ Array index is out of range 에러가 나는 사유

let numbers = [1, 2, 3, 4, 5]

print(numbers.prefix(upTo: 10)) // error!
print(numbers.prefix(10))

 

위 코드는 prefix(upTo:) 메소드때문에 crash가 발생.

Array index is out of range

 

💡 subscript notation을 사용한 예제

prefix(upTo:)를 사용하는것은 subscript notation을 아래와 같이 사용하는 것과 동일.

let numbers = [1, 2, 3, 4, 5]
print(numbers[..<4])
// [1, 2, 3, 4]

prefix(upTo:)를 사용하는 것 보다 subscript notation이 더 선호되는 표기법.

(The subscript notation is preferred over prefix(upTo:))

 


 

⭐️ prefix(through position: Int)

 

prefix(through:) | Apple Developer Documentation

Returns a subsequence from the start of the collection through the specified position.

developer.apple.com

prefix(through position: Int)는 Collection의 시작부터 지정된 위치까지(포함됨)의 하위 시퀀스를 반환.

upTo는 Argument를 포함안했다면 through는 포함.

let numbers = [1, 2, 3, 4, 5]

print(numbers.prefix(through: 4))
// [1, 2, 3, 4, 5]

startIndex를 사용 한 예제

let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(through: numbers.startIndex))
// [1]

startIndex는 0부터 시작이기때문에 0부터 1까지의 결과 반환.

 


⭐️ prefix(while predicate: (Element) -> Bool)

 

prefix(while:) | Apple Developer Documentation

Returns a subsequence containing the initial elements until returns and skipping the remaining elements.

developer.apple.com

prefix(while predicate: (Element) -> Bool)는 Collection의 predicate가 false를 반환하면 다시 호출되지 않음. 

요소를 포함해야하는 경우는 true, 요소를 제외해야하는 경우 false를 반환함.

 

let numbers = [3, 1, 2, 5, 4]

print(numbers.prefix(while: { $0 >= 3 }))
// [3]

첫번째 element의 3은 3보다 같거나 크니 true

두번째 element의 1은 3보다 작으므로 false

predicate가 false를 리턴했으므로 종료.

 


📌 suffix

  • suffix(_ maxLength: Int)
  • suffix(from start: Int)

⭐️ suffix(_ maxLength: Int)

 

suffix(_:) | Apple Developer Documentation

Returns a subsequence, up to the given maximum length, containing the final elements of the collection.

developer.apple.com

Collection에서 지정한 maxLength까지 뒤에서 부터 하위 시퀀스를 리턴. (maxLength는 0 이상이어야함)

prefix(_ maxLength:)와 같음.

 

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"

⭐️ suffix(from start: Int)

 

suffix(from:) | Apple Developer Documentation

Returns a subsequence from the specified position to the end of the collection.

developer.apple.com

suffix(from start: Int)는 Collection의 시작부터 지정된 위치까지(포함)의 하위 시퀀스를 반환.

suffix(from start: Int)는 이 Argument가 Index를 의미.

start로 넘긴 지정된 위치에서 Collection 끝까지의 하위 시퀀스를 반환.

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(from: 3))
// [4, 5]

 

🙅‍♀️ Range requires lowerBound 에러가 나는 사유

Index기반이기 때문에 반드시 Valid한 Index를 사용해야함.

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(from: 6)) // Fatal error: Range requires lowerBound < upperBound

Index 6부터 Index 4을 리턴해야하는데

lowerBound가 upperBound보다 크게 되어 에러발생. [6...4]

 

💡 subscript notation을 사용한 예제

suffix(from start: Int)를 사용하는것은 subscript notation을 아래와 같이 사용하는 것과 동일.

let numbers = [1, 2, 3, 4, 5]
print(numbers[3...])
// [4, 5]

suffix(from: 3)를 사용하는 것 보다 subscript notation이 더 선호되는 표기법.

 


👏 prefix 와 suffix의 리턴타입

prefix과 suffix은 Array의 인스턴스 메소드이지만, return 타입은 ArraySlice<Element>.

func someMethod(_ arr: [Int]) {}
let arr = [1, 2, 3, 4].prefix(3)
someMethod(arr) // Error!

[Int]의 prefix를 가져왔지만, [Int]가 나오지 않고 ArraySlice<Int>가 나왔기 때문에 위 코드는 컴파일 에러

func someMethod(_ arr: [Int]) {}
let arr = [1, 2, 3, 4].prefix(3)
someMethod(Array(arr))

Array로 한번 더 감싸서 사용.

'Dev > SWIFT' 카테고리의 다른 글

[Swift] if문과 switch문 기초문법  (1) 2023.10.30
[Swift] Swift 란?  (1) 2023.10.28
[Swift] init(repeating:count:)  (0) 2023.10.27
[Swift] enumerated() 배열의 인덱스 가져오기  (0) 2023.10.26
[Swift] zip 함수  (0) 2023.10.26