Programing

Kotlin의 Swift if let 문

lottogame 2020. 8. 24. 20:54
반응형

Kotlin의 Swift if let 문


Kotlin에는 아래 Swift 코드와 동일한 것이 있습니까?

if let a = b.val {

}
else {

}

다음 let과 같이 -function을 사용할 수 있습니다 .

val a = b?.let {
    // If b is not null.
} ?: run {
    // If b is null.
}

run코드 블록이 필요한 경우에만 함수 를 호출 해야합니다. runelvis-operator ( ?:) 뒤에 oneliner 만있는 경우 -block을 제거 할 수 있습니다 .

주의하십시오 run블록이 경우 중 평가됩니다 bnull의 경우, 또는 경우 let- 블록들을 평가에 null.

이 때문에 일반적으로 if표현 만 원합니다 .

val a = if (b == null) {
    // ...
} else {
    // ...
}

이 경우 else-block은가 bnull 인 경우에만 평가됩니다 .


먼저 제공된 Swift 관용구의 의미를 이해했는지 확인하겠습니다.

if let a = <expr> {
     // then-block
}
else {
     // else-block
}

이것은 의미합니다 : " <expr>결과가 nil이 아닌 선택 사항 인 경우 래핑되지 않은 값에 바인딩 된 then기호와 함께 -block을 a입력하고 그렇지 않으면 else블록을 입력합니다 .

특히 -block 내에서만a 바인딩 됩니다then . Kotlin에서는 다음을 호출하여 쉽게 얻을 수 있습니다.

<expr>?.also { a ->
    // then-block
}

다음과 else같이 -block을 추가 할 수 있습니다 .

<expr>?.also { a ->
    // then-block
} ?: run {
    // else-block
}

결과적으로 Swift 관용구와 동일한 의미가 생성됩니다.


내 대답은 완전히 다른 사람들의 모방 고양이입니다. 그러나 나는 그들의 표현을 쉽게 이해할 수 없다. 그래서 더 이해하기 쉬운 답변을 제공하는 것이 좋을 것 같습니다.

신속하게 :

if let a = b.val {
  //use "a" as unwrapped
}
else {

}

Kotlin에서 :

b.val?.let{a -> 
  //use "a" as unwrapped
} ?: run{
  //else case
}

namenull이 아닐 때만 코드를 실행하는 방법은 다음과 같습니다 .

var name: String? = null
name?.let { nameUnwrapp ->
    println(nameUnwrapp)  // not printed because name was null
}
name = "Alex"
name?.let { nameUnwrapp ->
    println(nameUnwrapp)  // printed "Alex"
}

if let 성명서.

Swift's Optional Binding (so called if-let statement) is used to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable. So, an Optional Binding for the if-let statement is as follows:

Swift's if-let statement:

let b: Int? = 50

if let a = b {
    print("Good news!")
} else {
    print("Equal to 'nil' or not set")
}

/*  RESULT: Good news!  */

In Kotlin, like in Swift, to avoid crashes caused by trying to access a null value when it’s not expected, a specific syntax (like b.let { } in second example) is provided for properly unwrapping nullable types:

Kotlin equivalent 1 of Swift's if-let statement:

val b: Int? = null
val a = b

if (a != null) { 
    println("Good news!")
} else { 
    println("Equal to 'null' or not set")
}

/*  RESULT: Equal to 'null' or not set  */

Kotlin’s let function, when used in combination with the safe-call operator ?:, provides a concise way to handle nullable expressions.

Kotlin equivalent 2 (Inline let function and Elvis Operator) of Swift's if-let statement:

val b: Int? = null

val a = b.let { nonNullable -> nonNullable } ?: "Equal to 'null' or not set"
println(a)

/*  RESULT: Equal to 'null' or not set  */

enter image description here

guard let statement.

guard-let statement in Swift is simple and powerful. It checks for some condition and if it evaluates to be false, then the else statement executes which normally will exit a method.

Let's explore a Swift's guard-let statement:

let b: Int? = nil

func testIt() {
    guard let a = b else {
        print("Equal to 'nil' or not set")
        return
    }
    print("Good news!")
}
testIt()

/*  RESULT: Equal to 'nil' or not set  */

Kotlin's similar effect of Swift's guard-let statement:

Unlike Swift, in Kotlin, there is no guard statement at all. However, you can use the Elvis Operator?: for getting a similar effect.

val b: Int? = 50

fun testIt() {
    val a = b ?: return println("Equal to 'null' or not set")
    return println("Good news!")
}
testIt()

/*  RESULT: Good news!  */

Hope this helps.


Unlike Swift, Its not necessary to unwrap the optional before using it in Kotlin. We could just check if the value is non null and the compiler tracks the information about the check you performed and allows to use it as unwrapped.

In Swift:

if let a = b.val {
  //use "a" as unwrapped
} else {

}

In Kotlin:

if b.val != null {
  //use "b.val" as unwrapped
} else {

}

Refer Documentation: (null-safety) for more such use cases


Here's my variant, limited to the very common "if not null" case.

First of all, define this somewhere:

inline fun <T> ifNotNull(obj: T?, block: (T) -> Unit) {
    if (obj != null) {
        block(obj)
    }
}

It should probably be internal, to avoid conflicts.

Now, convert this Swift code:

if let item = obj.item {
    doSomething(item)
}

To this Kotlin code:

ifNotNull(obj.item) { item -> 
    doSomething(item)
}

Note that as always with blocks in Kotlin, you can drop the argument and use it:

ifNotNull(obj.item) {
    doSomething(it)
}

But if the block is more than 1-2 lines, it's probably best to be explicit.

This is as similar to Swift as I could find.


There is a similar way in kotlin to achieve Swift's style if-let

if (val a = b) {
    a.doFirst()
    a.doSecond()
}

You can also assigned multiple nullable values

if (val name = nullableName, val age = nullableAge) {
    doSomething(name, age)
}

This kind of approach will be more suitable if the nullable values is used for more than 1 times. In my opinion, it helps from the performance aspect because the nullable value will be checked only once.

source: Kotlin Discussion

참고URL : https://stackoverflow.com/questions/46723729/swift-if-let-statement-in-kotlin

반응형