zakishaheen zakishaheen - 3 months ago 9
Swift Question

Call a method once only for the lifetime of the object in Swift

Let's say we override

scrollViewDidScroll
method and for the first ever scroll only, we want to
doSomething()


A trivial way is to implement this is to have an instance level boolean variable and toggle/check it.

func scrollViewDidScroll(scrollView: UIScrollView!) {
if(!scrolled) {
scrolled = true;
doSomething();
}
}


I want a better solution that does not introduce a boolean variable
scrolled
. Something similar to
dispatch_once
but for the lifetime of the object rather than the whole process.

Is there a name for this pattern?

Answer

Something similar to dispatch_once but for the lifetime of the object rather than the whole process

Unfortunately, dispatch_once is not safe at instance level. People who use this in Objective-C are wrong to do so. That is why dispatch_once is not available in Swift.

Your if !scrolled pattern is in fact the correct implementation (except for your use of parentheses, semicolons, and other non-Swifty stuff). It's called a flag.