2017-11-11 409 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类型值。这只是一个空元组,写成()。 –