我有一个名为Hashtag的模型对象。这只包含一个名为hashtagName的可选String变量。我从Firebase数据库中获取数据,并将主题标签附加到我的fashionHashtags,即[Hashtag]
。我遇到的问题是我想通过使用insertElementAtIndexPath
函数将其附加到我的其他categoriesArray。我不能这样做因为它想要一个字符串数组而不是一个Hashtag数组。当我自动更正它时,它会用fashionHashtags as! [String]
替换它,但这会产生另一个错误。我如何解决这个问题,这样我才能这样做?我想坚持Model Object的做事方式。感谢你们。答案将受到高度赞赏。代码如下:
class Hashtag: NSObject {
vvar hashtagName: String?
}
private let reuseIdentifier = "Cell"
class HashtagView: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var catagoriesArray: [String] = ["FASHION", "FOOD", "HOBBIES", "MUSIC"]
var fashionHashtags = [Hashtag]()
var foodHashtags = [Hashtag]()
var hobbiesHashtags = [Hashtag]()
var musicHashtags = [Hashtag]()
var hashtagsArray: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.hashtagsArray.removeAll()
self.navigationController?.navigationBar.tintColor = .white
navigationItem.title = "Hashtag"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Finished", style: .plain, target: self, action: #selector(finishSelectingHashtags))
self.collectionView?.backgroundColor = .white
self.collectionView?.register(HashtagCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView?.contentInset = UIEdgeInsetsMake(10, 0, 0, 0)
handleFetchFashionHashtags()
}
func insertElementAtIndexPath(element: [String], index: Int) {
catagoriesArray.insert(contentsOf: element, at: index)
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.item == 0 {
insertElementAtIndexPath(element: fashionHashtags, index: indexPath.item + 1)
self.collectionView?.performBatchUpdates(
{
self.collectionView?.reloadSections(NSIndexSet(index: 0) as IndexSet)
}, completion: { (finished:Bool) -> Void in
})
}
}
答案 0 :(得分:0)
根据我的理解,可能会有几种不同的方法。这将是循环遍历Hashtag对象数组并将hashtagName字符串属性附加到stringsArray字符串的方法。
for hashTagItem in fashionHashtags {
if let hashTag = hashTagItem.hashtagName {
// Appends to categoriesArray as a string
categoriesArray.append(hashTag)
}
}
另一种方法是构建一组字符串,然后在有意义的时候插入它。
var hashTagString: [Strings] = []
for hashTagItem in fashionHashtags {
if let hashTag = hashTagItem.hashtagName {
hashTagStrings.append(hashTag)
}
}
// Insert or add the hash tag strings as it makes sense
categoriesArray += hashTagStrings // Add all at once if it makes sense