Trouble with casting let list = list as? List<Object>

25 views
Skip to first unread message

ChangSung kim

unread,
Jan 20, 2016, 4:46:25 AM1/20/16
to Realm
Hi 

I'm using RealmSwift version 0.97.0 

1. When I use under the code, result value is unexpected. here is the code.

class BDRUser:Object {
...
}

    func change(list:AnyObject) -> Bool {

        if let list = list as? List {

            return true

        } else {

            return false

        }

    }

    

    let list = List<BDRUser>()

    list.append(BDRUser())

    print(change(list))


-- 

print value is false 

I expected the printing value was true but  it didn't 
can you know me how can I fix it ? 

2.  here is another code 

        let list = List<BDRUser>()

        list.append(BDRUser())

        let v = list as? List<Object>

        print(v)


the result is 'nil' 


I wonder why type casting doesn't work well from List<BDRUser> to List<Object> ? That is always fail 


so could you fix it though? 


Thanks ! 

Marius Rackwitz

unread,
Jan 20, 2016, 7:31:42 AM1/20/16
to Changsung Kim, realm...@googlegroups.com
Hey,

what you're trying to achieve is not supported with Swift.
Collection types in Swift are not covariant.
The compiler should warn you, that what you're trying to do will never succeed.
You can use instead map:
let v = list.map { $0 as Object }

Best!

--
Marius Rackwitz
iOS Product Engineer
{#HS:162783134-2718#}
--
You received this message because you are subscribed to the Google Groups "Realm" group.
To unsubscribe from this group and stop receiving emails from it, send an email to realm-cocoa...@googlegroups.com.
To post to this group, send email to realm...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/realm-cocoa/cf3b2177-5d9f-4cf3-822d-41b3ec07bb91%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



Reply all
Reply to author
Forward
0 new messages