0
我目前在獲取一些數據時遇到了錯誤的類型轉換。Swift 3 - 在投入值時總是得到零
這裏是我在調試控制檯中的數據:
(7, ["name": Doe, "id": 2042, "website": http://somedomaine.com/, "logo": http://somedomaine.com/img/, "category_id": 33, "category": Institutional partners, "order": 7])
我相信這是真的很明顯,但我無法弄清楚如何獲得數據,如name
或id
和它給我頭痛。這是我所做的:
let section = (index as NSIndexPath).section + 1 as Int
let row = (index as NSIndexPath).row as Int
let sectionContent = posts![ section ] as? Array<Any>
let entry = (sectionContent?[ row ] as AnyObject)
之後,我能得到的最好的是nil
!
這裏是一個小更細節:posts
變量在類的,像這樣的頂部開始:
internal var posts: [ Int: AnyObject ]?
的數據分析是這樣的(原始數據來自JSON提要這是罰款):
func parsePosts(posts: [ Dictionary< String, AnyObject > ]) -> ([ Int: AnyObject ], Int) {
var theCategories = [ Int : AnyObject ]()
var theSponsors = [ Int : AnyObject ]()
var theDict = [ Int : Array<Any> ]()
for item in posts {
let itemID = item[ "id" ] as! Int
let sponsorMeta = item[ "sponsor_meta" ]
let category = sponsorMeta?[ "category" ] as? String
let title = item[ "title" ]
let name = title?[ "rendered" ] as? String
if !(category ?? "").isEmpty {
let order = Int((sponsorMeta?[ "order" ] as? String)!)
let categoryID = sponsorMeta?[ "category_id" ] as! Int
let categoryOrder = sponsorMeta?[ "category_order" ] as! Int
let website = sponsorMeta?[ "url" ] as? String
let logo = sponsorMeta?[ "logo" ] as? [ String: Any ]
let logoSizes = logo?[ "sizes" ] as? [ String: Any ]
let imgUrl = logoSizes?[ "medium_large" ] as? String
let sponsor = [ "id": itemID, "name": (name)! as String, "logo": imgUrl! as String, "website": (website)! as String, "category": category!, "order": order!, "category_id": categoryID ] as [ String : Any ]
let category = [ "name": category!, "order": categoryOrder ] as [ String : Any ]
theCategories[ categoryID ] = category as AnyObject
theSponsors[ itemID ] = sponsor as AnyObject
}
}
for (k, value) in theCategories {
let categoryOrder = value[ "order" ] as! Int
var catDict = [ Int : [ String: AnyObject ] ]()
for (_, element) in theSponsors {
let sponsorCategoryID = element[ "category_id" ] as! Int
if sponsorCategoryID == k {
let sponsorOrder = element[ "order" ] as! Int
catDict[ sponsorOrder ] = element as? [ String : AnyObject ]
}
}
let sortedCat = catDict.sorted(by: { $0.0 < $1.0 })
theDict[ categoryOrder ] = sortedCat
}
let sortedDict = theDict.sorted(by: { $0.0 < $1.0 })
var finalDict = [ Int: AnyObject ]()
for (t, v) in sortedDict {
finalDict[ t ] = v as AnyObject?
}
return (finalDict, theCategories.count)
}
我相信這只是一個很小的事情,但我已經玩了幾個小時與鑄造類型,我還沒有找到一個解決辦法。
有人有建議嗎?這將非常感激。謝謝!
無關你的問題,但應該沒有必要投'index'到'NSIndexPath':http://stackoverflow.com/questions/39631905/nsindexpath-and-indexpath-in-swift-3-0。 –
首先,'parsePosts'的返回類型是一個元組,其次是你使用了太多的'Any(Object)',其中類型顯然更具體'String'或'Int'。閱讀JSON並學習理解和區分類型。 – vadian
@vadian這就是我錯過的!謝謝!但是對於您的評論的其他部分,您是否有關於上述代碼的具體建議? – LancelotKiin