2016-10-31 10 views
0

선택 NSArray에서 첫 번째 객체를 인쇄하려고합니다. 온라인 데이터베이스에서 반환됩니다. 아무것도 인쇄되지 않습니다. 선택적 NSArray를 색인화 할 수있는 배열로 unwrap하는 방법을 모릅니다. 지금은 NSArray에서 첫 번째 값을 인쇄하려고합니다.선택 NSArray - Any 객체에 아래 첨자가 없습니다.

fireBaseRef.observeSingleEventOfType(.Value, withBlock: { snapshot in 

       if !snapshot.exists() { return } 

       for item in snapshot.children { 
       print("This is the child value of reference", item.value["reference"]) 

        if let referenceObjects = item.value["reference"] { 
         print("This is the first value", referenceObjects[0]) //error is Anyobject? has no subscript members 
        } 

       } 

      }) 

은 내가 당신의 코드에 따라

This is the child value of track-titles Optional(<__NSArrayM0x618000049000>(
The Chainsmokers - Don't Let Me Down (Illenium Remix), 
Flume - Say It ft. Tove Lo (Illenium Remix), 
The Chainsmokers Ft. Halsey - Closer (GhostDragon Remix), 
Major Lazer & Showtek - Believer, 
Fire, 
ONE DANCE -- DRAKE (feat. Wizkid & Kyla), 
Let Me Love You - Justin Bieber (Trap Edit) 
) 
) 
+0

현재 출력을 추가하십시오. –

+0

what * is *'item.value [ "reference"]'? 당신 NSArray에 대해 얘기하지만 NSDictionary로 unwrap하려고합니다. – luk2302

+0

@ luk2302, 그것은 나무 또는 참조 이름의 제목입니다. NSArray를 사용하고 있습니다 .. 나는 firebase를 사용하고 있습니다. 그렇습니다. NSDictionary가있는 곳에서 내가 무엇을하고 있는지 알지 못합니다. – cnichs27

답변

1

다음, referenceObjects가있는 NSDictionary 아닌있는 NSArray입니다받을 수 있습니다. 따라서 당신은 [0] 런타임 시도하고 당신이 작동합니다있는 NSArray, 다음과 같은 무언가를 검색하려면 키 0

의 값을 검색합니다 referenceObjects를 요청할 때

if let referenceObjects = item.value["reference"] as? NSArray where !referenceObjects.isEmpty { 
    print("This is the first object: \(referenceObjects.first!)") 
} 

희망을 도움이됩니다.

+0

@ cnichs27 관계없이, 당신은 여전히 ​​캐스팅을해야합니다. – Alexander

+0

@AlexanderMomchliov 당신 말이 맞아요! – cnichs27

-1

스냅 샷이 선택적 NSArray로 되돌아 왔으므로이 객체가 nil 인 경우 다운 캐스트의 조건부 형식을 사용해야합니다.

if let referenceObjects = item.value["reference"] as? NSArray { 
print(referenceObjects[0]) 
} 
+0

이 코드 단편은 질문에 대답 할 수 있지만, 방법이나 이유를 설명하는 컨텍스트를 제공하지는 않습니다. 답을 설명하기 위해 한 두 문장을 더하는 것을 고려하십시오. – brandonscript

+0

내 대답이 귀하의 질문에 답변이되지 않았습니까? 피드백은 내가 혼란스럽게 환영합니다. – Sparky

+0

또한 referenceObject가 비어있는 경우 사용자가 제시 한 대답이 실패합니다. – Sparky