美文网首页swift
手把手带你学习Swift3.0(23):构造函数

手把手带你学习Swift3.0(23):构造函数

作者: 阿凡提说AI | 来源:发表于2017-10-30 20:54 被阅读0次

1.类的构造函数

//: Playground - noun: a place where people can play

import UIKit


/*
 @interface Person : NSObject
 
 @property (nonautomic, copy) NSString *name;
 @property (nonautomic, assign) NSInteger age;
 
 - (instanceType)initWithName:(NSString *)name age:(NSInteger)age;
 - (instanceType)initWithDict:(NSDictionary *)dict;
 
 @end
 
 
 Person *p = [Person alloc] init];
 Person *p = [Person alloc] initWithName:@"why" age:18];
 */

class Person {
    var name : String = ""
    var age : Int = 0
    
    // 在Swift开发中, 如果在对象函数中, 用到成员属性, 那么self.可以省略
    // 注意: 如果在函数中, 有和成员属性重名的局部变量,那么self.不能省略
    
    
    
    // 注意: 如果有自定义构造函数, 那么会将系统提供的构造函数覆盖掉
    init() {
        
    }
    
    init(name : String, age : Int) {
        self.name = name
        self.age = age
    }
    
    // Dictionary<String, Any> --> [String : Any]
    init(dict : [String : Any]) {
        /*
        let dictName = dict["name"]
        name = dictName as! String
        */
        if let name = dict["name"] as? String {
            self.name = name
        }
        
        if let age = dict["age"] as? Int {
            self.age = age
        }
    }
}


let p1 = Person()
let p2 = Person(name: "why", age: 18)
let p3 = Person(dict: ["name" : "why", "age" : 18])

print(p3.name, p3.age)

2.类的构造函数KVC

//: Playground - noun: a place where people can play

import UIKit

/*
 使用KVC条件
    1> 必须继承自NSObject
    2> 必须在构造函数中,先调用super.init()
    3> 调用setValuesForKeys
    4> 如果字典中某一个key没有对应的属性, 则需要重写setValue forUndefinedKey方法
 */

class Person : NSObject {
    var name : String = ""
    var age : Int = 0
    var height : Double = 0
    
    init(dict : [String : Any]) {
        /*
        if let name = dict["name"] as? String {
            self.name = name
        }
        
        if let age = dict["age"] as? Int {
            self.age = age
        }
        
        if let height = dict["height"] as? Double {
            self.height = height
        }
        */
        super.init()
        setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}

//let p = Person()

let p = Person(dict: ["name" : "why", "age" : 18, "height" : 1.88, "phoneNum" : "+86 110"])
print(p.age, p.name, p.height)

相关文章

网友评论

    本文标题:手把手带你学习Swift3.0(23):构造函数

    本文链接:https://www.haomeiwen.com/subject/odbmpxtx.html