March 08, 2017

Apple starts rejecting apps with “hot code push” features

This thread from Apple's Developer Forums is making some waves on the internets today. Apparently, they're now rejecting apps that include code that can modify your app after it's released to the store.

Rollout.io seems to be the SDK that's setting the alarm off, so far.

If you use Rollout.io, or another "push code after you release to the store" service, it's time to start thinking about changing your strategy. (clears throat I told you).

From Rollout.io's FAQ:

Does Rollout comply to Apple’s Guidelines?

Yes. As per Apple’s official guidelines, Rollout.io does NOT alter binaries. Rollout uses JavascriptCore to add logic to your patches. For more details, check out how Rollout is compliant with App Store guidelines.

I wouldn't build my business on such a fine line.

And also, please don't act surprised when Apple start rejecting React Native apps down the road.

The moral of the story: stay away from JavaScript.


September 16, 2016

Bringing piping syntax from Elixir to Swift

I've been writing Elixir for my main backend needs for the past few months and I've really liked it — specially its syntax. In fact, I've gotten so into its syntax that I've often found myself trying to write Swift as if it were Elixir.

Oops!

So I decided to experiment a little bit with bringing my favourite syntax from Elixir over to Swift natively.

Disclaimer: This is just an experiment. To get this to work on an actual project, a lot more work needs be done.


Elixir is a functional language that's gained a lot of traction in the past few months thanks to its simplicity and core features, such as the supervision tree.

Every type in Elixir is a value, which means that it gets copied when passed to a function — the function gets a new copy of the value, which it can then modify without affecting the original instance.

> aMap = %{a: 1}
  %{a: 1}

> bMap = Map.update(aMap, :a, 0, &(&1 * 3))
  %{a: 3}

> aMap 
  %{a: 1}

> bMap
  %{a: 3}

Also, Elixir has this great "pipe" operator that lets you write cleaner code and streamline data manipulation in a really easy way:

> cMap = aMap |> Map.update(:a, 0, &(&1 / 3))

The "pipe" (|> ) operator takes the value on its left and passes it to the function on the right as its first parameter. This is included as part of the language and works with any function.

Let's bring that to Swift!

In this example, I'm going to use two simple structs (value types in Swift):

struct Company {  
    let name: String
}

struct Person {  
    let name: String
    let work: Company
}

let apple = Company(name: "")  
let joe = Person(name: "Joe", work: apple)  

A characteristic of functional programming languages is that they strive for immutability. Vaues should not mutate during program execution, but copying values and modifying them is good.

Tipically, if we wanted to update joe's name, we'd do something like

joe.name = "Joe Wood"  

If we did this, the Swift compiler would raise two errors:

  1. the name property on Person is declared as a constant (let), which means it can't mutate during execution — a change to var is suggested.
  2. the joe instance was declared as a constant (let), which means it can't mutate during execution — a change to var is suggested.

What we don't want, though, is enable the ground to shift under our feet, so let's keep everything as a constant.

Another approach would be to create a function that did so:

extension Person {  
  mutating func update(name: String) {
    self.name = newName
  }
}

But again, that mutating keyword there is a code-smell in the functional world. The way to do this the functional way is:

extension Person {  
  func update(name: String) -> Person {
    return Person(name: newName, work: self.work)
  }
}

We created a function that changes only one property on the instance — it receives the new value for the property, and returns a whole new instance of the type with that value replacing the original one.

joe.update(name: "Joe Wood").name // Joe Wood  
joe.name                          // Joe  

Now, the problem with this is that the function that we created is operating on the type-instance.

Note: In Elixir, a map literal can be written as %{a: 1}, but to transform and operate on that instance, we have to use the Map module. That's kind of what we want to achieve here.

