Skip to content

Learning iOS’s Swift, for JavaScripters

I recently blitzed through the Treehouse Swift course (referral link) and was quite a bit surprised at how familiar it was writing Swift as a person who mostly writes JavaScript. You can probably skip this post and read through the X in Y minutes for Swift to believe me, but here are the larger points I noticed.

  1. Super similar syntax Add an “unction” to that, and this is JavaScript. (okay, no println, but deal)
    func myFunction() {
      println("Does something")
    }
  2. Types! Types are implied, thus not required, but you may want them. For example, the above function would be signed:
    func myFunction() -> Void {
      println("Does something")
    }

    with a designated return signature. I really like that -> probably because I just spent a bunch of time learning Scala.

    func addNumbers(a:Int, b:Int) -> Int {
      return a + b
    }
  3. Mutability vs. Immutability You get it all! Choose whether your data is stored as a mutable or immutable value.
    let fruits = ["apple", "pear", "orange"] // immutable array (and arrays in Swift must be the same type)
    var todaysBreakfast = fruits[0] // mutable variable
  4. Structs Feels like an object literal to me
    struct CoolClassLikeThing {
        let property = 2
        func tellMeSomething() -> Int {
            return self.property
        }
    }
    
    var x = CoolClassLikeThing()
    x.tellMeSomething()
    

    Maybe it’s just me, but declaring a struct felt a hell of a lot like the OO pattern for writing object literals. This is even how they’re laid out in the IDE for completion:

    Swift struct definition

    Property/value pairs all the way down, my friends.

    Structs and classes in Swift are highly related, with a class having a bit more power than a struct.

  5. Go play!
    File navigation to make a playgroundFrom the stance of learnability, it’s pretty great that you can open a “playground” to start messing around and see how things work (it’s how I wrote the examples here to make sure they work!). Reminds me of Scala worksheets 🙂

Other cool things that aren’t necessarily related to JavaScript: Closures, Optionals, Enums, and more.

Have you tried Swift? Disagree vehemently with me? Tell me why!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.