Objective-C/Swift判断集合中是否存在指定子集合(非循环实现)
Hey there! Since you're new to programming and want to avoid writing explicit loops, both Swift and Objective-C have built-in methods that handle the checking for you under the hood—no need to write for/while loops yourself. Let's break down the solutions for each language:
In Swift, arrays of Equatable types (like Int, which your values are) automatically conform to Equatable themselves. This means you can use the built-in contains(_:) method directly to check if your input array exists in the source collection:
let source = [[8,6,7],[8,7,8],[7,6,5]] let input = [8,7,8] let exists = source.contains(input) print(exists) // Outputs: true
The contains(_:) method handles all the iteration logic for you behind the scenes—you don't have to write any loops manually. It compares each subarray in the source to your input array using value equality, which works perfectly here since all elements are integers.
In Objective-C, we'll use NSArray and its containsObject: method. Note that we need to wrap integer values in NSNumber (since Objective-C collections can't store primitive types directly):
NSArray *source = @[@[@8, @6, @7], @[@8, @7, @8], @[@7, @6, @5]]; NSArray *input = @[@8, @7, @8]; BOOL exists = [source containsObject:input]; NSLog(@"%d", exists); // Outputs: 1 (which represents true)
The containsObject: method uses isEqual: to compare elements. For NSArray, isEqual: checks if two arrays have the same elements in the same order—exactly what we need here. Just like the Swift solution, all the looping logic is handled by the framework, so you don't have to write it yourself.
内容的提问来源于stack exchange,提问作者Subha

