Swift에서 목록 항목의 인덱스를 찾는 방법은 무엇입니까?
나는 찾고 있다.item index
검색하여list
어떻게 하는지 아는 사람?
그렇구나list.StartIndex
그리고.list.EndIndex
하지만 나는 비단뱀과 같은 것을 원한다.list.index("text")
.
swift는 오브젝트 지향보다 기능적인 경우도 있기 때문에 (어레이는 오브젝트가 아닌 구조체) "find" 함수를 사용하여 어레이를 조작합니다.그러면 옵션 값이 반환되므로 0 값을 처리할 준비를 합니다.
let arr:Array = ["a","b","c"]
find(arr, "c")! // 2
find(arr, "d") // nil
사용하다firstIndex
그리고.lastIndex
- 항목의 첫 번째 인덱스와 마지막 인덱스 중 어느 쪽을 찾느냐에 따라 달라집니다.
let arr = ["a","b","c","a"]
let indexOfA = arr.firstIndex(of: "a") // 0
let indexOfB = arr.lastIndex(of: "a") // 3
tl;dr:
수업의 경우 다음을 찾을 수 있습니다.
let index = someArray.firstIndex{$0 === someObject}
완전한 답변:
레퍼런스 타입에 대해서는 언급할 필요가 있다고 생각합니다.class
아이덴티티 비교를 실행할 수 있습니다.이 경우, 필요한 것은,===
identity 연산자는 술어 폐쇄에 있습니다.
Swift 5, Swift 4.2:
let person1 = Person(name: "John")
let person2 = Person(name: "Sue")
let person3 = Person(name: "Maria")
let person4 = Person(name: "Loner")
let people = [person1, person2, person3]
let indexOfPerson1 = people.firstIndex{$0 === person1} // 0
let indexOfPerson2 = people.firstIndex{$0 === person2} // 1
let indexOfPerson3 = people.firstIndex{$0 === person3} // 2
let indexOfPerson4 = people.firstIndex{$0 === person4} // nil
위의 구문은 후행 폐쇄 구문을 사용하며 다음과 같습니다.
let indexOfPerson1 = people.firstIndex(where: {$0 === person1})
Swift 4 / Swift 3 - 이전에 호출되었던 함수index
Swift 2 - 이전에 호출되었던 함수indexOf
* paulbailey에 의한 적절하고 유용한 코멘트에 주의해당 코멘트는 다음과 같습니다.class
실장하는 타입Equatable
를 사용하여 비교해야 하는지 여부를 고려해야 합니다.===
(오퍼레이터) 또는==
(오퍼레이터).일치시키기로 결정한 경우==
다른 사람이 제안하는 방법을 사용할 수 있습니다.people.firstIndex(of: person1)
).
넌 할 수 있다.filter
닫힘이 있는 배열:
var myList = [1, 2, 3, 4]
var filtered = myList.filter { $0 == 3 } // <= returns [3]
어레이를 카운트할 수 있습니다.
filtered.count // <= returns 1
따라서 다음과 같이 조합하여 배열에 요소가 포함되어 있는지 여부를 확인할 수 있습니다.
myList.filter { $0 == 3 }.count > 0 // <= returns true if the array includes 3
만약 당신이 그 자리를 찾고 싶다면, 나는 화려한 방법이 보이지 않지만, 당신은 분명히 이렇게 할 수 있습니다.
var found: Int? // <= will hold the index if it was found, or else will be nil
for i in (0..x.count) {
if x[i] == 3 {
found = i
}
}
편집
이왕 하는 김에 재밌는 운동을 위해서Array
을 가지다find
방법:
extension Array {
func find(includedElement: T -> Bool) -> Int? {
for (idx, element) in enumerate(self) {
if includedElement(element) {
return idx
}
}
return nil
}
}
이제 이 작업을 수행할 수 있습니다.
myList.find { $0 == 3 }
// returns the index position of 3 or nil if not found
스위프트 5
func firstIndex(of element: Element) -> Int?
var alphabets = ["A", "B", "E", "D"]
예 1
let index = alphabets.firstIndex(where: {$0 == "A"})
예2
if let i = alphabets.firstIndex(of: "E") {
alphabets[i] = "C" // i is the index
}
print(alphabets)
// Prints "["A", "B", "C", "D"]"
하는 동안에indexOf()
완벽하게 작동하며 하나의 인덱스만 반환합니다.
어떤 조건을 만족시키는 요소의 인덱스를 얻을 수 있는 우아한 방법을 찾고 있었습니다.
방법은 다음과 같습니다.
스위프트 3:
let array = ["apple", "dog", "log"]
let indexes = array.enumerated().filter {
$0.element.contains("og")
}.map{$0.offset}
print(indexes)
스위프트 2:
let array = ["apple", "dog", "log"]
let indexes = array.enumerate().filter {
$0.element.containsString("og")
}.map{$0.index}
print(indexes)
Swift 4.2에서
.index(여기:)가 .firstIndex(여기:)로 변경되었습니다.
array.firstIndex(where: {$0 == "person1"})
사용자 지정 클래스의 경우 Equatable 프로토콜을 구현해야 합니다.
import Foundation
func ==(l: MyClass, r: MyClass) -> Bool {
return l.id == r.id
}
class MyClass: Equtable {
init(id: String) {
self.msgID = id
}
let msgID: String
}
let item = MyClass(3)
let itemList = [MyClass(1), MyClass(2), item]
let idx = itemList.indexOf(item)
printl(idx)
Swift 4에서는 firstIndex 메서드를 사용할 수 있습니다.의 사용 예==
배열에서 개체를 찾기 위한 equality 연산자id
:
let index = array.firstIndex{ $0.id == object.id }
- 이 솔루션은 오브젝트 전체가 아닌 속성을 비교하기 때문에 Equitable 프로토콜을 준수할 필요가 없습니다.
이 음은 '다 '에 대한 입니다.==
»===
지금까지 투고된 답변의 대부분은 사용법이 다르기 때문입니다.
==
을 사용하다값이 동일한지 여부를 확인합니다.===
는 ID 연산자입니다.클래스의 두 인스턴스가 같은 메모리를 가리키는지 여부를 확인합니다.동일한 값을 사용하여 독립적으로 생성된 두 개체는 ==를 사용하여 동등하다고 간주되지만 서로 다른 개체이므로 ===를 사용하여 동등하다고 간주되지 않습니다. (출처)
Swift의 문서에서 이러한 운영자에 대한 자세한 내용을 읽어볼 가치가 있습니다.
firstIndex 메서드를 사용합니다.
array.firstIndex(where: { $0 == searchedItem })
Swift 2 업데이트:
sequence.displicate(실행):지정된 시퀀스(배열 등)에 지정된 요소가 포함되어 있는 경우 true를 반환합니다.
스위프트 1:
내에 되어 있는지 즉표시기만 .그러면, 「」를 사용해 주세요.contains(sequence, element)
find(array, element)
contains(시퀀스, 요소):지정된 시퀀스(배열 등)에 지정된 요소가 포함되어 있는 경우 true를 반환합니다.
아래의 예를 참조해 주세요.
var languages = ["Swift", "Objective-C"]
contains(languages, "Swift") == true
contains(languages, "Java") == false
contains([29, 85, 42, 96, 75], 42) == true
if (contains(languages, "Swift")) {
// Use contains in these cases, instead of find.
}
스위프트 4배열에 [String:]유형의 요소가 포함되어 있는 경우AnyObject]를 선택합니다.그래서 요소의 인덱스를 찾으려면 아래 코드를 사용합니다.
var array = [[String: AnyObject]]()// Save your data in array
let objectAtZero = array[0] // get first object
let index = (self.array as NSArray).index(of: objectAtZero)
또는 사전의 키를 기준으로 인덱스를 찾으려는 경우.이 배열에는 Objects of Model 클래스가 포함되어 있으며 ID 속성과 일치합니다.
let userId = 20
if let index = array.index(where: { (dict) -> Bool in
return dict.id == userId // Will found index of matched id
}) {
print("Index found")
}
OR
let storeId = Int(surveyCurrent.store_id) // Accessing model key value
indexArrUpTo = self.arrEarnUpTo.index { Int($0.store_id) == storeId }! // Array contains models and finding specific one
Swift 4에서 DataModel 어레이를 통과하는 경우 데이터 모델이 Equatable Protocol에 준거하고 있는지 확인하고 lhs=rhs 메서드를 구현해야 ".index(of)"를 사용할 수 있습니다.
class Photo : Equatable{
var imageURL: URL?
init(imageURL: URL){
self.imageURL = imageURL
}
static func == (lhs: Photo, rhs: Photo) -> Bool{
return lhs.imageURL == rhs.imageURL
}
}
그리고 나서.
let index = self.photos.index(of: aPhoto)
★★★의 (>= swift 4.0)
아주 간단합니다.의 것을 생각해 보세요.Array
★★★★★★ 。
var names: [String] = ["jack", "rose", "jill"]
의 rose
필요한 것은 다음과 같습니다.
names.index(of: "rose") // returns 1
주의:
Array.index(of:)
Optional<Int>
nil
는 요소가 배열에 존재하지 않음을 나타냅니다." " " 를 할 수 .
if-let
옵션을 회피할 수 있습니다.
스위프트 2.1
var array = ["0","1","2","3"]
if let index = array.indexOf("1") {
array.removeAtIndex(index)
}
print(array) // ["0","2","3"]
스위프트 3
var array = ["0","1","2","3"]
if let index = array.index(of: "1") {
array.remove(at: index)
}
array.remove(at: 1)
27 ), Swift 2(Xcode 7 포함)의 Array
에는 프로토콜에 의해 제공되는 메서드가 포함되어 있습니다.(실제로는 2개입니다)indexOf
methods: 인수를 대조하기 위해 등식을 사용하는 방법 및 closure를 사용하는 방법).
Swift 2 이전에는 컬렉션과 같은 범용 타입에서 파생된 구체적인 타입(어레이 등)에 대한 메서드를 제공하는 방법이 없었습니다.재빠른 1.x의 '재빠르게'1.이 를 Swift 1.x라고 .find
.
꼭 필요한 .indexOfObject
from method method method method 。NSArray
한 것이... 또는 Swift 표준 라이브러리에는 동등한 항목이 없는 Foundation의 다른 보다 정교한 검색 메트입니다. ★★★★★★★★★★★★★★★★★.import Foundation
Foundation을 으로 Import하는 을합니다.(「 Foundation 」 「 Import 」 「 Import 」Array
로로 합니다.NSArray
방법은 많이 사용하실 수 .NSArray
.
이 솔루션 중 어느 것이든 나에게 효과가 있다
이것이 Swift 4의 솔루션입니다.
let monday = Day(name: "M")
let tuesday = Day(name: "T")
let friday = Day(name: "F")
let days = [monday, tuesday, friday]
let index = days.index(where: {
//important to test with === to be sure it's the same object reference
$0 === tuesday
})
또한 기능 라이브러리 $를 사용하여 http://www.dollarswift.org/ #index of-index of 와 같은 어레이에서 index Of 를 수행할 수도 있습니다.
$.indexOf([1, 2, 3, 1, 2, 3], value: 2)
=> 1
아직 Swift 1.x에서 작업 중인 경우
그럼 한번 해봐
let testArray = ["A","B","C"]
let indexOfA = find(testArray, "A")
let indexOfB = find(testArray, "B")
let indexOfC = find(testArray, "C")
SWIFT 3은 간단한 기능을 사용할 수 있습니다.
func find(objecToFind: String?) -> Int? {
for i in 0...arrayName.count {
if arrayName[i] == objectToFind {
return i
}
}
return nil
}
이렇게 하면 번호 위치가 표시되므로 다음과 같이 사용할 수 있습니다.
arrayName.remove(at: (find(objecToFind))!)
도움이 되기를 바라다
Swift 4/5에서 색인 찾기에 "firstIndex"를 사용합니다.
let index = array.firstIndex{$0 == value}
스위프트 4
참조 유형의 경우:
extension Array where Array.Element: AnyObject {
func index(ofElement element: Element) -> Int? {
for (currentIndex, currentElement) in self.enumerated() {
if currentElement === element {
return currentIndex
}
}
return nil
}
}
누군가 이 문제를 가지고 있는 경우
Cannot invoke initializer for type 'Int' with an argument list of type '(Array<Element>.Index?)'
이것을 해라.
extension Int {
var toInt: Int {
return self
}
}
그리고나서
guard let finalIndex = index?.toInt else {
return false
}
SWIFT 4
cardButtons라는 배열의 번호를 cardNumber에 저장하는 경우 다음과 같이 할 수 있습니다.
let cardNumber = cardButtons.index(of: sender)
sender는 버튼 이름입니다.
언급URL : https://stackoverflow.com/questions/24028860/how-to-find-index-of-list-item-in-swift
'programing' 카테고리의 다른 글
커밋 메시지 내 GitHub의 이슈 번호 링크 (0) | 2023.04.17 |
---|---|
읽기 전용 종속성 속성을 생성하려면 어떻게 해야 합니까? (0) | 2023.04.17 |
vba의 쓰기 문에서 큰따옴표 제거 (0) | 2023.04.17 |
WPF 비트맵 소스 이미지를 파일에 저장하는 방법 (0) | 2023.04.17 |
디렉토리와 하위 디렉토리에서 가장 큰 파일을 찾으려면 어떻게 해야 합니까? (0) | 2023.04.12 |