Structures and Classes : Quick Reference Guide

great work! a few notes:

  • all swift types, including structs and enums support typecasting, because all (copyable) types can conform to protocols.
enum E:Error
{
    case e
}

let erased:any Error = E.e

if let e:E = erased as? E
{
    ...
}
  • @_moveOnly structs do support deinitializers, at least according to the rumors.

  • letting an optional instance property use implicit initialization is a bad idea for performance reasons. write out var name:String? = nil explicitly, or better, assign it from an init. see this thread for an explanation why: What is a 'variable initialization expression'?

  • memberwise struct initializers will never be more than internal, to expose a public initializer, you have to write it out explicitly.

  • “a value type sends a copy whenever it is passed” is largely meaningless in practical swift development, both because of the prevalence of inlining, and because many structs are just values of references, which could possibly be copy-on-write references to make them behave as if they were values from a mutation perspective (e.g., [Int]).

    also, don’t confuse value types with value semantics. classes can have value semantics, if they are completely immutable, and a struct that wraps a class with mutable state can also have value semantics, by implementing copy-on-write.

  • a class value is literally a pointer. this is actually quite important when writing generic data structures, because if you can constrain the element type parameter to AnyObject the compiler is able to optimize layout more aggressively.

2 Likes