요소가 배열에 있는지 확인하는 방법
Swift에서 배열에 요소가 있는지 확인하려면 어떻게 해야 합니까?Xcode에 대한 제안 사항이 없습니다.contain,include또는has책을 뒤졌지만 아무것도 발견되지 않았습니다.이것을 어떻게 확인해야 할지 아십니까?나는 방법이 있다는 것을 알고 있습니다.find번호를 의 인스번반환하루만과 ?#include??
필요한 것의 예:
var elements = [1,2,3,4,5]
if elements.contains(5) {
//do something
}
스위프트 2, 3, 4, 5:
let elements = [1, 2, 3, 4, 5]
if elements.contains(5) {
print("yes")
}
contains()의 프로토콜 확장 방법입니다(의 시퀀스에 대한).Equatable이전 릴리스와 같은 글로벌 메서드가 아닙니다.
비고:
- 것이.
contains()가 방은시퀀요다채요택구록도합다니하음을소가법스▁the▁adopt▁the▁method다를 채택하도록 합니다.Equatable프로토콜, 비교(예:앤드류스의 대답. - 가 시스요의인경인우의
NSObject하위 클래스를 무시해야 합니다.isEqual:자세한 내용은 Swift의 NSObject 하위 클래스인 hash vs hashValue, is Equal vs ==를 참조하십시오. - 더 일반적인 또 다른 것이 있습니다.
contains()요소들이 동등할 필요가 없고 술어를 인수로 사용하는 방법. 예:Swift의 배열에 개체가 존재하는지 테스트하기 위한 속기?
신속한 이전 버전:
let elements = [1,2,3,4,5]
if contains(elements, 5) {
println("yes")
}
배열에서 개체를 찾아서 제거하려는 사용자:
스위프트 1
if let index = find(itemList, item) {
itemList.removeAtIndex(index)
}
스위프트 2
if let index = itemList.indexOf(item) {
itemList.removeAtIndex(index)
}
스위프트 3, 4
if let index = itemList.index(of: item) {
itemList.remove(at: index)
}
스위프트 5.2
if let index = itemList.firstIndex(of: item) {
itemList.remove(at: index)
}
Swift 2+용으로 업데이트됨
3 ( 2)으로, 의 확장은 더 Swift 3 (는지심어또않다습니아확는더글의지필이하이요래장서후상로로이벌에)▁the▁note▁swift▁global▁is(▁below▁necessary)contains는 가수한쌍확방만법들다니습어졌로으장함의▁▁on에 한 의 확장 방법으로 .Array다음 중 하나를 수행할 수 있습니다.
let a = [ 1, 2, 3, 4 ]
a.contains(2) // => true, only usable if Element : Equatable
a.contains { $0 < 1 } // => false
Swift 1에 대한 역사적 답변:
다음 확장 사용: (Swift 5.2로 업데이트됨)
extension Array {
func contains<T>(obj: T) -> Bool where T: Equatable {
return !self.filter({$0 as? T == obj}).isEmpty
}
}
다음으로 사용:
array.contains(1)
사용자 지정 클래스 또는 구조체의 인스턴스가 배열에 포함되어 있는지 확인하는 경우 .contains(myObject)를 사용하려면 먼저 Equatable 프로토콜을 구현해야 합니다.
예:
struct Cup: Equatable {
let filled:Bool
}
static func ==(lhs:Cup, rhs:Cup) -> Bool { // Implement Equatable
return lhs.filled == rhs.filled
}
그러면 다음을 수행할 수 있습니다.
cupArray.contains(myCup)
팁: == 오버라이드는 클래스/컨트롤러 내가 아닌 글로벌 레벨이어야 합니다.
필터 했어요.
let results = elements.filter { el in el == 5 }
if results.count > 0 {
// any matching items are in results
} else {
// not found
}
당신이 원한다면, 당신은 그것을 압축할 수 있습니다.
if elements.filter({ el in el == 5 }).count > 0 {
}
도움이 되길 바랍니다.
스위프트 2용 업데이트
기본 구현을 위해 만세!
if elements.contains(5) {
// any matching items are in results
} else {
// not found
}
(스위프트 3)
배열에 요소가 있는지 확인하고(일부 기준 충족), 있는 경우 첫 번째 요소 작업을 계속합니다.
목적이 다음과 같은 경우:
- 배열에 요소가 있는지 확인하려면(/일부 부울 기준 충족, 반드시 동일성 검정은 아님),
- 그리고 만약 그렇다면, 계속해서 첫 번째 요소와 함께 작업하십시오.
그렇다면 청사진에 대한 대안Sequence~의 것입니다.Sequence:
let elements = [1, 2, 3, 4, 5]
if let firstSuchElement = elements.first(where: { $0 == 4 }) {
print(firstSuchElement) // 4
// ...
}
이 조작된 예에서는 사용 방법이 어리석어 보일 수 있지만, 기본 요소 유형이 아닌 배열에서 어떤 조건을 충족하는 요소의 존재 여부를 쿼리할 때 매우 유용합니다.예.
struct Person {
let age: Int
let name: String
init(_ age: Int, _ name: String) {
self.age = age
self.name = name
}
}
let persons = [Person(17, "Fred"), Person(16, "Susan"),
Person(19, "Hannah"), Person(18, "Sarah"),
Person(23, "Sam"), Person(18, "Jane")]
if let eligableDriver = persons.first(where: { $0.age >= 18 }) {
print("\(eligableDriver.name) can possibly drive the rental car in Sweden.")
// ...
} // Hannah can possibly drive the rental car in Sweden.
let daniel = Person(18, "Daniel")
if let sameAgeAsDaniel = persons.first(where: { $0.age == daniel.age }) {
print("\(sameAgeAsDaniel.name) is the same age as \(daniel.name).")
// ...
} // Sarah is the same age as Daniel.
사용하는 .filter { ... some condition }.first 수할있으로 할 수 .first(where:)후자는 의도를 더 잘 보여주며, 가능한 느리지 않은 애플리케이션에 비해 성능 이점이 있습니다..filter필터를 통과하는 첫 번째 요소를 추출하기 전에 전체 배열을 통과하기 때문입니다.
배열에 요소가 있는지 확인하고(일부 기준 충족), 있으면 첫 번째 요소를 제거합니다.
아래의 의견은 질문을 던집니다.
어떻게 제거할 수 있습니까?
firstSuchElement열에서배?
위의 것과 유사한 사용 사례는 주어진 술어를 만족시키는 첫 번째 요소를 제거하는 것입니다.이를 위해, (어레이 수집에 쉽게 이용 가능한) 방법을 사용하여 술어를 만족시키는 첫 번째 원소의 색인을 찾을 수 있으며, 이후 색인은 다음의 방법으로 사용될 수 있습니다.Array(존재하는 경우) 해당 요소를 제거합니다.
var elements = ["a", "b", "c", "d", "e", "a", "b", "c"]
if let indexOfFirstSuchElement = elements.index(where: { $0 == "c" }) {
elements.remove(at: indexOfFirstSuchElement)
print(elements) // ["a", "b", "d", "e", "a", "b", "c"]
}
또는 배열에서 요소를 제거하고 관련 작업을 수행하려면Optional:s 메소드를 조건부로 사용합니다..some(...)에서돌에서 index(where:) 에서를 사용합니다.index(where:)배열에서 제거된 요소를 제거하고 캡처합니다(선택적 바인딩 절 내).
var elements = ["a", "b", "c", "d", "e", "a", "b", "c"]
if let firstSuchElement = elements.index(where: { $0 == "c" })
.map({ elements.remove(at: $0) }) {
// if we enter here, the first such element have now been
// remove from the array
print(elements) // ["a", "b", "d", "e", "a", "b", "c"]
// and we may work with it
print(firstSuchElement) // c
}
값 유형("" " " " " " " " ")입니다.String입니다. 한 예), 그서주진구찾을위기사술어용것다것는니입과하를해성래도은한다소원어▁the▁using▁instances▁is▁test다▁for),▁so▁somewhat▁might것▁simpler▁simply),니▁we입예를 사용하여 동일성을 테스트할 수 있습니다. 우리가 단순히 더 간단한 것을 사용하여 동등성을 테스트할 수 있기 때문입니다.index(of:)방법은 @DogCoffee의 답변에 나와 있습니다.위의 찾기 및 제거 접근법을 적용하는 경우Person예제, 용사를 사용합니다.index(where:)(더 이상 동등성을 테스트하지 않고 제공된 서술어를 충족하기 위해) 서술어를 사용하는 것이 적절합니다.
다음과 같은 속성을 포함하는 배열
yourArray.contains(where: {$0.propertyToCheck == value })
부울을 반환합니다.
가장 간단한 방법은 어레이에서 필터를 사용하는 것입니다.
let result = elements.filter { $0==5 }
result발견된 요소가 있는 경우에는 요소가 있고 요소가 없는 경우에는 비어 있습니다.그래서 단순히 확인하기만 하면 됩니다.result.is empty에 .다음을 사용합니다.
if result.isEmpty {
// element does not exist in array
} else {
// element exists
}
스위프트 4/5
이를 달성하는 또 다른 방법은 필터 기능입니다.
var elements = [1,2,3,4,5]
if let object = elements.filter({ $0 == 5 }).first {
print("found")
} else {
print("not found")
}
2 NSA 는 Swift 2.1 는 NSA rays를 보유하고 .containsObject다음과 같이 사용할 수 있습니다.
if myArray.containsObject(objectImCheckingFor){
//myArray has the objectImCheckingFor
}
배열
let elements = [1, 2, 3, 4, 5, 5]
요소가 있는지 확인합니다.
elements.contains(5) // true
요소 인덱스 가져오기
elements.firstIndex(of: 5) // 4
elements.firstIndex(of: 10) // nil
요소 개수 가져오기
let results = elements.filter { element in element == 5 }
results.count // 2
혹시라도 누군가가 범인을 찾으려 할 때를 대비해서요indexPath것 중 예: a).UICollectionView또는UITableView cellForItemAtIndexPath함수):
var isSelectedItem = false
if let selectedIndexPaths = collectionView.indexPathsForSelectedItems() as? [NSIndexPath]{
if contains(selectedIndexPaths, indexPath) {
isSelectedItem = true
}
}
사용자가 특정 배열 요소를 찾으면 정수 값과 동일한 아래 코드를 사용합니다.
var arrelemnts = ["sachin", "test", "test1", "test3"]
if arrelemnts.contains("test"){
print("found") }else{
print("not found") }
다음은 대리자 배열에 대리자 개체가 포함되어 있는지 확인하기 위해 방금 작성한 작은 내선 번호입니다(Swift 2).:) 매력적인 가치 유형과도 연동됩니다.
extension Array
{
func containsObject(object: Any) -> Bool
{
if let anObject: AnyObject = object as? AnyObject
{
for obj in self
{
if let anObj: AnyObject = obj as? AnyObject
{
if anObj === anObject { return true }
}
}
}
return false
}
}
이 코드를 최적화하는 방법을 알고 있다면 알려주십시오.
다음에 대한 확장을 추가할 수 있습니다.Array이와 같이:
extension Array {
func contains<T>(_ object: T) -> Bool where T: Equatable {
!self.filter {$0 as? T == object }.isEmpty
}
}
다음과 같은 용도로 사용할 수 있습니다.
if myArray.contains(myItem) {
// code here
}
스위프트
개체를 사용하지 않는 경우 이 코드를 사용하여 다음을 포함할 수 있습니다.
let elements = [ 10, 20, 30, 40, 50]
if elements.contains(50) {
print("true")
}
NSObject 클래스를 swift로 사용하는 경우.이 변수는 제 요구 사항에 부합합니다.요구 사항에 맞게 수정할 수 있습니다.
var cliectScreenList = [ATModelLeadInfo]()
var cliectScreenSelectedObject: ATModelLeadInfo!
이는 동일한 데이터 유형에 대한 것입니다.
{ $0.user_id == cliectScreenSelectedObject.user_id }
AnyObject를 입력하려면 다음과 같이 입력합니다.
{ "\($0.user_id)" == "\(cliectScreenSelectedObject.user_id)" }
완전한 상태
if cliectScreenSelected.contains( { $0.user_id == cliectScreenSelectedObject.user_id } ) == false {
cliectScreenSelected.append(cliectScreenSelectedObject)
print("Object Added")
} else {
print("Object already exists")
}
이런 식으로 해시 테이블을 작업에 사용하는 것은 어떻습니까?
먼저, "해시 맵" 일반 함수를 생성하여 시퀀스 프로토콜을 확장합니다.
extension Sequence where Element: Hashable {
func hashMap() -> [Element: Int] {
var dict: [Element: Int] = [:]
for (i, value) in self.enumerated() {
dict[value] = i
}
return dict
}
}
이 확장은 배열의 항목이 정수나 문자열과 같이 해시 가능한 경우에만 작동합니다. 여기에 사용법이 있습니다...
let numbers = Array(0...50)
let hashMappedNumbers = numbers.hashMap()
let numToDetect = 35
let indexOfnumToDetect = hashMappedNumbers[numToDetect] // returns the index of the item and if all the elements in the array are different, it will work to get the index of the object!
print(indexOfnumToDetect) // prints 35
하지만 지금은 요소가 배열에 있는지 확인하는 데 집중해 보겠습니다.
let numExists = indexOfnumToDetect != nil // if the key does not exist
means the number is not contained in the collection.
print(numExists) // prints true
스위프트 4.2 +
다음 함수를 사용하여 인스턴스가 배열인지 여부를 쉽게 확인할 수 있습니다.
func verifyIsObjectOfAnArray<T>(_ object: T) -> Bool {
if let _ = object as? [T] {
return true
}
return false
}
당신도 다음과 같이 접속할 수 있습니다.▁receive니▁will를 받게 될 것입니다.nil대상이 배열이 아닐 경우.
func verifyIsObjectOfAnArray<T>(_ object: T) -> [T]? {
if let array = object as? [T] {
return array
}
return nil
}
언급URL : https://stackoverflow.com/questions/24102024/how-to-check-if-an-element-is-in-an-array
'source' 카테고리의 다른 글
| 파이썬에서 주어진 픽셀의 RGB 값을 읽는 방법은 무엇입니까? (0) | 2023.07.15 |
|---|---|
| 엔티티 매핑에서 시퀀스의 증분 크기는 [50]으로 설정되고 연결된 데이터베이스 시퀀스 증분 크기는 [1]입니다. (0) | 2023.07.15 |
| 파이썬 멀티스레드는 모든 스레드가 완료될 때까지 기다립니다. (0) | 2023.07.15 |
| com.google.android.gms.common.api에 로그인하지 못했습니다.API 예외: 10: (0) | 2023.07.15 |
| R에서 실행을 일시 중지하고, 자고, X초 동안 기다리도록 하는 방법은 무엇입니까? (0) | 2023.07.15 |