UFO ET IT

선택적 배열이 비어 있는지 확인

ufoet 2020. 11. 26. 20:25
반응형

선택적 배열이 비어 있는지 확인


Objective-C에서 배열이있을 때

NSArray *array;

비어 있지 않은지 확인하고 싶습니다. 항상 다음을 수행합니다.

if (array.count > 0) {
    NSLog(@"There are objects!");
} else {
    NSLog(@"There are no objects...");
}

array == nil이렇게 하면 이 상황이 코드가 else케이스 에 빠지게 할 뿐만 nil아니라 비어 있지 않지만 빈 배열이 수행 할 수 있는지 확인할 필요가 없습니다 .

그러나 Swift에서는 선택적 배열이있는 상황을 우연히 발견했습니다.

var array: [Int]?

어떤 조건을 사용해야할지 알 수 없습니다. 다음과 같은 몇 가지 옵션이 있습니다.

옵션 A :nil 동일한 조건에서 비어 있지 않은 케이스와 비어있는 케이스를 모두 선택 하십시오 .

if array != nil && array!.count > 0 {
    println("There are objects")
} else {
    println("No objects")
}

옵션 B : 다음을 사용하여 어레이 바인딩 해제 let:

if let unbindArray = array {
    if (unbindArray.count > 0) {
        println("There are objects!")
    } else {
        println("There are no objects...")
    }
} else {
    println("There are no objects...")
}

옵션 C : Swift가 제공하는 통합 연산자 사용 :

if (array?.count ?? 0) > 0 {
    println("There are objects")
} else {
    println("No objects")
}

나는 두 가지 조건에서 코드를 반복하고 있기 때문에 옵션 B를 별로 좋아하지 않습니다 . 그러나 옵션 AC 가 올바른지 또는 다른 방법을 사용 해야하는지 확실하지 않습니다 .

상황에 따라 선택적 배열의 사용을 피할 수 있다는 것을 알고 있지만 어떤 경우에는 비어 있는지 물어볼 필요가 있습니다. 그래서 가장 간단한 방법이 무엇인지 알고 싶습니다.


편집하다:

@vacawama가 지적했듯이 다음과 같은 간단한 확인 방법이 작동합니다.

if array?.count > 0 {
    println("There are objects")
} else {
    println("No objects")
}

그러나 나는 그것이 nil있거나 비어 있을 때만 특별한 것을 하고 배열에 요소가 있는지 여부에 관계없이 계속 하려는 경우를 시도했습니다 . 그래서 나는 시도했다.

if array?.count == 0 {
    println("There are no objects")
}

// Do something regardless whether the array has elements or not.

그리고 또한

if array?.isEmpty == true {
    println("There are no objects")
}

// Do something regardless whether the array has elements or not.

그러나 array가 nil이면 if몸에 떨어지지 않습니다 . 그리고 이것은이 경우 array?.count == nilarray?.isEmpty == nil이므로 표현식 array?.count == 0array?.isEmpty == true둘 다 false.

그래서 나는 단지 하나의 조건으로 이것을 달성하는 방법이 있는지 알아 내려고 노력하고 있습니다.


Swift 3 이상에 대한 답변 업데이트 :

스위프트 3와 선택적 항목을 비교할 수있는 기능 제거했습니다 ><이전 대답의 일부가 더 이상 유효 정도.

선택 사항을와 비교할 수 ==있으므로 선택 사항 배열에 값이 포함되어 있는지 확인하는 가장 간단한 방법은 다음과 같습니다.

if array?.isEmpty == false {
    print("There are objects!")
}

수행 할 수있는 다른 방법 :

if array?.count ?? 0 > 0 {
    print("There are objects!")
}

if !(array?.isEmpty ?? true) {
    print("There are objects!")
}

if array != nil && !array!.isEmpty {
    print("There are objects!")
}

if array != nil && array!.count > 0 {
    print("There are objects!")
}

if !(array ?? []).isEmpty {
    print("There are objects!")
}

if (array ?? []).count > 0 {
    print("There are objects!")
}

if let array = array, array.count > 0 {
    print("There are objects!")
}

if let array = array, !array.isEmpty {
    print("There are objects!")
}

배열이 nil있거나 비어 있을 때 무언가를하고 싶다면 적어도 6 가지 선택이 있습니다 :

옵션 A :

if !(array?.isEmpty == false) {
    print("There are no objects")
}

옵션 B :

if array == nil || array!.count == 0 {
    print("There are no objects")
}

옵션 C :

if array == nil || array!.isEmpty {
    print("There are no objects")
}

옵션 D :

if (array ?? []).isEmpty {
    print("There are no objects")
}

옵션 E :

if array?.isEmpty ?? true {
    print("There are no objects")
}

옵션 F :

if (array?.count ?? 0) == 0 {
    print("There are no objects")
}

옵션 C 는 사용자가 영어로 설명하는 방식을 정확하게 포착합니다. "특별한 작업은 0이거나 비어있을 때만하고 싶습니다." 이해하기 쉽기 때문에 이것을 사용하는 것이 좋습니다. 특히 "단락"되고 변수가 인 경우 비어 있는지 확인을 건너 뛰기 때문에이 문제는 없습니다 nil.



