drewpts
drewpts

Reputation: 446

Why I can not interpolate string inside class definition?

I can not do such thing inside class definition:

let parametersForFeedRequest = "?fields=type,id,created_time,description&limit="+"\(self.postsPerScreen)"

but code like this:

let parametersForFeedRequest = "?fields=type,id,created_time,description&limit="+"\(25)"

compiling well. Why?

btw: parametersForFeedRequest is class value-member.

Here is the code in the class (moved from the comments):

class FbFeedViewController: UITableViewController, FBSDKLoginButtonDelegate {
    @IBOutlet weak var menuButton:UIBarButtonItem!
    let postsPerScreen = 25
    let parametersForFeedRequest = "?fields=type,id,created_time,description&limit="+"\(self.postsPerScreen)"
}

Upvotes: 0

Views: 72

Answers (1)

vacawama
vacawama

Reputation: 154631

self.postsPerScreen is not available at class instantiation time (because self isn't defined until the instance has been initialized). So, you can't define one property using the value of another. To get around this you have a few different choices:

  1. You could assign parametersForFeedRequest in an initializer.

  2. You can use the keyword lazy to set up a closure that will initialize your property the first time it is accessed:

    lazy var parametersForFeedRequest: String = {return "?fields=type,id,created_time,description&limit="+"\(self.postsPerScreen)"}()
    

    By the time you access the property, the instance will be initialized and self will be available. This will only initialize the property once.

  3. You can define a computed property that will run each and every time you access the property:

    var parametersForFeedRequest:String {return "?fields=type,id,created_time,description&limit="+"\(self.postsPerScreen)"}
    

Upvotes: 1

Related Questions