0
votes

I'm trying to cast/ convert a custom object to string but keep getting the error:

Cannot invoke initializer for type 'String' with an argument list of type '(ArtInfo)'

I have a custom class:

class ArtInfo {

  var poster: String?
  var artwork: String?
  var fanart: String?

  init (poster: String?, artwork: String?, fanart: String?){
    self.poster = poster
    self.artwork = artwork
    self.fanart = fanart
  }
}

After retrieving the values (json data) I'm trying to put them in local arrays. The arrays are split up by category, the json retrieval and parsing covers all the data not just this particular class. Here is how I append the data to the local array:

      var photosArray: [String] = []

  override func viewDidLoad() {
    super.viewDidLoad() 
        DetailShowInfo.updateAllDetails(urlExtension: url, completionHandler: { details in

      let artPics = ArtInfo.init(poster: details[0].poster, artwork: details[0].artwork, fanart: details[0].fanart)
          self.photosArray.append(String(artPics))// Error happens here
    })
}
1
What is String(artPics) supposed to do? - luk2302
its supposed to convert the custom object 'ArtInfo' to string - SwiftyJD
"convert" in what way? What is the expected outcome? - luk2302
take the data in ArtInfo and change it to string format - SwiftyJD
How is the program supposed to know how to compose a string of that object? Should it put the three inner variables just next to each other or reverse them, put a comma in between them, shuffle them, multiply them, sort them? You have to tell the program how to create a string based on your object. - luk2302

1 Answers

2
votes

You need to use the function String(describing:).

So you'd use String(describing:artPics).

That will display a string describing any object, but the string returned is not very useful by default.

In order to get a useful string, you need to make your custom object conform to the CustomStringConvertible protocol, which means it has a String description property. Here's what your class might look like:

class ArtInfo: CustomStringConvertible {

  var poster: String?
  var artwork: String?
  var fanart: String?

  init (poster: String?, artwork: String?, fanart: String?){
    self.poster = poster
    self.artwork = artwork
    self.fanart = fanart
  }
  var description: String {
    return "ArtInfo object. Poster = " + 
    poster + ", artwork = " + artwork +
    ", fanart = " + fanart
  }
}

(Adjust the code behind your computed description property to get the format you want. The above would yield the rather nasty 'optional("value")' you get from optionals.)