将数据添加到 AnyObject Var 以便我可以制作原生广告的问题

Issue with adding Data to an AnyObject Var so that I could make native ads work

 for postdata in postdata {
        if index < tableViewItems.count {
            tableViewItems.insert(postdata, at: index)
            index += adInterval
        } else {
            break
        }
    }

我需要在同一个 AnyObject Var 上同时添加 Post 数据广告和原生广告才能使其正常工作,但我找不到添加 Post 的方法数据,因为它说出现错误,说“参数类型 'PostData' 应该是 class 或 class 约束类型的实例。”非常感谢您的帮助,谢谢。

编辑 1

class Ad {
    var postimage: String!
    var publisher: String!
    var timestring: String!
    var timestamp = Date().timeIntervalSince1970
}

class PostDataAd: Ad {

    // Declare here your custom properties
    struct PostData1
    {
        var postimage: String
        var publisher: String
        var timestring : String
        var timestamp = Date().timeIntervalSince1970
    }
}

class NativeAd: Ad {
    // Declare here your custom properties
    struct NativeAd
    {
        var nativeAds: [GADUnifiedNativeAd] = [GADUnifiedNativeAd]()
    }
}

我的模型class将两个数据合并为一个 AnyObject Var

然后尝试通过执行此操作从 Firebase 附加数据

var ads: [Ad] = [PostDataAd(), NativeAd()]

let postList = PostDataAd.PostData1(postimage: postimage, publisher: 
postpublisher, timestring: postid, timestamp: timestamp)

self.ads.insert(postList, at:0)

发生错误,提示无法将类型 'PostDataAd.PostData1' 的值转换为预期的参数类型 'Ad'

我希望我得到你想要的正确。所以基本上你有两个对象要存储在一个数组中,在 AnyObject 下。如果那是正确的,我建议您朝不同的方向前进。这是一个很好的示例,您可以在其中使用 subclassing。您可以声明一个名为 Ad 的 class,您可以在其中定义对 PostDataAdsNativeAds.

都适用的公共属性
class Ad {
    // Add here the common elements you want to retrieve from both classes
    var name: String = ""
}

在定义继承自 AdPostDataAdsNativeAds 之后:

class PostDataAd: Ad {
    // Declare here your custom properties
}

class NativeAd: Ad {
    // Declare here your custom properties
}

如果你想用两种类型的对象定义一个数组,你可以去:

let ads: [Ad] = [PostDataAd(), NativeAd()]

检索时可以检查它们的类型:

if let item = ads.first as? PostDataAd {
     // The Ad is a PostDataAd
} else if let item = ad as? NativeAd {
    // The Ad is a NativeAd
}

或者在某些情况下,您甚至不知道确切的类型,因为您无需检查就可以访问 Ad 中定义的属性。

更新:

首先你的PostData1Ad对象是一样的,你不需要复制它们。如果你真的想要两个 classes 你可以从 Ad.

继承 PostData1
class Ad {
    var postimage: String
    var publisher: String
    var timestring: String
    var timestamp = Date().timeIntervalSince1970

    // You can add timestamp here also if you wish
    init(postimage: String, publisher: String, timestring: String) {
        self.postimage = postimage
        self.publisher = publisher
        self.timestring = timestring
    }
}

class PostDataAd: Ad {
    // Define some custom properties
}

如果您想将 PostData 附加到 [Ad] 数组,您可以执行以下操作:

var ads: [Ad] = []
// Replace with your values
let postList = PostDataAd(postimage: "", publisher: "", timestring: "") 
ads.insert(postList, at: 0)

// Appending NativeAd works also
let nativeAdd = NativeAd(postimage: "", publisher: "", timestring: "")
ads.append(nativeAdd)