2017-02-22 7 views
0

튜토리얼 서적을 작성 중이며 Swift에서 배열에 액세스하는 방법에 대한 질문이 있습니다. 이 유형이 트리 또는 배열 내의 특정 노드에 대한 경로를 나타내는 것으로 가정하기 때문에 IndexPath 유형을 직접 사용하면 어떤 일이 발생하는지 궁금합니다. "Cannot subscript value of type [ToDoItem] with an index of type IndexPath"Swift에서 Int 유형과 IndexPath 유형 사용

func item(at indexIWant: IndexPath) -> ToDoItem { 

     return toDoItems[indexIWant] 
    } 

내가이 평신도 측면에서 의미 하는가 알고 그냥 궁금 해요 왜이 허용되지 않습니다 : 그러나, 다음과 같은 기능을 말한다 반환 라인에 오류가 표시?

다음은 튜토리얼의 코드이며 IndexPath 유형 대신 Int 유형을 사용하는 컴파일입니다. 배열의 인덱스 N

import Foundation 


class ItemManager { 

    var toDoCount: Int = 0 

    var doneCount: Int = 0 

    private var toDoItems: [ToDoItem] = [] 

    func add(_ item: ToDoItem) { 

     toDoCount += 1 

     toDoItems.append(item) 
    } 


    func item(at index: Int) -> ToDoItem { 

     return toDoItems[index] 

    } 
} 

답변

3

subscriptInt 기대 때문에 당신은 유형 Int의 아닌 IndexPath을 전달하고 있습니다.

당신이 Apple IndexPath Documentation를 읽어보십시오

, IndexPath 유형 Int의이다 row 또는 section 같은 속성이 있습니다. 이를 사용하여 배열의 요소에 액세스 할 수 있습니다.

func item(at indexIWant: IndexPath) -> ToDoItem { 
    return toDoItems[indexIWant.row] 
} 

IndexPath으로 배열에 실제로 액세스하려는 경우 Array 클래스를 확장 할 수 있습니다. 이제 코드가 컴파일되지만이 코드를 권장하는지 잘 모르겠습니다.

extension Array { 
    subscript(indexPath: IndexPath) -> Element { 
     get { 
      return self[indexPath.row] 
     } 
     set { 
      self[indexPath.row] = newValue 
     } 
    } 
} 
1

NSIndexPath 클래스 중첩 배열 모음

그래서

enter image description here

row 트리 내의 특정 노드에 대한 경로를 표시하고 section가있다 배열 번호 그래서 첫 번째 화살표는 row 1과 section 0에서 두 번째는 row 4와 section입니다. 1.and 에.

Doc