Am I able to add a member-wise initializer to a Codable-conforming object? [closed] - swift

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I currently have a class that conforms to Codable and has an initializer like so
public class A: Codable {
var aString: String?
public init(input: String?) {
self.aString = input
}
}
When I try to create an instance of it, I get an error
let myA = A(input: "Goodbye world")
Incorrect argument label in call (have 'input:', expected 'from:')
Am I restricted to only the init(from decoder: Decoder) throws initializer for Codable classes?

Your code is correct, double check whether you actually have a public initializer not a private one.
I put this into my Xcode Playground and everything works as expected:
public class A: Codable {
var aString: String?
public init(input: String?) {
self.aString = input
}
}
let a = A(input: "123")

Related

Parameter can not be represented in Objective C [duplicate]

This question already has answers here:
How to make a Swift String enum available in Objective-C?
(10 answers)
Closed 1 year ago.
I have a singleton class and a function that use one of its shared properties. I am getting this error:
"Method can not be marked as #objc because the type of the parameter 2 can not be represented in Objective-C".
My singleton class:
public class MessageManager {
public static var shared = MessageManager()
private init () {}
public enum messageFlag: String { // this is the enum causing the error when used
case sensitive
}
}
The error is happening when i use the enum from singleton:
#objc func checkMessage (_sender: UIBarButtonItem? , messageId: String? = nil , flag: MessageManager.messageFlag ) {
}
I have seen other people's solutions like the use of NSObject in class but still not working. Any fix for this?
The enum is the problem. As suggested by #Cristik, you need to declare your enum as #obj as well, and in order to do that it needs to be an integer type.

Get the coding key for a keypath in Swift [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
What I have: A codable struct with different properties.
What I want: A function, where I can get the exact name of the property when it is encoded in a Json. I think the most promising approach is using Keypath, but I have no idea how and whether it is possible at all. Thanks!
There is no way to do this out of the box, since there's no 1-1 mapping between properties of a Codable type and its coding keys, since there might be properties that aren't part of the encoded model or properties that depend on several encoded keys.
However, you should be able to achieve your goals by defining a mapping between the properties and their coding keys. You were on the right track with KeyPaths, you just need to define a function that takes a KeyPath whose root type is your codable model and return the coding key from said function.
struct MyCodable: Codable {
let id: Int
let name: String
// This property isn't part of the JSON
var description: String {
"\(id) \(name)"
}
enum CodingKeys: String, CodingKey {
case name = "Name"
case id = "identifier"
}
static func codingKey<Value>(for keyPath: KeyPath<MyCodable, Value>) -> String? {
let codingKey: CodingKeys
switch keyPath {
case \MyCodable.id:
codingKey = .id
case \MyCodable.name:
codingKey = .name
default: // handle properties that aren't encoded
return nil
}
return codingKey.rawValue
}
}
MyCodable.codingKey(for: \.id)

How to use a protocol inside a function in Swift? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm going through a series of Swift tutorials and I don't want to move forward without understanding the point of this
protocol Identifiable {
var id: String { get set }
}
/*:
We can’t create instances of that protocol - it’s a description, not a type by itself.
But we can create a struct that conforms to it:
*/
struct User: Identifiable {
var id: String
}
//: Finally, we’ll write a `displayID()` function that accepts any `Identifiable` object:
func displayID(thing: Identifiable) {
print("My ID is \(thing.id)")
}
This is the tutorial page
Say I want to now run displayID and get the thing.id, how would that work?
You can try it on swift playgrounds this is one way you can use it for example:
import Foundation
protocol Identifiable {
var id: String { get set }
}
struct User: Identifiable {
var id: String
}
class ViewController {
func displayID(thing: Identifiable) {
print("My ID is \(thing.id)")
}
}
let vc = ViewController()
let user = User(id: "12")
vc.displayID(thing: user)
// My ID is 12
Usually protocols are seen like contracts (interfaces in java/android) for a class or struct to follow, so you know that making a class or a struct comforming to a protocol will assure you an implementation of your basic methods that you might require for that kind of object/instance in future.
As well they are meant to allow you to provide in your automated tests for example a mocked sample of the implementation in order to get a mock id instead of a real one as in this example.
A protocol simply means ...
you MUST have all the stuff stated!
That is all a protocol is!
Here's your protocol
protocol Identifiable {
var id: String { get set }
}
all that means is you MUST have a "id" !
So this:
class Test: Identifiable {
}
is wrong !!!
But this:
class Test: Identifiable {
var id: String
}
is correct !!!
That's all it is!
Protocols are that simple!
Yes, it is true you cannot create an instance of protocol. But you can create an instance of classes and struct that implements protocol. Protocol just ensure that the struct or class that implements this protocol must have all these properties and methods that are defined in the protocol. You can say that Protocol is a contract. You need to fulfill it if you implements it.

'init' is inaccessible due to 'internal' protection level [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
public class SelectedValue {
static let sharedInstance = SelectedValue()
public var reportPostId : Int? = nil
public var report_GroupId : Int? = nil
public var postType : String? = nil
}
'init' is inaccessible due to 'internal' protection level
Please help me to solve this.
Thanks
As it says, the init method (that you probably called without it's name) is private. make it more public to access it.
Click on the gray lines that say 'init' declared here to jump to the source of the issue.
Note that MyClass() is equal to MyClass.init(). that means you are calling the init method each time you build an object.
And also note that if you don't specify the access level, it will be internal by default.
So this:
class MyClass { }
is equal to:
internal class MyClass {}
So you should change it to:
public MyClass { }

Value type of string? Has no member components. (Struct) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I look at each thread but can't find any solution for my case.
I have a model:
import Foundation
public struct Destinos: Data {
public var idDestino : Int?
public var desDestino : String?
public func dictionary() -> NSDictionary {
let dictionary = NSMutableDictionary()
dictionary.setValue(self.idDestino, forKey: "idDestino")
dictionary.setValue(self.desDestino, forKey: "desDestino")
return dictionary
}
}
So I want to change the desDestino "string" to [String] to use later and show in at tableView. For this.I write this line of code in another file.swift:
var cadena = Destinos()
cadena.desDestino = "HOLA, nada, algo, otra, cosa, mas que eso"
let array = cadena.desDestino.components(separatedBy: ", ") // in this line i get the error: value type of string? has no member components.
so... what is the problem?
There's no reason to use NSDictionary here. Just use a native Swift dictionary (with a literal).
public struct Destinos {
public let idDestino : Int?
public let desDestino : String?
public func toDictionary() -> [String: Any?] {
return [
"idDestino": idDestino,
"desDestino": desDestino
]
}
}
As for generating your array, you have two issues:
1. components(seperatedBy:) is misspelt
2. cadena.desDestino is an is a String? (Also known as a Optional<String>) which hasn't been unwrapped. The nicest way to take care of this is to use optional chaining, and then use nil coalescence (??) to make it an empty array in the case cadena.desDestino is nil.
var cadena = Destinos(
idDestino: 123,
desDestino: "HOLA, nada, algo, otra, cosa, mas que eso"
)
let array = cadena.desDestino?.components(separatedBy: ", ") ?? []