๐๐ป ์ค์ํํธ์ Guard์ ์ฝํ๋ฆฐ์ If๋ฅผ ๋น๊ตํ๊ธฐ ์ํ ์ค๋ช
์
๋๋ค.
Here’s a comparison between Swift’s Guard and Kotlin’s If.
๐๐ป ์ฝํ๋ฆฐ์๋ Guard๋ฌธ๋ฒ์ด ์์ต๋๋ค.
There is no guard syntax in Kotlin.
๐๐ป ์ค์ํํธ์ Guard๋ฌธ๋ฒ๊ณผ IF๊ฐ ์ด๋ป๊ฒ ๋ค๋ฅธ์ง ๋น๊ตํด ๋ณด์ธ์
Compare how Guard and IF statements differ in Swift.
๐๐ป ์ฝํ๋ฆฐ์์๋ ์ค์ํํธ์ Guard๋ฅผ ๋ค์๊ณผ ๊ฐ์ด If๋ฌธ์ผ๋ก ํํํ ์ ์์ต๋๋ค.
In Kotlin, Swift’s Guard can be expressed as an If statement as follows:
val v = value ?: return // guard let
if (v <= 0) return // guard value > 0
if (v == 999) return // guard value != 999
๐๐ป์ฝ๋ / Code
package com.freelifemakers.guardif
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Build
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.freelifemakers.guardif.ui.theme.GuardIfTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
GuardIfTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
ContentView(modifier = Modifier.padding(innerPadding))
}
}
}
}
}
@Composable
fun ContentView(modifier: Modifier = Modifier) {
// SwiftUI์ @State
var text by remember { mutableStateOf("") }
// Swift guard ํจํด โ Kotlin if + early return
fun process(value: Int?) {
val v = value ?: return // guard let
if (v <= 0) return // guard value > 0
if (v == 999) return // guard value != 999
println("Print Value: $v")
text = "$v"
}
// ์๋์ฒ๋ผ ์คํํด๋ ๋์ํฉ๋๋ค.
// It also works if you run it like below.
// process(1)
// SwiftUI onAppear โ Compose LaunchedEffect
LaunchedEffect(Unit) {
process(2)
}
// UI
Column(
modifier = modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center, // ์์ง ์ค์ ์ ๋ ฌ / vertical center alignment
horizontalAlignment = Alignment.CenterHorizontally // ์ํ ์ค์ ์ ๋ ฌ / horizontal center alignment
) {
Icon(
imageVector = Icons.Default.Build,
contentDescription = "Globe"
)
Spacer(modifier = Modifier.height(16.dp))
Text(text = "Text1: $text")
}
}
@Preview(showBackground = true)
@Composable
fun ContentViewPreview() {
GuardIfTheme {
ContentView()
}
}
๐๐ป ์คํฌ๋ฆฐ์ท/ScreenShot