Swift3 - String 字符串、Array 数组、Dictionary 字典的使用

Swift相关知识,本随笔为 字符串、数组、字典的简单使用。

///***********************************************************************************************************/

///  2016.12.29

///***********************************************************************************************************/

1、Swift3 ,字符串的简单使用,直接将代码贴过来,更方便查看

//  字符串 string
    func stringTest() -> Void {
        // 字符串
        let str1 = "yiyi"
        let str2 = "2222"
        var str3 = String()//空string
        var str4 = ""// 空string
        
        // 字符(字符为 一 个)
        let char1:Character = "d"
        
        // 字符串长度
        var strCount = str1.characters.count
        strCount = str1.lengthOfBytes(using: String.Encoding.utf8)
        print(String(format:"strCount == "),strCount)
        
        // 字符串转换integer
        print((str2 as NSString).integerValue)
        
        // 字符串拼接
        str3 = str1 + str2
//        str3 = "\(str1)\(str2)"
//        str3 = globalStr + String(str1)
        print(String(format:"str3 == "),str3)
        
        // 字符串与字符拼接
//        str4 = str1+String(char1)
        str4 = "\(str1)\(char1)"
        str4 = str1.appending(String(char1))// 其他类型转换string  String() exp:String(strCount)
        print(String(format:""),str4)
        
        //字符串与其他类型值的拼接
        let int1 = 10
        let int2 = 11.1
        let str5 = String(format:"%i%.1f",int1,int2)
        print(String(format:"str5 == "),str5)
        
        // 字符串枚举 遍历每个字符
        let s1 = "hello world!"
        if strCount != 0 {
            print("判断string长度不为0,不是空")
        }
        for c in s1.characters {
            print(c)
        }
        
        // 字符串比较
        let ss1 = "hello"
        let ss2 = ",banana"
        var ss3 = ss1+ss2
        if ss1 == ss2 {
            print("ss1=ss2")
        }
        if ss1+ss2 == ss3 {
            print("ss1+ss2=ss3")
        }
        if ss1 > ss2 {// h大于b
            print("ss1>ss2")
        }
        // 判断字符串是否包含字符串
        if (ss3 .range(of: ss1) != nil) {
            print("字符串包含子串")
        }
     if ss3.hasPrefix("he") {}
     if ss3.hasSuffix("a") {}
// 字符串 大小写
        print(ss3.uppercased())// HELLO,BANANA
        print(ss3.capitalized)// Hello,Banana
        print(ss3.lowercased())// hello,banana
        /*
         // 这两个用法没 明白 
        print(ss3.uppercased(with: Locale(identifier: "l")))// HELLO,BANANA
        print(ss3.lowercased(with: Locale(identifier: "o")))// hello,banana
         */
        
        
        // 截取 修剪 字符串
        print(ss3.substring(from: ss3.characters.index(of: ",")!))//,banana 截取字符串从“,”开始
        print(ss3.substring(to: ss3.characters.index(of: ",")!))//hello 截取字符串到“,”结束
        print(ss3.unicodeScalars[ss3.unicodeScalars.startIndex ..< ss3.unicodeScalars.index(of: ",")!]);// hello
        print(ss3[ss3.index(ss3.startIndex, offsetBy: 4)])// o  取字符串的某个字符
        ss3.remove(at: ss3.characters.index(of: ",")!)// 去除字符串中特殊字符
        print(ss3)// hellobanana
        
    }

 2、数组的简单使用

