iOS Build a Simple iPhone App with Swift Getting Started with iOS Development Swift Recap Part 1

How do I initialize the property "tag"

struct Tag { let name: String }

struct Post { var title: String var author: String var tag: Tag init(title: String, author: String, tag: Tag) { self.title = title self.author = author self.tag = Tag(name: name) }

}

let somePost = Post(title: "p", author: "p", tag: Tag)

structs.swift
struct Tag {
  let name: String
}

struct Post {
    var title: String
  var author: String 
  var tag: Tag

}

2 Answers

Structs in swift have default initializers. You can initialise it the same way as you did with the post, it wood look like this:

struct Tag {
    let name: String
}

struct Post {
    var title: String
    var author: String 
    var tag: Tag
}

let tag = Tag(name: "some tag 1")
let firstPost = Post(title: "First Post", author: "author 1", tag: tag) 

// you can also do it directly
let secondPost = Post(title: "Second Post", author: "author 2", tag: Tag(name: "some tag 2")) 

This is what the initialiser really looks like:

struct Tag {
    let name: String

    init(name: String) {
        self.name = name
    }
}

struct Post {
    var title: String
    var author: String 
    var tag: Tag

    init(title: String, author: String, tag: tag) {
        self.title = title
        self.author = author
        self.tag = tag
    }
}
Ryan Sady
Ryan Sady
20,594 Points

Like stated above, Structs in Swift have 'default' initializers. If you don't declare an initializer within your struct the compiler does it for you based on your declared properties. If you have optional properties or want to do certain logic in your initializer you can manually declare one and perform your logic and initialize your properties.