Why Choose Struct Over Class?

前端 未结 16 2091

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

    Some advantages:

    • automatically threadsafe due to not being shareable
    • uses less memory due to no isa and refcount (and in fact is stack allocated generally)
    • methods are always statically dispatched, so can be inlined (though @final can do this for classes)
    • easier to reason about (no need to "defensively copy" as is typical with NSArray, NSString, etc...) for the same reason as thread safety
    0 讨论(0)
  • 2020-11-22 06:26

    In Swift, a new programming pattern has been introduced known as Protocol Oriented Programming.

    Creational Pattern:

    In swift, Struct is a value types which are automatically cloned. Therefore we get the required behavior to implement the prototype pattern for free.

    Whereas classes are the reference type, which is not automatically cloned during the assignment. To implement the prototype pattern, classes must adopt the NSCopying protocol.


    Shallow copy duplicates only the reference, that points to those objects whereas deep copy duplicates object’s reference.


    Implementing deep copy for each reference type has become a tedious task. If classes include further reference type, we have to implement prototype pattern for each of the references properties. And then we have to actually copy the entire object graph by implementing the NSCopying protocol.

    class Contact{
      var firstName:String
      var lastName:String
      var workAddress:Address // Reference type
    }
    
    class Address{
       var street:String
       ...
    } 
    

    By using structs and enums, we made our code simpler since we don’t have to implement the copy logic.

    0 讨论(0)
  • 2020-11-22 06:26

    Many Cocoa APIs require NSObject subclasses, which forces you into using class. But other than that, you can use the following cases from Apple’s Swift blog to decide whether to use a struct / enum value type or a class reference type.

    https://developer.apple.com/swift/blog/?id=10

    0 讨论(0)
  • 2020-11-22 06:27
    • Structure and class are user defied data types

    • By default, structure is a public whereas class is private

    • Class implements the principal of encapsulation

    • Objects of a class are created on the heap memory

    • Class is used for re usability whereas structure is used for grouping the data in the same structure

    • Structure data members cannot be initialized directly but they can be assigned by the outside the structure

    • Class data members can be initialized directly by the parameter less constructor and assigned by the parameterized constructor

    0 讨论(0)
提交回复
热议问题