The exercise was: For further practice, extend the Song struct below by adding a isLongerThan method. You can paste your code from page 6 as a starting point. Then use a loop to find the longest song in the array and print it to the console. (Hint: use a variable to keep track of the longest song and initialize it to the first one in the array.)
I've created this code to find out the longest song in my array:
struct Song {
let title: String
let artist: String
let duration: Int //seconds
/* Code from page 6 here, plus the new method */
var formattedDuration: String {
let minutes = duration / 60
// The modulus (%) operator gives the remainder
let seconds = duration % 60
return "\(minutes)m \(seconds)s"
}
}
let songs = [
Song(title: "Ooh yeah", artist: "Brenda and the Del-chords", duration: 90),
Song(title: "Maybe", artist: "Brenda and the Del-chords", duration: 200),
Song(title: "No, no, no", artist: "Fizz", duration: 150),
Song(title: "Makin' up your mind", artist: "Boom!", duration: 440)
]
var index = 0
var max = songs[0].duration
for i in 0 ... songs.count - 1 {
if songs[i].duration > max {
max = songs[i].duration
index = i
}
}
print("The longest song has a duration of \(max) seconds and this is a song number \(index) in the array")
print("This is " + songs[3].formattedDuration)
Tell me please if I did it right and are there any other options to do this exercise? :)
Yes, it is OK.
Except the last:
print("This is " + songs[3].formattedDuration)
You should write:
print("This is " + songs[index].formattedDuration)
Note: even though it has no importance here as you know songs has some items, in general, it is safer to test:
if songs.count > 0 {
var max = songs[0].duration
for i in 0 ... songs.count - 1 {
You can also retrieve the song directly, without need for intermediate index:
if songs.isEmpty {
print("You have no song in the playlist")
} else {
var max = 0
var theSong = songs[0]
for song in songs {
if song.duration > max {
theSong = song
}
}
print("The longest song lasts for \(theSong.duration) seconds and its title is \(theSong.title).")
print("This is " + theSong.formattedDuration)
}