Hướng dẫn về style và quy ước code trong Swift(Phần 2) - Cách mô tả Struct,Class,Method,Closures...



Tiếp theo phần trước chúng ta sẽ đến với một số style code và chuẩn code được nhiều người ưa dùng khi làm việc với Struct, Class, Method, Closures….Để làm cho những dòng code của mình trở bên rõ ràng và dễ hiểu hơn. Bây giờ chúng ta sẽ bắt đầu tìm hiểu chi tiết với bài viết bên dưới.
Class and Struct
Dưới đây là một ví dụ về cách trình bày và định nghĩa một class, còn đối với struct thì cũng tương tự như vậy. Các bạn cùng tham khảo.

class Circle: Shape {
var x: Int, y: Int
var radius: Double
var diameter: Double {
get {
return radius * 2
}
set {
radius = newValue / 2
}
}
init(x: Int, y: Int, radius: Double) {
self.x = x
self.y = y
self.radius = radius
}
convenience init(x: Int, y: Int, diameter: Double) {
self.init(x: x, y: y, radius: diameter / 2)
}
override func area() -> Double {
return Double.pi * radius * radius
}
}
extension Circle: CustomStringConvertible {
var description: String {
return "center = \(centerString) area = \(area())"
}
private var centerString: String {
return "(\(x),\(y))"
}
}
view raw sampleClass hosted with ❤ by GitHub


Computed Properties
Nếu Computed properties chỉ dùng để đọc thì chúng ta nên bỏ qua từ khóa get.
Khuyên dùng:
var diameter: Double {
return radius * 2
}
Không nên dùng:
var diameter: Double {
get {
return radius * 2
}
}
Có thể mô tả một biến singleton như sau:
class PirateManager {
static let shared = PirateManager()
/* ... */
}


Function Declarations
Luôn luôn khái báo tên hàm và mở ngoặc nhọn luôn nằm trên 1 dòng.
Ví dụ:
func reticulateSplines(spline: [Double]) -> Bool {
// reticulate code goes here
}
view raw sample_2 hosted with ❤ by GitHub
Nếu trường hợp hàm quá dài thì nên ngắt dòng tại vị trí thích hợp và Tab vào một khoảng cách thích hợp.
func reticulateSplines(spline: [Double], adjustmentFactor: Double,
translateConstant: Int, comment: String) -> Bool {
// reticulate code goes here
}
view raw sample_1 hosted with ❤ by GitHub


Closures Expressions
Khuyên dùng:
UIView.animate(withDuration: 1.0) {
self.myView.alpha = 0
}
UIView.animate(withDuration: 1.0, animations: {
self.myView.alpha = 0
}, completion: { finished in
self.myView.removeFromSuperview()
})
hoặc là
attendeeList.sort { a, b in
a > b
}
Không nên dùng:
UIView.animate(withDuration: 1.0, animations: {
self.myView.alpha = 0
})
UIView.animate(withDuration: 1.0, animations: {
self.myView.alpha = 0
}) { f in
self.myView.removeFromSuperview()
}
view raw sampleClouse hosted with ❤ by GitHub


Ngoài việc sử dụng các kiểu dữ liệu của Swift cung cấp. Swift còn hỗ trợ khả năng cầu nối với Objective-C để sử dụng các kiểu dữ liệu bên Objective-C.
Khuyên dùng:
let width = 120.0 // Double
let widthString = (width as NSNumber).stringValue // String
Không nên dùng:
let width: NSNumber = 120.0 // NSNumber
let widthString: NSString = width.stringValue // NSString
view raw sampleTypeData hosted with ❤ by GitHub


Hằng(Constants)
Để khái báo một hằng số ta dùng từ khóa let.
Thông thường để khái báo một biến hằng toàn cục thì mọi người thường ưu chuộng sử dụng từ khóa static let. Vì khi đó ta có thể nhận biết được biến hằng này là biến toàn cục hay chỉ là biến cục bộ trong một lớp hay một phạm vị nào đó.
Khuyên dùng:
enum Math {
static let e = 2.718281828459045235360287
static let root2 = 1.41421356237309504880168872
}
let hypotenuse = side * Math.root2
Không nên dùng:
let e = 2.718281828459045235360287
let root2 = 1.41421356237309504880168872
let hypotenuse = side * root2 // root2 là gì?
view raw sampleConstant hosted with ❤ by GitHub


Để mô tả một biến hay hàm có kiểu trả về kiểu optional chúng ta sẽ dùng ký tự ? và để “unwarpped” nó thì chúng ta dùng ký tự !.
Vậy chúng ta sẽ có một số cách sử dụng biến optional như sau:
Khuyên dùng:
var subview: UIView?
var volume: Double?
// later on...
if let subview = subview, let volume = volume {
// do something with unwrapped subview and volume
}
Không nên dùng:
var optionalSubview: UIView?
var volume: Double?
if let unwrappedSubview = optionalSubview {
if let realVolume = volume {
// do something with unwrappedSubview and realVolume
}
}


Khuyên dùng cú pháp sau để unwarpped biến optional để có được một biến unwarpped giống tên.
guard let myValue = myValue else {
return
}
Hoặc có thể dùng:
Khuyên dùng:
guard let number1 = number1,
let number2 = number2,
let number3 = number3 else {
fatalError("impossible")
}
// do something with numbers
Không nên dùng:
if let number1 = number1 {
if let number2 = number2 {
if let number3 = number3 {
// do something with numbers
} else {
fatalError("impossible")
}
} else {
fatalError("impossible")
}
} else {
fatalError("impossible")
}


Đừng bao giờ sử dụng as!try! Nếu không biết rõ và chắc cú rằng các biến hay các hàm mình dùng sẽ không xảy ra một ngoài lệ nào khác. Nếu có ngoại lệ nào đó, chắc chắn một điều là chương trình sẽ bị crash ngay.
Để kiểm tra nil một biến Optional ta nên:
Khuyên dùng
if someOptional != nil {
// do something
}
Không nên dùng
if let _ = someOptional {
// do something
}


Khởi tạo biến lazy
Thông thường nên khởi tạo biến lazy theo cách như sau:
lazy var locationManager: CLLocationManager = self.makeLocationManager()
private func makeLocationManager() -> CLLocationManager {
let manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.delegate = self
manager.requestAlwaysAuthorization()
return manager
}
lazy var pickerViewController: UIImagePickerController = {
let picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = false
picker.mediaTypes = [kUTTypeMovie as NSString as String, kUTTypeImage as NSString as String]
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
picker.sourceType = .camera
} else {
log.error("Cannot open cammera")
}
return picker
}()
view raw sampleLazy hosted with ❤ by GitHub


Sau bài này chắc các bạn cũng đã biết thêm một số kiến thức để làm việc với Class, Struct, Method, Closures, các properties….và làm việc quen với khởi tạo biến, hằng.
Hy vọng các bạn hiểu và biết thêm nhiều kiến thức hữu ích trong quá trình code của bản thân. Phần kế tiếp chúng ta sẽ đi sâu hơn về một số style và quy ước(convention) khi sử dụng tất cả các kiểu dữ liệu, Access control, control flow...mà các bạn thường code.

Hy vọng các bạn thích và học được nhiều kiến thức từ bài viết này. Mong các bạn chia sẽ nó để mọi người cùng học và cùng trao đổi. Mọi thắc mắc hay trao đổi về bài viết, các bạn có thể để lại bình luận bên dưới mình sẽ hỗ trợ sớm nhất.
Chân thành cảm ơn các bạn đã theo dõi.
VHX.

Post a Comment

0 Comments