Search code examples
swiftvariablessyntax-errorstring-concatenation

Instance Member API_KEY can not be used on type 'DataType'


I'm assigning some variables at the start of my class and I get the error (Instance Member API_KEY can not be used on type 'DataType') and (Instance Member LANG can not be used on type 'DataType') when creating the baseURL variable. But why?

class DataManager{
    let LANG: String = NSLocale.preferredLanguages()[0].substringToIndex(NSLocale.preferredLanguages()[0].startIndex.advancedBy(2))
    let DATE = NSCalendar.currentCalendar().component([.Day, .Month, .Year], fromDate: NSDate())
    let API_KEY: String = "astringgoeshere"
    let BASE_URL: String = ("http://api.colnect.net/" + LANG + "/api/" + API_KEY + "/")
    let CAT_STAMPS: String = ("cat/stamps/")
}

Solution

  • The value of BASE_URL depends on other properties (LANG and API_KEY) which causes the error. A solution is to declare BASE_URL as computed property

    var BASE_URL: String {
      return "http://api.colnect.net/" + LANG + "/api/" + API_KEY + "/"
    }