6

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!

3
  • 4
    You can define static property within a class using the first syntax. But where are you trying to do this? The Objective-C static keyword can be used at different scopes (a global, to make it accessible only to that compilation unit; a local variable within a method implementation) that aren't permitted in Swift. You have to show us where you're trying to do this for us to comment further. Commented Jul 2, 2016 at 20:40
  • 1
    Possible duplicate of Static properties in Swift Commented Jul 2, 2016 at 20:43
  • That are function-scoped static vars, and my suggestion should work. – But why don't you make them instance variables of the enclosing class instead? Commented Jul 4, 2016 at 4:46

2 Answers 2

15

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
Sign up to request clarification or add additional context in comments.

8 Comments

Private and static are definitely NOT the same thing. Private only affects scope, i.e., visibility. Static in a C-family language has many different semantics, depending on the context in which it is used. At file scope it's similar to private, at class scope it denotes a class variable vs an instance variable, at subroutine scope it denotes a persistent non-stack based value, etc.
@DavidBerry: That's why I explicitly said "static on the file level". I did not mention "static on class scope" (nor does the question, as far as I can tell). "At file scope it's similar to private," – that's exactly what I tried to explain.
I guess my point was in agreement with @rob, there's not enough info to answer the question because they say nothing about scope. My assumption was/is actually that they're asking about function scoped...
@DavidBerry: It seems that you were right with your assumption, the question is about function-scoped static variables. I have updated the answer accordingly.
Vehicle().car = "Mercedes", Vehicle().car, giving Lexus , but, let vehObj = Vehicle(); vehObj.car, giving Mercedes . I don't know why. Whats the diff? Can u Guide me?
|
5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.