1

I created a class in Swift like below, but it gives error:

'ApiUrls.Type' does not have a member named 'webUrl'

Here is my code:

import UIKit

class ApiUrls {

    let webUrl:NSString = "192.168.0.106:8888"
    var getKey:NSString = webUrl + NSString("dev/sys/getkey") // here comes the error ApiUrls.Type' does not have a member named 'webUrl

}

What's wrong in it?

halfer
  • 19,824
  • 17
  • 99
  • 186
Qadir Hussain
  • 8,721
  • 13
  • 89
  • 124

2 Answers2

5

You cannot initialize an instance property with the value of another property, because self is not available until all instance properties have been initialized.

Even moving the properties initialization in an initializer doesn't work, because getKey relies on webUrl, so getKey cannot be initialized until itself is initialized.

I see that webUrl is a constant, so maybe it's a good idea to make it a static property - classes don't support statics as of yet, so the best way is to use a private struct:

class ApiUrls {
    private struct Static {
        static let webUrl: String = "192.168.0.106:8888"
    }

    var getKey: String = Static.webUrl + "dev/sys/getkey"

}

Also, unless you have a good reason, it's better to use swift strings and not NSString.

Antonio
  • 71,651
  • 11
  • 148
  • 165
0

As far as I know, you cannot initialise variables like that in the class definition.

Try declaring your variables as

let webUrl:NSString = "192.168.0.106:8888"
var getKey:NSString = ""

and add this in viewDidLoad

getKey = webUrl + NSString("dev/sys/getkey")
Rajeev Bhatia
  • 2,974
  • 1
  • 21
  • 29