Using .map to map an array of one class to an array of another - ios

I'm new to Swift, and am trying to get my head around using .map. My understanding is that the behaviour is similar to that of Javascript, but maybe I'm not nailing the Swift syntax correctly?
I've created a public Array of my custom class CustomItem (which is a subclass of the type coming back in the response):
public var availableItems: [CustomItem] = []
public static func getAvailableItems(id: String, completion: (items: [CustomItem]) -> ()) -> Void {
DataConnector.getRelated(type: "users", id: id, relationship: "available") { (response) -> Void in
availableItems = (response.data?.map { return $0 as! CustomItem })!
completion(items: availableItems)
}
}
When I do a po response.data.map { return $0 } in the console with a breakpoint after the response is received, I get:
(lldb) po response.data.map { return $0 }
▿ Optional([<AnSDK.RemoteDataObject: 0x7f8a0b9c16b0>])
▿ Some : 1 elements
▿ [0] : < AnSDK.RemoteDataObject: 0x7f8a0b9c16b0>
So it definitely seems that part works, but when I try to cast the data object to CustomItem class, I get:
Could not cast value of type 'AnSDK.RemoteDataObject' (0x100abbda0) to 'Project.CustomItem' (0x100882c60).
Here's my CustomItem class just in case:
import AnSDK
public class CustomItem: RemoteDataObject {
var displayName: String = ""
var value: Float = 0.0
var owner: User?
}
If I don't use the ! to force downcast, I get:
RemoteDataObject is not convertible to CustomItem [...]
... in the compiler.

(I'm really just restating Ben Gottlieb's answer here, but hopefully a bit clearer since I believe some readers were confused by his attempt.)
The message seems fairly clear. You've received an array of AnSDK.RemoteDataObject. As best I can tell from your output, that is the actual class of the objects. You can't just say "it's really this subclass of RDO" unless it really is that subclass. Looking at your code, that seems unlikely. Somewhere in AnSDK it would have to construct a CustomItem and then just happen to return it as a RemoteDataObject. That doesn't appear to be what's happening inside of getRelated. Given your code, I doubt AnSDK knows anything about CustomItem, so how would it have constructed one?
There are numerous ways to fix this depending on what the types really are and how they interact. Ben's solution is one, which basically creates a copy of the object (though in that case, there's no particular reason for CustomItem to be a subclass of RDO, and probably shouldn't be.)
If you just want to add methods to RemoteDataObject, you can do that with extensions. You don't need to create a subclass.

Related

Can #dynamicMemberLookup be used to call methods?

