Swift

Getting Started with Swift: A Brief Intro to the New Programming Language


Along with the announcement of iOS 8 and Yosemite, Apple surprised all developers in the WWDC by launching a new programming language called Swift. At AppCoda, we’re all excited about the release of Swift. We enjoy programming in Objective-C but the language has showed its age (which is now 30 years old) as compared to some modern programming languages like Ruby. Swift is advertised as a “fast, modern, safe, interactive” programming language. The language is easier to learn and comes with features to make programming more productive. It seems to me Swift is designed to lure web developers to build apps. The syntax of Swift would be more familiar to web developers. If you have some programming experience with Javascript (or other scripting languages), it would be easier for you to pick up Swift rather than Objective-C.

If you’ve watched the WWDC keynote, you should be amazed by an innovative feature called Playgrounds that allow you to experiment Swift and see the result in real-time. In other words, you no longer need to compile and run your app in the Simulator. As you type the code in Playgrounds, you’ll see the actual result immediately without the overheads of compilation.

At the time of this writing, Swift has only been announced for a week. Like many of you, I’m new to Swift. I have downloaded Apple’s free Swift book and played around with Swift a bit. Swift is a neat language and will definitely make developing iOS apps more attractive. In this post, I’ll share what I’ve learnt so far and the basics of Swift.

Variables, Constants and Type Inference

In Swift, you declare variables with the “var” keyword and constants using the “let” keyword. Here is an example:

These are the two keywords you need to know for variable and constant declaration. You simply use the “let” keyword for storing value that is unchanged. Otherwise, use “var” keyword for storing value that can be changed.

What’s interesting is that Swift allows you to use nearly any character for both variable and constant names. You can even use emoji character for the naming:

Swift Variable Name in Emoji
Tip: You may wonder how you can type emoji character in Mac OS. It’s easy. Just press Control-Command-spacebar and an emoji picker will be displayed.

You may notice a huge difference in variable declaration between Objective C and Swift. In Objective-C, developers have to specify explicitly the type information when declaring a variable. Be it an int or double or NSString, etc.

It’s your responsibility to specify the type. For Swift, you no longer needs to annotate variables with type information. It provides a huge feature known as Type inference. The feature enables the compiler to deduce the type automatically by examining the values you provide in the variable.

It makes variable and constant declaration much simpler, as compared to Objective C. Swift provides an option for you to explicitly specify the type information if you wish. The below example shows how to specify type information when declaring a variable in Swift:

No Semicolons

In Objective C, you need to end each statement in your code with a semicolon. If you forget to do so, you’ll end up with a compilation error.

As you can see from the above examples, Swift doesn’t require you to write a semicolon (;) after each statement, though you can still do so if you like.

Basic String Manipulation

In Swift, strings are represented by the String type, which is fully Unicode-compliant. You can declare strings as variables or constants:

In Objective C, you have to choose between NSString and NSMutableString classes to indicate whether the string can be modified. You do not need to make such choice in Swift. Whenever you assign a string as variable (i.e. var), the string can be modified in your code.

Swift simplifies string manipulating and allows you to create a new string from a mix of constants, variables, literals, as well as, expressions. Concatenating strings is super easy. Simply add two strings together using the “+” operator:

Swift automatically combines both messages and you should the following message in console. Note that println is a global function in Swift to print the message in console.


Swift is awesome. What do you think?

You can do that in Objective C by using stringWithFormat: method. But isn't the Swift version more readable?

String comparison is more straightforward. In Objective C, you can't use the == operator to compare two strings. Instead you use the isEqualToString: method of NSString to check if both strings are equal. Finally, Swift allows you to compare strings directly by using the == operator.

Arrays

The syntax of declaring an array in Swift is similar to that in Objective C. Here is an example:

Objective C:

Swift:

While you can put any objects in NSArray or NSMutableArray in Objective C, arrays in Swift can only store items of the same type. Say, you can only store strings in the above string array. With type inference, Swift automatically detects the array type. But if you like, you can also specify the type in the following form:

