iOS When use the '@State'?

운영 체제: macOS Monterey 12.3.1
사용 버전: Xcode 13.3, SwiftUI

iOS When use the '@State'를 알아보겠습니다.


struct의 변수를 변경할 수 있게 만들 때 사용합니다.


Xcode에서 SwiftUI를 사용하다 보면 다음과 같은 황당한 경우를 맞이합니다.



오류를 조금 더 자세히 들여다봅시다.

Left side of mutating operator isn't mutable: 'self' is immutable.




변경할 수 있게 var로 선언을 했음에도 변경할 수 없다고 나옵니다.

신기하군요.


자세히 들여다보면 우리가 작업하는 ContentView는 struct입니다. struct는 기본적으로 immutable이라고 생각하시면 됩니다.


자, 그럼 이것을 변경 가능하게 만드는 방법을 알아봅시다.

바로 '@State'를 적어주면 됩니다.




오류가 없어졌습니다.

내부에서만 사용하려면 private를 붙여줍니다.






미리 보기를 보면 잘 작동합니다.





끝.

카테고리: iOS

댓글

이 블로그의 인기 게시물

Python urllib.parse.quote()

KiCad 시작하기 4 (기존 회로도 수정 및 추가)

Android Compose Coil library

KiCad 시작하기 1 (회로도 만들기)

Android Notification with Full Screen

iOS Swift callAsFunction

Android Custom IME(Input method editor) 만들기

iOS Error Undefined symbol Testing.Trait

Android Compose automation for getting localized images to use on Play Store app image

tensorflow tf.expand_dims()