Friday, June 16, 2017

Swift 3.1 Failable Initializers

It’s quite common, We are not always 100% sure like what type of value a service response returns.

Lets take an example of an item price coming from service response and see how to check whether that value is a plain Int or a double/float value.

Swift 3.1 has failable initializers for all numeric type.

  var needChange = false
  let itemPrice  = 70.51

I have got item price value from service response. Now I need to check whether user should play any change or not for this item.

  let price:Int? = Int(exactly: itemPrice)

  if price == nil {
      needChange = true

Using bailable initialization, I check itemPrice, If it’s not an Int value, price will be nil. If it’s an Int value price will have value of itemPrice.

Hope this post is useful. Feel free to comment incase of any queries.