스위프트 4 영역 루프 일반 및 재사용 확인 여기에 9.2엑스 코드, 스위프트
몇 가지 영역 클래스는 내가 가지고있다 이 위대한 작품을
let remoteDogs = remoteRealm.objects(Dog.self)
for remoteDog in remoteDogs{
if let localDog = realm.objects(Dog.self).filter("id = %@",remoteDog.id).first{
// Update
if localDog.updated < remoteDog.updated{
//Remote is newer; replace local with it
realm.create(Dog.self, value: remoteDog, update:true)
}
}
}
,하지만 전체 롤빵에이 같은 물건을 수행해야합니다 영역은 특정 Dog
클래스와 객체를 생성하고 내가 가지고있는 영역 강의들. 그래서 나는이 같은 좀 더 일반적인 만들려고 노력 해요 : 작품의
let animals = [Dog.self, Cat.self, Horse.self]
for animal in animals{
let remoteAnimals = remoteRealm.objects(animal)
for remoteAnimal in remoteAnimals{
if let localAnimal = realm.objects(animal).filter("id = %@",remoteAnimal.id).first{
// Update
if localAnimal.updated < remoteAnimal.updated{
//Remote is newer; replace local with it
realm.create(animal, value: remoteAnimal, update:true)
}
}
}
}
이런 종류의,하지만 언제 내가 (remoteAnimal.id
와 remoteAnimal.updated
와 같은) 객체의 속성을 참조 할 것이 아무튼 때문에 다음 컴파일러는 불평 어떤 종류의 물체가 remoteAnimal
인지 알지 못합니다.
누구나 전에 이렇게 해본 적이 있습니까? 모든 렐름 클래스에 대해이 동일한 코드를 반복해서 작성할 필요가 없도록 어떻게 할 수 있습니까? 감사!
여기서 문제는'realm.objects (T.self가)의'가' 결과'와 animals''의 유형 [Object.Type]''입니다 반환 것입니다 : 여기에 놀이터입니다. 이것은'animals'의 모든 요소에 대해 가장 가까운 공통 부모가'Object'이기 때문입니다. 조쉬의 대답은 : 모든 세 객체가'Animal'으로부터 상속받은 경우,'animals'는'[Animal.Type]'타입을 가질 것이고, 컴파일러는'localAnimal'을위한 동물을 정확하게 되돌려 주어야합니다. –