美文网首页SwiftSwift开发iOS-swift
使用Playground快速练习Swift语法--类与面向对象

使用Playground快速练习Swift语法--类与面向对象

作者: 阳春面 | 来源:发表于2015-07-21 02:24 被阅读472次

    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定义和使用

    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 Train: 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())
    

    参考资料

    The Swift Programming Language 中文版
    The Swift Programming Language 2.0 官方教程

    本文作者: 阳春面
    原文地址:http://www.aswifter.com/2015/07/21/learn-swift-with-playground-class/

    欢迎关注我的微信公众号,分享Android 开发,IOS开发,Swift开发和互联网内容
    微信号:APP开发者

    相关文章

      网友评论

      本文标题:使用Playground快速练习Swift语法--类与面向对象

      本文链接:https://www.haomeiwen.com/subject/txmpqttx.html