我目前正在尝试DynamicArray
在 Swift 中实现我自己的数据类型。为此,我使用了一些指针。作为我的root
我使用的UnsafeMutablePointer
是泛型类型T
:
struct DynamicArray<T> {
private var root: UnsafeMutablePointer<T> = nil
private var capacity = 0 {
didSet {
//...
}
}
//...
init(capacity: Int) {
root = UnsafeMutablePointer<T>.alloc(capacity)
self.capacity = capacity
}
init(count: Int, repeatedValue: T) {
self.init(capacity: count)
for index in 0..<count {
(root + index).memory = repeatedValue
}
self.count = count
}
//...
}
现在你可以看到我还实现了一个capacity
属性,它告诉我当前分配了多少内存root
。因此,可以创建一个DynamicArray
使用init(capacity:)
初始化程序的实例,它分配适当的内存量并设置capacity
属性。
但后来我也实现了init(count:repeatedValue:)
初始化程序,它首先使用init(capacity: count)
. 然后它将那部分内存中的每个段设置为repeatedValue
.
当使用init(count:repeatedValue:)
带有数字类型的初始化程序时Int
,Double
或者Float
它工作得很好。然后使用Character
, 或者String
虽然它崩溃了。虽然它不会一直崩溃,但实际上有时可以通过编译几次来运行,正如可以在此处看到的那样。
var a = DynamicArray<Character>(count: 5, repeatedValue: "A")
println(a.description) //prints [A, A, A, A, A]
//crashes most of the time
var b = DynamicArray<Int>(count: 5, repeatedValue: 1)
println(a.description) //prints [1, 1, 1, 1, 1]
//works consistently
为什么会这样?它是否与不同长度的值有关String
并Character
持有不同的值?
更新#1:
现在@AirspeedVelocity 用init(count:repeatedValue:)
. 但是,它DynamicArray
包含另一个初始化程序,它最初的工作方式与init(count:repeatedValue:)
. 正如@AirspeedVelocity 所描述的那样,我将其更改为工作init(count:repeatedValue:)
:
init<C: CollectionType where C.Generator.Element == T, C.Index.Distance == Int>(collection: C) {
let collectionCount = countElements(collection)
self.init(capacity: collectionCount)
root.initializeFrom(collection)
count = collectionCount
}
我正在使用这里initializeFrom(source:)
描述的方法。而且由于符合它应该可以正常工作。
我现在收到此错误:collection
CollectionType
<stdin>:144:29: error: missing argument for parameter 'count' in call
root.initializeFrom(collection)
^
这只是一个误导性的错误信息吗?