zoukankan      html  css  js  c++  java
  • [Swift 语法点滴]—— Struct Vs Class

    摘自:stackoverflow.com/questions/24232799/why-choose-struct-over-class

    Structure instances are always passed by value, and class instances are always passed by reference. This means that they are suited to different kinds of tasks. As you consider the data constructs and functionality that you need for a project, decide whether each data construct should be defined as a class or as a structure.

    As a general guideline, consider creating a structure when one or more of these conditions apply:

    • The structure’s primary purpose is to encapsulate a few relatively simple data values.
    • It is reasonable to expect that the encapsulated values will be copied rather than referenced when you assign or pass around an instance of that structure.
    • Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced.
    • The structure does not need to inherit properties or behavior from another existing type.

    Examples of good candidates for structures include:

    • The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.
    • A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.
    • A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.

    In all other cases, define a class, and create instances of that class to be managed and passed by reference. In practice, this means that most custom data constructs should be classes, not structures.

    Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple reference to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multithreaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.

    With Structs there is no need to worry about memory leaks or multiple threads racing to access/modify a single instance of a variable.

    My personal advice is to always default to using a Struct because they greatly reduce complexity and fallback to Classes if the Struct becomes very large or requires inheritance.

     
  • 相关阅读:
    [转帖]Mootools源码分析03 Hash
    iphone的手势与触摸编程学习笔记
    怎样使项目中的cocos2d默认模板支持ARC内存管理
    xCode4.2下添加TableViewController会出现”Prototype cells“警告
    关于31天App教程示例中一些因SDK版本而出现的问题
    带你掌握二进制SCA检测工具的短板及应对措施
    HDZ城市行深圳站|AIoT时代,如何抓住智联生活的战略机会点?
    分析内部运行机制,教你解决Redis性能问题
    今天谈谈用户故事地图,不是用户故事
    云图说|ModelArts Pro:让AI开发更简单
  • 原文地址:https://www.cnblogs.com/chutianshu1981/p/4363001.html
Copyright © 2011-2022 走看看