无法为“AnyObject”类型调用初始化程序?没有争论 [英] Cannot invoke initializer for type 'AnyObject?' with no arguments

查看:507
本文介绍了无法为“AnyObject”类型调用初始化程序?没有争论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用swift 3来构建一种聊天信使。
为了存储loggedIn Users,我尝试使用AnyObject类型的onject。

I am using swift 3 to build a type of chat messenger. To store loggedIn Users, I try to use an onject of type AnyObject.

    var loggedInUser = AnyObject?()

它出现以下错误:
ViewController.swift:29:24:无法调用没有参数的'AnyObject?'类型的初始值设定项

And it gives the following error: ViewController.swift:29:24: Cannot invoke initializer for type 'AnyObject?' with no arguments

推荐答案

AnyObject 是协议。

协议没有初始化程序。您永远不能通过 ProtocolName()初始化协议实例。您必须为协议中的方法提供实现,并创建具有这些实现的类的实例。

Protocols don't have initializers. You can never initialize an instance of a protocol by ProtocolName(). You must provide implementations for the methods in the protocol, and create an instance of the class that has those implementations.

我认为它不适合存储记录在用户中作为 AnyObject 因为用户不仅仅是任何对象。用户是用户!

I don't think it is suitable to store the logged in user as an AnyObject because well, a user isn't just any object. A user is a user!

我认为你应该做的是创建一个名为 User 的结构/类,将登录用户存储为该类型的实例。

What I think you should do, is create a struct/class named User and store the logged-in user as an instance of that type.

这篇关于无法为“AnyObject”类型调用初始化程序?没有争论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