xcode Swift 类的函数调用中的“顶层不允许表达式”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24929978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Expression are not allowed at top level" in function call of a class in Swift
提问by Myaaoonn
Following is my code.. I don't understand why this error shows me everytime.
以下是我的代码..我不明白为什么每次都会显示这个错误。
import UIKit
import Foundation
class BaseLabel:UILabel
{
func setFontAndTitle(FontName:String,FontSize:CGFloat,Title:String) {
self.font = UIFont(name: FontName, size: FontSize)
self.text = Title
}
}
var lbl = BaseLabel()
lbl.setFontAndTitle ("Areal", FontSize: 14, Title: "Check label")
In the last line I am getting the the error "Expression are not allowed at top level"
在最后一行中,我收到错误“顶层不允许表达式”
采纳答案by Evgeniy Kleban
You trying to typing code outside of class. You need to put it in you class and enclose in function body. Please take a look at my solution:
您试图在课外键入代码。你需要把它放在你的类中并包含在函数体中。请看一下我的解决方案:
import UIKit
import Foundation
class BaseLabel:UILabel
{
func setFontAndTitle(FontName:String,FontSize:CGFloat,Title:String) {
self.font = UIFont(name: FontName, size: FontSize)
self.text = Title
}
func changePropertiesOfLabel(){
var lbl = BaseLabel()
lbl.setFontAndTitle ("Areal", FontSize: 14, Title: "Check label")
}
}