Like NSArray, the Swift provides various methods for you to query and manipulate an array.

Simply use the count method to find out the number of items in the array:

In Objective C you use the addObject: method of NSMutableArray to add a new item to an array. Swift makes the operation even simpler. You can add an item by using the "+=" operator:

This applies when you need to add multiple items:

To access or change a particular item in an array, pass the index of the item by using subscript syntax just like that in Objective C.

One interesting feature of Swift is that you can use "..." to change a range of values. Here is an example:

This changes the item 2 to 4 of the recipes array to "Cheese Cake", "Greek Salad" and "Braised Beef Cheeks".

Dictionaries

Swift only provides two collection types. One is arrays and the other is dictionaries. Each value in a dictionary is associated with a unique key. If you're familiar with NSDictionary in Objective C, the syntax of initializing a dictionary in Swift is quite similar. Here is an example:

Objective C:

Swift:

The key and value in the key-value pairs are separated by a colon. Like array and other variables, Swift automatically detects the type of the key and value. However, if you like, you can specify the type information by using the following syntax:

To iterate through a dictionary, use the for-in loop.

You can also use the keys and values properties to retrieve the keys and values of the dictionary.

To access the value of a particular key, specify the key using the subscript syntax. If you want to add a new key-value pair to the dictionary, simply use the key as the subscript and assign it with a value like below:

Now the companies dictionary contains a total of 5 items. The "TWTR":"Twitter Inc" pair is automatically added to the companies dictionary.

Classes

In Objective C, you create separate interface (.h) and implementation (.m) files for classes. Swift no longer requires developers to do that. You can define classes in a single file (.swift) without separating the external interface and implementation.

To define a class, you use the class keyword. Here is a sample class in Swift:

Similar to Objective C, right? In the above example, we define a Recipe class with three properties including name duration and ingredients. Swift requires you to provide the default values of the properties. You'll end up with compilation error if the initial values are missing.

What if you don't want to assign a default value? Swift allows you to write a question mark (?) after the type of a value to mark the value as optional.

In the above code, the name and ingredients properties are automatically assigned with a default value of nil. To create an instance of a class, just use the below syntax:

You use the dot notation to access or change the property of an instance.

Swift allows you to subclass Objective-C classes and adopt Objective-C protocols. For example, you have a SimpleTableViewController class that extends from UIViewController class and adopts both UITableViewDelegate and UITableViewDataSource protocols. You can still use the Objective C classes and protocols but the syntax is a bit different.

Objective C:

Swift:

Methods

Swift allows you to define methods in class, structure or enumeration. I'll focus on instance methods of a class here. You can use the func keyword to declare a method. Here is a sample method without return value and parameters:

In Objective C, you call a method like this:

In Swift, you call a method by using dot syntax:

If you need to declare a method with parameters and return values, the method will look this:

The syntax looks a bit awkward especially for the -> operator. The above method takes a name parameter in String type as the input. The -> operator is used as an indicator for method with a return value. In the above code, you specify a return type of Int that returns the total number of todo items. Below demonstrates how you call the method:

Control Flow

Control flow and loops employ a very C-like syntax. As you can see above, Swift provides for-in loop to iterate through arrays and dictionaries. You can use if statement to execute code based on a certain condition. Here I'd just like to highlight the switch statement in Swift which is much powerful than that in Objective C. Take a look at the following sample switch statement. Do you notice anything special?

Yes, switch statement can now handle strings. You can't do switching on NSString in Objective C. You had to use several if statements to implement the above code. At last Swift brings us this most sought after utilization of switch statement.

Another enhancement of switch statement is the support of range matching. Take a look at the below code:

The switch cases now lets you check values within a certain range by using two new operators: "..." and "..<". Both operators serve as a shortcut for expressing a range of values. Consider the sample range of "41...70", the ... operator defines a range that runs from 41 to 70, including both 41 and 70. If we use the ..< operator instead of ... in the example, this defines a range that runs from 41 to 69. In other words, 70 is excluded from the range.

Should I Still Learn Objective C?

I hope this short tutorial gives you a very brief introduction of Swift. This is just the beginning of the Swift tutorials. We'll continue to explore the language and share anything new with you. Of course, we'll develop more detailed tutorials when Apple officially releases Xcode 6 and iOS 8 this fall. Meanwhile, if you want to further study the language, grab the free Swift book from iBooks Store.

Before I end this post, I'd like to take this chance to answer a common question after the announcement of Swift.

Should I continue to learn Objective C?

My view on Swift is it is the future of programming for iOS. Apple will continue to promote and add features to the language. As you can see in this tutorial, the syntax is more developer-friendly and it's easier for beginner to learn, particular for those who have scripting background. It will definitely encourage more people to learn iOS programming and build iOS apps. That said, I think Objective C will not disappear overnight and is here to stay for years. There are tons of apps and code libraries that are written in Objective C. It'll take time for developers to convert the code to Swift. As Xcode supports both Objective C and Swift, some developers may even keep the existing code in Objective C and only develop new library/app in Swift. Thus, I suggest you to learn both languages. If you can manage the fundamentals of Objective C, it'll be very easy for you to switch over to Swift as the two languages are quite similar. And it would definitely give you an edge over other Swift-only developers in the market.

What do you think about Swift? Leave me comment and share your thought.

Swift
Using CocoaPods in Your Swift and Objective-C Projects
Announcement
Our Swift Programming Book for Beginners Now Supports iOS 9, Xcode 7 and Swift 2
Swift
Mastering Swift: Enumerations, Closures, Generics, Protocols and High Order Functions
  • ohdowload

    ohdowloadohdowload

    Author Reply

    nice intro for swift.


  • Danny

    DannyDanny

    Author Reply

    I think objective-c will become history so it will be good to go with swift as quick as we can,thanks for tutorial Simon.


  • Anan Adli

    Anan AdliAnan Adli

    Author Reply

    Swift is about the future but if we talking about now we can’t loos objective-c


  • Anan Adli

    Anan AdliAnan Adli

    Author Reply

    Thank you for this intro


  • Derek

    DerekDerek

    Author Reply

    the only concern for me on ObjC is the current library we are using…e.g. AFNetworking, seems we have to wait for some time to let them provide swift ver.


    • David DelMonte

      You should be able to intermix Obj-C controls and Swift controls. So AFNetworking should run, as is for a long while..


  • Lakshmy

    LakshmyLakshmy

    Author Reply

    Swift seems to be more readable language compared to objective-C..Thanks for the introduction.


  • antwerpenr

    antwerpenrantwerpenr

    Author Reply

    Great stuff, Simon – you are the best! I agree completely – Swift is the way to go and it is likely to go faster than any of us imagine. That said – a good grounding in Objective-C and the basics of Object oriented programming will help you get going…..as well as *lots* of hands-on practice! Your iOS 7 material is just superb and I cannot wait to get your iOS 8 material!


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      Thanks for your kind words! We will definitely publish more iOS 8 tutorials when Apple officially releases iOS 8 in Sep/Oct.


  • Simon Archer

    nice post!
    So is there no way that we can quietly learn the language together leading up to its official launch? I want to start getting my hands dirty and working through some tutorials, but waiting till Sept/Oct seems so far away. 🙁


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      We wish to publish detailed tutorials on Swift. However, under Apple’s NDA, developers are not allowed to post any screenshots of iOS 8 / Xcode 6 beta. For now, we can only talk about Swift as the information is publicly available.


      • Simon Archer

        Fair enough, I guess it makes sense. 🙂 I’ll just catch up on your other iOS7 Obj-C tutorials in the meantime, since it wont hurt I guess. 🙂
        Thanks for the reply!


  • David DelMonte

    Great intro to Swift. Cohesive, and yet, a bit more filling than the Apple docs/examples so far. Thanks!


  • seangore

    seangoreseangore

    Author Reply

    Can anyone comment on using third-party libraries with swift? As in with tools like cocoapods?


  • Asim

    AsimAsim

    Author Reply

    “This changes the item 2 to 4 ”
    are you sure is not “1 to 3”?

    thank you


    • BPmanSC

      BPmanSCBPmanSC

      Author Reply

      Don’t confuse the index with the number of the item. Index 1 is item 2, as index 0 is item 1.


  • João Pinho

    Great post!


  • Jack

    JackJack

    Author Reply

    You think there will be a book for IOS 8 by this fall?


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      Yes, we’ll publish one in this fall. If you don’t want to wait, you can grab the current AppCoda book (http://104.131.120.244/book/learn-ios7-programming-from-scratch.html) and you’ll receive free update when iOS 8 is released. All the stuffs covered in the book still apply in the next version of iOS. Swift is simply a different language with different syntax. You still need to learn the APIs in the iOS framework, which are mostly written in Objective-C.


      • JDillon

        JDillonJDillon

        Author Reply

        I do web development and I’m excited about swift. I dont have an Obj-C background and I have no functional knowledge of XCode other than its a powerful monster. Would you recommend learning the two together? If so, do you have a recommended approach. Is it possible to do iOS development outside of XCode? Thanks! I’m a complete n00b when it comes to iOS development


        • Simon Ng

          Simon NgSimon Ng

          Author Reply

          If you have web development experience, it may be easier for you to pick up Swift. But as I always mentioned, it would be better to learn both languages. I My suggestion for you is to start with the Hello World tutorial. After going through the Hello World series, you’ll familarize with the Xcode environment and have a very basic understanding of Objective-C.

          http://104.131.120.244/hello-world-app-using-xcode-5-xib/

          Have fun!


  • deepak muvvala

    Good to know that Apple introduced this, This language is more readable unlike objective c with wierd syntax compare to other programming languages. I love to see this evolve. I like to learn this instead of obj-c.


  • Kaliyarajalu

    Ya ! Its very easy to understand… If apple fix this one as primary language in future, its will good for all


  • cymst

    cymstcymst

    Author Reply

    very nice intro,thanks~~


  • Bill

    BillBill

    Author Reply

    can Swift be mixed with Objective-C?


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      Yes, Swift is designed to work side-by-side with Objective-C. You can mix both Objective-C and Swift in the same Xcode project.


  • isaac

    isaacisaac

    Author Reply

    if I have zero-knowledge on Objective-C, is it possible to just learn Swift?


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      Yes, you can learn Swift directly. However, while I love Swift, I encourage you to grasp the basics of Objective-C. Swift is just the programming language. In order to create an app, you still need to study the frameworks and learn how to use various APIs. The frameworks are mostly written in Objective-C, so as the documentation. If you have some Objective-C background, it would be easier for you to understand the SDK and build an app.


      • chella

        chellachella

        Author Reply

        Is swift gonna replace objective c? I just started learning objective c. Is it gonna be like, they do not need objective c developers any more? How important will be the role of objective c developers in near future along with swift?


        • Simon Ng

          Simon NgSimon Ng

          Author Reply

          As said, I don’t think Objective-C will disappear overnight. There are tons of code written in Objective-C. They still need someone who understands Objective-C to maintain. That’s why I always encourage people to learn both languages.

          But if you just want to pick one, Swift is a good choice.


          • chella

            chellachella

            Author

            I heard that we cannot develop standalone applications or applets with Javascript, and swift closely looks like similar to javaScript. Can we develop standalone applications with swift without out objective c?


          • Simon Ng

            Simon NgSimon Ng

            Author

            Yes, you can develop iOS apps using Swift. In the future, Swift is going to completely replace Objective C.


      • chella

        chellachella

        Author Reply

        What would you suggest somebody who comes to you after 8-9 years and wanted to become an iOS programmer? Would you suggest them to go with swift or objective c?


  • reden87

    reden87reden87

    Author Reply

    Great post! Just a little mistake: “two new operators: … and …”


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      Thanks. It’s now fixed.


      • Dave

        DaveDave

        Author Reply

        One more slight error:
        let secondMessage= “What do you think?” needs a space after secondMessage

        Great intro tut into Swift 🙂 Thanks a lot.


    • Gerardo Forliano

      I think half-closed range operator has changed from “..” to “..<"


  • BMV

    BMVBMV

    Author Reply

    let Swift = “It’s time to the Future (-_-)”


  • studmonkey03

    Hi, I’m completely new to programming and would like to learn quickly and efficiently. I’m wondering how many of the objective c lessons I need to do before I take on swift, because swift is simpler then the programming languages in the past.


  • chamu

    chamuchamu

    Author Reply

    Am an Android developer, it was tough to cope up with objective-C. Thanks to Apple for introducing Swift, this is looking super cool and easily readible


  • chamu

    chamuchamu

    Author Reply

    Am an Android developer.. it was tough to cope up with Objective-C.. Thanks to Apple for swift 🙂 Swift is super cool and easily readable ..


  • Annapurna priya

    Great Post.. But my question is what about all the frameworks and classes which we are currently using.?


    • Simon Ng

      Simon NgSimon Ng

      Author Reply

      You can still use the Objective-C classes provided by the frameworks. Here is an example how you can use UIImage to load an image:

      cell.thumbnailImageView.image = UIImage(named: “restaurant.jpg”)


  • 3Dgerbil

    3Dgerbil3Dgerbil

    Author Reply

    Swift will replace Objective-C in perspective making your life much easier as a developer; after all C is a 30-years old dinosaur, but no one dared to admit that; only now people are lifting their heads… To get a feeling with Swift there’s a nice course that I took myself (got at special discount because of Beta 5 release !) https://www.udemy.com/swiftdeveloper/?couponCode=SWIFT-BETA5


  • Coolsinus

    CoolsinusCoolsinus

    Author Reply

    Before starting to learn Swift I felt like ObjC was far from disappearing. But the more I play around with Swift, the more I feel like developers are quickly going to develop their new apps with Swift and let aside ObjC. I really wouldn’t be surprised considering things move so fast with iOS !
    Btw, the “…” already existed in C/ObjC 😉 I discovered that about a year ago, and was quite surprised I hadn’t encountered that syntax before.
    Keep up the good work btw !


  • CallMeWhy

    CallMeWhyCallMeWhy

    Author Reply

    Good post!

    BTW:

    According to the update of swift, this post need update.for example :

    class Recipe {

    var name: String = “”

    var duration: Int = 10

    var ingredients: [String] = [“egg”]

    }

    `


  • koteswar

    koteswarkoteswar

    Author Reply

    Very Good Explantation about Swift and Comparison with objective-C


  • Trapdaar

    TrapdaarTrapdaar

    Author Reply

    Swift looks a lot like python, without the horrendous space nazi rules. The syntax to declare function is atrocious, though and suggest that apple hasn’t been able to get away from its objective-c roots completely. They should have endorsed C++ style syntax, but that would have been an admission that they had been doing it wrong 😉


  • Ramya Aravind

    Great Tutorial and good comparison with Objective C. Really good one for the beginners like me..:) Thanks.


  • ranjiT

    ranjiTranjiT

    Author Reply

    Great Post 🙂 thank you. If you update this post it will be more useful.


  • Anitha bellana

    Hi very good explantation about Swift and Comparison with objective-C.thankQ so much. It’s really very helpfull to who want to know the basic differance b/w Objective-C and Swift.


  • Jignesh Solanki

    Hi Dear Good Day I know Only Xcode In Marvics Version. But I Know Swifit Programming Is Easy But How To Run And What Software Is Required please help me.


  • helper

    helperhelper

    Author Reply

    A curated list of resources for learning about the Swift Language

    https://github.com/hsavit1/Awesome-Swift-Education


  • Samba Korada

    For output statement “println” is no more used, now “print” function is used.


  • Jecky

    JeckyJecky

    Author Reply

    nice but this language is based on c++ i think.

    i am little bit poor at c++. I worked in objective-c so , should i learn c++ or on your think it is easy for me to convert on swift easily ?


  • S. V. Ranade

    Nice and lucid explanation.
    It seems println is deprecated use print instead


Shares