-
Swift - String Format SpecifierProgramming/Swift 2020. 10. 16. 23:25
안녕하세요 BeePeach입니다 :)
오늘은 지난 포스팅에서 말씀드렸던 Format Specifier에 대해서 공부하겠습니다.
기본적인 사용방법은 String에서 제공하는 생성자를 이용합니다.
이 부분은 구조체와 클래스, 그리고 생성자를 공부하시고 보시면 이해가 더 잘 될 거예요!
Format Specifier (포맷 지정자)
Format Specifier는 C언어를 공부하신 분들에게는 익숙한 문법입니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters%char Format Specifier는 % 와 Format Character로 구성된 문자입니다.
Format Specifier를 포함한 String을 Format String이라고 합니다.
예를 먼저 보고 설명을 이어나가도록 하겠습니다 :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersvar number = 30.0 var formatingStr = String(format: "%.0f", number) print(formatingStr) 여기서 주목해야 하는 부분은 format: "%.0f", number 입니다.
%.0f 가 Format Specifier이고 이를 포함한 "%.0f"가 Format String입니다.
%.0f를 자세히 살펴보겠습니다!
.0의 의미는 소수점 0번째 자리까지 출력하겠다는 의미입니다.
f는 실수를 의미하는 문자입니다.
그럼 %.0f는 실수를 소수점 0번째 자리까지 출력하겠다.라는 의미가 되겠죠?
그리고 뒤에 number는 f에 전달할 값입니다.
그럼 소수점 2번째까지 출력하겠다는 Format Specifier는 무엇일까요??
%.2f 입니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersnumber = 11.43566 formatingStr = String(format: "%.2f", number) print(formatingStr) 소수점을 자를 때는 반올림돼서 나타나게 됩니다.
11.435가 11.44로 반올림됐습니다.
그럼 다른 경우를 보겠습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersnumber = 11.43566 formatingStr = String(format: "%10.2f", number) print(formatingStr) formatingStr = String(format: "%010.2f", number) print(formatingStr) %10.2f와 같이 사용하면 .을 포함하여 총 10자리의 수를 소수점 두 번째 자리까지 출력한다는 의미입니다.
%010.2f는 위와 같지만 빈 부분은 0으로 채워서 출력한다는 의미입니다.
.을 포함한다는 것을 꼭 기억해주세요.
그런데 지금은 오른쪽 정렬로 되어있죠??
만약 왼쪽 정렬로 하고 싶다면
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersformatingStr = String(format: "%-10.2f", number) print(formatingStr) formatingStr = String(format: "[%-10.2f]", number) print(formatingStr) 이렇게 10 앞에 -를 붙여주면 됩니다!
Format Specifier에 실수를 제외한 나머지 형식을 보겠습니다.
- %@ (문자열, 참조 형식)
- %d (정수)
문자열이나 참조 형식을 전달할 때는 %@을 사용합니다.
정수는 %d를 사용하면 됩니다.
실수는 위에서 다뤘었죠? 이제 이 모든 것을 조합해서 예시를 보겠습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characterslet name = "Beepeach" let age = 1 let height = 130.6 let introduce = String(format: "안녕하세요? 제 이름은 %@입니다. 나이는 %d살이고 키는 %fcm입니다. ", name, age, height) print(introduce) 차례대로 %@, %d, %f에 name, age, height가 전달됐습니다.
지금까지는 %.2f와 같이 소수점을 제한했습니다. 만약 제한하지 않고 %f만 쓴다면 .을 포함하여 10글자까지 출력됩니다.
그렇다면 만약 형식에 맞지 않는 값을 전달하게 되면 어떻게 될까요??
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characterslet name = 2002 // Error!! let age = 1 let height = 130.6 let introduce = String(format: "안녕하세요? 제 이름은 %@입니다. 나이는 %d살이고 키는 %fcm입니다. ", name, age, height) print(introduce) %@에 문자열이 아닌 정수를 전달하면 에러가 발생합니다.
이번에는 %d에 실수를 전달하면 어떻게 될까요??
예상으로는 실수를 정수에 저장한다면 소수점을 저장한 부분은 삭제되고 정수 부분만 출력될 것 같습니다.
한번 확인해보도록 하겠습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characterslet name = "Beepeach" let age = 50.5 let height = 130.6 let introduce = String(format: "안녕하세요? 제 이름은 %@입니다. 나이는 %d살이고 키는 %fcm입니다. ", name, age, height) print(introduce) 나이를 주목해 주세요. 50.5에서 소수점이 잘린 50이 아니라 0이 출력됩니다.
소수점 부분을 제외한 정수 부분이 출력된게 아니죠??
그렇기 때문에 Format Specifier는 꼭 Type을 맞춰서 사용해야 합니다.
참고자료
여러분의 새로운 도전을 응원합니다 | KxCoding
Mastering SwiftUI 더 적은 코드로, 더 멋진 UI 만들기
kxcoding.com
https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html
Strings and Characters — The Swift Programming Language (Swift 5.6)
Strings and Characters A string is a series of characters, such as "hello, world" or "albatross". Swift strings are represented by the String type. The contents of a String can be accessed in various ways, including as a collection of Character values. Swi
docs.swift.org
728x90'Programming > Swift' 카테고리의 다른 글
Swift - String Index (0) 2020.10.21 Swift - Raw String (0) 2020.10.20 Swift - String - Escape sequence, String Interpolation (0) 2020.10.15 Swift - String - String의 종류, Multi-line String Literal (0) 2020.10.14 Swift - Tuple Decomposition, Matching (0) 2020.10.13