Avn*_*arr 1 tuples compile-time ios swift
我想用5个特定类型的元素强制执行(编译时)数组
我无法找到解决方案,因此通过创建元组来解决问题
(我知道这是滥用)
typealias FiveElementArray = (MyType,MyType,MyType,MyType,MyType) // mock array by using typed tuple
Run Code Online (Sandbox Code Playgroud)
它适用于我的需求 - 直到我需要在运行时通过索引访问元素.
例如:
var DB = FiveElementArray // the tuple of 5 elements
tableView(tableView : UITableView,cellForRowAtIndexPath:indexPath) -> UITableViewCell {
// would like to populate with the value at index
DB[indexpath.row] // no such syntax for tuples
}
Run Code Online (Sandbox Code Playgroud)
那么如何使用具有静态类型长度的正确swift数组
防止对值类型(例如数组)进行不必要更改的方法是didSet在其上放置一个观察者来充当警卫:
var arr = [1, 2, 3, 4, 5] {
didSet {
if arr.count > 5 {arr = oldValue}
}
}
arr.append(6)
println(arr) // [1, 2, 3, 4, 5], that change was illegal
arr[2] = 100
println(arr) // [1, 2, 100, 4, 5], that change was legal
Run Code Online (Sandbox Code Playgroud)
但是如果这还不够好,你需要使用一个包装器,即有一个数组而不是一个数组:
struct FiveElementArray<T> {
private var arr = Array<T>()
// methods for access go here
}
Run Code Online (Sandbox Code Playgroud)
"访问方法"可以包括修改您允许的所有数组的所有方法的实现(例如,下标),并且可以简单地不实现您不允许的所有方式(例如,追加和扩展).
如果你坚持编译时检查,那么只需坚持你的元组,甚至编写自己的集合.但在那一点上,我认为你只是对你的要求愚蠢.struct wrapper可以防止不必要的更改; 因此它是一种保证,因此无需在编译时进行保证.
| 归档时间: |
|
| 查看次数: |
2624 次 |
| 最近记录: |