jjzjj

ios - Swift 类指针作为?类协议(protocol)?

coder 2024-01-30 原文

我有一个类,我们称它为 SomeClass。 SomeClass 的实例有一个可选的指向 SomeOtherClass 的指针。这样就可以实例化SomeClass的实例,给定一个指向SomeOtherClass(或者SomeOtherClass的子类)的指针,然后这个指针就可以用来动态创建属于SomeClass的这个SomeOtherClass的实例。例如;

class SomeClass {
    var classPointer: SomeOtherClass.Type?
}

class SomeOtherClass {
}

到目前为止一切顺利。现在,我有一个协议(protocol) - 让我们称之为 SomeProtocol - 我希望 SomeOtherClass 遵守。这个协议(protocol)里面有类函数:

protocol SomeProtocol {
    static func someClassFunction()
}

extension SomeOtherClass : SomeProtocol {
    class func someClassFunction() {
        print("I am a class function being executed on SomeOtherClass")
    }
}

正如预期的那样,我可以像这样在 SomeOtherClass 上调用这个协议(protocol)类函数:

SomeOtherClass.someClassFunction() // Prints "I am a class function being executed on SomeOtherClass"

这是麻烦的部分。我想动态确定 SomeClass 的 classPointer 实例是否符合 SomeProtocol,如果符合,则在其上执行类函数。所以,我尝试使用 as? 转换指针:

// Create an instance of SomeClass and set it's classPointer to the SomeOtherClass class
let someInstance = SomeClass()
someInstance.classPointer = SomeOtherClass.self

// Check if the instance's classPointer class conforms to the SomeProtocol protocol
if let conformingClass = someInstance.classPointer as? SomeProtocol {
    // If so, execute the class function in SomeProtocol on the instance's classPointer
    conformingClass.someClassFunction() // Build fails "Static member someClassFunction cannot be used on instance of type SomeProtocol"
}

构建失败并出现错误“someClassFunction 的静态成员不能用于 SomeProtocol 类型的实例”。

有没有办法完成我正在尝试的事情?目前,如果这不起作用,我只能想到这些替代方案(没有一个是可取的,而且它们都很老套):

  1. 切换到 objective-c 。
  2. 将协议(protocol)改为使用实例函数,然后实例化 SomeClass 的 classPointer 的临时实例并向其发送任何必要函数的消息,然后释放该实例。

为了完整起见,这里是可以粘贴到 Playground 中的所有代码(由于我提到的错误,它不会构建):

class SomeClass {
    var classPointer: SomeOtherClass.Type?
}

class SomeOtherClass {
}

protocol SomeProtocol {
    static func someClassFunction()
}

extension SomeOtherClass : SomeProtocol {
    class func someClassFunction() {
        print("I am a class function being executed on SomeOtherClass")
    }
}

// Create an instance of SomeClass and set it's classPointer to the SomeOtherClass class
let someInstance = SomeClass()
someInstance.classPointer = SomeOtherClass.self

// Check if the instance's classPointer class conforms to the SomeProtocol protocol
if let conformingClass = someInstance.classPointer as? SomeProtocol {
    // If so, execute the class function in SomeProtocol on the instance's classPointer
    conformingClass.someClassFunction() // Build fails "Static member someClassFunction cannot be used on instance of type SomeProtocol"
}

感谢您提供的任何帮助, - 亚当

最佳答案

啊哈!像往常一样,一旦我发布了 SO 帖子,我就会找出答案。

对于那些疑惑的人,您必须将 classPointer 转换为协议(protocol)的类型,而不是协议(protocol)本身。线路:

