1

When I want to change a string to URL, I'm getting this error:

"Cannot use instance member 'haberUrl' within property initializer; property initializers run before 'self' is available."

What should I do?

var haberUrl = String()
var newsUrl = URL(String: haberUrl) //error in here
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • Beside your error: `var haberUrl = [String]()`: So `haberUrl` is an array of String objects. `URL(String: haberUrl)` That won't work, because `haberUrl` is not a String object, it's an array of String objects. – Larme Jan 15 '18 at 13:08
  • i change it but not work –  Jan 15 '18 at 13:13
  • As I said, that's another issue when you would have fixed your current problem. Now, you need to show more code, where is it written? The error: https://stackoverflow.com/questions/44648388/cannot-use-instance-member-server-within-property-initializer – Larme Jan 15 '18 at 15:29

2 Answers2

1

I can see two mistakes here :

  • haberUrl is an Array, convert it to String instead of [String]()
  • The URL constructor from string is URL(string: String), so it should be var newsUrl = URL(string: haberUrl)
CZ54
  • 5,488
  • 1
  • 24
  • 39
1

As the warning says, you can't reference another property in the instance when setting up a property - the object itself isn't initialised yet. Fortunately, in this case, it looks like you're setting the properties to default values. Just use a literal for the value you want for newsUrl (eg, URL(string: http://example.net)).

As an aside, given that haberUrl is an array of String, this would never have worked (URL expects a single string).

Adam Wright
  • 48,938
  • 12
  • 131
  • 152