2017-11-11 407 views
-1

我有點誤解如何正確使用 - (void)。每當我嘗試使用 - (Void)編寫代碼,但出現錯誤「Expected declaration」或有時「Binary operator '-' cannot be applied to operands of type 'UIFont' and '(Void).Type'」。如何解決Swift中的「預期聲明」錯誤?

這是怎麼發生的?在swift中正確使用此功能的正確方法是什麼?

{

- (Void)keyboardWillShow { //>> showing me the error "Binary operator '-' cannot be applied to operands of type 'UIFont' and '(Void).Type'" 
     // Animate the current view out of the way 
     if (self.view.frame.origin.y >= 0) 
     { 
      [self setViewMovedUp:YES]; 
     } 
     else if (self.view.frame.origin.y < 0) 
     { 
      [self setViewMovedUp:NO]; 
     } 
    } 

}

感謝

+1

請通讀了雨燕編程語言[Apple的文檔(https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/index.html)。 –

+1

用導致問題的實際代碼更新您的問題。 – rmaddy

+1

這是Objective-C代碼,而不是Swift代碼。請閱讀[Swift編程語言](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/)書。 – rmaddy

回答

5

這聽起來像你想聲明沒有返回值的函數。在斯威夫特這樣做是因爲:

func thisFunction() { 
    .. 
} 
-2

可以回到零值,如下面的代碼:

func myFunc(myVar: String) ->()? { 
    print(myVar) 
    return nil 
    } 
var c = myFunc("Hello") 
print(c) // nil 

但斯威夫特功能總是返回默認值零,如果沒有聲明。如下面的代碼:

func myFunc(myVar: String) { 
     print(myVar) 
     return 
     } 
    var c = myFunc("Hello") 
    print(c) //() 
+0

* Swift函數總是返回默認值nil,如果沒有聲明*是錯誤的。在第二個例子中,你會得到一個編譯器錯誤(實際上兩個在Swift 3+中)。 – vadian

+1

*「如果未聲明,Swift函數總是返回默認值nil」* - 否,這是不正確的。 – rmaddy

+0

嚴格地說,即使沒有定義返回值,myFunc(myVar :)函數的這個版本仍然會返回一個值。沒有定義返回類型的函數返回一個特殊的Void類型值。這只是一個空元組,寫成()。 –