Why Choose Struct Over Class?

前端 未结 16 2283

Playing around with Swift, coming from a Java background, why would you want to choose a Struct instead of a Class? Seems like they are the same thing, with a Struct offeri

16条回答
  •  没有蜡笔的小新
    2020-11-22 06:10

    Structs are value type and Classes are reference type

    • Value types are faster than Reference types
    • Value type instances are safe in a multi-threaded environment as multiple threads can mutate the instance without having to worry about the race conditions or deadlocks
    • Value type has no references unlike reference type; therefore there is no memory leaks.

    Use a value type when:

    • You want copies to have independent state, the data will be used in code across multiple threads

    Use a reference type when:

    • You want to create shared, mutable state.

    Further information could be also found in the Apple documentation

    https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html


    Additional Information

    Swift value types are kept in the stack. In a process, each thread has its own stack space, so no other thread will be able to access your value type directly. Hence no race conditions, locks, deadlocks or any related thread synchronization complexity.

    Value types do not need dynamic memory allocation or reference counting, both of which are expensive operations. At the same time methods on value types are dispatched statically. These create a huge advantage in favor of value types in terms of performance.

    As a reminder here is a list of Swift

    Value types:

    • Struct
    • Enum
    • Tuple
    • Primitives (Int, Double, Bool etc.)
    • Collections (Array, String, Dictionary, Set)

    Reference types:

    • Class
    • Anything coming from NSObject
    • Function
    • Closure

提交回复
热议问题