관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] NSAttributedString와 NSMutableAttributedString개념 (애플이 굳이 두가지로 나눈 이유, #불변성) 본문

iOS 응용 (swift)

[iOS - swift] NSAttributedString와 NSMutableAttributedString개념 (애플이 굳이 두가지로 나눈 이유, #불변성)

jake-kim 2023. 8. 20. 01:49

NSAttributedString과 NSMutableAttriubtedString 차이점

  • AttributedString 이란?
    • AttributedString은 내부적으로 guts라는 인스턴스가 String 타입을 받아서 String에 속성을 부여하여 사용할 수 있도록 구현해 놓은 것
    • 즉, String을 wrapping하여 단순 text에 색깔, 폰트와 같은 속성을 입힐 수 있도록 한 것
    • (구체적인 구현부는 swift-foundation 코드 참고)

https://developer.apple.com/documentation/foundation/attributedstring

  • 초기화하고 값을 바꿀수 있다면 NSMutableAttributedString, 초기화 이후 값을 변경할 수 없다면 NSAttributedString 사용

NSAttributedString 예제)

let attributes: [NSAttributedString.Key: Any] = [
    .font: UIFont.boldSystemFont(ofSize: 16),
    .foregroundColor: UIColor.blue
]
let attributedText = NSAttributedString(string: "Hello, ", attributes: attributes)

NSMutableAttributedString 예제)

let mutableAttributedText = NSMutableAttributedString(attributedString: attributedText)
let appendString = NSAttributedString(string: "world!", attributes: [
    .font: UIFont.italicSystemFont(ofSize: 18),
    .foregroundColor: UIColor.red
])
mutableAttributedText.append(appendString)

NSAttributedString, NSMutableAttributedString 굳이 두 가지로 나눈 이유?

  • 생각해보면 NSMutableAttributedString 하나만 가지고도 모든 기능을 수행할 수 있는데 NSAttributedString을 굳이 만든 이유?
  • swift는 객체지향+함수형 프로그래밍
    • 함수형 프로그래밍의 핵심 요소는 불변성 (multi thread에 안전함, 예측 가능성)
    • 함수형 프로그래밍 관련 자세한 내용은 이전 포스팅 글 참고
  • 즉 Swift는 함수형 프로그래밍을 지향하기 위해서 불변성을 지키는데, 이 때 NSAttributedString은 한번 초기화하면 값을 바꿀 수 없으므로 불변성을 지향할 수 있기 때문에 NSAttributedString을 둔 것

cf) swift의 collection type도 value type으로 둔 이유는 불변성을 위함

  • 함수형 프로그래밍의 불변성 - 데이터를 변경하려면 반드시 원래 데이터는 그대로 둔 채 변경하려는 값에 해당 복사본을 만들어서 반환한다는 개념을 사용

 

* 참고

https://github.com/apple/swift-foundation/blob/9649a9817125730b567e2357f5bed38f5cdc7622/Sources/FoundationEssentials/AttributedString/AttributedString.swift

https://developer.apple.com/documentation/foundation/attributedstring

 

Comments