无法使用类型为'(CustomObject)'

时间:2017-01-22 21:35:41

标签: ios arrays swift string

我正在尝试将自定义对象转换/转换为字符串,但不断收到错误:

  

无法使用参数列表调用类型为“String”的初始值设定项   输入'(ArtInfo)'

我有一个自定义类:

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
  }
}

检索值(json数据)后,我试图将它们放在本地数组中。数组按类别拆分,json检索和解析覆盖了不仅仅是这个特定类的所有数据。以下是我将数据附加到本地数组的方法:

      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 个答案:

答案 0 :(得分:2)

您需要使用函数String(describing:)

所以你要使用String(describing:artPics)

这将显示描述任何对象的字符串,但默认情况下返回的字符串不是很有用。

为了获得有用的字符串,您需要使自定义对象符合CustomStringConvertible协议,这意味着它具有String description属性。以下是您的课程的样子:

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
  }
}

(调整计算出的description属性后面的代码,以获得您想要的格式。上面会产生相当讨厌的选项("值")'你来自期权。)