Swift

[ Swift ] zip(_:_:)

Forest Yun 2023. 10. 8. 14:20
728x90

 

 zip(_:_:)

func zip<Sequence1, Sequence2>(
    _ sequence1: Sequence1,
    _ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2> where Sequence1 : Sequence, Sequence2 : Sequence

๋‘ ๊ฐœ์˜ sequence๋กœ ๊ตฌ์„ฑํ•œ sequence ์Œ์„ ๋งŒ๋“œ๋Š” ํ•จ์ˆ˜์ด๋‹ค.

Array, String, Range์ฒ˜๋Ÿผ Sequence ํ”„๋กœํ† ์ฝœ์„ ์ฑ„ํƒํ•œ ํƒ€์ž…์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์˜จ๋‹ค. ์ฆ‰, ์ˆœ์„œ๊ฐ€ ์žˆ๋Š” ํƒ€์ž…์„ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ๊ฐ€์ง„๋‹ค

 

 

 

ํŠœํ”Œ sequence ๋ฐ˜ํ™˜

zip์„ ์‚ฌ์šฉํ•ด ๋‘ sequence๋ฅผ ํ•ฉ์น˜๋ฉด ๊ฐ ์›์†Œ๋“ค์ด ๋™์ผํ•œ ์ธ๋ฑ์Šค ์›์†Œ๋“ค๊ณผ ์ง์„ ์ง€์–ด ํŠœํ”Œ ํƒ€์ž…์˜ Zip2Sequence๊ฐ€ ๋ฐ˜ํ™˜๋œ๋‹ค.

let strArray = ["๊ฐ€", "๋‚˜"]
let intArray = [1, 2]

let zipped: Zip2Sequence<[String], [Int]> = zip(strArray, intArray)

 

 

for-in ๊ตฌ๋ฌธ์— zip ์‚ฌ์šฉํ•˜๊ธฐ

zip์€ ๋‘ ๊ฐœ์˜ sequence ์š”์†Œ๋ฅผ ๋™์‹œ์— ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์œ ์šฉํ•˜๋‹ค. zip์„ ํ†ตํ•ด ๊ฐ ์›์†Œ์˜ ์Œ sequence๋ฅผ ๋งŒ๋“ค๊ณ  ๋ฐ”๋กœ ๋ฐ˜๋ณต(iterate)ํ•˜๋ฉด ๋œ๋‹ค.

๋งŒ์•ฝ ๋‘ sequence์˜ ๊ธธ์ด๊ฐ€ ๋‹ค๋ฅด๋ฉด, ๊ธธ์ด๊ฐ€ ์งง์€ sequence์— ๋งž์ถฐ Zip2Sequnece๊ฐ€ ์ƒ์„ฑ๋œ๋‹ค.

let info = ["1๋ฐ˜", "2๋ฐ˜", "3๋ฐ˜"]
let name = ["๊น€์˜ํฌ", "์ด์ฒ ์ˆ˜"]

for (i, n) in zip(info, name) {
    print(i, n, separator: " ")
}
// Prints
// 1๋ฐ˜ ๊น€์˜ํฌ
// 2๋ฐ˜ ์ด์ฒ ์ˆ˜

 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ๊ธฐ์ดˆ ๋ฌธ์ œ๋ฅผ ํ’€๋‹ค๋ณด๋ฉด String์„ ์ž์ฃผ ๋งŒ๋‚˜๊ฒŒ ๋˜๋Š”๋ฐ, Int๋ฅผ ์‚ฌ์šฉํ•˜๋Š” Array์™€ ๋‹ค๋ฅด๊ฒŒ String์€ ๊ฐœ๋ณ„ ์š”์†Œ์— ์ ‘๊ทผํ•˜๋ ค๋ฉด String.Index๊ฐ€ ํ•„์š”ํ•˜๋‹ค.  ๊ทธ๋ž˜์„œ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋ฅผ ์–ป๊ธฐ ์œ„ํ•ด startIndex ํ”„๋กœํผํ‹ฐ๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ•œ๋‹ค. ๋˜ ํŠน์ • ์œ„์น˜์˜ ์š”์†Œ์— ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•ด์„œ index(_:offsetBy:)์„ ํ†ตํ•ด String.index๋ฅผ ๊ตฌํ•ด์•ผํ•œ๋‹ค. ์ด์™ธ String.Index๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋‹ค์–‘ํ•œ ๋ฉ”์„œ๋“œ๋“ค์ด ์žˆ๋‹ค.

๋ชจ๋“  ์š”์†Œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ ์ ‘๊ทผํ•˜๋Š” ๊ฒฝ์šฐ, O(n) ์‹œ๊ฐ„์ด ์†Œ์š”๋˜๋Š” index(_:offsetBy:)๋ฅผ ๋งค๋ฒˆ ์‚ฌ์šฉํ•˜๋Š” ๊ฑด ๋น„ํšจ์œจ์ ์ด๋‹ค. ์ด๋Ÿด ๋•Œ๋Š” for-in ๊ตฌ๋ฌธ์ด๋‚˜ forEach ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค. 

๋งŒ์•ฝ ๋™์‹œ์— ๋‘ String์˜ ์š”์†Œ๋ฅผ ํ•„์š”๋กœ ํ•œ๋‹ค๋ฉด ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ• ๊นŒ? ์ด๋Ÿด ๋•Œ ๋ฐ”๋กœ zip ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

let str1 = "๊ฐ€๋‚˜๋‹ค๋ผ"
let str2 = "1234"

var result = ""
let zipped = zip(str1, str2)
    
for (fir, sec) in zipped {
    result.append(fir)
    result.append(sec)
}
    
print(result)
// Prints ๊ฐ€1๋‚˜2๋‹ค3๋ผ4

 

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 

 

 

zip(_:_:)
728x90

'Swift' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[ Swift ] Swift๋ž€?  (0) 2023.10.08
[ Swift ] isCase | isLowercase | isUppercase  (0) 2023.10.04
[ Swift ] print(_:separator:terminator:)  (0) 2023.10.04
[ Swift ] ํ”„๋กœํ† ์ฝœ ์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ  (0) 2023.09.24
[ Swift ] Serialization์ด๋ž€?  (0) 2023.01.18