ios - 无法将数组添加到具有空数组的字典中

标签 ios arrays swift dictionary singleton

我有一个配置文件数据单例类,如下所示。

我正在尝试将数据存储到字典中的空数组中。

将数据追加到数组后,数组的计数也为 0。

        class ProfileData{

            static let sharedInstance = ProfileData()

             var artistProfileDict = [String : Profile]()
             var loggedInUserProfile = Profile(artistName: "John Smith", artistDescription: "Admiral of New England, English soldier, explorer, and author.", totalLikes: "174", totalViews: "200", totalFollowing: "100",totalFollowers:"50",imageUrl:"image_singer", feeds:[] )


            private init() {
                getProfilesDictionary()
            }

             func getProfilesDictionary()->[String: Profile]{
                artistProfileDict["John Smith"] = loggedInUserProfile
                return artistProfileDict
            }

            func add(array: Feed, artistName: String) {

               artistProfileDict[artistName]!.feeds.append(array)

            }

        }

在另一个 View Controller 中,我尝试将数组添加到字典中的空数组中,如下所示

    let newFeed = Feed(profilePicture: "image",artistName: "New", 
    videoUrl: "url",videoTitle:"New", videoViews: "160",likes: 
    "200",shoutouts: "200",comments: [],votes: "50", dateCreated: Date(),
     userActivity :"This user liked your video")


ProfileData.sharedInstance.add(array: newFeed,artistName:"John Smith")

将数组附加到字典中的空数组后,我仍然得到数组的计数为 0。

我无法弄清楚这里的问题。任何帮助将不胜感激。谢谢。

配置文件类

struct Profile {
    var artistName: String
    var artistDescription: String
    var totalLikes: String
    var totalViews: String
    var totalFollowing: String
    var totalFollowers: String
    var imageUrl: String
    var feeds : [Feed]

    init(artistName: String,artistDescription:String,totalLikes:String,totalViews:String,totalFollowing:String,totalFollowers:String,imageUrl:String, feeds:[Feed]) {

        self.artistName = artistName
        self.artistDescription = artistDescription
        self.totalLikes = totalLikes
        self.totalViews = totalViews
        self.totalFollowing = totalFollowing
        self.totalFollowers = totalFollowers
        self.imageUrl = imageUrl
        self.feeds = feeds
    }
}

最佳答案

工作正常

ProfileData.sharedInstance.add(array: newFeed,artistName:"John Smith")

ProfileData.sharedInstance.artistProfileDict["John Smith"]?.feeds.count // 1

您可能使用了错误的类 ArtistProfileData 而不是 ProfileData

关于ios - 无法将数组添加到具有空数组的字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42997362/

相关文章:

html - iOS Web 应用程序启动画面问题

ios - UIStackView - 使用动画隐藏和折叠 subview

ios - Swift Closure 中的可选链接,其中返回类型必须为 Void

不同维度的Python zip numpy数组

javascript - 检查数组中是否存在键并替换其值

ios - 首次运行时关键帧动画延迟

java - 如何找到已打印的元素并跳过它们再次打印?

ios - 当我按下 iPhone 主页按钮、 sleep /电源按钮或终止我的应用程序并再次重新运行它时,TestButtonAction 不打印

Swift playground 结果位置错误

ios - 滚动 collectionview 时数据已被替换或丢失