Class vs struct for Swift

Post on 12-Apr-2017

401 Views

Category:

Software

1 Downloads

Preview:

Click to see full reader

Transcript

Class or Structby Akira Hirakawa @ Burpple

which should I create? class or struct?

What is the difference?

Apple says…

Both can• Define properties

• Define methods

• Define subscripts

• Define initializers

• Be extended

• Conform to protocols

class can, struct can not

• Inheritance

• Type casting

• Deinitialize

• Reference counting

• class is allocated on heap, struct is on stack

Inheritance

struct SampleStruct { var num = 0 }

// cannot:( struct SampleStruct2: SampleStruct { }

Reference countingclass SampleClass { } var array: [SampleClass] = .... for p in array { // increment reference counting ... // decrement reference counting }

struct SampleStruct { } var array: [SampleStruct] = .... for p in array { ... }

main difference is…

struct is Value Type

class is Reference Type

demo

so,which should I create? class or struct?

Apple says…

create struct, when…

• data structure is simple

• properties are value type(struct)

• purpose is not to update itself, when data is passed to a method

ex: CGPointpublic struct CGPoint { public var x: CGFloat public var y: CGFloat public init() public init(x: CGFloat, y: CGFloat) }

• data structure is simple

• properties are value type

• purpose is not to update itself, when data is passed to a method

be careful of creating struct, when …

many properties

• That struct is value type means it’s copied when assigned

• the more properties a struct has, the more memory machine needs, when copied

class object in struct

demo

Struct• String

• Array

• Dictionary

• Bool

• Int

• Double

• Float

different from other languages

performance?

case 1

small class VS small struct

just create instance

case 2

class with properties VS struct with properties

just create instance

case 3

call method with parameter

case 4

NSArray VS Array

case 5

Array<class> VS Array<struct>

Summary

• having few properties is better for struct

• “struct or class” depends on purpose

• ex: class can be used for Data object from API

• ex: struct can be used for Request data to API

Akira Hirakawa http://akirahrkw.xyz

https://github.com/akirahrkw

Thanks:)

top related