Swift 的模型框架。
假设我们使用 GitHub Issues API。它看起来是这样的
@objc enum GHState: Int, StringEnum {
case Open
case Closed
var rawValues: [Int: String] {
return [
GHState.Open.rawValue: "open",
GHState.Closed.rawValue: "closed",
]
}
}
class GHIssue: SwiftyModel {
var id: Int!
var URL: NSURL!
var HTMLURL: NSURL!
var number: Int!
var state: GHState = .Closed // enum must have a default value
var title: String!
var body: String!
var user: GHUser!
var labels: [GHLabel]?
var milestoneTitle: String?
override class func keyPathForKeys() -> [String: String]? {
return [
"URL": "url",
"HTMLURL": "html_url",
"milestoneTitle": "milestone.title",
]
}
override class func dateFormatterForKey(key: String) -> NSDateFormatter? {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
return dateFormatter
}
}
使用 CocoaPods。必需的 CocoaPods 版本至少为 0.36,它支持 Swift 框架。
Podfile
pod 'SwiftyModel'
建议您尝试 CocoaSeeds,它使用源代码而不是动态框架。
Seedfile
github 'SwiftyModel/SwiftyModel', '0.1.0', :files => 'SwiftyModel/SwiftyModel.swift'
let issue = GHIssue(JSONDictionary)
let issues = GHIssue.fromArray(JSONArray) as! [GHIssue]
{
"id": 123,
"author": {
"id": 456,
"name": "Suyeol Jeon",
"nickname": "devxoul"
}
}
class Post: SwiftyModel {
var id: Int!
var authorID: Int! // will be `456`
var authorNickname: String? // will be `devxoul`
override class func keyPathForKeys() -> [String: String]? {
return [
"authorID": "author.id",
"authorNickname": "author.nickname",
]
}
let post = Post(JSONDictionary)
post.toDictionary() // will return JSON dictionary
SwiftyModel 完全支持可选。不再需要 NSNumber
,也不再需要初始化属性。
class HealthData: SwiftyModel {
var birthyear: Int?
var weight: Float?
}
let health = HelathData(...)
if let weight = health.weight {
...
}
注意: 如果您使用原始类型的可选,SwiftyModel 与 Objective-C 不兼容。(例如
Int?
、Float!
、Bool?
)因为这些没有被转换为 Objective-C。
SwiftyModel 支持 Swift 有限制的枚举。有两种类型的枚举:SuperEnum
和 StringEnum
。SuperEnum
描述的是整型枚举,而 StringEnum
描述的是字符串枚举。
@objc
属性声明。SuperEnum
的原始类型必须是 Int
,实现 StringEnum
协议。StringEnum
必须实现 rawValues()
函数。SuperEnum
的示例
@objc enum Direction: Int, SuperEnum {
case Up
case Down
case Left
case Right
}
StringEnum
的示例
@objc enum GHState: Int, StringEnum {
case Open
case Closed
var rawValues: [Int: String] {
return [
GHState.Open.rawValue: "open",
GHState.Closed.rawValue: "closed",
]
}
}
您可以为模型定义关系。
class Post: SwiftyModel {
var author: User!
var comments: [Comment]?
}
SwiftyModel采用MIT许可。更多信息请参阅LICENSE文件。