Search code examples
swiftclasswatchos

Class Declaration and Usage


Newbie question. I am simply trying to declare a class (or even struct) as a separate Swift file and then build it or use it inside a separate class. Consider this:

import Foundation

class PayloadTest{
    var label: String
    init(label:String) {
          self.label = label
    }
}

---- then separate file

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
    .
    .
    .
}

I can't figure out why if I make a class or struct at the same level in my watchOS extension, it is not allowed to be accessed or recognized when I try to access the variables.


Solution

  • As dfd mentioned in the comment section this is a scope issue. In many programming languages you just can't write statements (expressions) which is not either a declaration or initialization or a method call outside the function or a method.

    Let me explain what I said,

    In a class or a structure definition any statements(expressions) apart from declaration & initialization should be present in the function (method) definition.

    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
      }
    }
    

    However in your second snippet,

    import WatchKit import Foundation

    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
    ....
    }
    

    To make the second snippet work put the below line of code in a method and call that method,

    payloadtest.label = "test"
    

    So always remember any statements apart from declaration, initialization should be present inside a method or function definition and this applies to most of the languages.

    Please go through the various scope levels present. HTH :)