//类可以不继承自NSObject
class Student {
//成员变量/实例变量
var name: String = ""
var age: Int = 20
//类的存储属性:static
static var classProperty: Int = 0
class var calculateProperty: Int {
set {
print("setter")
}
get {
return 200
}
}
//创建单利对象
class var defaultStudent: Student {
struct TempType {
static let student = Student()
}
return TempType.student
}
//普通成员方法与结构体相同
func normalFunc() {
print("普通方法")
}
//类方法:static或class
static func staticFunc() {
print("static方法")
}
class func classFunc() {
print("class方法")
}
/*
*/
}
//类方法测试
Student.staticFunc()
@H_301_404@ Student.classFunc()//类属性测试
//Student.classProperty = 100
print(Student.classProperty)
//实例对象
var laoWang = Student()
var xiaoWang = laoWang
//实例变量访问与结构体相同
laoWang.name = "小明"
laoWang.age = 25
print("name:\(laoWang.name) age:\(laoWang.age)")
//打印内容一样,说明指向同一对象,因此对象是引用类型
print("name:\(xiaoWang.name) age:\(xiaoWang.age)")
//判断变量是否指向类的同一个实例(===、!==)
if laoWang === xiaoWang {
print("YES")
}
原文链接:https://www.f2er.com/swift/321700.html