I'm not that much into structs. Can you point me in the right direction?
Sure. To continue my previous example, here’s how I’d define a struct to hold all the info for a given knight.
struct Knight {
var name: String
var question: String
var answer: String
}
Here’s how I’d set up an array of those:
let knights: [Knight] = [
Knight(name: "Lancelot", question: "favourite colour", answer: "blue"),
Knight(name: "Robin", question: "capital of assyria", answer: "I don't know that"),
Knight(name: "Galahad", question: "favourite colour", answer: "blue no yellow"),
Knight(name: "Arthur", question: "airspeed velocity of an unladen swallow", answer: "african or european?")
]
and here’s how to get a sorted array from that:
let sortedKnights = knights.sorted(by: { (lhs, rhs) -> Bool in
return lhs.name < rhs.name
})
If you’re starting off with multiple parallel arrays (for example, because that’s how the data is store in a file on disk), it’s relatively straightforward to build your array of structures from those arrays:
let names = ["Lancelot", "Robin", "Galahad", "Arthur"]
let questions = ["favourite colour", "capital of assyria", "favourite colour", "airspeed velocity of an unladen swallow"]
let answers = ["blue", "I don't know that", "blue no yellow", "african or european?"]
let knights = (0..<names.count).map { index in
return Knight(name: names[index], question: questions[index], answer: answers[index])
}
Structs are a critical part of any Swift app — for example, the bulk of the functionality in the Swift standard library is exposed via structs — so it’s really important that you get to know them. They are discussed in depth in The Swift Programming Language, and presumably all other tutorial introductions to Swift.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"