👉🏻 아래는 변수와 상수를 사용해서 화면과 터미널에 값을 출력하는 앱입니다.
Below is an app that uses variables and constants to output values to the screen and terminal.
👉🏻 변수란 어떤 값을 담는 그릇과 같으며 최초에 값이 할당된 후(초기화라고 함) 값의 변경이 가능은 것을 의미합니다.
A variable is like a container that holds a value, and it means that the value can be changed after it is initially assigned a value (called initialization).
👉🏻상수란 어떤 값을 담는 그릇과 같으며 최초에 값이 할당된 후(초기화라고 함) 값을 변경 할 수 없는 것을 의미합니다.
A constant is like a container that holds a value, and after a value is initially assigned to it (called initialization), its value cannot be changed.
👉🏻 변수와 상수 선언
Declare variables and constants
✔️ Swift에서 상수는 다음과 같은 형식으로 선언합니다.
In Swift, constants are declared in the following format:
— 타입추론이 가능해서 타입을 생략해서 사용할 수 있습니다.
Because type inference is possible, you can omit the type and use it.
let 상수명[constant name] : 타입[Type] = 값[Value]
let 상수명[constant name] = 값[Value]
✔️ Swift에서 변수 선언은 다음과 같은 형식으로 선언합니다.
In Swift, variable declarations are declared in the following format:
— 타입추론이 가능해서 타입을 생략해서 사용 할 수 있습니다.
Because type inference is possible, you can use it by omitting the type.
var 변수명[variable name] : 타입[Type] = 값[Value]
var 변수명[variable name] = 값[Value]
👉🏻 변수와 상수의 사용방법 예
Examples of how to use variables and constants
// 변수 / Variable
var countVar2 = 10 // 초기화 / Initialization
countVar2 = 10 + 1 // 값의 변경 가능 / Values can be changed
// 상수 / Constant
let countLet2:Int
countLet2 = 20 // 초기화 / Initialization
countLet2 = 20 + 1 // 에러발생 / Error occurred
👉🏻 Swift에서 변수나 상수 사용시 주의 사항
Things to keep in mind when using variables and constants in Swift
✔️ Swift에서는 body안에 변수 선언 할 수 없습니다.
In Swift, you cannot declare variables inside the body.
✔️ 변수나 상수를 사용시 아래와 같은 코드 형식은 오류를 발생 시킵니다.
When using variables or constants, the following code format will cause an error.
var countVar = 10
var changeVarCount: Int = countVar + 1 --> error
let countLet = 10
let countLetCount: Int = countLet + 1 --> error
✔️ 위의 코드는 내부적으로 다음과 같은 방식으로 처리 됩니다.
The above code is internally processed in the following way:
✔️ self는 struct ContentView: View {} 를 의미합니다.
self refers to struct ContentView: View {}.
self.countLet = 10
self.countLetCount = self.countLet + 1
✔️ 그래서 changeVarCount나 countLetCount 초기화시 self가 아직 완전히 초기화 되었는지 확실 하지 않기 때문에 에러를 발생 시킵니다.
So when initializing changeVarCount or countLetCount, it raises an error because it is not sure if self is fully initialized yet.
✔️ 위의 문제를 해결하기 위해서는 init(){}안에 값의 변경과 출력을 수행하도록 합니다.
To solve the above problem, change the value and output it inside init(){}.
👉🏻 변수와 상수의 출력
Output of variables and constants
✔️터미널 출력 :
terminal output
— self 초기화 문제로 인해서 init(){}안에 값을 출력 할 수 있습니다.
Due to the self initialization issue, you can print the value inside init(){}.
init() {
countLet = countVar + 1
print("countLet: \(countLet)") // 출력 / print
countVar2 = 10
countVar2 = 10 + 1
countLet2 = 20
}
— 앱의 VStack{}의 속성인 onAppear(){}를 사용해서 출력 할 수 있습니다.
You can output it using onAppear(){}, which is a property of the app’s VStack{}.
struct ContentView: View {
var body: some View {
VStack {
..... code ....
}
.padding()
.onAppear{
print("countVar2:\(countVar2)")
}
}
}
✔️뷰에 출력 :
output to view
— 뷰에는 다음과 같은 방식으로 출력 할 수 있습니다.
The view can be output in the following ways:
// 변수나 상수 값만 출력 / Print only variable or constant values
Text(countVar)
// 변수나 상수가 문자열과 함께 출력 / Print variables or constants with strings
Text("Count Variable:\(countVar)")
👉🏻 코드 / Code
// 변수와 상수 / Variables and Constants
import SwiftUI
struct ContentView: View {
// let :
// 상수 / constant --> 초기화 후 값을 변경 할 수 없음.
// constant --> The value cannot be changed after initialization.
// var :
// 변수 / variable --> 초기화 후에도 값을 바꿀 수 있음.
// variable --> The value can be changed even after initialization.
// 모든 사항이 초기화 되었다고 컴파일러가 판단 할 수 없습니다.
// 그래서 Swift는 이런 형태의 초기화를 막고 있습니다.
// The compiler cannot determine that everything has been initialized.
// That's why Swift prevents this type of initialization.
// var countVar = 10
// var countVar2 = 20
// var changeVarCount: Int = count + 1 --> error
// let countLet = 10
// let countLet2 = 20
// let countLetCount: Int = countLet + 1 --> error
/*
let countLet = 10
let countLetCount = countLet + 1
바로 위의 형태는 내부적으로 다음과 같이 해석됩니다.
The form just above is internally interpreted as follows:
self.countLet = 10
self.countLetCount = self.countLet + 1
그래서 self(struct ContentView)가 아직 완전히 초기화 되었는지
보장 할 수 없기 때문에 오류가 발생합니다.
So, the error occurs because Swift can't guarantee that self(struct ContentView) is fully initialized.
*/
var countVar = 10
var countVar2: Int
let countLet: Int
let countLet2:Int
// init()을 사용하여 self가 생성된 이후 초기화 하기
// Initialize self after it is created using init()
init() {
countLet = countVar + 1
print("countLet: \(countLet)")
countVar2 = 10
countVar2 = 10 + 1
countLet2 = 20
// let은 상수이기 때문에 아래의 코드 실행시 다음과 오류가 발생합니다.
// Since let is a constant, the following error occurs when executing the code below.
// countLet2 = 20 + 1
// error: Immutable value 'self.countLet2' may only be initialized once
}
// ==== body안에 변수 선언 할 수 없음. ==== //
// ==== Cannot declare variables inside body ==== //
var body: some View {
VStack {
// ==== 뷰 안에서 변수 출력 방법 ==== //
// ==== How to output variables in a view ==== //
// Text(countVar) --> error
Text("\(countVar)")
Text("Count Variable:\(countVar)")
Text("Count:\(String(countVar))")
}
.padding()
.onAppear{
// countLet이 두번씩 출력되는 이유는
// 값 타입 구조체(View)라서 body가 재계산될 때마다 새로운 인스턴스가 만들어집니다.
// The reason countLet is printed twice is because it is a value type structure (View),
// so a new instance is created each time body is recalculated.
//onAppear는 화면에 나타날때 한번만 실행하는 코드부분입니다.
//onAppear is a code section that runs only once when it appears on the screen.
print("countVar2:\(countVar2)")
}
}
}
#Preview {
ContentView()
}