-2

I'm trying to declare a URL variable but it's giving me the error:

Cannot use instance member 'url' within property initializer; property initializers run before 'self' is available

I'm trying to create a hard coded data so it's fine to write is inside the array, is there a way to do so?

For example inside the array I have many strings "myString", can I do that with the URL?

This is my code:

class UserSalonViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    // This is the view to display all posts from all Authors
    @IBOutlet var allPostsTableView: UITableView!

//    var posts = [UserPosts]()

    let url = URL(string: "https://duckduckgo.com/")!

    var posts = [
        UserPosts(author: "Arturo", postTitle: "Hello World", postDescription: "First Post", postUrl: url, postAddress: "1 NW 1 ave")
    ]



    override func viewDidLoad() {
        super.viewDidLoad()

...

What can I do?

Arturo
  • 3,254
  • 2
  • 22
  • 61
  • Your `UserPosts` type appears to be misnamed. It only models a single post, so it should be `UserPost`. Additionally, the "post" predixes on `UserPosts(author:postTitle:postDescription:postUrl:postAddress:)` are redundant. Consider using simply `UserPost(author:title:description:url:address:)` – Alexander Nov 08 '19 at 21:13

1 Answers1

0

You can't use static initializers to initialize properties using other properties. While there are workarounds for this, it's better that you don't even bother, and just inline the value, like so:

var posts = [
    UserPosts(
        author: "Arturo",
        postTitle: "Hello World",
        postDescription: "First Post",
        postUrl: URL(string: "https://duckduckgo.com/")!,
        postAddress: "1 NW 1 ave"
    ),
]
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • @Arturo It also fits within most code style guides' rules about max line width (which is typically somewhere between 80 and 120), and it's easier to read :) – Alexander Nov 08 '19 at 21:16