swift4 特性

extension Date {

    private var timeInter:Double { return 1999 }
}

extension Date {

    // 获取struct 中private 属性
    public static func ==(lhs: Date, rhs: Date) -> Bool {

        return lhs.timeInter == lhs.timeInter
    }
}

// 关联类型 where 修饰
protocol TypeAssociate {

    associatedtype T  where Self.T == Any
    func useAssociateType(_:T)
}

class Class1:TypeAssociate {

    typealias T = Any
    func useAssociateType(_ name: Any) {

        debugPrint(name)
    }
}
//  Key Paths
struct Person {
    var nickname: String = ""
    var age: Double = 0.0
}

var p1 = Person(nickname: "zhansan", age: 8)
let name = p1[keyPath:\Person.age]

// 下标支持泛型
struct GenericDictionary {


    private var data: [Key: Value]

    init(data: [Key: Value]) {
        self.data = data
    }

    // 下标
    subscript(key: Key) -> T? {
        return data[key] as? T
    }
}

let dictionary = GenericDictionary(data: ["Name": "Xiaoming"])
let dicName: String? = dictionary["Name"]

// Encoding and Decoding
struct CommonModel:Codable {

    var name:String?
    var ver:String?
}

let model1 = CommonModel.init(name: "HAHA", ver: "1.00")
let encoded = try? JSONEncoder().encode(model1)
let decode = try? JSONDecoder().decode(CommonModel.self, from: encoded!)

你可能感兴趣的:(swift4 特性)