【问题标题】:Why am I getting: "Cannot convert value of type '[String]?' to expected argument type 'String?'"为什么我会收到:“无法转换 '[String] 类型的值?'到预期的参数类型“字符串?”
【发布时间】:2020-04-22 11:26:15
【问题描述】:

我正在使用 swift 开发一个应用程序。我正在加载带有来自 firebase 的图像的集合视图。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "subPostCell", for: indexPath) as! SubPostCell

    cell.subPostImage.downloadImage(from: self.subposts[indexPath.row].pathToImage)

    return cell
}

它在cell.subPostImage 行中给出错误:

无法转换类型“[String]?”的值到预期的参数类型“字符串?”

这是我的子帖子对象:

import Foundation

struct SubPost: Decodable {
    var pathToImage: [String]?
    var postID: String!
    var userID: String!

    init(pathToImage: [String]? = nil, postID: String? = nil, userID: String? = nil) {
        self.pathToImage = pathToImage
        self.postID = postID
        self.userID = userID
    }

}

这是我的 subpostscell 代码:

import UIKit

class SubPostCell: UICollectionViewCell {

    @IBOutlet weak var stepLabel: UILabel!
    @IBOutlet weak var subPostImage: UIImageView!

}

我做错了什么?

【问题讨论】:

  • 错误很清楚发生了什么,它说它需要一个字符串?要在您使用时传递的是传递一个字符串数组?,即您的 pathToImage。很可能您需要将数组的字符串连接成一个字符串。
  • 是的,但是每个 supbost 都有一个类似于“缩略图”的主要 url,其他的是其他东西。我需要下载其他网址,而不是缩略图。

标签: swift firebase firebase-realtime-database


【解决方案1】:

根据你的代码pathToImage有多个url,所以需要获取具体的url并下载,

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "subPostCell", for: indexPath) as! SubPostCell
        if pathToImage.count > 0 {
            cell.subPostImage.downloadImage(from: self.subposts[indexPath.row].pathToImage[0])
        }

    return cell
}

【讨论】:

  • 我如何指定下载 4 个 url 中的 3 个?
  • 因为它是一个包含 4 个字符串的字符串数组
  • self.subposts[indexPath.row].pathToImage[0] 将 0 更改为要下载的数字(0-1st url , 1-2nd url , 2-3rd url, 3-4th url )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
  • 2019-12-24
  • 1970-01-01
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多