草庐IT

ios - 仅获取协议(protocol)中定义的属性在修改对象的内部属性时导致编译错误

coder 2024-01-29 原文

考虑这样的代码:

protocol SomeProtocol {
    var something: Bool { get set }
}

class SomeProtocolImplementation: SomeProtocol {
    var something: Bool = false {
        didSet {
            print("something changed!")
        }
    }
}

protocol MyProtocol {
    var myProperty: SomeProtocol { get }
}

class MyClass: MyProtocol {
    var myProperty: SomeProtocol = SomeProtocolImplementation() {
        didSet {
            print("myProperty has changed")
        }
    }
}


var o: MyProtocol = MyClass()
o.myProperty.something = true

这段代码没有编译错误:

error: cannot assign to property: 'myProperty' is a get-only property
o.myProperty.something = true
~~~~~~~~~~~~           ^

为什么?我的属性是 SomeProtocolImplementation 类型,它是类类型,因此应该可以使用对 myProperty 的引用来修改它的内部属性。

更进一步,在修改 myProperty 定义之后,它看起来像这样:

var myProperty: SomeProtocol { get set }

奇怪的事情发生了。现在代码可以编译(不足为奇),但输出是:

something changed!
myProperty has changed

所以此时 SomeProtocolImplementation 开始表现得像一个值类型 - 修改它的内部状态会导致触发 myProperty 的“didSet”回调。正如 SomeProtocolImplementation 将是结构化的...

我实际上找到了解决方案,但我也想了解发生了什么。解决方案是将 SomeProtocol 定义修改为:

protocol SomeProtocol: class {
    var something: Bool { get set }
}

它工作正常,但我试图理解为什么它会这样。谁能解释一下?

最佳答案

先读什么Class Only Protocol是。专注于说明部分:

Use a class-only protocol when the behavior defined by that protocol’s requirements assumes or requires that a conforming type has reference semantics rather than value semantics.

上面的引述应该让你明白了。

您正在尝试为您的 SomeProtocol 的符合类(即 SomeProtocolImplementation)获取引用类型的行为。您希望将来能够更改 something 的值。所以基本上你是在指向上面引用的句子。

如果您需要更多说明,请考虑以下更有意义的设计,为方便起见,我更改了命名:

protocol Base: class {
    var referenceTypeProperty: Bool { get set }
    // By now you are assuming: this property should be modifiable from any reference.
    // So, instantly make the protocol `Class-only`
}

class BaseImplementation: Base {
    var referenceTypeProperty: Bool = false {
        didSet {
            print("referenceTypeProperty did set")
        }
    }
}

protocol Child {
    var valueTypeProperty: Base { get }
    // This property shouldn't be modifiable from anywhere.
    // So, you don't need to declare the protocol as Class-only
}

class ChildImplementation: Child {
    var valueTypeProperty: Base = BaseImplementation() {
        didSet {
            print("valueTypeProperty did set")
        }
    }
}

let object: Child = ChildImplementation()
object.valueTypeProperty.referenceTypeProperty = true

关于ios - 仅获取协议(protocol)中定义的属性在修改对象的内部属性时导致编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45836642/

有关ios - 仅获取协议(protocol)中定义的属性在修改对象的内部属性时导致编译错误的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  3. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  4. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  5. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  6. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  7. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  8. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  9. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  10. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

随机推荐