Swift 項目實戰

項目實用

  1. 存在的循環引用-容易被忽略的地方
  • Cell中, 可以實用 [weak self]
    // 在cell中實用閉包會存在循環引用的情況
     cell.callback = {[weak self] type in
                if self?.callback != nil {
                    self?.callback!(type, model)
                }
    }   
  • 在SB中跳轉頁面的時候實用閉包
      if segue.identifier == "selectmic" {
            let selectmic = segue.destination as! SelectMicController
            selectmic.callback = {[weak self] str in
                self?.micName.text = str
            }
            
       }
  • 使用EmptyDataSet的時候,
tableView.emptyDataSetView({[weak self] (view) in
                view.titleLabelString(NSAttributedString(string: "沒有數據喲!"))
                    .didTapContentView { // 在此處使用weak self,還是會造成循環引用,self->tableView->emptyView.didTap->self
                        self?.tableView.mj_header.beginRefreshing()
                }
            })
  1. where 從句的用法,主要用於追加判斷
// 1. 在if中, 忽略寫法

if let model = UserManager.staned.userModel, model.id == "1" {
    // do somthing
}

// 2. 可以在for、do catch、switch中類似於if中一樣追加判斷
let tmp = (1, 2)

switch tmp {
case (let x, let y) where x > y: // 滿足條件x>y才進入case 語句中
    // do somthing
default: break
}


// 在class、protocol、類似於在後面追加實現條件
// RxSwift 一個UIViewController 的擴展,在擴展中只有在UIViewController中實現該方法

extension Reactive where Base: UIViewController {

        /// Bindable sink for `title`.
        public var title: Binder<String> {
            return Binder(self.base) { viewController, title in
                viewController.title = title
            }
        }
    
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章