Some tips about coding in swift efficiently and elegantly. Download two playground files to have fun.
This playground file has some tips about how to write funny swift which saves your time and fingers.
private extension Selector {
static let btnTapped = #selector(ViewController.btnTapped(btn:))
}
btn.addTarget(self, action: .btnTapped, for: .touchUpInside)
extension Notification.Name {
static let changed = NSNotification.Name(rawValue: "changed")
}
NotificationCenter.default.post(name: .changed, object: nil)
if let v = city {
para["city"] = v
}
vs
city.flatMap { para["city"] = $0 }
user.storyboard
topic.storyboard
...
let userVC = AppStoryboard.user.viewController(UserViewController.self)
let topicVC = AppStoryboard.topic.viewController("TopicViewController")
let p = CGPoint(x:10, y:10.1)
let r = CGRect(x:10, y:10, width:100, height:100)
//lazy code
let p = CGPoint(10, 10.1)
let r = CGRect(10, 10, 100, 100)
let view = UIView()
.backgroundColor(.white)
.tag(1)
...
This playground file is all about Protocol and Protocol Oriented Programming.
let btn = UIButton() {
$0.frame = CGRect(x: 10, y: 10, width: 44, height: 44)
$0.backgroundColor = .red
...
}
final class ViewController: UIViewController {
...
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
addKeyboardObservers()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeKeyboardObservers()
}
}
extension User: RemoteFetchable { }
User.request(RemoteResouce("api.example.com", "/users", .get),
success: { data in
},
failure: { err in
})
extension Callable where Self.PhoneNumberType : SignedInteger {
func call() {
print("this is a number", phone)
}
}