Tuesday, December 30, 2014

Swift coding style guide













Found two coding styles for Swift:
Interesting notes:

1. In github style, it suggests that let should be used over var binding whenever possible. This is to explicitly show the intent that a value is supposed to or not supposed to change.


2. In raywenderlich style, when declaring protocol conformance, use separate extension instead of declaring all together. Also, do not forget to add // MARK comments.

Preferred:
class MyViewcontroller: UIViewController {
  // class stuff here
}

// MARK: - UITableViewDataSource
extension MyViewcontroller: UITableViewDataSource {
  // table view data source methods
}

// MARK: - UIScrollViewDelegate
extension MyViewcontroller: UIScrollViewDelegate {
  // scroll view delegate methods
}
Not Preferred:
class MyViewcontroller: UIViewController, UITableViewDataSource, UIScrollViewDelegate {
  // all methods
}

3. In raywenderlich style, when unwrapping the optional, shadow the original name instead of using a new name.

Preferred:
var subview: UIView?

// later on...
if let subview = subview {
  // do something with unwrapped subview
}
Not Preferred:
var optionalSubview: UIView?

if let unwrappedSubview = optionalSubview {
  // do something with unwrappedSubview
}

4. In github style, prefer implicit getters on read-only properties.

Preferred:
var myGreatProperty: Int {
    return 4
}

subscript(index: Int) -> T {
    return objects[index]
}
Not Preferred:
var myGreatProperty: Int {
    get {
        return 4
    }
}

subscript(index: Int) -> T {
    get {
        return objects[index]
    }
}

5. In github style guide, it is mentioned to prefer structs over classes. Since I am still quite new to Swift, I will need to learn a bit more to really understand it.

3 comments:

  1. I just love how people get so professional in their programming language skills. And your work is just amazing. Keep it up and keep posting.

    ReplyDelete
  2. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! webstagram

    ReplyDelete
  3. MGM Casino Atlantic City - Mapyro
    Get directions, reviews and information for MGM Casino Atlantic 서산 출장마사지 City in Atlantic City, NJ. MGM Resort Atlantic City, NJ, United States. Rating: 안산 출장샵 8.5/10 구리 출장샵 · ‎4,521 reviews · ‎Price range: Prices for upcoming dates start at $136 per 김해 출장샵 night (We 안산 출장안마 Price Match)

    ReplyDelete