if let conformingClass = someInstance.classPointer as? SomeProtocol {

需要改为:

if let conformingClass = someInstance.classPointer as? SomeProtocol.Type {

然后您将能够使用在 SomeProtocol 中声明的类函数向 conformingClass 发送消息。完整的工作代码是:

class SomeClass {
    var classPointer: SomeOtherClass.Type?
}

class SomeOtherClass {
}

protocol SomeProtocol {
    static func someClassFunction()
}

extension SomeOtherClass : SomeProtocol {
    class func someClassFunction() {
        print("I am a class function being executed on SomeOtherClass")
    }
}

// Create an instance of SomeClass and set it's classPointer to the SomeOtherClass class
let someInstance = SomeClass()
someInstance.classPointer = SomeOtherClass.self

// Check if the instance's classPointer class conforms to the SomeProtocol protocol
if let conformingClass = someInstance.classPointer as? SomeProtocol.Type {
    // If so, execute the class function in SomeProtocol on the instance's classPointer
    conformingClass.someClassFunction()
}

而且有效:)。

关于ios - Swift 类指针作为?类协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35871200/

有关ios - Swift 类指针作为?类协议(protocol)?的更多相关文章

  1. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  2. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  3. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  4. ruby - 字符串文字中的转义状态作为 `String#tr` 的参数 - 2

    对于作为String#tr参数的单引号字符串文字中反斜杠的转义状态,我觉得有些神秘。你能解释一下下面三个例子之间的对比吗?我特别不明白第二个。为了避免复杂化,我在这里使用了'd',在双引号中转义时不会改变含义("\d"="d")。'\\'.tr('\\','x')#=>"x"'\\'.tr('\\d','x')#=>"\\"'\\'.tr('\\\d','x')#=>"x" 最佳答案 在tr中转义tr的第一个参数非常类似于正则表达式中的括号字符分组。您可以在表达式的开头使用^来否定匹配(替换任何不匹配的内容)并使用例如a-f来匹配一

  5. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  6. CAN协议的学习与理解 - 2

    最近在学习CAN,记录一下,也供大家参考交流。推荐几个我觉得很好的CAN学习,本文也是在看了他们的好文之后做的笔记首先是瑞萨的CAN入门,真的通透;秀!靠这篇我竟然2天理解了CAN协议!实战STM32F4CAN!原文链接:https://blog.csdn.net/XiaoXiaoPengBo/article/details/116206252CAN详解(小白教程)原文链接:https://blog.csdn.net/xwwwj/article/details/105372234一篇易懂的CAN通讯协议指南1一篇易懂的CAN通讯协议指南1-知乎(zhihu.com)视频推荐CAN总线个人知识总

  7. ruby-on-rails - 应用程序的名称是否可以作为变量使用? - 2

    当我创建一个Rails应用程序时,控制台:railsnewfoo我的代码可以使用字符串“foo”吗?puts"Yourapp'snameis"+app_name_bar 最佳答案 Rails.application.class将为您提供应用程序的全名(例如YourAppName::Application)。从那里您可以使用Rails.application.class.parent获取模块名称。 关于ruby-on-rails-应用程序的名称是否可以作为变量使用?,我们在StackOve

  8. ruby-on-rails - 使用作为方法的值在 ruby​​ 中搜索哈希 - 2

    我在搜索我的值是方法的散列时遇到问题。我只是不想运行plan_type与键匹配的方法。defmethod(plan_type,plan,user){foo:plan_is_foo(plan,user),bar:plan_is_bar(plan,user),waa:plan_is_waa(plan,user),har:plan_is_har(user)}[plan_type]end目前如果我传入“bar”作为plan_type,所有方法都会运行,我怎么能只运行plan_is_bar方法呢? 最佳答案 这个变体怎么样?defmethod

  9. ruby - 无法在 Ruby 中将 ffmpeg 作为子进程运行 - 2

    我正在尝试使用以下代码通过将ffmpeg实用程序作为子进程运行并获取其输出并解析它来确定视频分辨率:IO.popen'ffmpeg-i'+path_to_filedo|ffmpegIO|#myparsegoeshereend...但是ffmpeg输出仍然连接到标准输出并且ffmepgIO.readlines是空的。ffmpeg实用程序是否需要一些特殊处理?或者还有其他方法可以获得ffmpeg输出吗?我在WinXP和FedoraLinux下测试了这段代码-结果是一样的。 最佳答案 要跟进mouviciel的评论,您需要使用类似pope

  10. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

随机推荐