🍏

[Kotlin] Swiftのguard let, if letをしたい

2023/01/30に公開

guard let

Kotlin

val optionalId: Int? = null

optionalId?.let { id ->
// use id
} ?: return

Swift

let optionalId: Int? = nil

guard let id = optionalId else { return }
// use id

if let

Kotlin

val optionalId: Int? = null

optionalId?.also { id ->
    // use id
} ?: run { 
    // optionalId is null
}

Swift

let optionalId: Int? = nil

if let id = optionalId { 
    // use id
} else {
    // optionalId is nil
}

Discussion