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!
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
There are two problems here:
static
or class
members are allowed only inside a class
, andstatic
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With