Skip to content

Instantly share code, notes, and snippets.

@bryanluby
Last active July 28, 2016 14:57
Show Gist options
  • Save bryanluby/548beba8f8062c81ed68 to your computer and use it in GitHub Desktop.
Save bryanluby/548beba8f8062c81ed68 to your computer and use it in GitHub Desktop.
Static variable inside of a function in Swift.
func staticInsideFunction() {
struct Temp { static var hasAnimated = false }
if Temp.hasAnimated == false {
// ... do something only on the first function call.
Temp.hasAnimated = true
} else {
// ... do something on all subsequent function calls.
}
}
Copy link

ghost commented Feb 23, 2015

Very nice. Thank you for sharing!

@wiseseaman
Copy link

It didn't work for me and I've got the following errors:
Type 'Temp' nested in generic function 'myFunction' is not allowed
Static stored properties not yet supported in generic types

Any other suggestions?

@Gerst20051
Copy link

any idea how to do this in Swift 3? can't seem to figure it out.

screenshot 2016-07-22 17 17 38

@mingyeow
Copy link

This looks genius. What are examples where you would use this pattern?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment