Swift Then - Swift 初始化语法糖


MIT
iOS
Swift

软件简介

Then 是实现 Swift 对象初始化的一个语法糖

初始化 UILabel 并设置其属性

let label = UILabel().then {
  $0.textAlignment = .center
  $0.textColor = .black
  $0.text = "Hello, World!"
}

相当于:

let label: UILabel = {
  let label = UILabel()
  label.textAlignment = .center
  label.textColor = .black
  label.text = "Hello, World!"
  return label
}()

技巧

  • 在所有的 NSObject 子类中使用 then()

    let queue = OperationQueue().then {
    $0.maxConcurrentOperationCount = 1
    }

  • 在自定义类中使用,只需进行简单扩展:

    extension MyType: Then {}

    let instance = MyType().then {
    $0.really = “awesome!”
    }

  • 拷贝值类型数据时候 with()

    let newFrame = oldFrame.with {
    $0.size.width = 200
    $0.size.height = 100
    }
    newFrame.width // 200
    newFrame.height // 100

  • 使用 do() 减少类型处理

    UserDefaults.standard.do {
    $0.set(“devxoul”, forKey: “username”)
    $0.set("devxoul@gmail.com”, forKey: “email”)
    $0.synchronize()
    }

真实示例:

final class MyViewController: UIViewController {

  let titleLabel = UILabel().then {
    $0.textColor = .black
    $0.textAlignment = .center
  }

  let tableView = UITableView().then {
    $0.backgroundColor = .clear
    $0.separatorStyle = .none
    $0.register(MyCell.self, forCellReuseIdentifier: "myCell")
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    self.view.addSubview(self.titleLabel)
    self.view.addSubview(self.tableView)
  }

}

安装

  • For iOS 8+ projects with CocoaPods:

    pod ‘Then’

  • For iOS 8+ projects with Carthage:

    github “devxoul/Then”

  • UsingSwift Package Manager:

    import PackageDescription

    let package = Package(
    name: “MyAwesomeApp”,
    dependencies: [
    .Package(url: "https://github.com/devxoul/Then”, majorVersion: 2),
    ]
    )