新手问题。我只是尝试将一个类(或甚至struct)声明为一个单独的Swift文件,然后构建它或在一个单独的类中使用它。考虑一下:
import Foundation
class PayloadTest{
var label: String
init(label:String) {
self.label = label
}
}
----然后分开文件
import WatchKit
import Foundation
class InterfaceController2: WKInterfaceController {
var payloadtest = PayloadTest(label: "test string init")
payloadtest.label = "test" // this line gives error - says it was expecting a declaration
.
.
.
}
我无法弄清楚为什么如果我在watchOS扩展中的同一级别创建一个类或结构,当我尝试访问变量时,不允许访问或识别它。
答案 0 :(得分:2)
如评论部分中提到的 dfd ,这是一个范围问题。在许多编程语言中,您只能编写语句(表达式),这些语句不是声明或初始化,也不是函数或方法之外的方法调用。
让我解释一下我说的话,
在类或结构定义中,除声明和声明之外的任何语句(表达式)。初始化应该存在于函数(方法)定义中。
class PayloadTest{
//The below statement is declaration, which declares label is an property of type string.
var label: String
init(label:String) {
//The below statement is an assignment, and it compiles and execute fine as this is inside a init method.
self.label = label
}
}
然而,在你的第二个片段中,
导入WatchKit 进口基金会
class InterfaceController2: WKInterfaceController {
//The below statement compiles fine even tough it isn't present inside a method coz it is initialization statement.
var payloadtest = PayloadTest(label: "test string init")
//However the compiler complains about the below assignment statement because, this is neither an declaration nor an initialization statement and it should not be outside method.
//So you've to keep this statement inside a method for compiler to stop complaining.
payloadtest.label = "test" // this line gives error - says it was expecting a declaration
....
}
要使第二个代码段工作,请将以下代码行放在方法中并调用该方法
payloadtest.label = "test"
所以请记住除声明之外的任何声明,初始化应该存在于方法或函数定义中,这适用于大多数语言。
请仔细阅读目前的各种范围。 HTH:)
答案 1 :(得分:1)
你不能在这样的类中嵌套表达式。您可以通过将代码放入一个您立即调用的闭包中来解决这个问题:
class InterfaceController2:WKInterfaceController {
var payloadtest = {
let pt = PayloadTest(label: "test string init")
pt.label = "test"
return pt
}()
答案 2 :(得分:1)
您可以尝试在函数中移动该代码。 (Swift 3.0版)
class InterfaceController: WKInterfaceController {
var payloadtest = PayloadTest(label: "test string init")
fileprivate func test() {
payloadtest.label = "test" // tape this line in a function
}
}
答案 3 :(得分:0)