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

问题描述

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

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

编辑 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]()
    }
}

我的模型类将两个数据合并为一个 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 下。如果那是正确的,我建议您朝不同的方向前进。这是一个很好的示例,您可以在其中使用子类化。您可以声明一个名为 Ad 的类,您可以在其中定义对 PostDataAdsNativeAds 都适用的公共属性。

class Ad {
    // Add here the common elements you want to retrieve from both classes
    var name: String = ""
}

在定义继承自 PostDataAdsNativeAdsAd 之后:

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 对象是相同的,您不需要复制它们。如果你真的想要两个类,你可以从 PostData1 继承 Ad

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: "",timestring: "")
ads.append(nativeAdd)