[Swift]: Learning 3

swift

04/17/2019


Tuples

Tuple is grouping of values. Useful when returning multiple values from a func

SWIFT
let x: (w: String, i: Int, v: Double) = ("hello", 10, 0.2)
print(x.w) // prints hello
print(x.i) // prints 10
print(x.v) // prints 0.2
let (wrd, num, val) = x // renames tuple's elements

Other way of declaring (NOT preferred way)

SWIFT
let x: (String, Int, Double) = ("hello", 10, 0.2)
let (word, number, value) = x
print(word)
print(number)
print (value)

Tuples as return value

SWIFT
func getSize() -> (weight: Double, height: Double) {return (250,80)}

To access the return value

SWIFT
let x = getSize()
print("weight: \(x.weight)") // weight: 250

OR

SWIFT
print("height: \(getSize().height)") // height: 80

Playing sound by using AVAudioPlayer

1) make sure that the desired file is properly imported in navigation pane

you can drag & drop file and make a reference to the file. Otherwise, you can go to Project -> Project Build Phases -> Copy Bundle Resources and add folder into it

2) import the framework

SWIFT
import AVFoundation

3) Create an instance variable

SWIFT
var audioPlayer: AVAudioPlayer?
SWIFT
override func viewDidLoad() {
super.viewDidLoad()
do {
if let fileURL = Bundle.main.path(forResource: "fileName", ofType: "mp3") {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileURL))
} else {
print("No file with specified name exists")
}
} catch let error {
print("\(error.localizedDescription)")
}
}

Put in desired fileName with an extention. Bundle API will find the path and pass it into audioPlayer.

5) Play music once

SWIFT
audioPlayer?.play()

Example:

SWIFT
@IBAction func touchCard(_ sender: UIButton){
audioPlayer?.stop()
audioPlayer?.currentTime = 0
audioPlayer?.play()
}

In Concentration, audio plays every time user touches a card. Having audioPlayer?.play() by itself, won't let it play multiple times at once

+

SWIFT
audioPlayer?.stop()

stops the music

SWIFT
audioPlayer?.numberOfLoops = 0

value 0 plays it once (default) 1 plays it twice -1 plays it continuously


WRITTEN BY

Keeping a record