Why Choose Struct Over Class?

前端 未结 16 2273

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:06

    Answering the question from the perspective of value types vs reference types, from this Apple blog post it would appear very simple:

    Use a value type [e.g. struct, enum] when:

    • Comparing instance data with == makes sense
    • You want copies to have independent state
    • The data will be used in code across multiple threads

    Use a reference type [e.g. class] when:

    • Comparing instance identity with === makes sense
    • You want to create shared, mutable state

    As mentioned in that article, a class with no writeable properties will behave identically with a struct, with (I will add) one caveat: structs are best for thread-safe models -- an increasingly imminent requirement in modern app architecture.

提交回复
热议问题