Swift Playgrounds: Use of unresolved identifier 'Model' [duplicate] - swift

I am using a .playground file and I can't seem to add my CoreML model to it. I drag it into the Resources folder and this is my code:
func predict(image: CGImage) {
let model = try! VNCoreMLModel(for: Inceptionv3().model)
let request = VNCoreMLRequest(model: model, completionHandler: results)
let handler = VNSequenceRequestHandler()
try! handler.perform([request], on: image)
}
However, I get the error saying:
Use of Undeclared Type Inceptionv3
Can someone please help me out?

The compiler raises this error, because it cannot find a declaration of the class Inceptionv3, that you try to instantiate an object of.
This class is automatically created for you as long as you have a regular Xcode project. If you want to work with it inside a Swift playground, you will need to add this file manually:
First, create a regular Xcode project (an iOS app for example) and integrate your mlmodel there. Xcode will then generate an interface for that model automatically. These are exactly the files that are missing in your project and contain the definition of the Inceptionv3 class.
The same problem has been asked and answered here. There you can also find an image showing how to find the automatically generated classes.

Related

Xcode Playgrounds: Source files are unable to be accessed by each other

I am creating a playground in Xcode and I do not understand why the "Sources" files cannot talk to each other. I am using SpriteKit which means it is ideal to have one swift file per scene, in my case I have one scene per level. I cannot use a quick workaround and add everything into one massive file... there has to be a better way. Both classes for the two swift files are public. You should be able to access them. Thanks!
I get this error when I try to an object from one class, LevelScene, in the other class TitleScene.
After this
let levelScene = LevelScene(fileNamed: "LevelScene")
This happens
Cannot find 'LevelScene' in scope
I am aware of this post. This solution still does not work for me.
Xcode playgrounds can't access swift files in Sources folder
I am on Xcode 12.4.
Thanks!
You need to declare all your classes/struct in each file as public.
So, if you have defined a struct like this in a file:
struct Node {
var id: Int
}
You need to declare is like so:
public struct Node {
var id: Int
}
Then your code should work. You can use a struct from one file in another file as long as you declare them as public. Similar concept goes for any functions/methods inside those structs/classes. Even with this solution, you may find Xcode 12.4 complaining about not finding the type in scope. That, I believe, is a known bug. I have the same bug on my Xcode 12.4. I am able to build and run the code even with that error.

How to expose CoreData to swift package unit tests?

