Skip to content

Instantly share code, notes, and snippets.

@to4iki
Last active June 12, 2016 12:55
Show Gist options
  • Save to4iki/39ff6600a6b6d57204b3c625c636ade1 to your computer and use it in GitHub Desktop.
Save to4iki/39ff6600a6b6d57204b3c625c636ade1 to your computer and use it in GitHub Desktop.
Execute just once function (SeeAlso: http://qiita.com/YusukeHosonuma/items/95315add4004b59e5f00)
typealias ExecuteOnce = () -> Void
func executeOnce(f: () -> Void) -> ExecuteOnce {
var first = true
return {
if first {
first = false
f()
}
}
}
/// Ex01
final class ViewController: UIViewController {
private var someInitilize: ExecuteOnce = {}
override func viewDidLoad() {
someInitilize = executeOnce { [unowned self] in
// implement.
}
}
override func viewWillAppear(animated: Bool) {
someInitilize()
}
}
/// Ex02
final class UseCase {
private var executeOnce: ExecuteOnce? = {
// Implement.
print("first execute.")
}
func executeJustOnce() {
executeOnce?()
executeOnce = nil
}
}
let uc = UseCase()
uc.executeJustOnce() // first execute.
uc.executeJustOnce()
/// Ex03
func executeOnce(inout execute: ExecuteOnce?) {
if let f = execute {
f()
execute = nil
}
}
class UseCase2 {
var exec: ExecuteOnce? = {
print("first execute2.")
}
func executeJustOnce() {
executeOnce(&exec)
}
}
let uc2 = UseCase2()
uc2.executeJustOnce() // first execute2.
uc2.executeJustOnce()
/// Ex4
// http://qiita.com/codelynx/items/f0243d631f2448e89026
class UseCase3 {
private lazy var executeOnce: ExecuteOnce? = {
print("first execute3.")
self.executeOnce = nil
}
private lazy var executeOnce2: ExecuteOnce? = {
print("first execute3'.")
return nil
}()
func executeJustOnce() {
executeOnce?()
}
func executeJustOnce2() {
executeOnce2?()
}
}
let uc3 = UseCase3()
uc3.executeJustOnce() // first execute3.
uc3.executeJustOnce()
uc3.executeJustOnce2() // first execute3'.
uc3.executeJustOnce2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment