-
[Swift] CustomStringConvertibleSwift 2022. 1. 10. 21:06
Protocol
CustomStringConvertible
์ฌ์ฉ์ ์ ์ํ๋ ํ ์คํธ ํํ์ด ์๋ ํ์ .
Declaration
protocol
CustomStringConvertibleOverview
CustomStringConvertibleํ๋กํ ์ฝ์ ์ฑ์ฉํ๋ ํ์ ์ ์ธ์คํด์ค๋ฅผ ๋ฌธ์์ด๋ก ๋ณํํ ๋ ์ฌ์ฉ๋๋ ๊ณ ์ ํ ํํ์ ์ ๊ณตํ ์ ์๋ค. String(describing:) ์ด๋์ ๋ผ์ด์ ๋ ๋ชจ๋ ํ์ ์ ์ธ์คํด์ค๋ฅผ ๋ฌธ์์ด๋ก ๋ณํํ๋ ๋ฐ ์ ํธ๋๋ ๋ฐฉ๋ฒ์ด๋ค. ์ ๋ฌ๋ ์ธ์คํด์ค๊ฐ CustomStringConvertible์ ์ค์ํ๋ ๊ฒฝ์ฐ,String(describing:)์ด๋์ ๋ผ์ด์ ๊ทธ๋ฆฌ๊ณprint(_:)ํจ์๊ฐ ์ธ์คํด์ค์ ์ฌ์ฉ์ ์ง์ ์์ฑ์ ์ฌ์ฉํ๋ค. ํ์ ์ description ์์ฑ์ ์ง์ ์ ์ผ๋ก ์ ๊ทผํ๊ฑฐ๋CustomStringConvertible์ ์ผ๋ฐ ์ ์ฝ ์กฐ๊ฑด์ผ๋ก ์ฌ์ฉํ๋ ๊ฒ์ ๊ถ์ฅํ์ง ์๋๋ค.Conforming to the CustomStringConvertible Protocol
description ์์ฑ์ ์ ์ํ์ฌ ์ฌ์ฉ์ ์ง์ ํ์ ์
CustomStringConvertible์ ์ถ๊ฐํ๋ค.์๋ฅผ ๋ค๋ฉด, ์ด Point ๊ตฌ์กฐ์ฒด๋ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ์์ ์ ๊ณตํ๋ ๊ธฐ๋ณธ ํํ์ ์ฌ์ฉํ๋ค.
struct Point { let x: Int, y: Int } let p = Point(x: 21, y: 30) print(p) // Prints "Point(x: 21, y: 30)"๋ง์ฝ Point ๊ตฌ์กฐ์ฒด์ description ์์ฑ์ ๊ตฌํํ๊ณ
CustomStringConvertible์ ์ฑ์ฉํ๋ค๋ฉด, Point ํ์ ์ ๊ณ ์ ํ ์ฌ์ฉ์ ์ง์ ํํ์ ์ ๊ณตํ๋ค.extension Point: CustomStringConvertible { var description: String { return "(\(x), \(y))" } } print(p) // Prints "(21, 30)"์์
enum Shape: Character { case spade = "♠" case diamond = "โ" case heart = "♥" case club = "♣" } let heart = Shape.heart print(heart) // heart์์ ์ฝ๋๋ Shape๋ ์ด๊ฑฐํ์ ์์ฑํ๊ณ , heart๋ฅผ ์ถ๋ ฅํ๋๋ก ํ ๊ฒ์ด๋ค.
enum Shape: Character, CustomStringConvertible { case spade = "♠" case diamond = "โ" case heart = "♥" case club = "♣" var description: String { return String(rawValue) } }์์ Shape ์ด๊ฑฐํ์ rawValue ํ์ ์ด Character์ด๊ณ , CustomStringConvertible ํ๋กํ ์ฝ์ ์ฑ์ฉํ๊ณ ์๋ค.
CustomStringConvertible์ ์ฑ์ฉํ๊ณ ์๊ธฐ ๋๋ฌธ์ description ์์ฑ์ ์ ์ํ ์ ์๊ณ , ์ด๋ฅผ ์ฌ์ฉํ๋ฉด ๋ค์๊ณผ ๊ฐ๋ค.
let heart = Shape.heart print(heart) // ♥https://developer.apple.com/documentation/swift/customstringconvertible
'Swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] Loop Statements (for-in, while) (๋ฐ๋ณต๋ฌธ) (0) 2022.01.11 [Swift] Conditional Statements (if, switch, guard) (์กฐ๊ฑด๋ฌธ) (0) 2022.01.10 [Swift] Range Operator (๋ฒ์ ์ฐ์ฐ์) (0) 2022.01.09 [Swift] ๋จ๋ฝ ํ๊ฐ (Short-circuit Evaluation) (0) 2022.01.07 [Swift] ์ฐ์ฐ์ (Operator) (0) 2022.01.06