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()
이라는 함수를 알게되었습니다.
.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
*/
}