Swift

Swift 类型属性、类型方法

2017-09-24  本文已影响47人  本源道人

简述

Swift中的类型(classstructenum等)属性和类型方法分别属于静态属性和静态方法。这种类型的属性、方法不属于类型的实例,而属于类型本身;类型第一次被加载时保存在静态存储区,在程序运行过程中一直存在并且只保存一份。在使用时,通过类型来调用类型属性和类型方法。

示例:

1、枚举(enum)

enum NetFire  {
    
    case WiFi
    case WWAN
    
    var connect: Bool {
        switch self {
        case .WiFi: return true
        case .WWAN: return false
        }
    }
    
    static var isUpload: Bool {
        return true
    }
    
    static func isDownload(flag: String) -> Bool {
        if flag == "largeFile" {
            return true
        }
        return false
    }
}

在枚举中,存储型属性无法使用,故而更不可能使用静态存储型属性了。计算型属性或方法用static修饰,是为枚举属性、枚举方法(静态属性、静态方法)。

2、结构体(struct)

struct Api {
    
    static let baseUrl = "https://www.baidu.com"
    
    static var login: String {
        return "/login"
    }
    
    static func register() -> String {
        return "/register"
    }
}

在结构体中,存储型属性、计算型属性、方法用static修饰,是为结构体属性、结构体方法(静态属性、静态方法)。

3、类(class)

class User: NSObject {
    
    static var name = "young"
    static var sex: String? {
        return "male"
    }
    static func getAge() -> Int {
        return 18
    }
    
    class var inheritableSex: String? {
        return "female"
    }
    class func inheritableAge() -> Int {
        return 28
    }
}

在类中,存储型属性、计算型属性、方法用static修饰,是为类属性、类方法(静态属性、静态方法)。PS: 在使用类属性或类方法时,如果需要子类继承重写,则使用class关键字修饰。

上一篇下一篇

猜你喜欢

热点阅读