Swift作为现代语言,面向对象编程是必须支持的。
class Person{
var name: String = ""
var age: Int = 0
init(name:String,age:Int){
self.name = name
self.age = age
}
deinit {
// 执行析构过程
}
}
let p1 = Person(name: "张三", age: 25)
print(p1.name)
init是类的构造函数,deinit为析构函数
Swift 会使用引用计数自动释放不再需要的实例以释放资源。
但是有时候需要在deinit中执行一些释放代码,比如关闭文件。
class Site{
var domain = ""
init(domain:String){
self.domain = domain
}
var url: String{
get{
return "http://"+domain;
}
set{
var url = newValue
let range = Range<String.Index>(start: url.startIndex,end: advance(url.startIndex, 7))
url.removeRange(range)
self.domain = url
}
}
}
let s1 = Site(domain: "www.aswifter.com")
print(s1.url)
s1.url = "http://www.baidu.com"
print(s1.domain)
set方法中的newValue是默认预设的变量,代表将要设置的值,newValue是常量,不能改变
class Counter {
var count = 0
func increment() {
count++
}
func incrementBy(amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
let counter = Counter()
// 初始计数值是0
counter.increment()
// 计数值现在是1
counter.incrementBy(5)
// 计数值现在是6
counter.reset()
// 计数值现在是0
class Hello{
class func sayHello(name: String){
print("hello " + name)
}
}
Hello.sayHello("阳春面")
subscript有点像‘[]’这个符号的运算符重载。
class TimesTable {
var multiplier: Int = 0
init(multiplier: Int){
self.multiplier = multiplier
}
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print("3的6倍是/(threeTimesTable[6])")
通过threeTimesTable[6]这样的下标调用,访问subscript定义的方法。
class Vehicle {
var currentSpeed = 0.0
var description: String {
return "traveling at /(currentSpeed) miles per hour"
}
func makeNoise() {
}
}
class Bicycle: Vehicle {
var hasBasket = false
override func makeNoise() {
print("Choo Choo")
}
}
let train = Train()
train.makeNoise()
继承的写法与C++相同,使用override关键字重写方法;如果一个方法不想被重写,可以在override加final关键字
使用is判断类型,使用as转换类型
let vehicles = [
Vehicle(),
Train()
]
var trainCount = 0
for item in vehicles{
if item is Train{
++trainCount
}
if let train = item as? Train{
train.makeNoise()
}
}
print("trainCount=/(trainCount)")
class Outer{
class Inner{
func hello() -> String{
return "hello"
}
}
}
let inner = Outer.Inner()
print(inner.hello())