美文网首页
Swift 语法进阶

Swift 语法进阶

作者: 醉看红尘这场梦 | 来源:发表于2018-01-09 21:41 被阅读139次

    初始化字符串

    let wiseWords = "输入换行符号\n,输入双引号\",输入单引号"
    print(wiseWords)
    
    let dollarSign = "\u{24}"
    let blackHeart = "\u{2665}"
    let sparkLingHeart = "\u{1F496}"
    print(dollarSign)
    print(blackHeart)
    print(blackHeart)
    
    
    字符串常用方法介绍
    var varString = "iphonetrain"
    varString = "iphonetrain.com"
    
    let constantString = "the url"
    /*
     编译错误无法调用"+="类型
    constantString += "is iphonetran.com"
    */
    
    let string1 = "hello"
    let string2 = "iphonetrain"
    var welcome = string1 + string2
    
    
    var instruction = "look over"
    instruction += string2
    
    
    let exclamationMark: Character = "!"
    welcome.append(exclamationMark)
    
    //使用字符串Character
    for Character in "iphonetrain" {
        print(Character)
    }
    
    //计算字符数量
    let countring = "iphonetrain ????, is ????, the ????, best ????"
    print("countring has \(strlen(countring)) Characters")
    
    //字符串插值
    let multiplier = 5
    let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
    print(message)
    
    //比较字符串
    let quotation = "the url is iphonetran.com"
    let sameQutation = "the url is iphonetran.com."
    if quotation == sameQutation {
        print("相同")
    }else{
        print("不相同")
    }
    
    let completeString = "the url is iphonetran.com"
    //判断是否包含前缀
    if completeString.hasPrefix("the url"){
        print("包含前缀the url")
    }else{
        print("不包含前缀")
    }
    
    //判断是否包含后缀
    if completeString.hasSuffix(".com"){
        print("包含前缀.com")
    }else{
        print("不包含前缀")
    }
    
    //大小写
    let normal = "Could you help me,please?"
    let uppercaseString = normal.uppercased()
    print(uppercaseString)
    
    let lowercaseString = normal.lowercased()
    print(lowercaseString)
    
    let capitalizedString = normal.capitalized
    print(capitalizedString)
    
    //空判断
    var emptyString = ""
    if emptyString.isEmpty{
        print("emptyString字符串为空")
    }
    
    //字符串截取
    var completeString: String = "the url is iphonetrain.com"
    
    var formString = (completeString as NSString).substring(from: 5)
    var toString = (completeString as NSString).substring(to: 4)
    var rangeString = (completeString as NSString).substring(with: NSMakeRange(4, 1))
    print(formString)
    print(toString)
    print(rangeString)
    
    

    集合类型

    数组
    var teachers = ["Mr.wang","Mr Liu"]
    var arrayCount = teachers.count
    print("tearcher数组一共\(arrayCount)位老师")
    
    if teachers.isEmpty{
        print("The teachers array is empty")
    }else{
        print("The teachers array is not empty")
    }
    //teachers现在包含三个元素
    teachers.append("Mr Li")
    //teachers现在包含四个元素
    teachers += ["Mr jiang"]
    //teachers现在包含六个元素
    teachers += ["Mr jiang","Heri.Ren"]
    //teachers现在包含七个元素,清单的第一个元素现在是HomgJun
    teachers.insert("HomgJun", at: 0)
    //索引为1的元素已从数组删除掉了
    let oneTearcher = teachers.remove(at: 1)
    print(teachers)
    //数组的最后一个元素被删除
    let delTearcher = teachers.removeLast()
    
    //数组的遍历
    for item in teachers {
        print(item)
    }
    
    字典
    var languageDic = ["French":"fr","English":"en"]
    var dicCount = languageDic.count
    //languageDic字典现在有3个数据项
    languageDic["German"] = "ger"
    
    let oldValue = languageDic.updateValue("Ge", forKey: "German")
    print(oldValue)
    
    let englishShorthand = languageDic["English"]
    
    //English现在被移除了
    languageDic["English"] = nil
    
    //字典的遍历
    for (language,shorthand) in languageDic {
        print("\(language): \(shorthand)")
    }
    
    //遍历key
    for language in languageDic.keys {
        print(language)
    }
    
    //遍历values
    for shorthand in languageDic.values {
        print(shorthand)
    }
    
    let languageArray = Array(languageDic.keys)
    print(languageArray)
    let sharthandArray = Array(languageDic.values)
    print(sharthandArray)
    

    解包(if let)

    if let 语句
    let possibleString: String? = "An optional string"
    print(possibleString)
    
    //隐式解包
    if let sValue = possibleString {
        let stirngValue = sValue
    }
    
    

    创建类和属性
    class SomeClass {
        var value1 = 0
        var value2 : Int = 0
    }
    //访问存储属性
    var someClass = SomeClass()
    var newValue1 = someClass.value1
    
    var teachers: Int = 0 {
        //完整的属性监控器
        willSet(newTearchers){
            print("新增老师\(newTearchers)")
        }
        didSet(old){
            if teachers > old {
                print("与原来相比增加了\(teachers - old) 位老师")
            }
        }
    }
    

    方法

    实例方法
    class GameRules {
        var score = 0
        
        func additive(){
            print(score)
        }
        
        func subtraction(amount: Int){
            score -= amount
            print(score)
        }
        
        func reset() {
            score = 0
            print(score)
        }
    }
    //实例化
    let gameRules = GameRules()
    //加1
    gameRules.additive()
    //减去指定的值
    gameRules.subtraction(amount: 10)
    //设置为0
    gameRules.reset()
    
    
    类方法
    class Weaponry {
        class func betterArmed(){
            print("你拥有最好的装备")
        }
    }
    
    //使用类型方法
    Weaponry.betterArmed()
    
    class NewWeaponry: Weaponry {
        override class func betterArmed() {
            print("子类,重写了类的方法")
        }
    }
    
    
    self属性
    class NewClass {
        var count : Int = 100
        func printcount(){
            var count: Int = 50
            //使用局部变量,输出50
            print(count)
            //使用存储变量,输出100
            print(self.count)
        }
    }
    

    函数和闭包

    函数
    func additive(a: Int, b: Int) -> Int {
        return a+b
    }
    
    func multiplication(a: Int, b: Int) -> Int {
        return a*b
    }
    
    //不带任何参数的返回值函数
    func printWelcome(){
        print("Welecome Swift Class!")
    }
    
    //使用函数类型
    var newFunc: (Int,Int) -> Int = additive
    print("Result:\(newFunc(2,3))")
    
    //函数类型的参数
    func printAdditiveResult(addFun: (Int, Int) -> Int, a:Int, b: Int) {
        print("Result: \(addFun(a,b))")
    }
    printAdditiveResult(addFun:additive, a: 4, b: 6)
    
    //函数类型的返回值
    //定义一个自增函数,传入Int类型参数,返回Int类型
    func increase(input: Int) -> Int {
        return input + 1
    }
    //定义一个自减函数,传入Int类型函数,返回Int类型
    func reduce(input: Int) -> Int {
        return input - 1
    }
    //定义一个返回函数类型的函数
    //传参Bool型,返回一个函数,该函数类型是(Int) -> Int
    func chooseFunction(bockwards: Bool) -> (Int) -> Int {
        return bockwards ? reduce : increase
    }
    
    let aFunc = chooseFunction(bockwards: 3>2)
    print(aFunc(3))
    
    //嵌套函数
    func mainFunction(input: Int) -> Int {
        func internalFunction(input: Int) -> Int {
            return input - 1
        }
        //调用内部函数internalFunction
        return internalFunction(input: 1)
    }
    
    闭包
    func GetList(arr: [Int], pre:(Int) -> Bool) ->[Int]{
        //定义一个空的可变整数集合
        var tempArr = [Int]()
            for temp in arr {
                if pre(temp){
                    tempArr.append(temp)
                }
                return tempArr;
        }
    }
    

    初始化与反初始化

    struct School {
        var name: String
        init() {
            name = "无限互联网"
        }
    }
    
    //初始化结构体
    var s = School()
    print("The school name is \(s.name)")
    
    //自定义初始化
    struct Distance {
        var meters: Double = 0.0
        
        init(fromKm km: Double) {
            meters = km * 1000.0
        }
        
        init(fromCm cm: Double) {
            meters = cm / 100.0
        }
    }
    //使用自定义的初始化方法,初始化结构体
    let metersl = Distance(fromKm: 1.0)
    print(metersl.meters)
    
    let meters2 = Distance(fromCm: 100.0)
    print(meters2.meters)
    
    //颜色构造器
    struct SwiftColor {
        let red = 0.0, green = 0.0, blue = 0.0
        init(red: Double,green: Double,blue: Double) {
            self.red = red
            self.green = green
            self.blue = blue
        }
    }
    
    
    deinit {
        //执行反初始化
    }
    
    

    继承

    class Base {
        var baseName: String
        var baseTag: Int
        func getBaseName() -> String {
            return baseName
        }
        init() {
            baseName = "Base Class"
            baseTag = 1
        }
    }
    
    //子类生成
    class SubClass: Base {
        func getsubName() -> String {
            return getBaseName() + "的子类"
        }
    }
    
    重写
    class overrideClass: Base {
        override func getBaseName() -> String {
            return "New Base Class"
        }
    }
    
    //重写属性
    class NewBaseName: Base {
        //重写父类Base的baseName属性
        override var baseName: String {
        //具有读方法
        
        get {
            return super.baseName
        }
        set {
            super.baseName = "New Name"
            }
        }
    }
    
    

    扩展

    扩展属性
    extension Double {
        var cm: Double{
            return self / 100.0
        }
        var km: Double{
            return self * 1000.0
        }
        var m: Double{
            return self
        }
    }
    //使用扩展
    let meters1 = 10.cm
    print("10 cm is \(meters1) meters")
    
    let meters2 = 5.0.km
    print("5 km is \(meters2) meters")
    
    //用于计算中
    let aMarathon = 42.km + 195.m
    print("A marmathon is \(aMarathon) meters long")
    
    扩展构造器
    struct Size {
        var width = 0.0,height = 0.0
    }
    
    struct Point {
        var x = 0.0,y = 0.0
    }
    
    struct Rect {
        var origin = Point()
        var size = Size()
    }
    //默认构造器
    let defaultRect = Rect()
    
    //成员构造器
    let memberwiseRect = Rect(origin: Point(x: 3.0, y: 3.0), size: Size(width:6.0,height:6.0))
    
    扩展方法
    extension Int {
        func cubedInt() -> Int {
            return self * self * self;
        }
    }
    
    let cubed3 = 3.cubedInt()
    print(cubed3)
    
    let cubed4 = 4.cubedInt()
    print(cubed4)
    
    extension Int {
        mutating func square() {
            self = self * self
        }
    }
    //使用修改实例方法
    var someInt = 3
    someInt.square()
    
    扩展下脚本
    extension Int {
        subscript(index: Int) -> Int {
            var decimal = 1
        for _ in 1...index{
            decimal *= 10
        }
            return (self/decimal) % 10
        }
    }
    
    print(9876534324567[1])
    print(9876534324567[3])
    print(9876534324567[5])
    print(9876534324567[6])
    print(9876534324567[13])
    
    扩展嵌套类型
    extension String {
        //扩展枚举一个Biological,分别为:植物,动物,微生物,未知
        enum Biological {
            case plants,Animals,Microbes,Unknown
        }
        var biological: Biological {
            switch String(self).lowercased() {
            case "rose","lily","orchild","azalea","apple":
                return .plants
            case "horse","ox","sheep","deer","cat","dog","bear","rabbit":
                return .Animals
            case "Bacterial","Fungus","Viruses":
                return .Microbes
            default:
                return .Unknown
            }
        }
    }
    
    func printStringKinds(word: String){
        print(word)
        
        switch word.biological {
        case .plants:
            print("plants")
        case .Animals:
            print("Animals")
        case .Microbes:
            print("Microbes")
        case .Unknown:
            print("Unknown")
    }
    print("\n")
    }
    printStringKinds(word: "sheep")
    
    协议
    • 协议可以要求采纳协议的类型实现指定的构造器。你可以像编写普通构造器那样,在协议的定义里写下构造器的声明,但不需要写花括号和构造器的实体:
    protocol CgProtocol : NSObjectProtocol {
        
        func compare(value : Int) ->Bool
    }
    
    class ClassA : NSObject,CgProtocol {
        
        var age = 0;
        init(age:Int){
            
            self.age = age
        }
        func compare(value : Int) ->Bool{
            if age > value {
                return true
            } else {
                return false
            }
        }
    }
    
    let classA = ClassA(age: 100)
    let ret = classA.compare(value: 5)
    print("ret is \(ret)")
    
    

    自动引用计数

    class Exam {
        let name: String?
        init(na: String) {
            self.name = na
            print("\(String(describing: self.name)) 被初始化")
        }
        deinit {
            print("\(String(describing: self.name)) 被反初始化")
        }
    }
    
    
    类实例之间的循环强引用解决办法
    class Teacher {
        var tName: String = ""
        //添加学生对象,初始化nil
        var student: Student?
        
        init(name: String) {
            tName = name
            print("老师\(tName) 实例初始化完成.")
        }
        func getName() -> String {
            return tName
        }
        deinit {
            print("老师\(tName) 实例反初始完成化.")
        }
    }
    
    
    class Student {
        var sName : String = ""
        //添加老师对象,初始化nil
        var teacher : Teacher?
        
        init(name: String) {
            sName = name
            print("学生\(sName) 实例初始化完成.")
        }
        func getName() -> String {
            return sName
        }
        deinit {
            print("学生\(sName) 实例反初始完成化.")
        }
    }
    
    var teacher : Teacher?
    var student : Student
    
    //创建实例老师,并初始化,name 引用计数1
    teacher = Teacher(name: "汪老师")
    //创建实例学生,并初始化,name 引用计数1
    student = Student(name: "张三同学")
    
    /**
     老师实例中的学生对象引用计数+1
    teacher!.student = student
     学生实例中的学生对象引用计数+1
    student!.teacher = teacher
    
     引用计数-1但是不等于0,因为学生还保留一份老师的引用计数
    teacher = nil
     引用计数-1但是不等于0,因为老师还保留一份学生的引用计数
    student = nil
    */
    print("类实例之间的循环强引用--内存泄漏测试完毕")
    
    无主引用
    class Teacher {
        var tName: String = ""
        //添加学生对象,初始化nil
        var student: Student?
        
        init(name: String) {
            tName = name
            print("老师\(tName) 实例初始化完成.")
        }
        func getName() -> String {
            return tName
        }
        deinit {
            print("老师\(tName) 实例反初始完成化.")
        }
    }
    
    
    class Student {
        var sName : String = ""
        //无宿主引用,不可以设置为nil
        unowned var teacher : Teacher
        
        init(name: String,tcher: Teacher) {
            sName = name
            //因为无宿主引用不能设为可选类型,所以必须初始化
            teacher = tcher
            print("学生\(sName) 实例初始化完成.")
        }
        func getName() -> String {
            return sName
        }
        deinit {
            print("学生\(sName) 实例反初始完成化.")
        }
    }
    
    //测试无主引用
    
    var teacher : Teacher?
    var student : Student
    
    //创建实例老师,并初始化,name 引用计数1
    teacher = Teacher(name: "汪老师")
    //创建实例学生,并初始化,name 引用计数1
    student = Student(name: "张三同学",tcher: teacher!)
    
    /**
     老师实例中的学生对象引用计数+1
    teacher!.student = student
     学生实例中的学生对象引用计数+1
    student!.teacher = teacher
    
     引用计数-1但是不等于0,因为学生还保留一份老师的引用计数
    teacher = nil
     引用计数-1但是不等于0,因为老师还保留一份学生的引用计数
    student = nil
    */
    print("类实例之间的循环强引用--内存泄漏测试完毕")
    
    
    闭包引起的循环强引用以及解决办法
    class JsonElement {
        var name: String = ""
        var jValue: String? = nil
        lazy var asJson:() ->String = {
            if let text = self.jValue {
                return "\(self.name):\(text)"
            }else{
                return "text is nil"
            }
        }
        init(name:String,text: String? = nil) {
            self.name = name
            self.jValue = text
            print("初始化闭包")
        }
        deinit {
            print("闭包释放")
        }
    }
    var paragraph: JsonElement? = JsonElement(name: "p",text: "hello world")
    print(paragraph?.asJson)
    paragraph = nil
    
    无主引用来解决强引用循环
    class JsonElement {
        var name: String = ""
        var jValue: String? = nil
        lazy var asJson:() ->String = {
            
            //使用无主引用来解决强引用循环
            [unowned self] in
            if let text = self.jValue {
                return "\(self.name):\(text)"
            }else{
                return "text is nil"
            }
        }
        init(name:String,text: String? = nil) {
            self.name = name
            self.jValue = text
            print("初始化闭包")
        }
        deinit {
            print("闭包释放")
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Swift 语法进阶

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