Passing structures between ViewControllers

I have a structure in one ViewController as shown. How can I pass this to the next ViewController via a segue? Do I have to declare the structure in the second VC as well?

    struct articles : Decodable {
    
        let source : sourceDetails
        let author : String?
        let title : String?
        let description : String?
        let url : String?
        let urlToImage : String?
        let publishedAt : String?
        let content : String?
   }

struct sourceDetails : Decodable {
    
    let id : String?
    let name : String?
}

Structs such as you show here don't normally "belong" to a ViewController, they should be declared on their own in their own files.

Also, because structs are types, not instances, their names should start with an uppercase letter.

And, since your first type describes a single article, its name should equally reflect that singularity.

// Article.swift
struct Article : Decodable
{    
  let source : SourceDetails
  let author : String?
  let title : String?
  let description : String?
  let url : String?
  let urlToImage : String?
  let publishedAt : String?
  let content : String?
}
// SourceDetails.swift
struct SourceDetails : Decodable
{
  let id : String?
  let name : String?
}

As to passing an instance of a struct between ViewControllers, you need to look at overriding the prepare(for:sender:) method of the sending ViewController.

Alright. Thank you for your help. I will look into that.

You should also look at implementing Codable rather than Decodable, unless you never plan on encoding your structs.

Terms of Service

Privacy Policy

Cookie Policy