background preloader

Programming fundamental

Facebook Twitter

Value and Reference Types in Swift. Since we took a rather long hiatus before iOS 8 rolled out, I figure we would start again with a simple introduction to value and reference types in Swift as well as a test of our new demo playgrounds. A couple weeks ago, Apple posted a short article about the difference between value and reference types in Swift. The short and long of it is that struct, enum and tuple objects are all value types and objects defined as class are reference types. Value type data is copied when you assign it around whereas reference type data is passed by reference and points to the same underlying data. We’re used to dealing with reference types in Objective-C. For those of you coming from an Objective-C background, this example should not strike you as surprising: DemoObject *obj1 = [[DemoObject alloc] init];obj1.name = @"hello"; DemoObject *obj2 = obj1;obj2.name = @"what"; // prints “what what”NSLog(@"%@ %@",obj1.name,obj2.name); As a struct (i.e. a value type): And as a class (i.e. a reference type):