2017-05-26 204 views
3

我將如何去檢查一個函數是否被調用?我創建了一個功能,看是否水平完成,像這樣:檢查函數是否被調用?

func levelOneCompleted(){ 

} 

當一個水平打,我叫()levelOneCompleted功能。

現場然後去另一個場景。在這個場景中,我想檢查函數是否被調用。我想我可以做出某種「如果陳述」。

if levelOneCompleted is called { 
//do this 

else{ 

//do this 
} 

這樣做的最好方法是什麼?

回答

3

設置一個布爾標誌,truelevelOneCompleted()

var isLevelOneCompleted = false 

func levelOneCompleted(){ 
    // do things... 
    isLevelOneCompleted = true 
} 

後來......

if isLevelOneCompleted { 
    //do this 
} else { 
    //do this 
} 
+0

感謝您的回覆!有兩種方法可以在兩個不同的場景中執行此操作嗎?場景1調用功能並切換到場景2.場景2是否可以從場景1中查看功能? –

+0

@MattCantrelle場景2如何呈現?使用故事板賽格?如果是這樣,我會在視圖控制器中設置一個屬性,指出在'prepareForSegue'方法中調用了'levelOneCompleted()'。 – Paolo

+0

不,先生,我實際上不使用故事板爲這個項目。在第一個場景中,我通過一個簡單的「let sceneTwo = SKscene(filenamed:」this「)」設置了第二個場景。然後我打電話來呈現這個場景。 –

1

斯威夫特3 &的Xcode 8.3.2

有2招做到這一點,這裏是代碼:

// Async operation 
func levelOneCompleted(completion: (_ completed: Bool) -> Void) { 
    // do your function here 
    completion(true) 
} 

// Here is how to use it 
// than u can declare this in viewDidLoad or viewDidAppear, everywhere you name it 
override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 

    // this is async operation 
    levelOneCompleted { (completed) in 
     if completed { 
      print("levelOneCompleted is complete") 
      // do something if levelOneCompleted is complete 

      DispatchQueue.main.async { 
       // Update your UI 
      } 
     } else { 
      print("levelOneCompleted is not completee") 
      // do something if levelOneCompleted is not complete 

      DispatchQueue.main.async { 
       // Update your UI or show an alert 
      } 
     } 
    } 
} 


// Or u can use this code too, and this is Sync operation 
var isLevelTwoCompleted: Bool = false 
func levelOneCompleted() { 
    // do your function here 
    isLevelTwoCompleted = true 
} 


// to check it u can put this function everywhere you need it 
if isLevelTwoCompleted { 
    //do something if level two is complete 
} else { 
    //do something if level two is not complete 
} 
+0

嗨馬特,我想知道這是否足以讓你走上正軌。看起來,如果您從同一個控制器調用一級和二級,它將起作用。如果你仍然堅持,只需編輯上面的問題。 – Mozahler