Instance variable (ivar)
Essence
An instance variable (ivar) is data that each object stores separately: two Person instances have their own name and age, and changing one does not touch the other. The term "ivar" comes from Objective-C; in Swift the same thing is called a stored property.
Objective-C: ivars and @property (legacy)
@interface Person : NSObject {
NSString *_name; // an ivar declared explicitly (old style)
}
@property (nonatomic, copy) NSString *email; // the compiler synthesises _email
@end
@propertydeclares a getter/setter pair; with auto-synthesis the compiler creates the underscored ivar (_email) itself.- Inside the class the ivar was accessed directly (
_email), outside throughself.email. Ininitanddeallocusing the ivar was recommended, to avoid overridden setters and KVO. - The
strong/weak/copy/atomicattributes described ownership semantics.
Swift: stored and computed properties
final class Person {
var name: String // stored property — Swift's "ivar"
var email = "" // with a default value
lazy var greeting = "Hi, \(name)" // created on first access
var initials: String { String(name.prefix(1)) } // computed — no storage
var age = 0 {
didSet { print("age: \(oldValue) -> \(age)") }
}
init(name: String) { self.name = name }
}
let a = Person(name: "Ann"), b = Person(name: "Bob")
b.age = 30 // age: 0 -> 30; a has its own set of properties
print(a.age, b.age) // 0 30
- A stored property takes memory in every instance; a computed one does not — it is a pair of methods.
lazy varis initialised on first access (not thread-safe for classes).- Property observers
willSet/didSetreplace overriding setters. - Direct ivar access is impossible in Swift — only through the property; for
@objcclasses the compiler still creates an ivar, but that is an implementation detail. - All stored properties must be initialised by the end of
init— the compiler enforces it.
How it differs from other variables
- Local — lives in a function call.
- Static — one per type.
- Instance — one per object, lives with it; for a class on the heap, for a struct inside the value (on the stack or inside its container).
What the interviewer looks for
In an Objective-C context: the difference between _ivar and self.property and why init writes _name = name. In Swift: stored vs computed, lazy, observers, and the fact that a struct with let properties is fully immutable.