Trouble with Struct Challenge

I seem to be completely lost now when it comes to implementing structures. I was given what seems like a very simple task in an online course and I'm somehow not able to figure out the answer to the chalenge:

"Given the struct below in the editor, we want to add a method that returns the person’s full name. Declare a method named fullName() that returns a string containing the person’s full name. Note: Make sure to allow for a space between the first and last name."

struct Person {
    let firstName: String
    let lastName: String
}

I wrote the following in my Swift Playground, which isn't giving the desired result:

struct Person {
    let firstName: String
    let lastName: String
 
  func fullName() -> String {
    return (firstName) + "" + (lastName)
}
  
}

let aPerson = Person(firstName: "Helga", lastName: "Strompf")

Could someone please let me know where I'm going wrong and how to complete this challenge? I've been looking at it now for a week and just seem to be lost for whatever reason. Please help. Thank you.

+ doesn't add any extra character, it'll simply concatenate strings.

So you need " " instead of "" (note the space). That is:

func fullName() -> String {
  firstName + " " + lastName
}

Thank you, that was a typo, there's actually a space in the Playground code. With (or without) the space, it doesn't return the desired output.

I tried using Person.fullName(), but I cannot figure out what to put in the placeholder text that Swift provides. When I type Person.fullName(), Swift offers the following as placeholder text:

Person.fullName(self: Person)

What do I type here to make it print the first and last name (with a space in between of course) of this struct?

You need to use the instance of the struct and not the type of the struct. Like this:

let aPerson = Person(firstName: "Helga", lastName: "Strompf")
aPerson.fullName()
1 Like

Thank you. I see where I made my mistake (finally).

No worries. We've all been there at some point. :slight_smile:

And Xcode makes it easy to do with illogical autocomplete, especially with variables that have the same name as a type.

1 Like