๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐ŸŽ iOS & Swift

first(where:)์™€ first

first(where:)

Array์˜ ์ธ์Šคํ„ด์Šค ๋ฉ”์„œ๋“œ์ด๋‹ค.
์ƒ๊ฐ๋ณด๋‹ค ์ •๋ง ๋งŽ์€ ๊ณณ์—์„œ ์ฝ”๋“œ๊ฐ€ ์‚ฌ์šฉ๋˜์–ด์„œ ์ด๋ฒˆ์— ์ •๋ฆฌํ•ด์•ผ๊ฒ ๋‹ค๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹ค.

์ •์˜

func first(where predicate: (Element) throws -> Bool rethrows -> Element?

Parameter

predicate

  • ์‹œํ€€์Šค์˜ ์š”์†Œ๋ฅผ ์ธ์ˆ˜๋กœ ์‚ฌ์šฉํ•˜๊ณ  ์š”์†Œ๊ฐ€ ์ผ์น˜ํ•˜๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋ถ€์šธ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ํด๋กœ์ €.

Return

  • Predicate๋ฅผ ๋งŒ์กฑํ•˜๋Š” ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ฑฐ๋‚˜, ์—†๋‹ค๋ฉด nil์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

Example 1 (Apple ๊ณต์‹ ๋ฌธ์„œ)

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
if let firstNegative = numbers.first(where: { $0 < 0 }) {
    print("The first negative number is \(firstNegative).")
}
// Prints "The first negative number is -2."

numbers๋ผ๋Š” ์‹œํ€€์Šค(<<๋ฐฐ์—ด)์—์„œ ์Œ์ˆ˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

 


 

first

๋‹ค์Œ์€ ์ธ์Šคํ„ด์Šค ํ”„๋กœํผํ‹ฐ์ด๋‹ค.
์ปฌ๋ ‰์…˜์˜ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค.

Discussion

  • ์ปฌ๋ ‰์…˜์— ์š”์†Œ๊ฐ€ ์žˆ๋‹ค๋ฉด ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋ฅผ ๊ฐ€์ง€๊ณ , ์ปฌ๋ ‰์…˜์ด ๋น„์–ด์žˆ๋‹ค๋ฉด nil์„ ๊ฐ€์ง„๋‹ค.
  • ๋ฐฐ์—ด์€ ํ•ญ์ƒ ๊ฐ’์ด ์žˆ์„ ์ˆ˜๋„ ์žˆ๊ณ , ์—†์„ ์ˆ˜๋„ ์žˆ๋Š” ๊ฐ€๋Šฅ์„ฑ์„ ๋‚ดํฌํ•œ๋‹ค. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— Subscript๋‚˜ ๋ฒ”์œ„(Range<>)๋กœ ์ ‘๊ทผํ•˜๋Š” ๊ฒƒ์€ ์œ„ํ—˜ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ฒซ ๋ฒˆ์งธ ์š”์†Œ์— ์ ‘๊ทผํ•˜๋Š” ๊ฒƒ์ด๋ผ๋ฉด first ํ”„๋กœํผํ‹ฐ๋ฅผ ์ด์šฉํ•˜๋Š” ๊ฒƒ์ด ๋” ์•ˆ์ „ํ•˜๋‹ค. (cf. ๋งˆ์ง€๋ง‰ ์š”์†Œ๋Š” last ํ”„๋กœํผํ‹ฐ ์‚ฌ์šฉ)

Example 1(Apple ๊ณต์‹ ๋ฌธ์„œ)

let numbers = [10, 20, 30, 40, 50]
if let firstNumber = numbers.first {
    print(firstNumber)
}

Example 2

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)
  
    if let touch = touches.first, // โœ…  touch ๊ฐ์ฒด ๊ฐ€์ ธ์˜ค๋Š” ์ƒํ™ฉ
       touch.view == self.view {
        dismiss(animated: true)
    }    
}