Skip to content

Instantly share code, notes, and snippets.

@wuyongrui
Last active November 13, 2016 14:47
Show Gist options
  • Select an option

  • Save wuyongrui/b786fe1c0b70128414a54f6e4b43a92c to your computer and use it in GitHub Desktop.

Select an option

Save wuyongrui/b786fe1c0b70128414a54f6e4b43a92c to your computer and use it in GitHub Desktop.
Swift泛型的理解使用1
//
// ViewController.swift
// ObjectMappingDemo
//
// Created by wuyongrui on 2016/11/13.
// Copyright © 2016年 wuyr. All rights reserved.
//
import UIKit
protocol FMDBTable:Mappable {
static func model<T>(json:[String:Any]?, type:T.Type) -> T? where T : Mappable
}
extension FMDBTable {
static func formatJson(originJson:[String:Any]?) -> [String:Any]? {
return originJson
}
// type只是为了确定返回值,在函数中并没有什么作用
static func model<T>(json:[String:Any]?, type:T.Type) -> T? where T : Mappable {
if let formatJson = self.formatJson(originJson: json) {
return self.init(JSON: formatJson) as? T
}
return nil
}
}
struct User: FMDBTable {
var id = "" // 素材id
var name = "" // 素材名称
init?(map: Map) { }
mutating func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let json = ["id":"1", "name":"aName"]
let u = User.model(json: json, type: User.self)
print(u?.name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment