using failable init, can't access part of struct. Help!

code as follows, can't access the "contents" var in the struct (see line 37). what am i doing wrong? thank you!

Code Block
import Cocoa
class Food {
  var name: String
   
  init?(name: String) {
    if name.isEmpty { return nil }
    self.name = name
  }
   
}
class Fruit : Food {
   
  var color: String
   
  init?(name: String, color: String) {
    self.color = color
    super.init(name: name)
  }
   
}
struct Bowl {
  var contents: Fruit?
  var quantity: Int
}
var toast = Food(name: "toast")
var banana = Fruit(name: "banana", color: "yellow")
var myFruitBowl = Bowl(contents: banana, quantity: 5)
print(toast?.name as Any) //works
print(banana?.color as Any) //works
print(myFruitBowl.contents?.color as Any) //works
print(myFruitBowl.quantity as Any) //even this works!
print(myFruitBowl.contents as Any) // log: Optional(__lldb_expr_25.Fruit)

Answered by Claude31 in 639759022
You need to access the property, not the full class:

Code Block
print(myFruitBowl.contents!.name)

Gives banana

To have more robust code:
Code Block
print(myFruitBowl.contents?.name ?? "No fruit")

Accepted Answer
You need to access the property, not the full class:

Code Block
print(myFruitBowl.contents!.name)

Gives banana

To have more robust code:
Code Block
print(myFruitBowl.contents?.name ?? "No fruit")

I’m not sure what you mean by “can't access”. I put your code into a small test project here and this is what line 37 prints:

Code Block
Optional(TestProject.Fruit)


There’s two parts to this:
  • The Optional(…) is because myFruitBowl.contents is optional.

  • TestProject.Fruit is the name of the class.

If you want to strip off the first, you can unwrap the optional. For example:

Code Block
if let contents = myFruitBowl.contents {
print(contents) // prints: TestProject.Fruit
}


If you want to customise the second, let me introduce you to CustomDebugStringConvertible:

Code Block
class Fruit: Food, CustomDebugStringConvertible {
… other stuff unchanged …
var debugDescription: String {
"Fruit(\(color))"
}
}


Once you make this change then the code snippet above prints Fruit(yellow).

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"
Thank you Claude31 and Quinn! That works.
using failable init, can't access part of struct. Help!
 
 
Q