swift optional chaining with cast

Derrek

The code below highlights a problem I'm having combining optional chaining and casts with Apple's swift language

import Foundation
import CoreData

class MyExample {

    var detailItem: NSManagedObject?

    func example() {
        //In the actual implementation it is assigned to a UITableViewCell textLabel.text with the same result.
        let name: String = self.detailItem?.valueForKey("name") as String
    }
}

The above results in:

'AnyObject' is not convertible to 'String'

I am able to do this by making the class variable an implicitly unwrapped optional as follows:

class MyExample2 {

    var detailItem: NSManagedObject!

    func example() {
        let name: String = self.detailItem.valueForKey("name") as String
    }
}

This works, but now this variable doesn't reflect my real world need for it to be optional

This next example also works with detailItem as optional:

class MyExample3 {

    var detailItem: NSManagedObject?

    func example() {
        let name: String = self.detailItem?.valueForKey("name").description as String
    }
}

The problem with the above is I had to use description. It's generally not a good idea to use output from this function to show to the user (according to Apple, and just common sense)

The above also only works because I am looking for a string. If I needed an object, it wouldn't work.

As a point of interest this example throws a different error:

class MyExample4 {

    var detailItem: NSManagedObject?

    func example() {
        let name: String = self.detailItem?.valueForKey("name")
    }
}

The above throws:

Could not find member 'valueForKey'

NSmanagedObject clearly has a valueForKey.

Trying one more thing, I discovered a potential solution:

class MyExamplePotentialSolution {

    var detailItem: NSManagedObject?

    func example() {
        let name: NSString = self.detailItem?.valueForKey("name") as NSString
    }
}

The problem with the above, is it doesn't work when actually assigned to a UITableViewCell detailTextLabel.text attribute.

Any ideas?

Updated Answer

The simplest real world usage turned out to be this:

cell.detailTextLabel.text = self.detailItem?.valueForKey("name") as? NSString

The key is AnyObject can't be cast to a native swift type directly. As the accepted answer showed, it can be cast as a native Swift string from NSString. It just isn't necessary in this case.

Antonio

There are 2 problems: the first is that in this line:

let name: String = self.detailItem?.valueForKey("name") as String

the right part is an optional (detailItem is optional), so whatever the expression returns, it cannot be assigned to a non-optional variable having type String

The second problem is that valueForKey returns AnyObject!, which can be an instance of any class - but String is not a class, you'd need Any in order to be able to cast that into a String. I presume that NSManagedObject returns an NSString, so you can achieve what you need with this line:

let name: String? = (self.detailItem?.valueForKey("name") as? NSString) as? String

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Swift 3.0 Optional Chaining

From Dev

Optional chaining with Swift strings

From Dev

Optional chaining and Array in swift

From Dev

Optional Chaining or ternary expression in Swift?

From Dev

Swift optional chaining doesn't work in closure

From Dev

Is there something like the swift optional chaining in javascript?

From Dev

Optional chaining used in left side of assignment in Swift

From Dev

Accessing boolValue in a NSNumber var with optional chaining (in Swift)

From Dev

How to use optional chaining while searching through a dictionary in swift?

From Dev

Is Swift optional chaining lazily evaluated left-to-right?

From Dev

optional chaining in Swift 3: why does one example work and not the other?

From Dev

In swift, why can I set a computed property of a polymorphic variable via optional chaining, but not on an unwrapped optional?

From Dev

Is Swift optional chaining always done with the if let construction, or is it just done using a question mark with an optional?

From Dev

In swift, why can I set a computed property of a polymorphic variable via optional chaining, but not on an unwrapped optional?

From Java

Optional chaining (?.) in nashorn

From Dev

Optional Chaining returning an Int

From Dev

Optional Chaining in JavaScript

From Dev

Optional Chaining Not Working As Expected

From Dev

Chaining Optional.orElseThrow

From Dev

Optional chaining for constructor calls?

From Dev

an unexpected error while writing a piece of code from Swift programming by Apple(optional chaining)

From Dev

Optional chaining not working for optional protocol requirements

From Dev

Is there an equivalent to optional chaining with arithmetic operators?

From Dev

dynamicType of optional chaining not the same as assignment

From Dev

Optional.ofNullable and method chaining

From Dev

Is it possible to cast Any to an Optional?

From Dev

Cast the content of optional or streams

From Dev

Swift - Method chaining

From Dev

Swift chaining optionals

Related Related

  1. 1

    Swift 3.0 Optional Chaining

  2. 2

    Optional chaining with Swift strings

  3. 3

    Optional chaining and Array in swift

  4. 4

    Optional Chaining or ternary expression in Swift?

  5. 5

    Swift optional chaining doesn't work in closure

  6. 6

    Is there something like the swift optional chaining in javascript?

  7. 7

    Optional chaining used in left side of assignment in Swift

  8. 8

    Accessing boolValue in a NSNumber var with optional chaining (in Swift)

  9. 9

    How to use optional chaining while searching through a dictionary in swift?

  10. 10

    Is Swift optional chaining lazily evaluated left-to-right?

  11. 11

    optional chaining in Swift 3: why does one example work and not the other?

  12. 12

    In swift, why can I set a computed property of a polymorphic variable via optional chaining, but not on an unwrapped optional?

  13. 13

    Is Swift optional chaining always done with the if let construction, or is it just done using a question mark with an optional?

  14. 14

    In swift, why can I set a computed property of a polymorphic variable via optional chaining, but not on an unwrapped optional?

  15. 15

    Optional chaining (?.) in nashorn

  16. 16

    Optional Chaining returning an Int

  17. 17

    Optional Chaining in JavaScript

  18. 18

    Optional Chaining Not Working As Expected

  19. 19

    Chaining Optional.orElseThrow

  20. 20

    Optional chaining for constructor calls?

  21. 21

    an unexpected error while writing a piece of code from Swift programming by Apple(optional chaining)

  22. 22

    Optional chaining not working for optional protocol requirements

  23. 23

    Is there an equivalent to optional chaining with arithmetic operators?

  24. 24

    dynamicType of optional chaining not the same as assignment

  25. 25

    Optional.ofNullable and method chaining

  26. 26

    Is it possible to cast Any to an Optional?

  27. 27

    Cast the content of optional or streams

  28. 28

    Swift - Method chaining

  29. 29

    Swift chaining optionals

HotTag

Archive