# 能在编码时做的事，就不要推迟到运行时

#### Case 1：OC Runtime的Non fragile ivars

OC为了做到ABI兼容，改变了C、C++以来对象的内存结构，每个成员变量都需要两次寻址才能访问到。比如要获取obj的第n个变量的偏移地址，就要

``*((&obj->isa.cls->data()->ro->ivars->first)[N]->offset);``

``obj->myInt = 42;``

``````int32_t g_ivar_MyClass_myInt = 40;  // 全局变量
*(int32_t *)((uint8_t *)obj + g_ivar_MyClass_myInt) = 42;``````

``````struct ivar_t {
int32_t *offset;  //注意，这里是指针
const char *name;
const char *type;

//...
}``````

#### Case 2：矩阵相乘

``````struct Matrix {
let rows: Int
let columns: Int
}

func multiply(m1: Matrix, _ m2: Matrix) -> Matrix? {
// do the matrices have the correct sizes?
precondition(m1.columns == m2.rows)

// bunch of math...
}``````

``````protocol Dimension {
static var size: Int { get set }
}

func multiply<U: Dimension, V: Dimension, W: Dimension>
(m1: Matrix<U,V>, _ m2: Matrix<V,W>) -> Matrix<U,W> {
// bunch of math...
return Matrix<U,W>()
}``````

``````struct NumExamples: Dimension { static var size = 20 }
struct NumFeatures: Dimension { static var size = 10 }
struct OneDimensional: Dimension { static var size = 1 }

let A = Matrix<NumExamples, NumFeatures>()
let B = Matrix<NumFeatures, OneDimensional>()

let C = multiply(A, B)   // yay!

let D = multiply(B, A)   // compiler error``````

#### 参考链接

原文作者：NSFish
原文地址: https://segmentfault.com/a/1190000015684020
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。