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

Jared Feingold
Jared Feingold
316 Points

Struct within a struct

How exactly do you create a struct so that it contains another struct as one of its properties?

structs.swift
struct Tag {
  let name: String
}

struct Post {
  var title: String
  var author: String
  let tag: Tag()
}

let firstPost = Post(title: "hi", author: "Jeff")

2 Answers

Rogier Nitschelm
Rogier Nitschelm
iOS Development Techdegree Student 5,461 Points

You are almost there. When you specify a variable with a type you should put the type after the :

let tag: Tag = Tag(name: "some tag")

Or you could just let swift infer the type:

let tag = Tag(name: "some tag")
Scott Ho
Scott Ho
288 Points

struct Tag { let name: String }

struct Post { var title: String var author: String let tag: Tag /<<<******/ }

let tag = Tag(name: "drop the ()") let firstPost = Post(title: "Hi", author: "Jeff", tag: tag)