Swift 2 and iOS9 is here! Whats new?

I have been away for a long time, trying to fit my day job and learning Swift at once. Its been one long, arduous journey. I am not specifically known for my consistency when doing something. So one of my friends suggested a log, a very public one to keep me honest. That was the idea of this blog – the whole “how a I learned swift”, specially with a non-developer, non-Object oriented programming background. And frankly, I need to be more consistent with this.

In the meantime, Apple had their annual WWDC yesterday. As expected, they have announced the next big Programming update. Swift 2 and iOS9 are here!

So whats new in Swift 2? Here’s a highlight list:
– Recursive Nested functions
– Swift 1.2 to 2.0 Migrator
– Improved option sets
– Markdown in comments
– Faster Debug modes
– Objective – C generics
– Error handling model
– C Function pointer APIs
– Availability checking
– Shorter compiler time
– Mutability warnings
– Pattern matching in “if”
– Multi pay load Enums
– New Playground
– do {} –> The “do” loop.
– Parallelized WMO
– @testable –> To help with testing codes within Xcode
– Protocol extensions
– Faster runtime
– defer
– Nullability in Objective C
– Synthesized “headers” in Xcode
– quard
– SIMD support

Now this a rather long list! I will try and update this page as and when I come to know about more changes.

As I am still a student, the importance of some of these might be lost on me. I will try and learn some example code and update the list with specific examples. Wish me luck!

Playground – First step in learning swift programming for iOS8

REPL or a “Read–eval–print loop” in layman terms is an environment where you can see your code results realtime. Its pretty interactive and prints the output as you type out your code. Think of something like terminal inputs on MacOSX (or command line in Windows).

Once you type in a “command”, say “ls”(list) and hit return:
1. Terminal reads the command “ls”
2. Evaluates the list of folders in the current directory
3. Prints the output on screen

This way, you are able to get instant feedback of things you are doing. Cool, right!

Now over the last few weeks, I have spent a lot of time looking for tutorials on Swift and iOS8 programming. These include:

1. Standford’s Developing iOS 8 Apps with Swift,
2. Udacity’s iOS Developer nano degree,
3. BitFountain’s The Bitfountain iOS 8 with Swift Immersive

to name a few. If you are like me and have attended some of the other online programming courses, you might have noticed something. Most of these courses dive head first into creating a single view app. They tend to assume (Stanford’s one states it clearly) that you have some sort of programming experience. But if you are like me, you would rather see and understand the language before jumping into an app. So wouldn’t it be great if we had an interactive shell?

Enter Playground

Playground was introduced during WWDC2014 (you can watch the videos here). It is a rather powerful tool which can you get familiar with the swift programming syntax.

So lets get right to it. Open Xcode (6.1.1) and click “Get started with a Playground”:
Get started with a Playground

Name your playground file and create it on your folder.

The playground gets initiated with the obligatory – “Hello World” using a string variable and comment statement. And you will be able to see the output on the right pane.
Hello World

You can try typing the print statement out:
Print Hello World

You can also do the Option + Click to show information on any components, like variables:
Variable check
or a function:
Check function

Command + clicking a variable will show you all the instances of the variable:
show all instances

Tip: Command + clicking brings out a down black arrow. There you can select “Edit all in scope”. This will allow you to rename all the variables within the code. This can be used while writing swift code too.

Even the errors are shown at realtime:
error in playground

Go ahead and try all the syntax you might have learned from other languages. See if it works and enhances your understanding of Swift.
Or go ahead writing a small code and see how it executes in Swift, it might just provide a valuable lesson.

Sound effects using AVAudioEngine

This post is a followup on the lesson 3b end exercise on the Udacity course, I discussed in my last post. Here’s the link:

https://www.udacity.com/course/ud585

We will also use this opportunity to trim down our final code.

Step1: Checking AVFoundation Framework

In iOS, all the audio visual media is contained within this framework. So it goes to reason that if there were any ways to change the rate, it should be contained here.

On searching through the framework, I found there were class to change the rate called AVAudioUnitTimePitch and AVAudioUnitVarispeed. Both the classes, have a property called rate which can be used for our purpose.

AVAudioUnitVarispeed is much closer in implementation to the AVAudioPlayer rate property but has a larger range – 0.25 to 4.0.

On the other hand AVAudioUnitTimePitch, not only has rate the range is much wider 1/32 (0.03125) to 32. It also has the pitch property which will be handy for doing other voice effects. Combining both the pitch and rate can lead to various others effects too.

Step2: Using AVAudioUnitTimePitch

If you were to google for an example code for AVAudioUnitTimePitch, you will end up on this stackoverflow page:

http://stackoverflow.com/questions/25333140/swift-using-sound-effects-with-audioengine

Now the example is about how to change the pitch of a sound:

//Audio Engine is initialized in viewDidLoad()
audioEngine = AVAudioEngine()