We want that the Person struct (or module, if you're thinking in Elixir) to have a series of methods that receive Person instances to operate with.

In order to achieve that, we need to do a bit of groundwork.

Lenses

There is a concept in functional programming called "data lenses". Explaining in detail what a data lens is, is way out of scope of this post, but you can read more about it here and here, and generally, just searching "lenses functional programming" in any search engine.

The idea is to have a data type (a Lens) that is generic and lets us get and set (a.k.a. zoom to) information on the type that the Lens is generic to.

Example:

struct Lens<Whole, Part> {  
  let get: (Whole) -> Part
  let set: (Whole, Part) -> Whole
}

let personNameLens = Lens<Person, String> (  
  get: { $0.name },
  set: { Person(name: $1, work: $0.work) }
)

personNameLens.get(joe)                  // Joe  
personNameLens.set(joe, "Joe Wood").name // Joe Wood  

That's a Lens. However, we'll only need a subset here, so let's define a new data type that gives us only the set method:

struct SetLens<Whole, Part> {  
  let set: (Whole, Part) -> Whole
}

To update a Person instance, we can do this now:

let setPersonNameLens = SetLens<Person, String> (  
  set: { Person(name: $1, work: $0.work) }
}

setPersonNameLens.set(joe, "Joe Wood")  

Now lets do a bit of work to move the interface up to type-level by making our SetLens a static property of Person, for brevity:

extension Person {  
  static let SetName = SetLens<Person, String> (
    set: { Person(name: $1, work: $0.work) }
  ) 
}

Person.SetName.set(joe, "Joe Wood")  

We still have the problem that we'd have to interact with the SetLens directly. To mimic the Elixir behaviour, we need to wrap the SetName property on a static function that returns a function that when called, calls the set method on the lens.

extension Person {  
  static func Update(name: String) -> Person -> Person {
    return { p in SetName.set(p, newName) }
  }
}

We define a static function that takes a new name as a parameter, and returns a function that takes a Person and returns a Person. Calling this function just passes the values to the SetLens.

Now, let's introduce the pipe operator:

precedencegroup Applicable {  
    associativity: left
}
infix operator |>  
func |> <A, B>(a: A, rhs: (A) -> B) -> B {  
    return rhs(a)
}

This new custom operator takes a value to the left and a function on the right, and just calls the function on the right passing the value on the left. How convenient!

We can now do this:

joe |> Person.UpdateName("Joe Wood")  

Ta'da!

Doing the appropriate amount of work, we could be writing this really soon:

joe  
  |> Person.Update(name: "Joe Wood")
  |> Person.Update(work: Company(name: "Apple"))

And voilá, we've migrated one of Elixir's core features to Swift, while maintaining type-safety!

Final comments

Admittedly, it took a long of work just to migrate this one feature over to Swift. This does not mean, though, that it can't be done for big code-bases and "real apps." One of the best features of Swift is that the compiler is real smart and can tell us on compile-time if we messed something up. ❤️

This was just a small exercise, but I do appreciate the similarities that Swift and Elixir have, and the fact that both languages are flexbile enough that we can do these sort of things. Pretty cool.


Hey! I'm writing a book on best practices for iOS development with Swift, and it's called (drum roll) Best Practices for Developing iOS Apps with Swift.

Subscribe below to get a 50% off coupon code when the book is released — also get the first chapter for free when it is ready!


March 23, 2016

#selector

One of my favourite changes in Swift 2.2 is that Objective-C selectors now are first class citizens in the Swift ecosystem. So long to error-prone selector names as Strings.

Swift 2.2 lets you use the #selector expression to reference a selector from your Swift code.

class MyView: UIView {  
    private lazy var button: UIButton = {
        let b = UIButton()

        // Swift 2.1 and earlier
        b.addTarget(
            self,
            action: "buttonTapped:",
            forControlEvents: .TouchUpInside
        )

        // Swift 2.2
        b.addTarget(
            self,
            action: #selector(MyView.buttonTapped(_:)),
            forControlEvents: .TouchUpInside
        )
        return b
    }()

    func buttonTapped(sender: UIButton) {
        // ...
    }
}

My only complain about this is that the actions still need to be declared either internal or public, declaring the action as private returns the error Argument of '#selector' refers to a method that is not exposed to Objective-C, which makes sense if yout think about it.

EDIT: I should have read the error message more carefully.

Turns out that if you want your selector to be private, you only need to add the @objc attribute to the function declaration, and you're set:

extension Selector {  
    static let cancelButtonTapped = #selector(MyView.cancelButtonTapped)
}

class MyView: UIView {  
    @objc fileprivate func cancelButtonTapped() {
        // ...    
    }
}

EDIT: In Swift 3.0, the function needs to be set to fileprivate in order to be available from outside its scope.


February 11, 2016

How I deal with JSON in Swift

Edit: I've updated this post to Swift 3's syntax. The original post with Swift 2.X syntax can be found here.


It seems that the new hot thing these days is open sourcing your Swift JSON parsing library.

Lyft, Big Nerd Ranch, Thoughtbot, to name a few, have their own drop-in solutions for handling JSON with Swift available for us to integrate in our projects. Other libraries like SwiftyJSON and json-swift, ObjectMapper are there for us, too.

All of them are great. All of them get the job done.

This post is not a tutorial on how to use those libraries, but just a description of how I deal with JSON in my Swift apps.

Before we start

I'm pretty biased. Personally, I think that handling JSON in Swift, while challenging at first (specially if you're new to the language), can be a really simple task that can be overworked.