// 数组 array
    func arrayTest() -> Void {
        // 初始化
//        var array1:[Any] = []// 空 任意类型
//        var array2 = Array<Any>()
//        var array3:[String] = []// 空 string 类型
//        var array4 = Array<String>()
//        let array5 = Array<Any>(repeatElement("", count: 3))
        var arr0 = ["what","test","swift","array"]
        let arr1 = ["hyArr",1,"hySwift",3] as [Any]
        var arr2 = [1,"2","swiftArr2",3,9,5] as [Any]
        print(arr2[0], arr2[3], separator: "* ")

        // arr0.count  数组count
        print(String(format:"arr0 长度 == "),arr0.count)
        // 判断数组是否为空
        if arr1.isEmpty {
            print("arr1数组是空")
        }else {
            print("arr1数组不空")
        }
        // arr1[arr1.count-2] 取数组的某个元素
        print(arr1[arr1.count-2])// hySwift
//        print(arr1[0])// hyArr
        //  public var first: Self.Iterator.Element? { get }
        print(arr1.first!)// hyArr

        // 遍历数组
        for i in 0..<arr1.count {
            print(arr1[i])
        }
        // 包含
        if arr0 .contains("test") {
            print("数组包含 test")
        }else {
            print("数组不包含 test")
        }
        
        // 删除元素
//        arr2 .remove(at: 4)
//        arr2 .removeSubrange(1..<3)// 删除 1、2 两个元素
//        arr2 .removeLast()
//        arr2 .removeFirst()
        arr2 .removeAll()
        print(arr2)
        
        // 添加元素
        arr2 .append("new1")// ["new1"]
        arr2.append(contentsOf: ["Shakia", "William"])
        print(arr2)
        arr2 = arr1 + arr2// ["hyArr", 1, "hySwift", 3, "new1"]
        arr2 = arr1
        arr2 .insert("insertElement", at: 3)//["hyArr", 1, "hySwift", "insertElement", 3, "new1"]
        
        // 更换
        if let i = arr0.index(of: "test") {
            arr0[i] = "测试"
        }
        arr2[0] = "domy"
        print(arr2)
        
        // 数组排序
        var sortArr = [3,5,1,0,8,0]
        sortArr.sort(by: >)
        print(String(format:"排序后:"),sortArr)// 排序后: [8, 5, 3, 1, 0, 0]
        
        
        // 二维数组
        let tArr1 = [["tSwift","haha"],1,[3,2]] as [Any]
        let subArr1 = tArr1[0]
        print(subArr1)
        
        
        
        ///  Array => NSArray
        ///  苹果的例子
        /// Description:
        /// The following example shows how you can bridge an `Array` instance to
        /// `NSArray` to use the `write(to:atomically:)` method. In this example, the
        /// `colors` array can be bridged to `NSArray` because its `String` elements
        /// bridge to `NSString`. The compiler prevents bridging the `moreColors`
        /// array, on the other hand, because its `Element` type is
        /// `Optional<String>`, which does *not* bridge to a Foundation type.
             let colors = ["periwinkle", "rose", "moss"]
             let moreColors: [String?] = ["ochre", "pine"]
        
             let url = NSURL(fileURLWithPath: "names.plist")
             (colors as NSArray).write(to: url as URL, atomically: true)
             // true
        
             (moreColors as NSArray).write(to: url as URL, atomically: true)
             // error: cannot convert value of type '[String?]' to type 'NSArray'
        
        
        /// Array 的更多其他用法点进去查看方法文档
    }

3、字典的简单使用

    // 字典 dictionary
    func dictionaryTest() -> Void {        
        // 创建字典
        var dict = [200:"ok",400:"error"]// [key:value]
        var emptyDict: [String: Any] = [:]// 空字典 var emptyDict: [Int: String] = [:]
        emptyDict = ["key1":"value1","key2":2]
        
        // Getting and Setting Dictionary Values
        print(dict[200]!)// ok
        print(emptyDict["key1"]!)// value1
        // 添加键值对
        emptyDict["key3"] = "value3"
        print(emptyDict)// ["key2": 2, "key3": "value3", "key1": "value1"]
        // 更新键值对的value
        emptyDict["key2"] = "updateValue2"
        print(String(format:("更换value后:")),emptyDict)
        
        
        var interestingNumbers = ["primes": [2, 3, 5, 7, 11, 13, 15],
                                  "triangular": [1, 3, 6, 10, 15, 21, 28],
                                  "hexagonal": [1, 6, 15, 28, 45, 66, 91]]
        //  排序
        for key in interestingNumbers.keys {
            interestingNumbers[key]?.sort(by: >)
        }
        print(interestingNumbers["primes"]!)
        /// print(interestingNumbers)
        /// ["hexagonal": [91, 66, 45, 28, 15, 6, 1],
        /// "primes": [15, 13, 11, 7, 5, 3, 2],
        /// "triangular": [28, 21, 15, 10, 6, 3, 1]]
        
        // 遍历字典
        let imagePaths = ["star": "/glyphs/star.png",
                          "portrait": "/images/content/portrait.jpg",
                          "spacer": "/images/shared/spacer.gif"]
        for (key, value) in imagePaths {
            print("The path to '\(key)' is '\(value)'.")
        }
        
/// search a dictionary's contents for a particular value
//        let glyphIndex = imagePaths.index {
//            $0.value.hasPrefix("/glyphs")
//        }
//        print(imagePaths[glyphIndex!].value)// /glyphs/star.png
//        print(imagePaths[glyphIndex!].key)// star
        let glyphIndex = imagePaths.contains {
            $0.value.hasPrefix("/glyphx")
        }
        print(glyphIndex)// ture
        
        
/// Bridging Between Dictionary and NSDictionary
        // imagePaths as NSDictionary
        print("keys:\((imagePaths as NSDictionary).allKeys) ,values:\((imagePaths as NSDictionary).allValues)")
        
        

    }

 

posted @ 2016-12-23 18:28  张张_z  阅读(5248)  评论(0编辑  收藏  举报