big.nerd
big.nerd

Reputation: 375

Swift 3 - Proper way to store values, tuple, arrays, other?

I am working on a small project where I am playing a list of available MP3's which are embedded into my application - An educational app.

I've tried my hardest to find an answer but I can't seem to find something that fits, so my usual thing - if this is a duplicate I've searched my hardest to find something first.

The MP3's are named so that they coincide with 5 Units of 30 Chapters each.

I am trying to find a way to store and retrieve the correct chapter, similar to:

Learning Unit # Chapter ##.mp3

I am wondering what the best way to store and/or call the correct Unit and Chapter.

I am currently using two Table Views to select the Unit# and the Chapter/Lesson#.

That data is being passed to the view which plays the required MP3, so I am passing two variables, both Int's.

What I have tried here, which I realize is COMPLETELY WRONG, should illustrate what I am trying (hopefully) to do:

import Foundation

class LessonPlan {

var lessonMatrix = [(unit:Int,chapter:Int,filename:String)];

init() {
    for unitNo in 1 ... 5 {

        for chapterNo in 1 ... 30 {
            chapterWithLeadingZeros = String(format: "%02d", chapterNo)
            lessonMatrix.append(unit:unitNo, chapter:chapterNo, filename:"Learning Unit \(unitNo) Chapter \(chapterWithLeadingZeros).mp3")
            }
        }


    }
}

I realize the above doesn't compile, but its my thought process.

Thank you for any direction you can provide.

Swift3 / Xcode 8.3.1, Trying to target iOS9.

Upvotes: 0

Views: 73

Answers (1)

Alexander
Alexander

Reputation: 63399

This is how I would do this:

import Foundation

struct Lesson {
    let unit: Int
    let chapter: Int

    var chapterWithLeadingZeros: String { return String(format: "%02d", chapter) }

    var filename: String { return "Learning Unit \(unit) Chapter \(chapterWithLeadingZeros).mp3" }
}

class LessonPlan {
    var lessons = (1...5).flatMap { unit in
        (1...30).flatMap { chapter in
            Lesson(unit: unit, chapter: chapter) 
        }
    }
}

print(LessonPlan().lessons)

Upvotes: 1

Related Questions