Swift Calss

前端之家收集整理的这篇文章主要介绍了Swift Calss前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
// 类是一种引用类型
class Person {
    var firstName: String
    var lastName: String
    
    // 构造函数
    init(firstName: String,lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
    
    func fullName() -> String {
        return self.firstName + " " + self.lastName
    }
}

var person1 = Person(firstName: "Steve",lastName: "Jobs");
var person2 = person1
person1 === person2 // 判断两个实例是否相等用===,不能用==, == 来判断值类型


什么时候用结构体,什么时候用类

把结构体看作值的时候,比如温度,经纬,坐标。。。

把类看作物体的时候。比如人,动物,车。。。

结构体是值类型,类是引用类型,类是可以被继承的,结构体比类更加的轻量级

看下面的例子

struct Point {
    var x = 0.0
    var y = 0.0
}

struct Size {
    var width = 0.0
    var height = 0.0
}

class Rectangle { // 矩形
    
    var origin = Point() // 远点
    var size = Size() // 长宽
    var lengthOfSide:Double { // 边长
        get {
            return size.width * 2 + size.height * 2
        }
    }
    
    var area:Double { // 面积
        get {
            return size.width * size.height
        }
    }
    
    var center:Point {
    
        // get方法
        get {
            let centerX = origin.x + size.width/2
            let centerY = origin.y + size.height/2
            return Point(x: centerX,y: centerY)
        }
        
        // set方法
        set {
            origin.x = newValue.x - size.width/2
            origin.y = newValue.y - size.height/2
        }
    }
    
    // 构造方法
    init(origin: Point,size: Size) {
        self.origin = origin;
        self.size = size
    }
}

var rect = Rectangle(origin: Point(x: 0,y: 0),size: Size(width: 10,height: 10))
rect.center = Point(x: 10,y: 10)
print(rect.origin)
print(rect.lengthOfSide)
print(rect.area)
上面打印结果:

Point(x: 5.0,y: 5.0)

40.0

100.0


类可以有类属性(静态属性

class Player {
    static var highestscore = 0 // 静态属性记录所有玩家的最高分
    var name:String
    var score:Int = 0
    init(name: String) {
        self.name = name
    }
    
    // 静态方法方法
    static func getPlayerHighestscore() -> Int {
        return Player.highestscore
    }
    
    func play() -> Void {
        let score = (Int)(arc4random() % 99)
        print("\(name) palyer is get socre \(score)")
        
        self.score += score
        print("total score of \(name) is \(self.score)")
        
        if score > Player.highestscore {
            Player.highestscore = score
            print("Player highestscore is \(Player.highestscore)\n");
        }
    }
}

var player1 = Player(name: "player1")
player1.play()
player1.play()
print("static method Player highestscore is \(Player.getPlayerHighestscore())\n")
上面打印结果:

player1 palyer is get socre 87

total score of player1 is 87

Player highestscore is 87


player1 palyer is get socre 29

total score of player1 is 116

static method Player highestscore is 87

猜你在找的Swift相关文章