Static function variables in Swift -
i'm trying figure out how declare static variable scoped locally function in swift.
in c, might this:
int foo() { static int timescalled = 0; ++timescalled; return timescalled; }
in objective-c, it's same:
- (nsinteger)foo { static nsinteger timescalled = 0; ++timescalled; return timescalled; }
but can't seem in swift. i've tried declaring variable in following ways:
static var timescalleda = 0 var static timescalledb = 0 var timescalledc: static int = 0 var timescalledd: int static = 0
but these result in errors.
- the first complains "static properties may declared on type".
- the second complains "expected declaration" (where
static
is) , "expected pattern" (wheretimescalledb
is) - the third complains "consecutive statements on line must separated ';'" (in space between colon ,
static
) , "expected type" (wherestatic
is) - the fourth complains "consecutive statements on line must separated ';'" (in space between
int
,static
) , "expected declaration" (under equals sign)
i don't think swift supports static variable without having attached class/struct. try declaring private struct static variable.
func foo() -> int { struct holder { static var timescalled = 0 } holder.timescalled += 1 return holder.timescalled } 7> foo() $r0: int = 1 8> foo() $r1: int = 2 9> foo() $r2: int = 3
Comments
Post a Comment