Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Kit de desarrollo de software de Swift

Use Realm in Xcode Playgrounds

You can only use Swift packages within Xcode projects that have at least one scheme and target. To use Realm in Xcode Playgrounds, you must first have an Xcode project where you have Installed the Swift SDK.

Tip

Other quick starts and tutorials

Para obtener más orientación sobre cómo comenzar con Realm y Swift o SwiftUI, consulta cualquiera de estos tutoriales o guías rápidas:

  • Inicio rápido

  • Inicio rápido con SwiftUI

  • iOS Tutorial

Dentro de un proyecto, vaya a File > New > Playground. Selecciona el tipo de Playground que deseas. En este ejemplo, usamos un Playground iOS vacío.

Screenshot of Xcode Playground iOS types with Blank selected
haga clic para ampliar

Name and save the playground in the root of your project. Be sure to add it to the project:

Screenshot of the File Navigator with a Playground filename and the project selected
haga clic para ampliar

Debería ver su nuevo Playground en el navegador de su Proyecto.

Screenshot of a file named RealmPlayground.playground in the Xcode Project navigator
haga clic para ampliar

Add the following import statement to use Realm in the playground:

import RealmSwift

Experimenta con Realm. Para este ejemplo, haremos:

class Drink: Object {
@Persisted var name = ""
@Persisted var rating = 0
@Persisted var source = ""
@Persisted var drinkType = ""
}
let drink = Drink(value: ["name": "Los Cabellos", "rating": 10, "source": "AeroPress", "drinkType": "Coffee"])
let realm = try! Realm(configuration: config)
try! realm.write {
realm.add(drink)
}
let drinks = realm.objects(Drink.self)
let coffeeDrinks = drinks.where {
$0.drinkType == "Coffee"
}
print(coffeeDrinks.first?.name)

When you work with a default realm in a Playground, you might run into a situation where you need to delete the realm. For example, if you are experimenting with an object type and add properties to the object, you may get an error that you must migrate the realm.

You can specify Realm.configuration details to open the file at a specific path, and delete the realm if it exists at the path.

var config = Realm.Configuration()
config.fileURL!.deleteLastPathComponent()
config.fileURL!.appendPathComponent("playgroundRealm")
config.fileURL!.appendPathExtension("realm")
if Realm.fileExists(for: config) {
try Realm.deleteFiles(for: config)
print("Successfully deleted existing realm at path: \(config.fileURL!)")
} else {
print("No file currently exists at path")
}

Como alternativa, puede abrir el reino solo en la memoria o usar el método deleteRealmIfMigrationNeeded para eliminar automáticamente un reino cuando se necesita la migración.

Volver

Partition-Based Sync

En esta página