Reputation: 1
Global variables are variables that are defined outside of any function, method, closure, or type context.《The Swift programming Guide》。
So this is a question:
class Dog {
var name: String?
func run(){
}
}
name is a global variable or property?
@implementation Dog{
NSString *name;
- (void)run{
}
}
name is a global variable or property?
Upvotes: 0
Views: 186
Reputation: 7605
Since a class is a type, name
is a property in the Swift example.
In the Objective-C example, name
is a global variable since properties are defined in the @interface
scope and requires a @property
declaration. (Instance variables don't require any declaration but they have to be inside a block inside the @interface
or @implementation
scopes.)
Upvotes: 2
Reputation: 299275
name
is inside a type context, class Dog
, so it is a property of Dog
instances.
The second example is similar to Objective-C (it definitely isn't Swift), but it's incorrect ObjC syntax. It's not clear what the actual code is. If you meant:
@implementation Dog
NSString *name;
- (void)run {
}
@end
then name
is a global, but should never write it that way. It's very confusing. The name
declaration should go outside the @implementation
block to avoid confusion. If, on the other hand, you meant to write:
@implementation Dog {
NSString *name;
}
- (void)run {
}
@end
Then name
is a private instance variable (which is not the same thing as a property). This is an unusual syntax in modern ObjC and should generally be avoided.
Upvotes: 1