//The following Action is called on clicking a button
@IBAction func chipmunkPlayback(sender: UIButton) {
var pitchPlayer = AVAudioPlayerNode()
var timePitch = AVAudioUnitTimePitch()

timePitch.pitch = 1000
audioEngine.attachNode(pitchPlayer)
audioEngine.attachNode(timePitch)

audioEngine.connect(pitchPlayer, to: timePitch, format: myAudioFile.processingFormat)
audioEngine.connect(timePitch, to: audioEngine.outputNode, format: myAudioFile.processingFormat)

pitchPlayer.scheduleFile(myAudioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(&er)
pitchPlayer.play()
}

Notable part is the implementation of the pitch property. As rate is also a property, replacing “pitch” with “rate” should work. So my new code is:

var audioEngine: AVAudioEngine!
var audioFile: AVAudioFile!

override func viewDidLoad() {
super.viewDidLoad()

if var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3") {
var filePathURL = NSURL.fileURLWithPath(filePath)
audioEngine = AVAudioEngine()
audioFile = AVAudioFile(forReading: filePathUrl, error: nil)
}

@IBAction func playSoundSlowly(sender: UIButton) {

var audioPlayerNode = AVAudioPlayerNode()

audioPlayerNode.stop()
audioEngine.stop()
audioEngine.reset()

audioEngine.attachNode(audioPlayerNode)

var changeAudioUnitTime = AVAudioUnitTimePitch()

changeAudioUnitTime.rate = 0.5
audioEngine.attachNode(changeAudioUnitTime)
audioEngine.connect(audioPlayerNode, to: changeAudioUnitTime, format: nil)
audioEngine.connect(changeAudioUnitTime, to: audioEngine.outputNode, format: nil)
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(nil)

audioPlayerNode.play()
}

Step3: Building a common function

We can now build a common function to play both the slow and fast sound effects form a single function:

var audioEngine: AVAudioEngine!
var audioFile: AVAudioFile!

override func viewDidLoad() {
super.viewDidLoad()

if var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3") {
var filePathURL = NSURL.fileURLWithPath(filePath)
audioEngine = AVAudioEngine()
audioFile = AVAudioFile(forReading: filePathUrl, error: nil)
}

@IBAction func playSoundSlowly(sender: UIButton) {
commonAudioFunction(0.5)
}
@IBAction func playSoundFast(sender: UIButton) {
commonAudioFunction(1.5)
}

func commonAudioFunction(audioChangeNumber: Float){
var audioPlayerNode = AVAudioPlayerNode()

audioPlayerNode.stop()
audioEngine.stop()
audioEngine.reset()

audioEngine.attachNode(audioPlayerNode)

var changeAudioUnitTime = AVAudioUnitTimePitch()

changeAudioUnitTime.rate = audioChangeNumber
audioEngine.attachNode(changeAudioUnitTime)
audioEngine.connect(audioPlayerNode, to: changeAudioUnitTime, format: nil)
audioEngine.connect(changeAudioUnitTime, to: audioEngine.outputNode, format: nil)
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(nil)

audioPlayerNode.play()

}

Step 4: Robust end code

If you have completed the course, you will now have added the chipmunk and Darth Vader effect too. As both of those functions use the class, we can expand the common function to do more.

This also takes care of a bug which gets introduced due to using AVAudioPlayer and Engine separately:

var recievedAudio: RecordedAudio!
var audioEngine: AVAudioEngine!
var audioFile: AVAudioFile!

override func viewDidLoad() {
super.viewDidLoad()
audioEngine = AVAudioEngine()
audioFile = AVAudioFile(forReading: recievedAudio.filePathUrl, error: nil)
}

@IBAction func playSoundSlowly(sender: UIButton) {
commonAudioFunction(0.5, typeOfChange: "rate")

}

@IBAction func playSoundFast(sender: UIButton) {
commonAudioFunction(1.5, typeOfChange: "rate")
}

@IBAction func stopAudio(sender: UIButton) {
audioEngine.stop()
audioEngine.reset()

}

@IBAction func PlayChipmunkAction(sender: UIButton) {
commonAudioFunction(1000, typeOfChange: "pitch")
}

@IBAction func PlayDarthVaderAction(sender: UIButton) {
commonAudioFunction(-1000, typeOfChange: "pitch")
}

func commonAudioFunction(audioChangeNumber: Float, typeOfChange: String){
var audioPlayerNode = AVAudioPlayerNode()

audioPlayerNode.stop()
audioEngine.stop()
audioEngine.reset()

audioEngine.attachNode(audioPlayerNode)

var changeAudioUnitTime = AVAudioUnitTimePitch()

if (typeOfChange == "rate") {

changeAudioUnitTime.rate = audioChangeNumber

} else {
changeAudioUnitTime.pitch = audioChangeNumber
}
audioEngine.attachNode(changeAudioUnitTime)
audioEngine.connect(audioPlayerNode, to: changeAudioUnitTime, format: nil)
audioEngine.connect(changeAudioUnitTime, to: audioEngine.outputNode, format: nil)
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(nil)

audioPlayerNode.play()

}

Starting Bell

I recently completed a good introductory class on iOS, courtesy of Udacity:

https://www.udacity.com/course/ud585

You get to learn and design a live app, which I think is an excellent way to learn something. I would recommend anyone starting with iOS programming to go over this course. But it comes with a caveat…..

Objective Oriented Programming (OOP)

Though the course is basic in nature, if you are not attuned to objective oriented programming (OOP) concepts, it might prove little daunting. In that case, check out some basic tutorials on Java programming. Just the basic level stuff like classes, instance, objects, initialization, setter, getter etc. will be enough.

These will be required to actually be able to understand and write swift/iOS code. After all, it is heavily inspired from Objective C.

Using Google/stackoverflow

Using online resources effectively is one of the pre-requisite to being a good programmer. But once you are online, things do take a different colour. While google is your friend if you are stuck on some parts, you will find some pages which confuse you to no end. Its always better to copy the code verbatim and see what it does in real time. This again might be an issue if you see a code in Objective C and try to copy it into Swift. So, it better to suffix everything with “in swift”. That will be give you a good starting point.

Coming to stackoverflow, it is a treasure trove of information on programming. That said, it has down sides to it. Beginners like us, tend to be flamed a bit. You will find your questions which might be a genuine one be marked down. So use it wisely and specially if you can not be deterred from your learning path easily.

Create your own website, free on WordPress.com.Create your own website.
Start free