2016-12-20 1 views
1

Swift와 프로그래밍에 새로운 점이있어서 어디에 문제가 있는지 알 수 없습니다. 기존 주제에서 대답을 찾으려고했는데 할 수 없었습니다. 미리 감사드립니다.치명적인 오류 : 인덱스가 범위를 벗어남 (배열)

func smartAssigning(names: [String], statuses: [Bool], projects: [Int], tasks: [Int]) -> String { 
    //beginig 
    var collect: [Int] = [], nameLast = 0 
    var candidateNumber: [Int] = [] 
    for x in 0...statuses.count { 

     //Defines who is working 
     if statuses[x] == false { 
      collect.append(x) 
     } else {} 
    } 

    // Checks for min tasks assigned among those not on vacation 
    let rt: Int = tasks.min()! 
    let rp: Int = projects.min()! 
    for i in collect { 
     if tasks[i] == rt { 
      candidateNumber.append(i) 
     } else {} 
    } 
    // if there is only 1 with min tasks - returns his number in array 
    if candidateNumber.count == 1 { 
     nameLast = candidateNumber[0] 
    } else { 
     // checks for min projects 
     for e in candidateNumber { 
      if projects[e] == rp { 
       nameLast = e 
      } 
     } 
    } 
    return names[nameLast] 
} 
smartAssigning(names: ["sd", "dfsd","dfsdf"], statuses: [true, false, false], projects: [2, 1, 1], tasks: [3, 2, 1]) 

화면 :

Screen

+1

첫 번째 오류가에있다을'0 X 용 ... statuses.count'- 당신은 *로 * 디버그 시도해 봤어 문제? 이 기능을 한 단계 밟으면 문제가 빨리 드러납니다. –

+0

이름, 상태, 프로젝트 및 작업 배열의 요소가 모두 묶여 있습니까? 예 : 첫 번째 이름은 첫 번째 상태, 첫 번째 프로젝트 및 첫 번째 작업에 연결됩니까? – Alexander

+0

예, 그렇습니다. 하지만 내 문제를 발견했다. 너와 Martin R. Damn 덕분에. 너무 쉽게. XCODE가 오류로 인식하지 않는 이유는 무엇입니까? –

답변

0

오류 여기에 있습니다 : n입니다

for x in 0...statuses.count { // Error is here 

    //Defines who is working 
    if statuses[x] == false { 
     collect.append(x) 
    } else {} 
} 

statuses.count 경우, 최대 지수는 n-1입니다. 0..<statuses.count이어야합니다. 이러한 오타가 발생할 수 있기 때문에 이러한 범위를 수동으로 생성하지 않아야합니다. for x in status.indices을 수행하는 것이 훨씬 낫습니다.

아무런 조치가 없다면 else 절이있을 필요가 없습니다.

또한 false (== false)와 비교하기보다는 Bool을 부정합니다.

for x in statuses.indices { // Error is here 
    //Defines who is working 
    if !statuses[x] { 
     collect.append(x) 
    } 
} 

이 모든 코드는 하나의 filter(_:) 표현하여 작성 할 수 있습니다

// TODO: Give me a new meaningful name! 
let collect = statues.enumerated() // Get index, status pairs 
        .filter{ index, status in !status } // filter all false statuses 
        .map{ index, status in index } // Take just the indices 
+0

Thx. 첫 번째 오류가 발견 되었습니까? XCODE에서 작동하지만 CODECHALLENGE 창에 나타나지 않는 것처럼 보입니다. 말한다 : file.swift on line 15:24 : 오류 : '[Int]'유형의 값에 'min'멤버가 없다. tasks [i] == tasks.min() { ^ ~~~~~~~~ –

+0

당신이 무슨 말을하는지 잘 모르겠습니다. o.0 ' – Alexander

+0

https://www.dropbox.com/s/kruv2n1zj0vmxvt/Screenshot%202016-12-20%2016.18.41.png?dl=0 –

관련 문제