[英]Loop through NSArray and copy to new swift Array
嘿,伙計們,我對 swift 很陌生,我試圖遍歷從 plist 導入的 NSArray,然后我想用 CGPoints 列表填充二維 swift 數組。
我的 plist 是針對字母表的每個字母,在每個字母中我有一個 array[][] 第一行是筆划,第二行然后保存 x,y 坐標。
我的變量:
var letterPoints: NSDictionary?
var letterPointsArray: NSArray?
var letterCGPoints = [[Any]]()
我的代碼:
letterPoints = NSDictionary(contentsOfFile: Bundle.main.path(forResource: "LetterPoints", ofType: "plist")!)
letterPointsArray = (letterPoints?.value(forKey: image)) as? NSArray
var i = 0
for strokes in letterPointsArray! as! [[Int]]
{
for points in strokes
{
let x = strokes[i][0] // Error Value of type 'Int' has no subscripts.
let y = strokes[i][1]
letterCGPoints[i].append(CGPoint(x: x,y: y))
}
i = i+1
}
分配 x 和 y 時出現錯誤 - 'Int' 類型的值沒有下標。
我最初有這個工作,當我設置它時沒有為每個筆畫增加額外的行,但是在把它變成一個二維數組之后,我現在正在努力使用它,並且很迷失從我的網上找到正確的方法通過stackoverflow搜索和查看。 請原諒我對 swift 的無知和完全缺乏知識,非常感謝有關解決此問題的最佳方法的一些建議。 謝謝:)
從一開始就正確聲明您的數組
var letterPointsArray: [[[Int]]]?
然后直接投
letterPointsArray = (letterPoints?.value(forKey: "image")) as? [[[Int]]]
甚至更好的一行
let letterPointsArray = (letterPoints?.value(forKey: "image")) as? [[[Int]]]
然后通過使用enumerated()
您可以遍歷數組
if let letterPointsArray = (letterPoints?.value(forKey: "image")) as? [[[Int]]] {
for (i, strokes) in letterPointsArray.enumerated() {
檢查您的筆畫數組。 以下代碼可能有效。
let points: [[Int]] = [[10, 20], [30, 40]]
var i = 0
var j = 1
for point in points {
let a = point[i]
let b = point[j]
print(a,b)
}
i+=1
j+=1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.