關(guān)于Swift代碼風(fēng)格,能讓絕大部分人的眼前一亮,WTF?還能這樣寫?今天就帶來(lái)一段Swift常見(jiàn)的Generic + Protocol + Extension基礎(chǔ)代碼。
知識(shí)點(diǎn)介紹:
1.Generic,泛型便是擁有共同特性的類型的代表,定義特定的泛型去書寫代碼,免去了很多不必要的事情。
2.Protocol,不做很多解釋,你遵守我的協(xié)議就要幫我去做規(guī)定的事情。
3.Extension,為我們的日常代碼模塊化提供了很大的便利,讓代碼拓展更加輕松。
今天用這種方式實(shí)現(xiàn)UITableView方法做一些封裝。
比如這樣的代碼:
let cellIdentifier = "cellIdentifier"
let cell = tableView.dequeueReusableCell(withReuseIdentifier: cellIdentifier)
長(zhǎng)此以往,你或許已經(jīng)厭倦了這種方式。
今天的學(xué)習(xí)便是為此而開(kāi)展的,Go!
在Swift中,可以給Extension去實(shí)現(xiàn)一些底層的代碼,那么就意味著我們不用每次必須遵守協(xié)議、實(shí)現(xiàn)協(xié)議,因?yàn)槟憧梢栽贑lass的擴(kuò)展中讓它自己去實(shí)現(xiàn)。Excuse me?他自己都實(shí)現(xiàn)了,要我們何用?答案一會(huì)就知道。
1.首先聲明一個(gè)協(xié)議,并利用自身的拓展去實(shí)現(xiàn)這個(gè)協(xié)議
protocol Reusable {
/// 為cell準(zhǔn)備的Identifier
static var just_Idnentifier: String { get }
}
extension Reusable {
/// 利用自己的擴(kuò)展實(shí)現(xiàn)自己
static var just_Idnentifier: String {
return String(describing: self)
}
}
2.然后讓UITableViewCell遵守上面的協(xié)議
// MARK: - 遵守這個(gè)協(xié)議,且什么都不用操作,我們便有了just_Identifier這個(gè)屬性
extension UITableViewCell: Reusable { }
3.準(zhǔn)備工作到這里就結(jié)束了,接下來(lái)我們將用到泛型Generic,我們用一個(gè)UITableView的擴(kuò)展去添加一些方法
extension UITableView {
func just_dequeueReusableCell<T: UITableViewCell>(_: T.Type) -> T where T: Reusable {
guard let cell = self.dequeueReusableCell(withIdentifier: T.just_Idnentifier) as? T else {
fatalError("Could not dequeue cell with identifier: \(T.just_Idnentifier)")
}
return cell
}
func just_registerNib<T: UITableViewCell>(_: T.Type) {
register(UINib(nibName: T.just_Idnentifier, bundle: nil), forCellReuseIdentifier: T.just_Idnentifier)
}
}
最后:接下來(lái)讓咱們?nèi)タ匆幌率褂?/h5>
override func viewDidLoad() {
super.viewDidLoad()
tableView.just_registerNib(DemoCell.self)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.just_dequeueReusableCell(DemoCell.self)
cell.textLabel?.text = "Swift 最佳編程體驗(yàn)之 \(indexPath.row)"
return cell
}
這種方式是不是清爽了不少,且代碼更不容易出錯(cuò),逼格也上去了,所以還等什么呢?
override func viewDidLoad() {
super.viewDidLoad()
tableView.just_registerNib(DemoCell.self)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.just_dequeueReusableCell(DemoCell.self)
cell.textLabel?.text = "Swift 最佳編程體驗(yàn)之 \(indexPath.row)"
return cell
}
最后附上Demo