Sunday 12 February 2017

Working with Swift

Swift is Apple's new development language. When we switch from Objective C to Swift , we need some tricks so that we can reuse the code and can write less code  for our app .

1) Use Extension: 

Try to code less and reuse it whenever it's possible. Follow write once and use many  approach. For example, in our app there may be a requirement that most of the views should have border and round corner .
For this we can  write those line of code for each view in our view controller . But a better approach is that we can  write an extension to UIView, which will make the input view to have border and round corner.

extension UIView{
    
    func makeCornerRound(cornerRadius:CGFloat){
        self.layer.cornerRadius = cornerRadius
        self.layer.masksToBounds = true
    }
    
    func addBorderWith(color:UIColor, width:CGFloat){
        self.layer.borderWidth = width
        self.layer.borderColor = color.cgColor
        
    }

}

To use these as:
let myView = UIView()
myView.makeCornerRound(cornerRadius:3)
myView.addBorderWith(color:UIColor.gray,width:1.0)

2) Optional Unwrapping:

Guard vs If let

 var email:String?
var password:String?
if let mail_id = email{
  if let pwd = password {
    print("Welcome to my app!")
   }
}

The above code can be written with Guard statement like this:
guard let mail = email, let pwd = password  else{
   print("ohh no! we don't have email and password")
   return
}
print("Welcome to my app!")

You can see the difference here. The scope of unwrapped variable remains to the function in which they are unwrapped with Guard statement. But with if let , the scope is limits to the block in which they are unwrapped.

3) Nil Coalescing : 

What if the value of the optional is missing and you want to  perform some action in case of the absence of the value of an optional . Let's understand  this with an example:

var userName:String?

if let name = userName{
  print("Welcome \(user)")
} else{
  print("Welcome Guest")
}

We can short the above code with nil coalescing operator .

let name =  userName ?? "Guest"
print("Welcome \(name)")

No comments:

Post a Comment