宽容他人,放过自己。

swift 结构体

Posted on By anchoriteFili

import UIKit

class ViewController: UIViewController {
    
    struct student {
        
        var age: Int
        var name: String
        
        /**
         无参数构造函数
         */
        init() {
            name = "zs"
            age = 1
        }
        
        //有参数构造函数
        init(Name: String, Age: Int) {
            self.name = Name
            self.age = Age
        }
        
        //结构体内存放方法
        func GetAge() -> Int {
            return age
        }
    }
    
    struct Point {
        var x = 0.0
        var y = 0.0
        
//        //有参数构造函数 参数变量加_用法
//        init(_ x: Double,_ y: Double) {
//            self.x = x
//            self.y = y
//        }
        
    }
    
    struct CPoint {
        var p = Point()
        
        var GPoint: Point {
            get {
                return p
            }
            
            set(newPoint) {
                p.x = newPoint.x
                p.y = newPoint.y
            }
        }
    }
    
    var stu: student?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
//        stu = student()
        stu = student(Name: "ls", Age: 12)
        
        print("调用getAge方法,可以获取已经赋值的age \(stu?.GetAge())")
        print("name = \(stu?.name) age = \(stu?.age)")
        
        let data = [student(Name: "zhangsan",Age: 11),student(Name: "lisi",Age: 12),student(Name: "wangwu",Age: 13),student(Name: "xiaoer",Age: 14),]
        print(data)
        
        let p = Point(x: 10.0, y: 11.0)
        var CP = CPoint()
        CP.GPoint = p
        print("x = \(p.x) y = \(p.y)")
        print("x ===== \(CP.GPoint.x) y ===== \(CP.GPoint.y)")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}