Created
September 27, 2016 19:22
-
-
Save rayfix/e977e5ba7137036be1aa8c96c95605c2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //: Playground - noun: a place where people can play | |
| import UIKit | |
| extension String { | |
| var isBlank: Bool { | |
| return trimmingCharacters(in: CharacterSet.whitespaces).isEmpty | |
| } | |
| } | |
| protocol StringProvider { | |
| var getString: String { get } | |
| } | |
| extension String: StringProvider { | |
| var getString: String { | |
| return self | |
| } | |
| } | |
| extension Optional where Wrapped: StringProvider { | |
| var isBlank: Bool { | |
| return self?.getString.isBlank ?? true | |
| } | |
| } | |
| var s1: String? = nil | |
| var s2: String? = "" | |
| var s3: String? = " " | |
| var s4: String? = "car" | |
| s1.isBlank | |
| s2.isBlank | |
| s3.isBlank | |
| s4.isBlank | |
| // isBlank is the Rails way. A more Swift way to do it is to consider how it is used | |
| // at call site. We want to operate on a filled in text string. Make a property | |
| // filled that returns the string or nil if the string is empty. | |
| extension String { | |
| var filled: String? { | |
| return trimmingCharacters(in: .whitespaces).isEmpty ? nil : self | |
| } | |
| } | |
| // what about optionals?... for that we can just use standard optional chaining! (aka flatMap) | |
| let username = UILabel() | |
| username.text = "ray" | |
| let password = UILabel() | |
| password.text = "secret" | |
| func login(username: UILabel, password: UILabel) { | |
| guard let username = username.text?.filled else { | |
| print("no username") | |
| return | |
| } | |
| guard let password = password.text?.filled else { | |
| print("no password") | |
| return | |
| } | |
| print (username, password) | |
| } | |
| login(username: username, password: password) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment