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

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

Swift crifan 6884浏览

代码:

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

84 queries in 0.751 seconds, using 19.19MB memory