Swift 2.x에 대한 이전 답변 :

간단하게 할 수 있습니다.

if array?.count > 0 {
    print("There are objects")
} else {
    print("No objects")
}

@Martin이 주석에서 지적했듯이 func ><T : _Comparable>(lhs: T?, rhs: T?) -> Bool컴파일러가 0래핑됨을 의미 Int?하므로 Int?선택적 체인 호출로 인해 왼쪽과 비교할 수 있습니다 .

비슷한 방법으로 다음을 수행 할 수 있습니다.

if array?.isEmpty == false {
    print("There are objects")
} else {
    print("No objects")
}

참고 : false이 작업을 수행하려면 여기 와 명시 적으로 비교 해야합니다.


배열 nil이 비어 있거나 비어 있을 때 작업을 수행 하려면 최소한 7 가지 선택 사항이 있습니다.

옵션 A :

if !(array?.count > 0) {
    print("There are no objects")
}

옵션 B :

if !(array?.isEmpty == false) {
    print("There are no objects")
}

옵션 C :

if array == nil || array!.count == 0 {
    print("There are no objects")
}

옵션 D :

if array == nil || array!.isEmpty {
    print("There are no objects")
}

옵션 E :

if (array ?? []).isEmpty {
    print("There are no objects")
}

옵션 F :

if array?.isEmpty ?? true {
    print("There are no objects")
}

옵션 G :

if (array?.count ?? 0) == 0 {
    print("There are no objects")
}

옵션 D 는 사용자가 영어로 설명하는 방식을 정확히 포착합니다. "특별한 작업은 0이거나 비어있을 때만하고 싶습니다." 이해하기 쉽기 때문에 이것을 사용하는 것이 좋습니다. 특히 "단락"되고 변수가 인 경우 비어 있는지 확인을 건너 뛰기 때문에이 문제는 없습니다 nil.


Collection프로토콜의 확장 속성

* Swift 3로 작성

extension Optional where Wrapped: Collection {
    var isNilOrEmpty: Bool {
        switch self {
            case .some(let collection):
                return collection.isEmpty
            case .none:
                return true
        }
    }
}

사용 예 :

if array.isNilOrEmpty {
    print("The array is nil or empty")
}

 

다른 옵션

Other than the extension above, I find the following option most clear without force unwrapping optionals. I read this as unwrapping the optional array and if nil, substituting an empty array of the same type. Then, taking the (non-optional) result of that and if it isEmpty execute the conditional code.

Recommended

if (array ?? []).isEmpty {
    print("The array is nil or empty")
}

Though the following reads clearly, I suggest a habit of avoiding force unwrapping optionals whenever possible. Though you are guaranteed that array will never be nil when array!.isEmpty is executed in this specific case, it would be easy to edit it later and inadvertently introduce a crash. When you become comfortable force unwrapping optionals, you increase the chance that someone will make a change in the future that compiles but crashes at runtime.

Not Recommended!

if array == nil || array!.isEmpty {
    print("The array is nil or empty")
}

I find options that include array? (optional chaining) confusing such as:

Confusing?

if !(array?.isEmpty == false) {
    print("The array is nil or empty")
}

if array?.isEmpty ?? true {
    print("There are no objects")
}

Option D: If the array doesn't need to be optional, because you only really care if it's empty or not, initialise it as an empty array instead of an optional:

var array = [Int]()

Now it will always exist, and you can simply check for isEmpty.


Swift 3-4 compatible:

extension Optional where Wrapped: Collection {
        var nilIfEmpty: Optional {
            switch self {
            case .some(let collection):
                return collection.isEmpty ? nil : collection
            default:
                return nil
            }
        }

        var isNilOrEmpty: Bool {
            switch self {
            case .some(let collection):
                return collection.isEmpty
            case .none:
                return true
        }
}

Usage:

guard let array = myObject?.array.nilIfEmpty else { return }

Or

if myObject.array.isNilOrEmpty {
    // Do stuff here
}

Conditional unwrapping:

if let anArray = array {
    if !anArray.isEmpty {
        //do something
    }
}

EDIT: Possible since Swift 1.2:

if let myArray = array where !myArray.isEmpty {
    // do something with non empty 'myArray'
}

EDIT: Possible since Swift 2.0:

guard let myArray = array where !myArray.isEmpty else {
    return
}
// do something with non empty 'myArray'

The elegant built-in solution is Optional's map method. This method is often forgotten, but it does exactly what you need here; it allows you to send a message to the thing wrapped inside an Optional, safely. We end up in this case with a kind of threeway switch: we can say isEmpty to the Optional array, and get true, false, or nil (in case the array is itself nil).

var array : [Int]?
array.map {$0.isEmpty} // nil (because `array` is nil)
array = []
array.map {$0.isEmpty} // true (wrapped in an Optional)
array?.append(1)
array.map {$0.isEmpty} // false (wrapped in an Optional)

Instead of using if and else it is better way just to use guard to check for empty array without creating new variables for the same array.

guard !array.isEmpty else {
    return
}
// do something with non empty ‘array’

참고URL : https://stackoverflow.com/questions/27588964/check-if-optional-array-is-empty

반응형