You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

Swift Implementation

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.

Objective-C Implementation

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:19:40