1

With this Swift 3.0 lines:

struct Person {
    var name: String
    var surname: String
    var phone: Int
    var isCustomer: Bool
}
var contacts: [Person] = []
contacts.append(Person(name: "Jack", surname: "Johnson", phone: 2, isCustomer: false))
contacts.append(Person(name: "Mike", surname: "Morris", phone: 3, isCustomer: true))

I have created an array that includes two structures which include 4 variables each. I can print a single object of the array like this: print(contacts[0].name) but is there any way to print all the Strings of the name section at once?

3 Answers 3

6

Learn how to use map. I use it all the time.

print(contacts.map({ $0.name }))

Search for map in this Apple Documentation about Closures

Sign up to request clarification or add additional context in comments.

1 Comment

I think using forEach as par is using in the other answer is better. since you don't want to create a new variable, rather you just want to do something. Also for learning about closures and higher order functions I find this tutorial to be of the best.
2

You'll have to iterate over the array, either printing the values as you go, or capturing them into a string and printing them all at once.

Here's one way:

for contact in contacts {
    print(contact.name)
}

Here's another:

contacts.forEach { print($0.name) }

Finally, you could join all the strings into one value with a separator and just print once. When you do it this way the joinWithSeparator function iterates the array for you:

let names = contacts.map { $0.name }
let joinedNames = names.joinWithSeparator(" ")

print(joinedNames)

Comments

2

You should implement the protocol CustomStringConvertible by defining the computed property description:

struct Person: CustomStringConvertible {
    var name: String
    var surname: String
    var phone: Int
    var isCustomer: Bool

    var description: String { 
        return
            "Name: \(name)\n" + 
            "Surname: \(surname)\n" +
            "Phone: \(phone)\n" +
            "Is Customer? \(isCustomer)\n"
    }
}

And then:

var contacts: [Person] = []
contacts.append(Person(name: "Jack", surname: "Johnson", phone: 2, isCustomer: false))
contacts.append(Person(name: "Mike", surname: "Morris", phone: 3, isCustomer: true))
print(contacts)

Obviously you can define description as you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.