为什么这不起作用?
我试图将字典值赋值为false的错误是它失败的地方。它返回此错误“致命错误:数组索引超出范围”,如底部输出中所示。
var tupleCount = 0
for var i = 0; i < width; ++i {
for var j = 0; j < height; ++j {
arrayOfTupleClass.append(TupleClass(newX: i, newY: j, newXMax: width, newYMax: height))
print("arrayOfTupleClass.count: \(arrayOfTupleClass.count)")
print("arrayOfTupleClass[tupleCount]: \(arrayOfTupleClass[tupleCount])")
print("tupleCount: \(tupleCount)")
print("imageNum: \(imageNum)")
// placing '0' in place of dictionary Array index for simplicity
pointDictionaryArray[0][arrayOfTupleClass[tupleCount]] = false // <-- error here
tupleCount++
}
}
这就是我的词典数组的设置方式:
var arrayOfTupleClass = [TupleClass]()
var pointDictionaryArray = [[TupleClass: Bool]]()
这是我的TupleClass,它应该包含一个类作为字典的键,因为我使它可以删除。
class TupleClass: Hashable {
var x: Int!
var y: Int!
let yMax: Int!
let xMax: Int!
var weight: Int = 0
init(newX: Int, newY: Int, newXMax: Int, newYMax: Int) {
x = newX
y = newY
yMax = newYMax
xMax = newXMax
}
func setWeight(newWeight: Int) {
weight = newWeight
}
func getWeight() -> Int {
return weight
}
// required for the Hashable protocol
var hashValue: Int {
return x * yMax + y
}
};
// required function for the Equatable protocol, which Hashable inheirits from
func ==(left: TupleClass, right: TupleClass) -> Bool {
return (left.x == right.x) && (left.y == right.y)
}
这是输出:
arrayOfTupleClass.count: 1
arrayOfTupleClass[tupleCount]: My_Project_Name.TupleClass
tupleCount: 0
imageNum: 0
fatal error: Array index out of range
答案 0 :(得分:0)
据我所知,你不能使用swift Class Name作为参考(在较新的版本中也不能使用Obj-C)。但是,现在为什么要参考
let myclassName = self.className
let anotherClassName = NSClassFromString(self.classForCoder)
我刚刚把一个快速的游乐场示例打成了玩具:
import Foundation
debugPrint("Hello, World, Here we go from the PLayground template!")
let width = 100 // from your code
let height = 100 // from yoru code
typealias theTup = (newX: CGFloat, newY: CGFloat, newXMax: CGFloat, newYMax: CGFloat) // setting a typ alias to your tuple format
var theTupArray: [theTup] /*Strong typing*/ = [theTup]() // lets make a new array (with default zero element value)
// lets add some default values for testing, nothing special
theTupArray.appendContentsOf([
(newX: 1.0, newY: 2.0, newXMax: 2.0, newYMax: 5.0),
(newX: 2.0, newY: 3.0, newXMax: 4.0, newYMax: 10.0),
(newX: 3.0, newY: 4.0, newXMax: 6.0, newYMax: 15.0),
]
)
// now for-each element in the `theTupArray`... See Swift .forEach.. Or other shorthand methods like .map etc...
theTupArray.forEach { (
newX: CGFloat,
newY: CGFloat,
newXMax: CGFloat,
newYMax: CGFloat) in
debugPrint("NewX 1:\(newX), NewY: \(newY), NewXMax: \(newXMax), NewYMax: \(newYMax)", terminator: "\n")
}
希望这种快速重写有助于:)