Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Protocols in Swift Protocol Basics Conforming to a Protocol

Richard Pitts
PLUS
Richard Pitts
Courses Plus Student 1,243 Points

Unsure of what to differently when there is a get set versus just a get.

Unsure of what to differently when there is a get set versus just a get.

protocols.swift
protocol User {
  var name: String { get }
  var age: Int { get set }
}

struct Person {
  var name = "John"
  var age = 12
}

let somePerson = Person(name: "Johnny", age: 44)

1 Answer

Dan Lindsay
Dan Lindsay
39,611 Points

Hey Richard,

So the main difference(that I know of) between { get } and { get set }, is that when you have a class or struct that inherits from that protocol, the { get set } property cannot be a constant(let).

The two ways you can pass this challenge once your Person struct has adopted the User protocol are as follows.

First, use variables as the properties in the Person struct as follows:

struct Person: User {
    var age: Int
    var name: String
}

and for the second, use a constant for the get property, and a variable for the get set property, as seen below:

struct Person: User {
    let name: String
    var age: Int
}

but if you try this:

struct Person: User {
    let name: String
    let age: Int
}

it will fail, as age is a get AND set, while name is just get. To make it a bit more clear, if we think of a name for our Person, they will probably only be named one time, and that name will not change for the course of their life, so we just need to get their name. Their age, however, will change from year to year, so we must be able to get and set it.

Hope this helps!

Dan