Swift 5 - Argument passed to call that takes no arguments

Viewed 3104

I am trying to pass data to a new view in my app, so that my script can plug the data into the link and fetch the respective article information. My view is being called with ArticleView(articleID: 0) though this changes with the ID of the article. The beginning of my view begins as such...

struct ArticleView: View {
   var articleID: Int
   @Envionment(.\imageCache) var cache: ImageCache
   @ObservedObject private var data = Result2()
   let defaults = UserDefaults.standard

   ...

   init() {
      self.data.results.append(Story.init(id: 0, title: "test", image: "", story: "", published: "", author: ""))
      self.loadArticle(CDNLink: "http://\(self.defaults.object(forKey: "domain") as! String)/cdn?funct=fetchArticle&articleID=\(self.articleID)")
   }

What I am trying to understand is how do I get the article id from my dashboard to being stored in var articleID so my loadArticle function can then run the script and pull the content in? I can provide the information for Result2() along with the data structures for Response2 and Story upon request. Thanks!

1 Answers

You have 2 options:

  1. To ask for a parameter from initializer:
struct ArticleView: View {
    var articleID: Int
    ...

    init(articleID: Int) {
        self.articleID = articleID

        // Do whatever you need
    }

    var body: some View {
        SomeView()
    }
}
  1. Omit initializer and put all you need in .onAppear clause
struct ArticleView: View {
    var articleID: Int
    ...

    var body: some View {
        SomeView()
            .onApppear {
                // Do whatever you need
            }
    }
}

In second case the compiler will create an initializer automatically with all values needed (in your case - articleID)

Related