Home > AI > Uncategorized

swift – 数组复制

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)

 

Related posts:

Leave a Reply