美文网首页
swift数组

swift数组

作者: __Objc | 来源:发表于2017-05-02 16:45 被阅读12次

    2017年05月02日16:27:33

    直接代码

         let cast = ["Vivien", "Marlon", "Kim", "Karl"]
         var strArray = [String]()
         for item in  cast{
              strArray += (item+",")
         }
         if  strArray.length > 0{
                strArray = strArray.subStringTo(strArray.length - 1)
         }
         print(list)
         // Prints "Vivien, Marlon, Kim, Karl"
    

    上面代码是很多人的第一想法
    下面的代码就比较简洁了 效果一样

      let cast = ["Vivien", "Marlon", "Kim", "Karl"]
      let list = cast.joined(separator: ", ")
      print(list)
      // Prints "Vivien, Marlon, Kim, Karl"
    

    在拨盘选择数字的时候

    let array  = Array(1...10)
    /*
     以下两种写法一致
     */
    let result = array.map { (item) -> String in
        return "\(item)"
    }
    let result = array.map {"\($0)"}
    
    print(result)
    //["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
    

    关于swift数组中对象的深浅拷贝

    class IntegerReference :NSObject{
        var value = 10
        
    }
    var firstIntegers = [IntegerReference(), IntegerReference()]
    var secondIntegers = firstIntegers
    
    
    firstIntegers[0].value = 100
    print(secondIntegers[0].value) //两个数组对象值都会改变
    // Prints "100"
    
    secondIntegers[0].value = 50
    print(firstIntegers[0].value) //两个数组对象值都会改变
    // Prints "50"
    
    

    数组中拷贝对象要实现copyWithZone方法

    class IntegerReference :NSObject,NSCopying{
        var value = 10
        func copy(with zone: NSZone? = nil) -> Any {
            let copy = IntegerReference()
            copy.value = self.value
            return copy
        }
    }
    var firstIntegers = [IntegerReference(), IntegerReference()]
    var secondIntegers = firstIntegers.map{ ($0.copy() as! IntegerReference) }
    
    
    firstIntegers[0].value = 100
    print(secondIntegers[0].value) //改变数组一中对象的值   数组二不会被改变
    // Prints "10"
    
    secondIntegers[0].value = 50
    print(firstIntegers[0].value)
    // Prints "100"
    
    

    相关文章

      网友评论

          本文标题:swift数组

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