美文网首页
Swift3.0-数据类型

Swift3.0-数据类型

作者: 元昊 | 来源:发表于2017-08-16 15:49 被阅读11次

    学无止境 keep moving

    定义基本数据格式

        let myKobe = 24
        
        let myData : Double = 23.0  //指定类型定义
         
        let binaryInteger = 0b10001 //二进制数
        
        let octalInteger = 0o21     //八进制数
        
        let hexadecimalInteger = 0x11 //十六进制
        
        let scienceNumber = 1.234e3 //科学计数
    

    变量定义

    var myVariable =  23
    
    

    类型转换

            var leb  = "23"
            let str = "\(leb)"
            let str1 = String(str)
            let str2 = Int(str)
            let str3 = Int(leb)
            let str4 = Double(str1!)
    

    数组的定义方式

            let list1 = ["bonjour","23","3"]
            var list2 : [String] = ["bonjour","23","3"]
            let list3 : [Any] = ["bonjour","33","4"]
            let list4 : NSArray = ["bonjour","23","1"]
            let list5 :NSMutableArray = ["bonjour","423","4"]
            //remove
            list2.removeAll()  //var 可以
            list2 = []  //var 可以
            
            list5.removeAllObjects() // var 和 let 都可以
    
            tempArray[1...4] = ["沙扬娜拉","apple"] // 将数组4...6 的范围用指定的数组取代
            list5.add("34")
            list5.insert("Maple Syrup", at: 0)
            list5.removeObject(at: 1)
    

    字典的定义方式

            let dict1 : [String : Int] = [:]
            let dict2 = [String:Int]()
            let dict3 : NSDictionary = NSDictionary()
            let dict4 : NSMutableDictionary  = NSMutableDictionary()
    

    获取数据类型的最大和最小值

            let minValue = UInt8.min
            let maxValue = UInt8.max
    

    给数据类型设置别名

            typealias code = Int32
            var tel : code = 35232
    

    元祖

    1.定义

    
            //第一种定义方式
            let http404Error = (404,"Not Found")
            
            let codeNum = http404Error.0
            
            let error = http404Error.1
            
            //第二种定义方式
            
            let http404Error = (code:404, error:"Not Found")
            
            let codeNum = http404Error.code
            
            let error = http404Error.error
            
            //第三种定义方法
            let http404Error:(code:Int,error:String) = (404,"Not Found")
            
            let code = http404Error.code
            
            let error = http404Error.1
            
            //第四种定义方法
            
            let http404Error:(code:Int,error:String) = (code:404,error:"Not Found")
            
            let code = http404Error.code
            
            let error = http404Error.error
            
            //第五种定义方式
            
            var http404Error :(code:Int , error : String) = (_ :404, _ : "Not Found")
    
    //第四种定义的时候,等号坐标和右边的元素名称必须对应,不然系统会报错,建议不使用这种方式定义
    
    
    

    2.分解变量

            let (statusCode, _) = http404Error //缺省不需要的值
            let (statusCode, statusMessage) = http404Error
    
    1. 赋值
            var http404Error : (code:Int,error:String)
            http404Error = (code:404,error:"Not Found")//完整
            http404Error = (404, "Not Found") //全部名称缺省
            http404Error = (code : 404, "Not Found") //部分缺省
            http404Error = (_ :404 , "Not Found")
    

    字符串

            let string = "Hello." + "World" //so Fantice let
            
            var name = "natali"
            name.append("你好") // var 
            
            var anotherEmptyString = String()
            
            //判断字符串是否为空
            var emptyString = String()
            if emptyString.isEmpty {
                print("Nothing to see here")
            }
            
            //获取字符串中每个字符
            for character in "Dog!🐶".characters {
                print(character)
            }
            
            let nike = "Nothing is impossiable"
            for indedx in nike.characters.indices {
                print("\(nike[indedx])", separator: "1", terminator: "")
            }
            
            //定义字符
            let exclamationMark :(Character) = "!"
            //定义字符数组
            let carcharacters : [Character] = ["C", "a", "t", "!", "🐱"]
            //定义数组转字符串
            let catString = String(carcharacters)
            //Unicode编码
            let percomosed:Character = "\u{D55C}"                //🇰🇷
            let regionalIndicatorForUS: Character = "\u{1F1FA}\u{1F1F8}" //🇺🇸
            
            var nickname = "🐶东西add"
            print(nickname.characters.count) // 6 都是一个字符
            
            //截取字符串
            let greeting = "bonjunor"
            //截取单个
            greeting[greeting.startIndex]
            //截取一段
            greeting[greeting.index(greeting.startIndex, offsetBy: 2)..<greeting.index(greeting.endIndex, offsetBy: -3)]
            //在指定位置插入字符串
            var welcome = "welcome"
            welcome.insert("!", at: welcome.endIndex)
            welcome.insert(contentsOf: "here".characters, at: welcome.index(before: welcome.endIndex))
            
            //移除字符串
    //        welcome.remove(at: welcome.index(before: welcome.endIndex))
    
            let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
    
            welcome.removeSubrange(range)
            
            // 前缀和后缀
            
            let scene = "Capulet`s mansion"
            
            if scene.hasSuffix("Capulet`s mansion") {
                
            } //hasPrefix
            
            //获取对应的编码数据
            for codeunit in "🐶a店待你".utf16 {
                print("\(codeunit)")
            }
    

    深入学习

    拓展

    extension Int {
        func description() -> String {
            return "这是一个Int类型的数\(self)"
        }
    }
    
            print(2.description())
    
    这是一个Int类型的数2
    
    

    1.定义一个协议

    protocol NumberProtocl {
        
        func description() -> String
        
    }
    

    2.拓展实现协议

    extension Int : NumberProtocl {
        
        func description() -> String {
            return "This is a Int Number\(self)"
        }
        
    }
    
    extension Double : NumberProtocl {
        
        func description() -> String {
            return "This is a Double Number \(self)"
        }
        
    }
    

    3.定义一个协议类型

            var a:NumberProtocl = 3
            print(a.description())
            a = 3.4
            print(a.description())
    

    运行

    我是一个Int类型的数字3
    我是一个Double类型的数字3.4
    
    通过这种方法,我们可以给同一个变量,赋值不同类型的值了,其实这个符合swift的语法要求,只是我们利用它的灵活性,达到了我们的目的
    

    给系统类添加拓展

    给Int 类型和 Double类型增加一个方法,判断它的数据类型

    //定义一个协议
    protocol whichTypeProtocol {
        
    }
    
    //拓展实现协议
    extension Int : whichTypeProtocol{
        
    }
    
    extension Double : whichTypeProtocol {
        
    }
    
    //给协议拓展方法
    extension whichTypeProtocol {
        func description() -> String {
            if self is Int {
                return " This is Int \(self)"
            }
            if self is Double {
                return "This is Double \(self)"
            }
            
            return "Nothing"
        }
    }
    
    print(3.44.description())
    print(3.description())
    

    Self的好处

    专门用于不确定数据类型的
    

    需求:给所有数字类型,扩展一个平方的函数,返回自己的操作

    //定义一个协议
    protocol getSpuareValue {
    }
    
    //拓展实现协议
    extension Int : getSpuareValue {
        
    }
    
    extension Double : getSpuareValue {
        
    }
    
    extension getSpuareValue {
        
        //我们不确定返回的self 是什么类型
        func spuareValue() -> Self {
            if self is Int {
                let n = self as! Int
                return n * n as! Self
            }
            if self is Double {
                let m = self as! Int
                return m * m as! Self
            }
            return 0 as! Self
        }
        
    }
    print(3.44.squareValue())
    print(3.squareValue())
    
    11.8336
    9
    

    结论
    Self很强大

    需要注意的地方

    1.如果指出变量的类型,赋值的值必须是和他类型相同的值,不然编译不通过

    var num:Int = 43.0//(编译错误)
    

    2.浮点数类型推断出来的默认为Double类型

    let name = 30.0 // Double
    

    3.Float 类型的值 赋值给Double类型也必须转换

    let name:Float = 30.0
    let explicitDouble: Double = Double(name)
    

    4.数字之间的转换结果为非可选值,数字转字符串也是非可选值,但是字符串转数字就是可选值(因为它有可能转换失败)

    let str = "\(num1)"
    let str1 = String(num1)
    let num2 = Int(num1)
    let num3 = Int(str1)
    let num4 = Double(str1)
    

    输出结果:

    30.0
    30
    nil
    Optional(30.0)
    

    注意:

    字符串33.0 转Int 类型只会是nil 不会是33 因为字符串33.0 不是Int类型转换失败,但是浮点数33.0 可以转换为33
    

    5.不能推断出下面的类型

    let list1 = ["你好","2","3",3] // 不能这样写,swift推断不出来
    

    你应该:

    let list1 = ["你好","2","3",3] as [Any]
    let list1:[Any] = ["你好","2","3",3]
    let list1:NSArray = ["你好","2","3",3]
    let list1:NSMutableArray = ["你好","2","3",3]
    

    6.使用Dictionary定义字典必须指定数据类型

    let dic5:Dictionary = [:] // 错误
    let dic5:Dictionary = [String:Int]() // 正确
    

    Array 和NSArray,NSMutableArray的区别
    1.测试类型

    var list1:Array = ["你好","2","3","4"]
    let list2 = list1
    list1[1] = "哈哈"
    print(list1)
    print(list2)
    

    运行结果:

    ["你好", "哈哈", "3", "4"]
    ["你好", "2", "3", "4"]
    
    var list1:NSMutableArray = ["你好","2","3","4"]
    let list2 = list1
    
    list1[1]="哈哈"
    print(list1)
    print(list2)
    

    运行结果:

    ("你好", "哈哈", "3", "4")
    ("你好", "哈哈", "3", "4")
    

    结论:

    Array 为值类型,NSArray,NSMutableArray为引用类型
    

    2.测试内存占用

    func add(){
        var array: [Any] = [3]
        for _ in 0...10000000{
            array.append(3)
        }
    }
    
    执行代码前 3.5M 执行代码后 3.8 M 内存占用最高 308.6M
    
    func add(){
        let array: NSMutableArray = NSMutableArray()
        for i in 0...10000000{
            array.add(3)
            if i == 10000000{
    
            }
    
        }
    }
    
    执行代码前3.5 M ,代码执行完毕后 17.3M,内存占用最高为 422.3
    

    3.我们使用Array 放对象

    func add(){
        var array: [Any] = []
        for i in 0...10000{
            array.append([UILabel()])
        }
    运行前 3.5 运行后10.5 最高占内存 21.5,发现内存没有释放完毕
    

    尝试修改代码如下:

    autoreleasepool {
            var array: [Any] = []
            for i in 0...10000{
                array.append([UILabel()])
            }
        }
    

    运行结果依旧
    结论:

    Swift 中新增的Array 存放非对象类型,内存清理的更及时,更彻底!
    

    4.数据的上溢或者下溢系统都会报错

    Int8.min - 1
    Int8.max + 1
    
    arithmetic operation '127 + 1' (on type 'Int8') results in an overflow
    error: arithmetic operation '-128 - 1' (on type 'Int8') results in an overflow
    
    

    原文出处
    作者:酷走天涯
    链接:http://www.jianshu.com/p/a53429e4e2f3

    相关文章

      网友评论

          本文标题:Swift3.0-数据类型

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