Generic parameter 'Value' could not be inferred - xcode

I am trying to make a Data-Storage using NSCoder, for some weird reason, its showing this error to me where i try to use the .encode keyword, please help me understand what i'm doing wrong..
let encoder = PropertyListEncoder()
do {
let data = try encoder.encode(self.itemArray) // <--- showing error here
} catch {
}

Never-mind, I found the problem! If you guys are facing the same problem where you make your array takes data specified in a class, you need to make the class 'Encodable' ie
import Foundation
class CellItemReg : Encodable { // <-- 'Encodable'
var done : Bool = false
var title : String = ""
}

This fixed for me in Swift iOS.
Inherit Codable in the class which you are trying to encode.
In your case,
let encoder = PropertyListEncoder()
do {
let data = try encoder.encode(self.itemArray) // <--- showing error here
} catch {
}
Let's assume itemArray is the array of a class named 'Item'. Then your 'Item' needs to inherit Codable in swift.
Just as below.
import Foundation
class Item: Codable {
var id: Int!
}
All the best!

Related

CoreStore Xcode data fault issue when fetching objects

I'm new to CoreStore and attempting to test my ability to create, store, and fetch CoreStore Objects correctly. It appears entries are being created based on results of dataStack.fetchCount() and transaction.create(), but the data is unavailable or not stored correctly based on my results of dataStack.fetchAll() (it says data: fault at the end of each object) and inspection of the SQLite database with Liya software reveals no entries in the table. I'm using CoreStore v8.0.1 and Xcode v12.4. My example code (using synchronous execution) is below. I appreciate your input into troubleshooting the issue. Thanks.
MyImage.swift:
import CoreStore
final class MyImage: CoreStoreObject {
#Field.Stored("desc")
var desc: String = ""
}
MyApp.swift
import SwiftUI
import CoreStore
import Foundation
#main
struct MyApp: App {
static let dataStack: DataStack = {
let dataStack = DataStack(
CoreStoreSchema(
modelVersion: "V1",
entities: [
Entity<MyImage>("MyImage")
],
versionLock: [
"MyImage": [..., ..., ..., ...]
]
)
)
try! dataStack.addStorageAndWait(
SQLiteStore( fileName: "MyStore.sqlite",
//localStorageOptions: .allowSynchronousLightweightMigration,
localStorageOptions: .recreateStoreOnModelMismatch
)
)
print(dataStack.coreStoreDumpString)
return dataStack
}()
init() {
CoreStoreDefaults.dataStack = MyApp.dataStack
try! dataStack.perform(
synchronous: { (transaction) in
let test_obj = transaction.create(Into<MyImage>())
test_obj.desc = "Description"
},
waitForAllObservers: true
)
do {
let objects = try dataStack.fetchAll(From<MyImage>())
print(objects)
} catch { print("error fetching")}
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
I appreciate your help.
It turns out that the fetch results will display data:fault until the properties of the objects are accessed. The following example code will display the value of the properties:
let objects = try dataStack.fetchAll(From<MyImage>())
print(objects.map { $0.desc })

Swift 2.0 beta: are protocols kinda broken in Xcode beta 5?

Currently I'm working on my new App written with Swift 2.0. Today I faced two strange errors in Xcode beta 5. I'd love if someone with a previous beta version of Xcode can confirm if I'm right or not. I also could misunderstand something, so I'll appreciate any feedback.
Here is some example code that made me struggle a while:
// Frist bug
protocol SomeProtocol {
var someArray: [String] { get set } // #1 bug
}
extension SomeProtocol {
func someFunction(someString: String) {
self.someArray.append(someString) // #1: Immutable value of type '[String]' only has mutating members named 'append'
}
}
// Second bug
protocol SomeInterfaceProtocol {
var someBool: Bool { get set } // #2 bug
}
class SomeClass: SomeInterfaceProtocol {
var someBool: Bool = false
func returnInterface() -> SomeInterfaceProtocol {
return self
}
}
let someInstance = SomeClass()
// can't set the value
someInstance.returnInterface().someBool = true // #2: Cannot assign to property: function call returns immutable value
The first error can be solved if you add the modifier mutating before the extension func declaration like this:
mutating func someFunction(someString: String) {
I suspect that's a change in the language.
The other one puzzles me as well. At least, here's a work-around:
var c = someInstance.returnInterface()
c.someBool = true
I think the second one isn't a bug as well for the same reason that you can't modify an item in a dictionary directly, or that you can't change elem in for elem in array { ... }.
Something has to be saved to be able to change it. Because you're returning the protocol type, the compiler can't know whether it's a struct or a class, whereas if it's a struct the operation of changing it would have no effect because it's not persisted in any way and structs aren't passed by reference. That's why Thomas' workaround works. Maybe it'll work too if returnInterface returned a class instance, instead of the protocol type.
EDIT: Just tried it out: Indeed it works either if you return SomeClass instead of SomeInterfaceProtocol or if you change the protocol to a class protocol, as it can't be a struct
protocol SomeInterfaceProtocol : class {
var someBool: Bool { get set }
}
class SomeClass: SomeInterfaceProtocol {
var someBool: Bool = false
func returnInterface() -> SomeInterfaceProtocol {
return self
}
}
or
protocol SomeInterfaceProtocol {
var someBool: Bool { get set }
}
class SomeClass: SomeInterfaceProtocol {
var someBool: Bool = false
func returnInterface() -> SomeClass {
return self
}
}
both work

Swift filter function causes compile error

I have created a wrapper class for storing a weak object reference, and then. I want to remove objects that have not a valid reference inside.
class Weak<T: AnyObject> {
weak var value : T?
init (value: T) {
self.value = value
}
}
protocol CSLocationServicesDelegate : class{
}
class conformance : CSLocationServicesDelegate{
}
class Dispatcher{
var dispatchArray = Array<Weak<CSLocationServicesDelegate>>()
func add( delegate : CSLocationServicesDelegate!){
dispatchArray.append(Weak(value: delegate));
}
func remove(obj : CSLocationServicesDelegate!){
dispatchArray.filter { (weakRef : Weak<CSLocationServicesDelegate>) -> Bool in
return weakRef.value != nil; //change this line to "return true" and it works!!!
}
}
}
However Xcode compilation fails with an error being reported, which shows absolutely no specific error. I suspect that I am using the language in such a false manner, that Xcode cannot figure out what I want to do. If I change the line (in the comments) to what the comment says, it works.
Can anyone help me in achieving what I want?
I don't see anything wrong with your code, but the compiler is crashing when compiling it. That should definitely be reported to Apple.
One workaround for this seems to be to simply declare Weak as a struct instead of a class. This compiles just fine:
struct Weak<T: AnyObject> {
weak var value : T?
init (value: T) {
self.value = value
}
}
protocol CSLocationServicesDelegate : class{
}
class conformance : CSLocationServicesDelegate{
}
class Dispatcher{
var dispatchArray = Array<Weak<CSLocationServicesDelegate>>()
func add( delegate : CSLocationServicesDelegate!){
dispatchArray.append(Weak(value: delegate));
}
func remove(obj : CSLocationServicesDelegate!){
dispatchArray.filter { (weakRef : Weak<CSLocationServicesDelegate>) -> Bool in
return weakRef.value != nil
}
}
}

Swift: Error updating UI component when using a delegate

I'm trying to update a progress bar with the progress of loading a load of values into CoreData. However, whenever I try to call an update on my progressView component, I get a fatal error stating that "unexpectedly found nil while unwrapping an Optional value".
The interesting thing is that this happens even if I put 'self.progressView.progress = 0.5' in the delegate method of my program - indicating that it's the progressView component it can't find rather than an issue with the value. A quick check with println also confirms the value does exist and so isn't nil. Note that if I put the 'self.progressView.progress = 0.5' statement under a function connected directly to a button, it works fine so it must be some sort of issue with the command being called from the delegate.
Can anyone work out what I'm doing wrong here? Thanks for your help.
Delegate method:
class ViewControllerUpdate: UIViewController, NSURLSessionDelegate, NSURLSessionDownloadDelegate, saveUpdate {
[....]
func updateStatus(status: String, progress: Float?) {
if let percentProgress = progress? {
self.progressView.progress = 0.5
}
//println(progress) - NOTE THIS IS CORRECTLY POPULATED WITH THE APPROPRIATE VALUE
}
Calling class:
protocol saveUpdate {
func updateStatus(status:String, progress:Float?)
}
class sqlPullSave {
let classtoUpdate: saveUpdate = ViewControllerUpdate()
func saveTSVtoSQL(fromFile: NSURL) -> Int {
//Load up the information into a Dictionary (tsv)
//let tsvURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(fromFileName, ofType: fromFileExtension)!)
let tsvURL: NSURL = fromFile
let tab = NSCharacterSet(charactersInString: "\t")
let tsv = CSV(contentsOfURL: tsvURL, separator: tab)
//let defResult: AnyObject = tsv.rows[0]["Name"]!
//let tryagain:String = AnyObjecttoString(tsv.rows[1]["Name"]!)
//load the data into the SQLite database...
dispatch_async(dispatch_get_main_queue()) {
for a in 0..<tsv.rows.count {
self.SQLsaveLine(self.AnyObjecttoString(tsv.rows[a]["Name"]!),
name_l: "",
desc: self.AnyObjecttoString(tsv.rows[a]["1"]!),
jobTitle: self.AnyObjecttoString(tsv.rows[a]["2"]!),
extn: self.AnyObjecttoString(tsv.rows[a]["3"]!)
// update status
var percentComplete: Float = (Float(a) / Float(tsv.rows.count))
self.classtoUpdate.self.updateStatus("SQLload", progress: percentComplete)
}
}
return 0
}

Swift generic class type both subclass and conforms to protocol

I'm trying to write a generic class in Swift who's generic type both inherits from a class and conforms to a protocol. However, the following code results in a compiler crash with Segmentation fault: 11.
protocol Protocol {
var protocolProperty: Any? { get }
}
class Class {
var classProperty: Any?
}
class GenericClass<T: Class where T: Protocol> {
var genericProperty: T?
func foo() {
let classProperty: Any? = genericProperty!.classProperty
// This is the culprit
let protocolProperty: Any? = genericProperty!.protocolProperty
}
}
Commenting out the access to the protocol property allows the program to compile. There is no way to access anything from the protocol without the compiler crashing. Is there a workaround to creating a generic class that works like this?
As MikeS notes, you should open a radar for the crash. It should never crash.
But the solution is to focus on what protocol (i.e. list of methods) you actually need T to conform to rather than getting wrapped up in the class. For instance:
protocol WhatGenericClassHolds : Protocol {
var classProperty: Any? { get }
}
class GenericClass<T: WhatGenericClassHolds> { ... }
There is a problem in your declaration. conform your class to the protocol as below
protocol A {
var somePropertyInt : Int? {get }
}
class B:A {
var someProperty : String?
var somePropertyInt:Int?;
}
class GenericClass<T: B where T: A > {
var someGenericProperty : T?
func foo() {
println(someGenericProperty!.someProperty)
println(someGenericProperty!.somePropertyInt)
}
}
var someGen = GenericClass()
someGen.someGenericProperty?.somePropertyInt
someGen.someGenericProperty?.someProperty

Resources