swift

swift - New String Interpolation System(swift 5+)

행복하게사는게꿈 2021. 1. 6. 18:49

New String Interpolation System(swift 5+) 

struct Size{
    var width = 0.0
    var height = 0.0
}

let s = Size(width: 1.2, height: 3.4)
print("\(s)")


// 이렇게하면 String interpolation에서 return의 문자열이 사용된다.
//extension Size: CustomStringConvertible {
//    var description: String {
//        return "\(width) x \(height)"
//    }
//}

// 동일한 코드를 새로 도입된 방법으로 구현
extension String.StringInterpolation {
    // mutating func으로 반드시 생성
    // value는 String interpoltion을 사용할 수 있는 형태여야ㅑ 함
    mutating func appendInterpolation(_ value: Size) {
        // 여기에는 두가지 메소드를 사용할 수 있는데
        // 1. appendLiteral(<#T##literal: String##String#>)
        // 문자열 리터럴 추가
        
        // 2.appendInterpolation
        // String interpolation 결과에 문자열을 추가할 수 있다.
        appendInterpolation("\(value.width) x \(value.height)")
    }
    
    
    mutating func appendInterpolation(_ value: Size, style: NumberFormatter.Style) {
        let formatter = NumberFormatter()
        formatter.numberStyle = style
        
        if let width = formatter.string(for: value.width), let height = formatter.string(for: value.height) {
            appendInterpolation("\(width) x \(height)")
        }else{
            appendInterpolation("\(value.width) x \(value.height)")
        }
    }
}

print("\(s)")
print("\(s, style: .spellOut)")