본문 바로가기

IOS 개발

[iOS] ?? (_:_:) Generic Operator_nil-coalescing [일반 연산자 _ 무- 응집]

Generic Operator

?? (_:_:)

 

선택적 인스턴스의 랩핑 된 값 또는 기본 선택적 값을 리턴하여 nil-coalescing(무-응집) 조작을 수행합니다.

Performs a nil-coalescing operation, returning the wrapped value of an Optional instance or a default Optional value.

 

선언

Declaration

func ?? <T>(optional : T? , defaultValue: @autoclosure ( ) throws -> T ? ) rethrows -> T ?

 

 

 

매개변수

Parameters

 

  optional

     An optional value.

 

  기본값

  defaultValue

      기본값으로 사용할 값입니다. defaultValue와 옵션의 유형은 동일합니다.

      A value to use as a default. defaultValue and optional have the same type.

   

 

 

토론

Discussion


nil-coalescing (무-응집) 연산은 값이 있으면 왼쪽을 풀거나 오른쪽을 기본값으로 반환합니다. 이 연산의 결과는 인수와 동일한 유형입니다.

이 연산자는 단락 평가를 사용합니다. 선택 사항이 먼저 확인되고 선택 사항이 nil 인 경우에만 기본값으로 평가됩니다. 예를 들면 다음과 같습니다.

A nil-coalescing operation unwraps the left-hand side if it has a value, or returns the right-hand side as a default. The result of this operation will be the same type as its arguments.

This operator uses short-circuit evaluation: optional is checked first, and defaultValue is evaluated only if optional is nil. For example:

 

 

 

이 예에서, Int ( "100")가 0이 아닌 결과를 리턴하는 데 성공하므로 goodNumber에 값 100이 지정됩니다. notSoGoodNumber가 초기화되면 Int ( "invalid-input")가 실패하고 nil을 리턴하므로 Int ( "42")가 기본값을 제공하도록 호출됩니다.

이 무응답 연산의 결과 자체는 선택적인 값이므로 ?? 를 사용하여 기본값을 연결할 수 있습니다. 여러 번. 0이 아닌 첫 번째 선택적 값은 체인을 중지하고 전체 표현식의 결과가 됩니다. 다음 예제는 정적 기본값으로 돌아 가기 전에 두 개의 개별 사전에서 인사말에 대한 올바른 텍스트를 찾으려고 합니다.

In this example, goodNumber is assigned a value of 100 because Int("100") succeeds in returning a non-nil result. When notSoGoodNumber is initialized, Int("invalid-input") fails and returns nil, and so Int("42") is called to supply a default value.

Because the result of this nil-coalescing operation is itself an optional value, you can chain default values by using ?? multiple times. The first optional value that isn’t nil stops the chain and becomes the result of the whole expression. The next example tries to find the correct text for a greeting in two separate dictionaries before falling back to a static default.

 

userPrefs [greetingKey]에 값이 있으면 해당 값이 인사말에 할당됩니다. 그렇지 않은 경우 기본값 [greetingKey]의 값이 성공하고 그렇지 않은 경우 인사말은 선택 사항이 아닌 기본값 인 "Greetings!"로 설정됩니다.

If userPrefs[greetingKey] has a value, that value is assigned to greeting. If not, any value in defaults[greetingKey] will succeed, and if not that, greeting will be set to the non-optional default value, "Greetings!".

 

 

 

See Also

Coalescing Nil Values

func ?? <T> (T? , ( ) -> T) -> T

nil-coalescing (무-응집)작업을 수행하여 Optional 인스턴스의 래핑 된 값 또는 기본값을 반환합니다.

Performs a nil-coalescing operation, returning the wrapped value of an Optional instance or a default value.

 

 

토론

Discussion

nil-coalescing (무-응집)연산은 값이 있으면 왼쪽을 풀거나 오른쪽을 기본값으로 반환합니다. 이 작업의 결과는 비 선택적 유형의 왼쪽 포장 유형을 갖게됩니다.

이 연산자는 단락 평가를 사용합니다. 선택 사항이 먼저 확인되고 선택 사항이 nil 인 경우에만 기본값으로 평가됩니다. 예를 들면 다음과 같습니다.

A nil-coalescing operation unwraps the left-hand side if it has a value, or it returns the right-hand side as a default. The result of this operation will have the non-optional type of the left-hand side’s Wrapped type.

This operator uses short-circuit evaluation: optional is checked first, and defaultValue is evaluated only if optional is nil. For example:

 

이 예에서, Int ( "100")가 0이 아닌 결과를 리턴하는 데 성공했기 때문에 goodNumber에 값 100이 지정됩니다. notSoGoodNumber가 초기화되면 Int ( "invalid-input")가 실패하고 nil을 리턴하므로 getDefault () 메소드가 호출되어 기본값을 제공합니다.

In this example, goodNumber is assigned a value of 100 because Int("100") succeeded in returning a non-nil result. When notSoGoodNumber is initialized, Int("invalid-input") fails and returns nil, and so the getDefault() method is called to supply a default value.

 

 

 

 

 

 출처 : 애플공식문서 Swift Standard Library

'IOS 개발' 카테고리의 다른 글

[iOS] Predicate Programming Guide  (0) 2020.01.30
[iOS] NSPredicate  (0) 2020.01.30
[iOS] Self Expression  (0) 2020.01.21
[iOS] Keyword 간단 요약  (0) 2020.01.20
[iOS] Self  (0) 2020.01.20