👉🏻 스위프트의 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