Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a static variable in Swift

I want to define a static variable to hold an NSDate object in Swift 2.2. I've tried the following:

static var interval:NSDate
var static interval:NSDate
var interval:static NSDate

None are working. I've written the same thing in Objective-C with the normal:

static NSString* str

But just isn't working in Swift.

Let me be more clear, I want to use a static interval in the didUpdateLocation method for locationManager so that a function will only happen after five minutes, but the user's location will still be seen in real time. This is how I did it in Objective C

-(void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
static NSDate *previous; //<--- This in Swift
static int run = 0;

CLLocation *location = locations.lastObject;

if (run == 0 || [location.timestamp timeIntervalSinceDate:previous] > 10)
{
    [_dbObj insert: location.coordinate.latitude : location.coordinate.longitude : [NSDate date] : location.timestamp];

    previous = location.timestamp;

    run++;
}

MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 2*1609.34, 2*1609.34);

[[self mapView] setRegion:viewRegion animated:YES];

}

From what I gather, I would need to create a class tat contains this static NSDate variable and instantiate it in the didUpdateLocations method. Yes? Thanks!

like image 733
Nick D. Avatar asked Jul 02 '16 20:07

Nick D.


2 Answers

In C,

static <type> <name>;

at the file level defines a variable name whose scope is restricted to the same compilation unit (roughly speaking: to the same source file), and the same applies to your Objective-C code

static NSString* str;

In Swift, you achieve the same effect with a private property defined on the file level:

private var date = NSDate()

date is visible only in the same source file, compare Access Control in the Swift blog.


Function scoped static variables are possible in Swift as well, but you have to put them inside a struct. Example:

func foo() -> Int {
    struct StaticVars {
        static var counter = 0
    }
    StaticVars.counter += 1
    return StaticVars.counter
}

print(foo()) // 1
print(foo()) // 2
like image 123
Martin R Avatar answered Oct 08 '22 07:10

Martin R


There are two problems here:

  • static or class members are allowed only inside a class, and
  • static members need to be initialized (or be declared optional to be initialized with nil).

Example:

class Foo {
    static var dt : NSDate = NSDate()
    static var optDt : NSDate? = nil
}

Note that the first restriction is not present in Objective-C: you are allowed to have free-standing static variables, in addition to function-scoped static variables.

like image 41
Sergey Kalinichenko Avatar answered Oct 08 '22 06:10

Sergey Kalinichenko