我目前在获取一些数据的同时进行类型转换很麻烦。
这是调试控制台中的数据:
(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 )
}
我敢肯定这只是一件小事,但是我已经在转换类型上玩了几个小时,但还没有找到解决方案。
有人有建议吗?将不胜感激。谢谢!
最佳答案
我看到您已经创建了一个元组,并且为了从该元组访问该数据,我建议采用这种方法
let posts = (7, dataDictioanry: ["name": "Doe", "id": 2042, "website": "http://somedomaine.com/", "logo": "http://somedomaine.com/img/", "category_id": 33, "category": "Institutional partners", "order": 7])
posts.dataDictioanry["name"]
关于arrays - Swift 3-强制转换值始终为零,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40786703/