In the documentation for #dynamicMemberLookup it says,
Apply this attribute to a class, structure, enumeration, or protocol to enable members to be looked up by name at runtime.
If I'm not mistaken, instance methods are considered members of a struct / class. However, when I try to call a function dynamically I get an error saying:
Dynamic key path member lookup cannot refer to instance method foo()
To reproduce the problem:
struct Person {
var name: String
var age: Int
func greet() {
print("hello, my name is \(name)")
}
}
#dynamicMemberLookup
struct Wrapper {
var value: Person
subscript<T>(dynamicMember keypath: KeyPath<Person, T>) -> T {
value[keyPath: keypath]
}
}
let person = Person(name: "John Doe", age: 21)
let wrapper = Wrapper(value: person)
wrapper.greet() // << Error: Dynamic key path member lookup cannot refer to instance method `greet()`
// Or
let function = wrapper.greet // << Error: Dynamic key path member lookup cannot refer to instance method `greet()`
function()
How can I dynamically call greet() using #dynamicMemberLookup? Is there any way to achieve what I'm trying to do?
Thanks in advance!
No, dynamicMemberLookup does not work for methods. As the signature of the subscript suggests, it only works for things that can be represented as a KeyPath. Method calls cannot be part of a key path. :(
Key-Path Expression
A key-path expression refers to a property or subscript of a type.
The path consists of property names, subscripts, optional-chaining
expressions, and forced unwrapping expressions. Each of these key-path
components can be repeated as many times as needed, in any order.
At compile time, a key-path expression is replaced by an instance of
the KeyPath class.
I suspect the reason why it is called "dynamic member lookup" is because it also works with subscripts. The alternative of dynamicPropertyOrSubscriptLookup is rather a mouthful isn't it?
One rather hacky fix would be to change greet into a computed property:
var greet: () -> Void { {
print("hello, my name is \(name)")
} }
If greet has had parameters, you could also change it into a subscript, but I think that is an even uglier solution.

Error "nil requires a contextual type" using Swift

I'd like to achieve the following in code:
class MyService {
let mySubject = BehaviorSubject<MyData>(value: nil)
//....
}
Unfortunately, I get the "nil requires a contextual type" error. I want the subject to be "empty" till I actually put something in there. How can I pass nil as the argument then? Can I cast it to my own type to make it work?
Based on the reference for RxSwift BehaviorSubject, the init(value:) initializer is declared as
public init(value: Element)
Where the value parameter is described as:
value
Initial value sent to observers when no other value has been received
by the subject yet.
And where Element is the placeholder type of BehaviorSubject:
public final class BehaviorSubject<Element> ...
This means you need to specify the placeholder type Element as an Optional type if you are to be able to set the initial value (used when no other value has been received) to nil. E.g.:
class MyService {
let mySubject = BehaviorSubject<MyData?>(value: nil)
//....
}
Or, letting the compiler infer the placeholder as MyData? by using the non-sugared .none form for the nil argument:
class MyService {
let mySubject = BehaviorSubject(value: Optional<MyData>.none)
//....
}
As for understanding the actual error message better, consider the following self-contained example:
struct Foo<T> {
init(value: T) {}
}
struct Bar {}
let bar = Bar()
_ = Foo<Bar>(value: bar) // OK
_ = Foo(value: bar) // OK, T inferred as Bar
_ = Foo<Bar>(value: nil) // Error: error: 'nil' requires a contextual type
_ = Foo<Bar?>(value: nil) // OK
_ = Foo(value: Optional<Bar>.none) // OK, T inferred as Bar?
While dfri's answer is technically correct, you might want to consider a different type when working with RxSwift. Since you want your subject to be empty only at the beginning, I'd suggest to use ReplaySubject or PublishSubject.
A similar question has also been asked on RxSwift's GitHub issue page. Allow BehaviorSubject without initial value. There, kzaher suggests the ReplaySubject.
Your subject would then look like this, without any initial value and without MyData being Optional.
let subject = ReplaySubject<MyData>().create(bufferSize: 1)

Swift compile time errors when using generics and accessing dictionary's values

Below I have a class, B, with a generic type and the generic type has a subclass type constraint. In a separate class, A, I create a dictionary property, values, with the key as String and value as B. Class A then has methods to return or set values in the dictionary such that the values are not constrained to a single type (they maintain their generic SomeType type which is a subclass of NSObject). However, this produces the following two errors noted inline below:
class A: NSObject {
var values = [String : B]()
func get<SomeType: NSObject>(key: String) -> B<SomeType>? {
// #1 Error on line below: cannot convert return expression of type 'B<NSObject>?' to return type 'B<SomeType>?'
return values[key]
}
func set<SomeType: NSObject>(key: String, value: B<SomeType>) {
// #2 Error on line below: cannot assign value of type 'B<SomeType>' to type 'B<NSObject>?'
values[key] = value
}
}
class B<SomeType: NSObject>: NSObject {
}
I've attempted various forms of declaring the values dictionary to tell the compiler that SomeType is a subclass of NSObject and everything is going to be ok, but have been unsuccessful. Similarly to this question, I'm a bit stumped because the methods define SomeType as a subclass of NSObject and therefore things appear to be type safe when setting and getting from values.
I could remove the generic types from the methods and instead force the type to be <NSObject>, but then I'd run into the same problem as noted here.
This may not be doing what you think it's doing:
var values = [String : B]()
This isn't really [String : B], it's [String : B<NSObject>]. (I'm actually kind of surprised that this is legal syntax; I'd be tempted to open a bugreport about that; B isn't a proper type in Swift.) You may realize this already, but it's the first important note.
The second important note is that generic types are not covariant in Swift. A Thing<Cat> is not a subtype of Thing<Animal>. There are some type-theory reasons for this, and there are some technical implementation reasons for this, but the important fact is that it's not possible in Swift.
If you need to hold a variety of B types, then you'll need to build a type eraser. In your case, the type eraser could possibly be B<NSObject> with something like this:
class B<SomeType: NSObject>: NSObject {
let value: SomeType
init(value: SomeType) {
self.value = value
}
func liftGeneric() -> B<NSObject> {
return B<NSObject>(value: value)
}
}
If you need to hold just one kind of B type, then make A generic as well.

Swift how to "pass by value" of a object

I am quite new in Swift. And I create a class(for example):
class Fraction{
var a: Int
init(a:Int){
self.a = a
}
func toString() -> String{
return "\(self.a)"
}
}
and I also build a in other class function:
class func A_plusplus(f:Fraction){
f.a++
}
Then in the executive class I write:
var object = Fraction(a:10)
print("before run func = " + object.toString())
XXXclass.A_plusplus(object)
print("after ran func =" + object.toString() )
So the console output is
before run func = 10; after ran func =11
The question is how can I just send a copy of the "object" to keep its value which equal to 10
And if functions are always pass-by-reference, why we still need the keyword: "inout"
what does difference between A_plusplus(&object)//[if I make the parameter to be a inout parameter] and A_plusplus(object)
Universally, I don't want to use struct. Although this will solve my
problem exactly, I do pass-by-value rarely.So I don't want program's
copying processes slow my user's phone down :(
And It seems conforming the NSCopying protocol is a good option.But
I don't know how to implement the function:
func copyWithZone(zone:
NSZone)-> AnyObject? correctly
If your class is subclass of NSObject,better to use NSCopying
class Fraction:NSObject,NSCopying{
var a:Int
var b:NSString?
required init(a:Int){
self.a = a
}
func toString() -> String{
return "\(self.a)"
}
func copyWithZone(zone: NSZone) -> AnyObject {
let theCopy=self.dynamicType.init(a: self.a)
theCopy.b = self.b?.copy() as? NSString
return theCopy
}
}
class XXXclass{
class func A_plusplus(f:Fraction){
f.a++
f.b = "after"
}
}
var object = Fraction(a:10)
object.b = "before"
print("before run func = " + object.toString())
print(object.b!) //“Before”
XXXclass.A_plusplus(object.copy() as! Fraction)
print("after ran func =" + object.toString() )
print(object.b!)//“Before”
If it is just a common swift class,You have to create a copy method
class Fraction{
var a: Int
init(a:Int){
self.a = a
}
func toString() -> String{
return "\(self.a)"
}
func copy()->Fraction{
return Fraction(a: self.a)
}
}
class XXXclass{
class func A_plusplus(f:Fraction){
f.a++
}
}
var object = Fraction(a:10)
print("before run func = " + object.toString())
XXXclass.A_plusplus(object.copy())
print("after ran func =" + object.toString() )
To make it clear,you have to know that there are mainly two types in swift
Reference types. Like Class instance,function type
Value types,Like struct and others(Not class instance or function type)
If you pass in a Reference types,you pass in the copy of Reference,it still point to the original object.
If you pass in a Copy type,you pass in the copy of value,so it has nothing to do with the original value
Let us talk about inout,if you use it,it pass in the same object or value.It has effect on Value type
func add(inout input:Int){
input++
}
var a = 10
print(a)//10
add(&a)
print(a)//11
Swift has a new concept so called "struct"
You can define Fraction as struct (Not class)
And
struct Fraction{
...
}
var object = Fraction(a:10)
var object1 = object //then struct in swift is value type, so object1 is copy of object (not reference)
And if you use struct then try to use inout in A_plusplus function
Hope this will help you.
how can I just send a copy of the "object" to keep its value which equal to 10
In Swift classes and functions are always passed by reference. Structs, enums and primitive types are passed by value. See this answer.
You can't pass an object by value. You would have to manually copy it before passing it by reference (if that's what you really want).
Another way is to turn your class into a struct, since it would then be passed by value. However, keep in mind there a few other differences between classes and structs, and it might not necessarily be what you want.
And if functions are always pass-by-reference, why we still need the keyword: "inout"
According to the swift documentation, inout is used when
you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.
So in practice with inout you can pass a value type (such as struct or primitive) by reference. You shouldn't really use this very often. Swift provides tuples, that could be used instead.
what does difference between A_plusplus(&object)//[if I make the parameter to be a inout parameter] and A_plusplus(object)
There is no difference for your A_plusplus function. In that function you don't modify the parameter f itself, you modify the f.a property.
The following example shows the effect of using inout when passing a class object. Both functions are the same, differing only in its parameter definition.
class Person {
var name: String
init(name: String) { self.name = name }
}
var me = Person(name: "Lennon") // Must be var to be passed as inout
// Normal object by reference with a var
func normalCall(var p: Person) {
// We sure are able to update p's properties,
// and they will be reflected back to me
p.name = "McCartney"
// Now p points to a new object different from me,
// changes won't be reflected back to me
p = Person(name: "Ringo")
}
// Inout object reference by value
func inoutCall(inout p: Person) {
// We still can update p's properties,
p.name = "McCartney"
// p is an alias to me, updates made will persist to me
p = Person(name: "Ringo")
}
print("\(me.name)") //--> Lennon
normalCall(me)
print("\(me.name)") //--> McCartney
inoutCall(&me)
print("\(me.name)") //--> Ringo
In normalCall p and me are different variables that happen to point to the same object. When you instantiate and assign a new object to p, they no longer refer to the same object. Hence, further changes to this new object will not be reflected back to me.
Stating that p is a var argument just means that its value can change throughout the function, it does not mean the new value will be assigned to what was passed as argument.
On the other hand, in inoutCall you can think of p and me as aliases. As such, assigning a new object to p is the exact same as assigning a new object to me. Any and every change to p is persisted in me after the function ends.

Generic Swift function to test for object type

I'm trying to write a function that takes an object and a type as arguments and returns a boolean indicating whether or not the object is of the given type. There doesn't seem to be a Type type, so I'm not sure how to do this. The best I've been able to do is
func objectIsType<T>(object: AnyObject, someObjectOfType: T) -> Bool {
return object is T
}
So I can do objectIsType(x, 5), to test if x is an Int or objectIsType(x, "hi") to see if it's a string, but I'd like to be able to call objectIsType(x, Int) to see if x is an Int and objectIsType(x, String) to see if it's a String. Is something like this possible?
Edit:
Airspeed Velocity improved my function and made a great point about it doing exactly what is already does. The new function is this:
func objectIsType<T>(object: Any, someObjectOfType: T.Type) -> Bool {
return object is T
}
What I'm trying to do is to validate that the values of a [String: Any] dictionary are of the type that I expect. For instance:
let validator: [String: Any.Type] = [
"gimme an int": Int.self,
"this better be a string": String.self
]
let validatee: [String: Any] = [
"gimme an int": 3,
"this better be a string": "it is!"
]
for (key, type) in validator {
if !objectIsType(validatee[key], type) {
selfDestruct()
}
}
But I'm getting the error, <>protocol.Type is not convertible to T.type. I've looked at the Metatype documentation, but I'm still a bit confused.
If you want to supply a type as the argument, not a value, you can do the following:
func objectIsType<T>(object: Any, someObjectOfType: T.Type) -> Bool {
return object is T
}
let a: Any = 1
objectIsType(a, Int.self) // returns true
NB, AnyObject can only refer to classes, not structs or enums. Int and String are structs. If you change your code, as I have above, to take an Any, it works with structs too.
It might have seemed like your original worked without this change, but really what was happening was the interop was converting your Int into an NSNumber which is a bit of a roundabout way of doing things and won't adapt to the metatype-based approach.
But the question really is, why do you think you need this? is already does exactly this.

Resources