Bibi's DevLog ๐ค๐
[Swift / Array] enumerated() - ๋ฐฐ์ด์ ์ด๊ฑฐํ๋ ์ํ์ค ๋ง๋ค๊ธฐ ๋ณธ๋ฌธ
[Swift / Array] enumerated() - ๋ฐฐ์ด์ ์ด๊ฑฐํ๋ ์ํ์ค ๋ง๋ค๊ธฐ
๋น๋น bibi 2022. 9. 23. 21:44enumerate ์ด๊ฑฐํ๋ค
(n, x)์์ ์ํ์ค๋ฅผ ๋ฐํํฉ๋๋ค.
- n์ 0๋ถํฐ ์์ํ๋ ์ฐ์์ ์ธ integer๋ฅผ ์๋ฏธํ๋ฉฐ,
- x๋ ์ํ์ค์ ์์๋ฅผ ๋ํ๋ ๋๋ค.
์ ์ธ
func enumerated() -> EnumeratedSequence<Self>
๋ฆฌํด๊ฐ
์ํ์ค๋ฅผ ์ด๊ฑฐํ๋ ์์ ์ํ์ค๋ฅผ ๋ฐํํฉ๋๋ค.
์๊ฐ๋ณต์ก๋ : O(1)
์ค๋ช
์ด ์์๋ โSwiftโ ๋ผ๋ ๋ฌธ์์ด์ ๋ฌธ์๋ฅผ ์ด๊ฑฐํ๊ณ , ๋ฌธ์์ด ์์ ๊ฐ ๋ฌธ์๋ฅผ ๊ทธ ์๋ฆฌ์ ํจ๊ป ์ถ๋ ฅํฉ๋๋ค.
for (n, c) in "Swift".enumerated() {
print("\(n): '\(c)'")
}
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"
์ปฌ๋ ์
์ ์ด๊ฑฐํ ๋, ๊ฐ ์์ ์ ์๋ถ๋ ์ด๊ฑฐํ์ counter์ด์ง๋ง, ๋ฐ๋์ ์์ ์ด๋ฃจ๋ ๊ฐ์ ์ธ๋ฑ์ค์ธ ๊ฒ์ ์๋๋๋ค. ์ด๋ฌํ counter๋ 0๋ถํฐ ์์ํ๊ณ , ์ ์๋ก ์ธ๋ฑ์ฑ๋๋ ์ปฌ๋ ์
์ ์ธ์คํด์ค์ ๋ํด์๋ง ์ธ๋ฑ์ค๋ก ์ฌ์ฉ๋ ์ ์์ต๋๋ค(์๋ฅผ ๋ค์ด Array๋ ContiguousArray๊ฐ์). ๋ค๋ฅธ ์ปฌ๋ ์
์ ๋ํ counter๋ out of range๊ฐ ๋ฐ์ํ๊ฑฐ๋ ์ธ๋ฑ์ค๋ก ์ฐ๋ ค ํ ๋ ํ์
์ด ๋ถ์ ์ ํ ์ ์์ต๋๋ค. ์ปฌ๋ ์
์ ์ธ๋ฑ์ค๋ค๊ณผ ํจ๊ป ์์๋ค์ ์ํํ๊ณ ์ถ๋ค๋ฉด, zip(_:_:)
ํจ์๋ฅผ ์ฌ์ฉํ์ญ์์ค.
์๋ ์์๋ 5์ ์ดํ์ ์ด๋ฆ์ ์ธ๋ฑ์ค๋ฅผ ์ ์ฅํ๋ ๋ฆฌ์คํธ๋ฅผ ๊ตฌ์ฑํ๋ฉด์, Set์ ์์์ ์ธ๋ฑ์ค๋ค์ ์ํํ๊ณ ์์ต๋๋ค.
let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolรกs"]
var shorterIndices: [Set<String>.Index] = []
for (i, name) in zip(names.indices, names) {
if name.count <= 5 {
shorterIndices.append(i)
}
}
์ด์ shorterIndices
๋ฐฐ์ด์ด names
Set์ ์งง์ ์ด๋ฆ์ ์ธ๋ฑ์ค๋ค์ ๊ฐ์ง๊ณ ์๊ธฐ ๋๋ฌธ์, set์ ์์์ ์ ๊ทผํ๊ธฐ ์ํด ๊ทธ ์ธ๋ฑ์ค๋ค์ ํ์ฉํ ์ ์์ต๋๋ค.
for i in shorterIndices {
print(names[i])
}
// Prints "Sofia"
// Prints "Mateo"
'๐ฑ๐ iOS > ๐ Apple Developer Documentation' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] type(of:) (0) | 2022.09.28 |
---|---|
[Swift / Array] swapAt(_:_:) (0) | 2022.09.28 |
[๐ / UIKit] UINavigationController (1) | 2022.09.23 |
About the App Launch Sequence ์ฑ ์คํ ์ํ์ค์ ๋ํ์ฌ (0) | 2022.08.27 |
Dictionary - subscript(_: default:) (0) | 2022.08.25 |