iOS领域:我如何向下转换为Object

时间:2015-12-30 09:26:57

标签: ios swift realm

我有一个协议:

protocol DatabaseProtocol {
    func getObjects<T>(_: T.Type) -> [T]
}

然后我实施这个协议:

class RealmDatabase: Database {
    func getObjects<T>(object: T) -> [T] {
      //how can i return here the objects from realm?
         return realm.objects(T)
    }
}

我不想将协议更改为限制为&lt; T:对象&gt;,因为我希望能够更改为另一个数据库,而Object继承自领域。

enter image description here

enter image description here

更新#1

我也试过这个:

func getObjects<T>(object: T) -> [T] {
    let result = realm.objects(object as Object).map { $0 }
    return result
}

然后我无法转换类型&#39; T&#39;在强制中输入对象&#39;

2 个答案:

答案 0 :(得分:1)

func getObjects<T>(t: T.Type) -> [T] {
    return realm.objects(t as! Object.Type).map { $0 as! T }
}

答案 1 :(得分:0)

在Swift 3中。

Generic T需要继承自RealmSwift.Object

CREATE TABLE `tasks` (`id` int AUTO_INCREMENT PRIMARY KEY, 
`owner_id` int, 
`assignee_id` int, 
`created_at` datetime NOT NULL, 
`updated_at` datetime NOT NULL,  

INDEX `index_tasks_on_owner_id`  (`owner_id`),  

INDEX `index_tasks_on_assignee_id`  (`assignee_id`), 

CONSTRAINT `fk_rails_877a66d795`
FOREIGN KEY (`owner_id`)
  REFERENCES `owners` (`id`), 

CONSTRAINT `fk_rails_0016c50613`
FOREIGN KEY (`assignee_id`)
  REFERENCES `assignees` (`id`)
) ENGINE=InnoDB

ERROR 1215 (HY000): Cannot add foreign key constraint

否则,我认为更好的方法是你的协议应该创建一个associatedtype对象,如:

func add<T: Object>(_ object: T) -> Result<Void, Error> {
    return realmResult.flatMap { realm -> Result<Void, Error> in
        do {
            try realm.write {
                realm.add(object, update: false)
            }
            return .success()
        } catch {
            return .failure(error)
        }
    }
}