Also, I don't use any of the libraries that I mentioned earlier to parse JSON in any of my apps. My method, which I'm about to show you, might seem a lot more verbose (hint hint it is) — but bear with me.

That said, if you just want to parse some JSON right now, stop reading and use any of the libraries linked earlier (I'd go with SwiftyJSON or Freddy, from BNR). If you want to learn how to handle JSON in Swift, read along.


As a side note: I'm writing a book — subscribe now to get a 50% off discount code when the book launches late October.


Groundwork

Is there a way to decode JSON using native APIs on Cocoa/CocoaTouch? Yep:

do {  
    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
} catch { }

At this point, the constant json's type is Any. Typically, you'd cast json to a dictionary of some type (maybe an Array, depending on the API you're trying to consume):

do {  
    let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:Any]
} catch { }

Its our job now to extract data from that dictionary, and make sure we can build our Swift models in a type-safe manner.

Lets define what basic data types we can retrieve from a JSON structure:

  1. Ints
  2. Floats
  3. Strings
  4. Bools

Note: Nested objects and arrays are just arrangements of the basic data types.

Taking a chapter from Chris Eidhof's approach, let's define the following helper functions (updated for Swift 3, with the new operator declaration syntax and @discardableResult):

func flatten<A>(x: A??) -> A? {  
    if let y = x { return y }
    return nil
}

infix operator >>>=  
@discardableResult
public func >>>= <A, B> (optional: A?, f: (A) -> B?) -> B? {  
    return flatten(x: optional.map(f))
}

To explain briefly:

  • The flatten(x:) function takes a double optional and removes one level of optional-ness.
  • The custom operator >>>= takes an optional of type A to the left, and a function that takes an A as a parameter and returns an optional B to the right. Basically, it says "apply."

Then, by defining these next methods on a Dictionary extension, we can extract data from JSON structures in a type-safe manner. These are the building blocks of what I'm trying to do here.

extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {  
    public func p3_number(key: Key) -> NSNumber? {
        return self[key] >>>= { $0 as? NSNumber }
    }

    public func p3_int(key: Key) -> Int? {
        return self.p3_number(key: key).map { $0.intValue }
    }

    public func p3_float(key: Key) -> Float? {
        return self.p3_number(key: key).map { $0.floatValue }
    }

    public func p3_double(key: Key) -> Double? {
        return self.p3_number(key: key).map { $0.doubleValue }
    }

    public func p3_string(key: Key) -> String? {
        return self[key] >>>= { $0 as? String }
    }

    public func p3_bool(key: Key) -> Bool? {
        return self.p3_number(key: key).map { $0.boolValue }
    }
}

If we had the following JSON structure:

{
   name: "Oscar Swanros",
   age: 22
}

To get the age property, we can now do:

guard let age = json.p3_int(key: "age") else {  
    return
}

A lot cleaner than having to cast each member every time.

The fun part

The next step is to define a single protocol named JSONParselable:

public protocol JSONParselable {  
    static func with(json: [String:Any]) -> Self?
}

JSONParselable basically indicates that a given type can be inflated using JSON data. It requires a static function on the type that returns an instance of itself.

The types that can be inflated from a JSON structure need to conform to this protocol. The implementation is rather simple.

Say we have an API with the following JSON response:

{
  id: 289928,
  title: "Freakonomics: A Rogue Economist Explores the Hidden Side of Everything",
  number_of_pages: 320,
  authors: [
      {
        name: "Steven D. Levitt",
        website_url: "http://pricetheory.uchicago.edu/levitt/home.html",
        twitter_url: "http://twitter.com/freakonomics"
      },
      {
        name: "Stephen J. Dubner",
        website_url: "http://stephenjdubner.com",
      }
  ],
  reviews: [
    {
      comment: "If Indiana Jones were an economist, he’d be Steven Levitt… Criticizing Freakonomics would be like criticizing a hot fudge sundae.",
      reviewer: "Wall Street Journal"
    },
    {
      comment: "The guy is interesting!",
      reviewer: "Washington Post Book World"
    },
    {
      comment: "Principles of economics are used to examine daily life in this fun read.",
      reviewer: "Great Reads"
    }
  ]
}

Working from the inside-out, these are the models that I'd define:

struct Review {  
    let comment: String
    let reviewer: String

    init(
        comment: String,
        reviewer: String
        ) {
            self.comment  = comment
            self.reviewer = reviewer
    }
}

struct Author {  
    let name: String
    let websiteURL: String
    let twitterURL: String?
    // I defined twitterURL as optional because, judging from the sample
    // JSON, it is a field that may or may not be present in
    // the response. Ideally, this would be well defined
    // on the documentation for the API I'm trying to consume.

    init(
        name: String,
        websiteURL: String,
        twitterURL: String? = nil
        ) {
            self.name       = name
            self.websiteURL = websiteURL
            self.twitterURL = twitterURL
    }
}

struct Book {  
    let id: Int
    let title: String
    let numberOfPages: Int
    let authors: [Author]
    let reviews: [Review]

    init(
        id: Int,
        title: String,
        numberOfPages: Int,
        authors: [Author],
        reviews: [Review]
        ) {
            self.id            = id
            self.title         = title
            self.numberOfPages = numberOfPages
            self.authors       = authors
            self.reviews       = reviews
    }
}

Now I have models that map directly to my API definition, including proper handling of values that may not be in the response at all. Now, on to implementing the JSONParselable protocol.

I'll do one of the inner models first:

// Review.swift
extension Review: JSONParselable {  
    static func with(json: [String:Any]) -> Review? {
        guard
            let comment = json.p3_string(key: "comment"),
            reviewer    = json.p3_string(key: "reviewer")
            else {
                return nil
                // A valid Review always has a comment and a
                // reviewer.
            }

        return Review(
            comment: comment,
            reviewer: reviewer
        )
    }
}

Then...

// Author.swift
extension Author: JSONParselable {  
    static func with(json: [String:Any]) -> Author? {
        guard
            let name   = json.p3_string(key: "name"),
            websiteURL = json.p3_string(key: "website_url")
            else {
                return nil
            }

        // Since the twitterURL property is optional,
        // I can just call json.p3_string(key:) and pass that value to the
        // initializer. All good.
        return Author(
            name: name,
            websiteURL: websiteURL,
            twitterURL: json.p3_string(key: "twitter_url")
        )
    }
}

Attention:

  1. Notice how the protocol implementation is done in an extension for each type. This to emphasize the notion that the actual type does not care about how it is created, as long as it is valid. (Apple recommends another approach, which I'm not in favor of. Read my comments here.
  2. Up until this point, I haven't touched nested objects at all.

Next, I need to parse the main Book object. Here's how I do it:

// Book.swift
extension Book {  
    static func with(json: [String:Any]) -> Book? {
        // #1
        guard
            let id            = json.p3_int(key: "id"),
            let title         = json.p3_string(key: "title"),
            let numberOfPages = json.p3_int(key: "number_of_pages")
            else {
                return nil
            }

        // #2
        let authorsDicts = json["authors"] as? [[String:Any]]
        let reviewsDicts = json["reviews"] as? [[String:Any]]

        func sanitizedAuthors(dicts: [[String:Any]]?) -> [Author] {
            guard let dicts = dicts else {
                return [Author]()
            }

            return dicts.flatMap { Author.with($0) }
        }

        func sanitizedReviews(dicts: [[String:Any]]?) -> [Review] {
            guard let dicts = dicts else {
                return [Review]()
            }

            return dicts.flatMap { Review.with($0) }
        }

        // #3
        return Book(
            id: id,
            title: title,
            numberOfPages: numberOfPages,
            // #4
            authors: sanitizedAuthors(authorsDicts),
            reviews: sanitizedReviews(reviewsDicts)
        )
    }
}

Dissecting the last code listing:

  • #1: Make sure that the required data is in the JSON dictionary, and extract it accordingly.
  • #2: Extract the dictionaries for authors and reviews respectively.
  • #3: Return a new instance of Book passing the required data first.
  • #4: For authors and reviews, just .flatMap the array of dictionaries, and construct an array of only valid Authors and Reviews.

The final implementation would look like this:

// Omitting networking code for brevity

func dataTaskFinished(data: Data) {  
    do {
        guard
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any],
            let book = Book.with(json: json)
            else {
                return
        }

        // #1
        print(book)
    } catch {
        print(error)
    }
}

At this point (#1), I have a fully-packaged, type-safe, valid instance of Book, with nested models, even — not only a type-safe JSON type that I still have to extract data from. 🎉

Why do it this way

My method is (really) verbose, I know. But think about this few points before you call me crazy:

  • The end result is not a "type-safe-parsed JSON object," as most of the libraries out there give you, but a fully type-safe, valid model instance.
  • While this may seem a lot of work, it lets you be more granular about how you inflate your models from data from a server.
  • My method, at least to me, makes it easier to translate API documentation to code.

Other highlights:

  • There are no custom operators to deal with. Yes, the >>>= operator was defined, but it is not required for the actual implementation of the JSON parsing (Argo, for instance, requires you to use custom operators to perform the actual parsing).
  • Modularity. Dealing with nested objects kinda solves itself. If you make every nested model conform to JSONParselable, you can just send the original JSON blob to the outermost object, and you're done.

Extra!

Did you notice that Author has two properties that their name makes you think they're URLs but are actually Strings?

Using my method, they can actually be URL objects!

struct Author {  
    let name: String
    let websiteURL: URL
    let twitterURL: URL?

    init(
        name: String,
        websiteURL: URL,
        twitterURL: URL? = nil
    ) {
        self.name       = name
        self.websiteURL = websiteURL
        self.twitterURL = twitterURL
    }
}

extension Author: JSONParselable {  
    static func with(json: [String:Any]) -> Author? {
        guard
            let name              = json.p3_string(key: "name"),
            let websiteURLString    = json.p3_string(key: "website_url"),
            let websiteURL          = URL(string: websiteURLString)
            else {
                return nil
            }

        let twitterURLString = json.p3_string(key: "twitter_url")

        return Author(
            name: name,
            websiteURL: websiteURL,
            twitterURL: URL(string: twitterURLString)
        )
    }
}

So, there's that.

Wrapping up

As I said at the beginning of this post, the JSON parsing libraries that are out there are really popular (because they work), and they can help you get from point A to point B really quick (if that's what you want).

My issue with those libraries is that they are too general-purpose for my taste. They are designed to work out of the box with any generic JSON response.

However, my issue is that my apps are not interacting with a generic API expecting generic JSON — they interact with a very specific API that outputs very specific JSON.

If my problem is really specific, why not solve it very specifically?

Have anything to add? Let me know. You can reach me as @Swanros on Twitter.