Swift thinking cover?fm=jpg&fl=progressive&q=75&w=300

Swift Thinking

This past Thursday, Keith Smiley gave the second talk of the Swift Language User Group (#SLUG) in Thoughtbot’s San Francisco office. He began his talk with an introduction and a very brief recap of the previous SLUG talk before focusing on a couple of key features in Swift.

Operator Overloading (0:00)

Operator overloading is really just defining an operator to do a new operation.

Example #1: A simple example of operator overloading (2:00)

view1.al_left == view2.al_right 

This snippet of code doesn’t check for equality but is actually a neat DSL shorthand for auto-layout. In Objective-C, it looks like this:

NSLayoutConstraint(item: view 1, 
  attribute: NSLayoutAttribute.Left, 
  relatedBy: NSLayourRelation.Equal, 
  toItem: view2, 
  attribute: NSLayoutAttribute.Right

We can see why operator overloading has such a bad reputation - when people read through code, they may think they know what’s going on when the code is really doing something else. Code might also break due to typos - for example, when using multiple dots in the range operator in Swift. Four dots “….” returns a random range of integers, which could either return the range intended or no range at all.

Example #2: To create a new regex and check if a string matches (3:33)

NSRegularExpression *regex = [NSRegularExpression 
NSRange range = NSMakeRange(0, string.length)
NSUInteger numberOfMatches = [regex 
if (numberOfMatches > 0) { ... }

// Both Objective-C and Swift code are fairly verbose, but if you overload an operator, you can use code like this:
if string =~ "\\w+" { ... }

Get more development news like this

The same operator is used similarly in Haskell, Ruby, and Shell scripts. Apple has a sample application called Lister, written in both Objective-C and Swift, that has many such examples of operator overloading. Ultimately, operator overloading allows for code that can be concise but still expressive.

JSON Parsing (8:50)

JSON can return many different types with lots of nesting, so how does a language with a strict type system, like Swift, deal with it? Swift is safer no matter what type JSON returns, whether it is an array or a dictionary.

Example #3: Print the username if all conditions are met (9:45)

If the JSON can be cast as an NSDictionary, and you get an objectForKey back that is a string, then you can print the username.

if let userDict = JSON as? NSDictionary {
  if let username = userDict.objectForKey("username") as? String {

There is no native Swift API to deal with JSON. Many ideas in Swift came from other languages, like Haskell or Go. For insight, we look at languages with similar type to see how they deal with the same situations.

Example #4: JSON in Go (15:09)

Unmarshal is a JSON API that fills the user object with data from the JSON or returns an error. This is similar to Mantle or EasyMapping in Objective-C.

type User Struct {
  Username string `json:"username"` 

var user  User 
err = json.Unmarshal(JSON, &user)

Example #5: JSON in Haskell (16:45)

The Show type class looks very similar to the Principle protocol in Swift. A “Maybe” User is doing the same thing as an optional in Swift. The code still either prints the user or returns an error.

data User = User { username :: String
                 , userID   :: Integer
                 } deriving (Show)

instance FromJSON User where
  parseJSON (Objet j) =
    User <$>
      {j .: "username") <*>
      (j .:? "id")

case decode JSON :: Maybe User of
  Just user -> print user
  Nothing -> error "Invalid JSON"

Q&A (22:00)

Q: Like in the example in Go, can you decorate properties?
Keith: In Swift, probably not. In Objective-C, the types of libraries that do this make you define a single method to return a giant dictionary that’s the JSON key translated to the property name of your Objective-C thing.

Q: What is the difference between “?” and “!” ?
Keith: The question mark (?) returns an optional, either something or nothing. ! is special case of optionals where you don’t have to deal with unwrapping the optional. This exists for backwards compatibility with Objective-C APIs.

Q: If you include the libraries, is operator overloading global or scoped to files/classes?
Keith: If you’ve included the libraries, it’s global assuming your types match the types defined in the operator.

Q: If you’re linked with libraries, do you have to include headers?
Keith: Headers are something you don’t have to deal with. If you’re in the same project that’s all linking to the same thing, you’ll have that included automatically.

Q: Do you see Swift as being a replacement for Objective-C or something that will live side-by-side with it?
Keith: In my opinion, it’s a replacement in the long-term. They won’t deprecate Objective-C next year, but it might look completely different in ten years. For example, UITableView doesn’t make sense in Swift but new APIs should make more sense in Swift code. Person 2: This is similar to Carbon and Cocoa where they eventually made everyone use Cocoa, and that took three years for them to go from “Cocoa is great” to “we’re not supporting it”. Keith: And there are some features in Objective-C that were added because of Swift, like instance type.

Q: Will we see a divergence with the introduction of new DSLs, similar to what’s happening with JavaScript and transpilers?
Keith: I think we’ve already seen people write interesting things in Swift, like this cool testing framework called Quick that works in Objective-C and Swift.

Q: One problem with DSLs is tooling and IDE support. For example, if I see a strange operator, can I click on it and see its definition or the type of something?
Keith: It doesn’t support it now, probably because they’re still in beta. As far as I know, you can’t command-click something but I think they’ll add it.

Q: For apps that you’re working on now at thoughtbot, are you working in Swift or Objective-C?
Keith: We currently have two projects in Swift, which are half new and half not. Tooling support is still bad since there are lots of crashes so it’s still difficult to use. Internal tools are being ported to Swift (like Liftoff).

Q: Do you prefer to make apps programmatically or by using storyboards?
Keith: We usually use storyboards, but this is just a preference question.

Q: Do you foresee Swift coming server-side?
Keith: This could happen in the future, but it’s interesting to see how they develop. It’ll be interesting to see if they add an NSSet type of thing or a Regex library.

Q: Can you created a library or a module of certain libraries for things, or a linkable module from the command line?
JP: You can definitely create a Swift module from command line (which itself isn’t necessary). You need module map, a file to point to other swift files, and then you actually have to pass it in. Because the Swift compiler lives on top of Clang, you have to pass it in through an intermediate tool like the Swift IDE test.

Q: How well is CocoaPods supported in Swift projects?
Keith: There are tons of open bugs which we’re well aware of, but we’re working on it. Part of it also has to do with tooling - are they caused by our gem or the Xcodeproj gem, or is it because the tools are still in beta? Person 2: There’s also a difference in whether you use CocoaPods to create the project or Xcode. Keith: Another limiting factor are the file extensions. I don’t think that pull request has been merged to add Swift yet.

Q: Has anyone looked at libraries that would work on both a simulator and a device, so ARM and X86 in one bundable library?
Keith: I haven’t looked at dynamic libraries, but I don’t see any reason they wouldn’t work. JP: Yes, if you build an iOS framework, it’ll build a FAT library with all three architectures supported. You can have that framework built in Swift, Objective-C, or a mix of both, and all three of those work.

Q: Have you done any testing or BDD testing of Swift yet?
Keith: Not really, but Quick looks amazing. I’m hoping that the functional nature of Swift will help with that a lot too. The Rails side of Thoughtbot is big on TDD so that’s definitely something on our mind.

Q: There are some DSLs in RubyMotion like BubbleWrap, do you see anything similar in Swift?
Keith: I think it’s probably too early to see anything yet like that.

Q: What’s the best way to jump in and start learning Swift without any Objective-C experience?
Keith: I think frameworks are limiting factor, not the language. Learning what APIs from frameworks to use and how to include them is the hard part, but there are tons of articles about interesting things in Swift being posted now.

Next Up: Build a Realtime Swift App with Realm #1: Building Reactive Apps with Realm

General link arrow white

About the content

This content has been published here with the express permission of the author.

Keith Smiley

Keith is an iOS engineer at Lyft in San Francisco. Previously, he coded at Thoughtbot, and has occasionally clicked the big green button for CocoaPods.

4 design patterns for a RESTless mobile integration »