I'm trying to test CoreData in my swift package as SPM now supports bundled resources including .xcdatamodel, my tests can't seem to locate my NSManagedObjects though. What are the steps to unit test core data from the tests?
I'm getting this error when i try to create a NSManagedObject from a test:
+entityForName: could not locate an entity named 'StriveUser' in this model. (NSInternalInconsistencyException)
I've triple checked the naming and it's all correct.
I'm creating the object like this from my tests:
let object = NSEntityDescription.insertNewObject(forEntityName: "StriveUser", into: self.inMemoryStore.context)
And here's my code for locating the .xcdatamodel:
fileprivate var managedObjectModel: NSManagedObjectModel = {
guard let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main]) else {
preconditionFailure("Error getting ManagedObjectModel")
}
return managedObjectModel
}()
final class InMemoryStore {
let context: NSManagedObjectContext
init() {
let description = NSPersistentStoreDescription()
description.type = NSInMemoryStoreType
description.shouldAddStoreAsynchronously = false
let container = NSPersistentContainer(name: Constants.modelName, managedObjectModel: managedObjectModel)
container.persistentStoreDescriptions = [description]
container.loadPersistentStores {_, error in
if let error = error {
fatalError("Failed to load store: \(error.localizedDescription)")
}
}
self.context = container.viewContext
}
}
If you declare a Swift tools version of 5.3 or later in your package manifest, you can bundle resources with your source code as Swift packages. For example, Swift packages can contain asset catalogs, storyboards, and so on.
When resources are defined, a new static Bundle reference is created for the package. This can be accessed using Bundle.module.
So for your ManagedObjectModel you will need update the bundle reference. A good way of using this is to have an accessor in your package that will return the model.
For additional information, you can check out Apple's developer documentation Bundling Resources with a Swift Package.
I ran into a similar issue, where my app would crash with "YourManagedObject not found" errors any time I tried to do anything with my core data models.
This started happening as soon as I moved my core data dependency from cocoapods to swift package manager.
But here was my solution:
add #objc(ManagedObjectName) to all of my NSManagedObject classes
in the core data model editor, in the Data model inspector, delete Current Project Module and use the default for the Module configuration.
As the above answers are saying, make sure to use Bundle.module instead of Bundle.main when loading your NSManagedObjectModel.
I rewrote our core data stack to use NSPersistentStore instead of manually setting everything up (NSPersistentStoreCoordinator, NSManagedObjectContext, etc...) as per WWDC 2018 core data best practices
A few things to note:
The problem wasn't because of the wrong bundle, I had already applied that change when migrating over to SPM. For some reason the app just couldn't find any of my NSManagedObject classes at runtime.
Try #1 and #2 before you try #4. I have no idea if #4 helped with this issue or not as the app stopped crashing when I removed Current Project Module. It definitely cleaned up a lot of ugly legacy code though.
I built a new bare-bones Swift Package to demonstrate the error that seems to be a cause of these issues, as of Xcode Version 13.3.1 (13E500a)
No NSEntityDescriptions in any model claim the NSManagedObject subclass 'TestModel.EntityMO' so +entity is confused. Have you loaded your NSManagedObjectModel yet ?
Breaking just after the model was loaded, I could see the entity existed:
(lldb) po model
(<NSManagedObjectModel: 0x6000015f8d70>) isEditable 1, entities {
Entity = "(<NSEntityDescription: 0x6000001c4b00>) name Entity, managedObjectClassName TestModel_TestModel.EntityMO,
<snip>
The managedObjectClassName seems to be the problem. It's the result of using Current Product Module in the class definition within the model, which appears to be concatenating the package top-level name and the containing folder in Sources. If I replace it with a hard-coded module of TestModel, then the error goes away and the test passes. Not ideal, but it worked in my case.
Xcode support for Core Data in swift packages seems to be a work-in-progress, as the editor still does not load correctly for .xcdatamodeld files. Just creating the test model had to be done in another project and moved to the package since I couldn't add an entity to an empty model file.
For reference, I'll also include my model initialization, which is very basic, but I believe reasonable relative to Apple guidelines. At the very least, it demonstrates that issues can exist beyond Bundle.module usage.
public struct TestModel {
internal static let modelURL = Bundle.module.url(forResource: "Model", withExtension: "momd")!
public static func persistentContainer() -> NSPersistentContainer {
let model = NSManagedObjectModel(contentsOf: modelURL)!
let description = NSPersistentStoreDescription()
description.type = NSInMemoryStoreType
let container = NSPersistentContainer(name: "Test", managedObjectModel: model)
container.persistentStoreDescriptions = [description]
container.loadPersistentStores { storeDescription, error in
guard error == nil else {
fatalError("Could not load persistent stores. \(error!)")
}
}
return container
}
}

How To Get CoreML In Pure Playground Files

I am using a .playground file and I can't seem to add my CoreML model to it. I drag it into the Resources folder and this is my code:
func predict(image: CGImage) {
let model = try! VNCoreMLModel(for: Inceptionv3().model)
let request = VNCoreMLRequest(model: model, completionHandler: results)
let handler = VNSequenceRequestHandler()
try! handler.perform([request], on: image)
}
However, I get the error saying:
Use of Undeclared Type Inceptionv3
Can someone please help me out?
The compiler raises this error, because it cannot find a declaration of the class Inceptionv3, that you try to instantiate an object of.
This class is automatically created for you as long as you have a regular Xcode project. If you want to work with it inside a Swift playground, you will need to add this file manually:
First, create a regular Xcode project (an iOS app for example) and integrate your mlmodel there. Xcode will then generate an interface for that model automatically. These are exactly the files that are missing in your project and contain the definition of the Inceptionv3 class.
The same problem has been asked and answered here. There you can also find an image showing how to find the automatically generated classes.

Cannot call value of non-function type 'ThreadConfined.Type' - Swift 4.0

I upgraded a project I am working on to Swift 4.0. After doing so I realized this was not the best idea. I've fixed all bugs but one and can't figure it out. I have installed RealmSwift in my project and am getting the following error in one of the Realm files.
ERROR: Cannot call value of non-function type 'ThreadConfined.Type'
public init(to threadConfined: Confined) {
let bridged = (threadConfined as! AssistedObjectiveCBridgeable).bridged
swiftMetadata = bridged.metadata
type = type(of: threadConfined). ****ERROR CALLED ON THIS LINE****
objectiveCReference = RLMThreadSafeReference(threadConfined: bridged.objectiveCValue as! RLMThreadConfined)
}
Lesson learned about upgrading too soon. I was hoping someone could give me a hand so I can start developing again. Any thoughts?
Realm's master branch now contains support for Swift 4 and beta 1 of Xcode 9 (#5006). Using a build of Realm Swift from source should get you up and running.
I noticed that even though I was building from source (using CocoaPods), this issue was happening for me as well.
To solve it, two lines need to be removed (as seen in the file in #jonthornham's comment):
private let type: ThreadConfined.Type
and:
type = type(of:threadConfined)

Adding Module Name to Core Data Entities

I'm having trouble working out the implications of this note from Apple's "Using Swift with Cocoa and Objective-C":
Swift classes are namespaced—they’re scoped to the module (typically, the project) they are compiled in. To use a Swift subclass of the NSManagedObject class with your Core Data model, prefix the class name in the Class field in the model entity inspector with the name of your module.
I've done that, using my own application and just the stock master-detail template, so my entity's name is "Event" and its class is "Stock_Master_Detail.Event". When I then choose Create NSManagedObject Subclass from the Editor menu, and ask it to create a Swift subclass, it doesn't name the class right. Xcode creates a file called "Stock_Master_Detail.swift" with that's for a class called Stock_Master_Detail. And if I create multiple entities, all with the module name prefixed, Xcode can't generate more than one subclass since they'll all wind up having the same name.
I'll add that everything works fine in my limited testing if I just omit the module name entirely, counter to Apple's documentation. My question, then, is, what are the implications of not adding the module name to my class?
One way I got around this is to leave the data model file alone, so in this case the class would be "Event". Then in the code where the NSManagedObjectModel is created (AppDelegate if you used Apple's project template) I changed it to:
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle(forClass: self.classForCoder).URLForResource("Model", withExtension: "momd")!
var bundleModel = NSManagedObjectModel(contentsOfURL: modelURL)!
var objectModel = NSManagedObjectModel()
objectModel.entities = bundleModel.entities.map { ( entity ) -> NSEntityDescription in
var entityCopy = entity.copy() as NSEntityDescription
entityCopy.managedObjectClassName = "Stock_Master_Detail." + entity.managedObjectClassName
return entityCopy
}
return objectModel
}()
One improvement, I would like to figure out is how to find the module name dynamically. I know I could parse the current class's name, but that feels a weirder than I want.
I believe that it could be a bug with Swift/Core Data. First, generate your managed object without the module name(prefix). After it is generated, then go back and add the prefix in core data.