난이도
Bronze
문제
분류
구현, 사칙연산, 수학
문제 설명
두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
입력
첫째 줄에 A와 B가 주어진다. (0 < A, B < 10)
출력
첫째 줄에 A+B를 출력한다.
제출 답안
import Foundation
let input = readLine()!
let nums = input.split(separator: " ")
let a = Int(nums[0])!
let b = Int(nums[1])!
let result = a + b
print(result)
다른 Solution 분석 및 학습
// 예제 소스
import Foundation
let line = readLine()!
let lineArr = line.components(separatedBy: " ")
let a = Int(lineArr[0])!
let b = Int(lineArr[1])!
print(a+b)
- 답안으로 제출한 코드에서는 입력값을 나누는 데
split
을 사용하였는데 예제 소스를 보니components
가 사용되었다.
두 메서드의 차이가 뭘까?
split
과 components
의 차이에 대해 알아보자!
split
String의 Instance Method
split(separator:maxSplits:omittingEmptySubsequences:) | Apple Developer Documentation
Returns the longest possible subsequences of the collection, in order, around elements equal to the given element.
developer.apple.com
제출 답안에 보이는 파라미터 외에도 maxSplits, omittingEmptySubsequences 라는 파라미터가 존재한다. (기본값이 존재하므로 생략 가능)
- Parameters
- separator
분할되어야 하는 요소, 즉 어떤 기준으로 분할할 것인가에 대한 파라미터이다.
제출 답안에서는 공백을 기준으로 제거해야 하므로 공백 문자열인 " "을 넣어주었다. - maxSplits
컬렉션을 분할할 최대 횟수
여러번 분할할 수 있는 경우 최대 몇 번까지 분할할 수 있는지를 설정할 수 있는 파라미터이다.
0보다 크거나 같아야 하며, 기본값은 Int.max 이다.
예를 들면, 1로 설정하는 경우 더 나눌 수 있음에도 불구하고 한 번만 나눈 상태로 배열을 반환한다. - omittingEmptySubsequences
구분할 기준이 되는 요소가 연속적으로 존재하는 경우, 빈 하위 시퀀스를 제거할지 여부를 선택할 수 있는 파라미터이다.
기본값은 true로 비어있는 하위 시퀀스를 배열에 추가하지 않고 제거 후 반환한다.
- separator
반환값은 [Self.SubSequence]이다.
SubSequence | Apple Developer Documentation
There's never been a better time to develop for Apple platforms.
developer.apple.com
Substring | Apple Developer Documentation
A slice of a string.
developer.apple.com
- 분할하려는 요소의 SubSequence들의 배열로 반환된다.
- String protocol의 SubSequence는 Substring의 연관 타입이다.
- Substring
문자열 조각, 원본 문자열과 저장소를 공유하기 때문에 하위 문자열에 대한 작업이 빠르고 효율적이라고 한다.
문자열을 전체 대문자로 만들거나 이와 반대인 경우를 만드는 경우에 유용한 것 같다.
substring은 string에 대한 다른 참조가 없을 때에도 전체 문자열에 대한 참조를 유지한다.
때문에, 더이상 접근할 수 없는 string 데이터의 수명이 길어질 수 있고 이는 메모리 누수로도 이어질 수 있기 때문에 주의해야 한다.
Swift는 Type-safe language로 한 변수에는 같은 타입만 저장할 수 있다.
따라서 split을 통해 반환된 배열에는 split한 요소의 SubSequence 타입이 아니면 추가할 수 없다.
let input = "1//2"
var nums = input.split(separator: "/")
// 타입을 지정하지 않는 경우, 타입 추론을 통해 추가 가능
nums.append("4")
print(nums) // [1, 2, 4]
print(type(of: nums)) // Array<Substring>
// 타입을 지정한 경우, 타입이 다른 경우 추가할 수 없음
let additionalString: String = "5"
let additionalChar: Character = "6"
// 오류 메세지: No exact matches in call to instance method 'append'
nums.append(additionalString)
nums.append(additionalChar)
분할하려는 요소가 Equatable을 준수할 때 사용할 수 있다고 한다.
Equatable | Apple Developer Documentation
A type that can be compared for value equality.
developer.apple.com
- Equatable
값이 같은지를 비교할 수 있는 형식이다. Swift 표준 라이브러리의 기본 유형 대부분은 해당 프로토콜을 준수한다고 한다.
사용자 정의 유형에 해당 프로토콜을 추가하는 경우 컬렉션에서 특정 인스턴스를 검색할 때 편리하다고 한다.
components
NSString의 Instance Method
components(separatedBy:) | Apple Developer Documentation
Returns an array containing substrings from the receiver that have been divided by a given separator.
developer.apple.com
components(separatedBy:) | Apple Developer Documentation
Returns an array containing substrings from the receiver that have been divided by characters in a given set.
developer.apple.com
separator 외에 다른 파라미터는 존재하지 않는다.
문자열 뿐만 아니라 문자 집합(CharacterSet)으로도 문자열을 분할할 수 있다.
split과 달리 반환값이 [String]이다.
결론적으로,
분할한 문자열을 가지고 다른 문자열과 조합을 하는 경우, 혹은 여러 문자를 기준으로 문자열을 나눠야 하는 경우에는 components를
분할한 문자열 내에서 조합, 연산하는 경우 split을 사용하는 것이 더 효율적이라고 생각했다.
'Swift > Algorithm' 카테고리의 다른 글
Swift 프로그래머스 [120808] 분수의 덧셈! 최대공약수 알고리즘, 유클리드 호제법 (부제: 네이밍에 신경쓰자^^) (1) | 2024.02.26 |
---|---|
Swift 프로그래머스 [120807] 숫자 비교하기 알고리즘 (0) | 2024.02.09 |
Swift 프로그래머스 [120806] 두 수의 나눗셈 알고리즘 (0) | 2024.02.08 |
Swift 프로그래머스 [120805] 몫 구하기 (0) | 2024.02.06 |
Swift 프로그래머스 [120802, 3, 4] 두 수의 합·차·곱 (0) | 2024.02.05 |