swiftrealmnsautoreleasepool

Proper way to return object from autoreleasepool


I'm trying to wrap some of our code in autoreleasepool. But I stumble with a method where it returns a value. I plan to wrap all the contents in autoreleasepool but how could I return the value? I have this code:

func get(withId id: String) -> Student? {
    return autoreleasepool { () -> Student? in
        let realm = try! Realm()
        let results = realm.objects(Student.self).filter("id = %s", id)
        return results.first
    }
}

Is this proper to return the value? Most examples I found in the internet doesn't return a value from the autoreleasepool block.


Solution

  • Yes, since Swift 3, you can return a value in the function passed to autoreleasepool, and it will be the return value of the whole autoreleasepool call, like you have shown.