Shark Deng

Interactive Designer @Shanju Design in Shanghai

touched caffe / mxnet / python / wordpress / bootstrap / Arduino / Raspberry Pi / webgl / three.js / PIXI / 3dMax

Email

Github

swift – 数组复制

2019-11-18 23:01:40

swift中Array,oc中NSArray, NSMutableArray

//第一种: 不copy
        struct Person{
            var name: String!
            var age: Int!
            
        }
        
        var studentsCopy: Array<Person>!
        var students = Array<Person>()
        
        let mary = Person(name: "Mary", age: 25)
        let peter = Person(name: "Peter", age: 18)
        students = [mary, peter]

        //直接赋值
        studentsCopy = students
        print("students------", studentsCopy)
        
        
        studentsCopy[0].name = "Henry"
        print("wonderful----", studentsCopy[0])
 
    
        
        
        //第二种:
        class Teacher: NSObject, NSCopying {
            var name: String
            var studentNum: Int
            var level: Int
            
            init(name: String, studentNum: Int, level: Int) {
    
                self.name = name
                self.studentNum = studentNum
                self.level = level
                
                super.init()
            }
            
            func copy(with zone: NSZone? = nil) -> Any {
                let teacher = Teacher(name: self.name,
                                      studentNum: self.studentNum,
                                      level: self.level)
                return teacher
            }
        }
        
        let wang = Teacher(name: "Wang", studentNum: 2, level: 1)
        let zhang = Teacher(name: "Zhang", studentNum: 5, level: 2)
        let teachers: Array<Teacher> = [wang, zhang]
        let teachersCopy: Array<Teacher>!
       
        teachersCopy = teachers.map{
            $0.copy() as! Teacher
        }
        
        print("teacher---", teachersCopy) //只有内存地址
        teachersCopy[0].name = "Li"
        print(teachersCopy[0].name)

 



——By SharkDeng
如果你喜欢我的文章,欢迎红包赞赏

Leave a Reply

Your email address will not be published. Required fields are marked *