Search code examples
iosswiftwatchkitapple-watch

Make a Data Class with Swift in Watchkit Target


As simply using the sharedApplication() method is unavailable in WatchKit, utilizing the AppDelegate as a way to store data for all my interfaces/views is no longer an option in WatchKit. Is there an alternative method to do this in swift for WatchKit apps? I have tried making a singleton class like so:

import Foundation

import UIKit

class data: NSObject {
class var sharedInstance : data {
    struct Example {
        static let instance = data()
    }
    return Example.instance
}

var value:Int = 0
var increment:Int = 1

}

(This code is from another StackOverflow post, I just forgot the link.) I then try and access the Integer "value" by calling data.value in an interface controller but I get the error 'data.Type' does not have a member named 'value'. How can I fix this error? Or is there a better way to do what I am trying to achieve?

Thanks


Solution

  • The code data.value attempts to access a class variable or method on the class data called value. Since no such variable or method exists you get the error message.

    In your definition value is defined as a property on the class data, so to use it you need a valid instance of data. Your sharedInstance method provides the instance.

    Also, the convention in Swift is to capitalize class names, so I recommend using Data.