2016-07-09 2 views
0
import GameKit 

class FactModel { // See, this is a class now. 
    let facts = [ "Test1", "test2", "Test3", "test4", "Test5", "test6", "test7", "Test8", "test9", "test10", "Test11", "test12", "test13", "Test14", "test15", "test16", "Test17", "test18" ] 
    var index = 0 // This is the property that will allow us to track what fact we are up to. 

    func getRandomFact() -> String { // No change to this method. 
     let randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(facts.count) 

     return facts[randomNumber] 
    } 

    func getNextFact() -> String { 
     let fact = facts[index] // We grab the fact before we increment the index. 
     if index < facts.count - 1 { // We make sure we did not give the last fact in the list. 
      index += 1 // We increment the index so the next fact is ready to go. 
     } else { 
      index = 0 // We wrap around to the first fact because we just gave the last one. 
     }  
     return fact 
    } 

    func getPreviousFact() -> String { 
     let fact = facts[index] 
     if index < facts.count - 1{ 
      index -= 1 
     } else { 
      index = 0 
     } 
     return fact 
    } 
} 

let myFact = FactModel() 

답변

-1

u는 먼저 색인 개미를 늘려서 사실을 검색해야합니다. 색인을 다음과 같이 설정하십시오.

func getPreviousFact() -> String { 
    if index > facts.count { 
     index -= 1 
    } else { 
     index = 0 
    } 
    let fact = facts[index] 
    return fact 
} 
0

코드를 한 줄씩 살펴 보겠습니다.

FactModel이 초기화되면 index0입니다. 지금 당신은 getPreviousFact 전화 :

라인 1 : let fact = facts[index]

이제 fact이 될 것입니다 최초의 사실, 즉 Test1을.

라인 2 : if index < facts.count - 1{

facts.count - 1보다는 인덱스 적은 있습니까? 그것은! index 0이고 facts.count - 1 17

라인 3 : index -= 1

이제 index가 -1!

따라서 다음 번에 getPreviousFact으로 전화하면 let fact = facts[index]이 실행됩니다. index이 -1이 되었기 때문에 범위를 벗어났습니다! 당신이 index은 0 그래서이 다를 수 있습니다 때 어떻게해야 무엇 언급하지 않았기 때문에

if index < facts.count && index > 0 { 
     index -= 1 
    } else { 
     index = facts.count - 1 
    } 

이, 그냥 내 생각이다 : :(

나는 당신이 원하는 것은이 생각

+0

미세 선언! :-) –

+0

오류가 발생했습니다. 1) 줄에서의 연속적인 선언은 ";" 2) 세미 콜론을 넣을 때 그것은 선언을 기대한다. –

+0

@Dani 나는 대답을 편집했다. 그래도 오류가 발생하면 오류가 발생한 행을 알려주실 수 있습니까? – Sweeper

관련 문제