2016-08-23 19 views
0

我一直在試圖從對象 - 這個代碼轉換爲斯威夫特聲明:If statement based on whatever the previous view controller was(幾乎完全同樣的問題)如果基於以前的視圖控制器在斯威夫特

換句話說,我想回去到用戶來自的View Controller,無論是MainViewController還是SearchTableViewController都可以在兩個unwind segues之間進行選擇。

我的問題是:我如何編寫與上面的鏈接相同的功能代碼,但在Swift中而不是在Obj-c中?

這是我的翻譯至今(不工作,無法擺脫錯誤的)

//Method 
func backViewController() -> UIViewController { 
     let numberOfViewControllers = self.navigationController!.viewControllers.count 
     if numberOfViewControllers < 2 { 
      return nil 
     } 
     else { 
      return self.navigationController!.viewControllers[numberOfViewControllers - 2] 
     } 
    } 


    if self.backViewController() == MainViewController { 
//Back to MainViewController 
     self.performSegueWithIdentifier("AuthorBackMain", sender: self) 
    } 
    else { 
//Back to SearchTableViewController 
     self.performSegueWithIdentifier("AuthorBackSearch", sender: self) 
    } 

編輯/進展情況:

我已經改變了功能backViewController() -> UIViewController?,它擺脫那裏的錯誤。但在if語句中發生新的錯誤,關於二進制運算符'=='

"Binary operator '==' cannot be applied to operands of type 'UIViewController?' and 'MainViewController.Type'. 
+1

變化' - > UIViewController'到' - >'的UIViewController? – matt

+0

使用此鏈接將其轉換爲Swift https://objectivec2swift.com/#/home/converter/請注意,如果它工作 – Nik

+0

「不工作」和「所有幫助非常感謝」不是問題。太寬泛。要求我們爲您翻譯您的代碼也不是問題。 – matt

回答

2

這是Swift。只有一個可選項可以是nil。你正試圖從你的backViewController方法中返回一個UIViewController。 UIViewController不是可選的,因此它不能是nil。如果您需要它是nil,請將其設置爲可選:UIViewController?

+0

謝謝,解決了函數/方法中的第一個錯誤。但請看我對上述答案的評論(來自@Sam M的問題),在if語句中發生了新的錯誤。感謝您的時間和幫助。 – Mate

1
  1. 如果你想能夠返回nil你需要做的返回類型可選。
    func backViewController() -> UIViewController?

  2. 更換func backViewController() -> UIViewController
    既然你比較,你不能使用不同viewControllers '=='。您應該嘗試將其轉換爲您想要的viewController。
    替換此

    if self.backViewController() == MainViewController { 
    //Back to MainViewController 
        self.performSegueWithIdentifier("AuthorBackMain", sender: self) 
        } 
        else { 
    //Back to SearchTableViewController 
        self.performSegueWithIdentifier("AuthorBackSearch", sender: self) 
        } 
    

    if let _ = self.backViewController() as? MainViewController { 
    //Back to MainViewController 
        self.performSegueWithIdentifier("AuthorBackMain", sender: self) 
        } 
        else if let _ = self.backViewController() as? SearchTableViewController { 
    //Back to SearchTableViewController 
        self.performSegueWithIdentifier("AuthorBackSearch", sender: self) 
        } 
    
+0

嗨,謝謝你的幫助。我遵循你的建議,擺脫了有關方法/功能(1.)的錯誤。但是現在,當我用你的舊的if語句取代(2.)時,會發生新的錯誤。 「Binary operator'=='不能應用於'UIViewController'類型的操作數嗎?和'MainViewController.Type'@Sam M – Mate

+0

@Mate查看我編輯的答案。 –

相關問題