use*_*930 10 ios swift swifty-json
我正在看Ray Rayderlich教程http://www.raywenderlich.com/90971/introduction-mapkit-swift-tutorial他正在使用这个函数:
class func fromJSON(json: [JSONValue]) -> Artwork? {
// 1
var title: String
if let titleOrNil = json[16].string {
title = titleOrNil
} else {
title = ""
}
let locationName = json[12].string
let discipline = json[15].string
// 2
let latitude = (json[18].string! as NSString).doubleValue
let longitude = (json[19].string! as NSString).doubleValue
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
// 3
return Artwork(title: title, locationName: locationName!, discipline: discipline!, coordinate: coordinate)
}
Run Code Online (Sandbox Code Playgroud)
由于我在我的项目中使用SwiftyJSON,我想继续使用它,所以我考虑基于此重写这个功能.
如果我理解正确,这个函数需要一个json节点并Artwork
从中创建对象.
那么如何使用SwiftyJSON引用单个json节点?
我试过做:
class func fromJSON(JSON_: (data: dataFromNetworking))->Artwork?{
}
Run Code Online (Sandbox Code Playgroud)
但它会导致错误use of undeclared type dataFromNetworking
.另一方面,这正是他们在文档中使用它的方式https://github.com/SwiftyJSON/SwiftyJSON
你可以帮我改写吗?
我的建议:分开model layer
从presentation layer
.
首先,您需要一种表示数据的方法.结构非常适合这种情况.
struct ArtworkModel {
let title: String
let locationName: String
let discipline: String
let coordinate: CLLocationCoordinate2D
init?(json:JSON) {
guard let
locationName = json[12].string,
discipline = json[15].string,
latitudeString = json[18].string,
latitude = Double(latitudeString),
longitueString = json[19].string,
longitude = Double(longitueString) else { return nil }
self.title = json[16].string ?? ""
self.locationName = locationName
self.discipline = discipline
self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,ArtworkModel能够从json初始化自己.
现在Artwork
(符合MKAnnotation
)变得更容易.
class Artwork: NSObject, MKAnnotation {
private let artworkModel: ArtworkModel
init(artworkModel: ArtworkModel) {
self.artworkModel = artworkModel
super.init()
}
var title: String? { return artworkModel.title }
var subtitle: String? { return artworkModel.locationName }
var coordinate: CLLocationCoordinate2D { return artworkModel.coordinate }
}
Run Code Online (Sandbox Code Playgroud)
你的功能现在变成了
class func fromJSON(json: JSON) -> Artwork? {
guard let model = ArtworkModel(json: json) else { return nil }
return Artwork(artworkModel: model)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
449 次 |
最近记录: |