最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]Swift代码调用类的static变量出错:Static member cannot be used on instance of type

Swift crifan 6261浏览 0评论

代码:

class ChatViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MessageDelegate {

//  var chatWithUser: String = "teste03@local"
  static var chatWithUser: String = "teste03@local"
出错:
Static member ‘chatWithUser’ cannot be used on instance of type ‘ChatViewController’
Static member chatWithUser cannot be used on instance of type ChatViewController
搜:
swift Static member cannot be used on instance of type
参考:
后来改为:
message.addAttributeWithName("to", stringValue: ChatViewController.chatWithUser as String)
即可。
[总结]
Swift中,如果是一个SomeClass的static变量someStaticValue,则调用时,不能直接使用someStaticValue,而要写成SomeClass.someStaticValue的形式才可以。
即便是在当前自己的类里面,也要写成SomeClass.someStaticValue才可以。
实例:
class ChatViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MessageDelegate {
    static var chatWithUser: String = "teste03@local"

  @IBAction func sendMessage() {
    ...
        message.addAttributeWithName("to", stringValue: ChatViewController.chatWithUser as String)
      ...
    }
  }
}
供参考。

转载请注明:在路上 » [已解决]Swift代码调用类的static变量出错:Static member cannot be used on instance of type

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (1)

  1. 可以可以,谢谢了
    dscsc5年前 (2020-02-09)回复
88 queries in 0.182 seconds, using 22.11MB memory