🐥 Swift 문법 익숙해지기

Burkey·2024년 1월 20일
0

차근차근 Swift

목록 보기
13/15

Swift 익숙해지기 🐥(삐약)

오늘은 아래의 문제를 풀면서 알게 된 것과 다른 사람의 풀이방법에서 알게 된 것들을 기록하려고 한다.

문자열 섞기

나의 풀이

import Foundation

func solution(_ str1:String, _ str2:String) -> String {
    var result : String = ""
    for i in 0..<str1.count { //str1과 str2의 길이가 같다고 문제에 나옴
        let index : String.Index = str1.index(str1.startIndex, offsetBy: i)
        //시작 인덱스를 기준으로 offsetBy만큼 떨어진 인덱스를 가져옴
        result += (String(str1[index]) + String(str2[index]))
        //str1[index]의 타입은 Character 이기에 String타입으로 변경
    }
    return result
}

다른 풀이를 보고 다시 해결한 코드

import Foundation

func solution(_ str1:String, _ str2:String) -> String {
    var result : String = ""
    for (s1, s2) in zip(str1, str2) {
        result += String(s1) + String(s2)
    }
    return result
}

다른 사람의 풀이를 보고 .zip()이라는 함수를 알게되었습니다.

Apple 공식문서 .zip() 설명

.zip()
동일한 시퀀스를 인수로 받아 같은 인덱스를 가진것 끼리 시퀀스쌍으로 만들어 출력 합니다.

let test1 = ["a", "b", "c"]
let test2 = ["A", "B", "C"]

let test3 = zip(test1, test2)

for (s1, s2) in test3 {
	print(s1, s2) 
    /* 출력결과
    	a A
    	b B
    	c C
    */
}

만약 두 시퀀스의 크기가 다를 경우에는 작은 길이를 가진 값을 기준으로 반환합니다.

let test1 = ["a", "b", "c"]
let test2 = ["A"]

let test3 = zip(test1, test2)

for (s1, s2) in test3 {
	print(s1, s2) 
    /* 출력결과  
    	a A
    */
}
profile
스탯 올리는 중

0개의 댓글