Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么我不能从Objective-C对象到Swift属性使用KVC?_Objective C_Swift_Key Value Coding_Kvc - Fatal编程技术网

为什么我不能从Objective-C对象到Swift属性使用KVC?

为什么我不能从Objective-C对象到Swift属性使用KVC?,objective-c,swift,key-value-coding,kvc,Objective C,Swift,Key Value Coding,Kvc,我的团队已经决定新文件应该用swift编写,我发现在Objective-C对象中使用KVC来设置swift对象的属性有一个奇怪的问题 My Objective-C设置如下属性:[textObject setValue:0.0 forKey:@“fontSize”] 我的Swift对象(textObject)具有此属性的自定义setter/getter var fontSize: CGFloat? { get { return internalTextGraph

我的团队已经决定新文件应该用swift编写,我发现在Objective-C对象中使用KVC来设置swift对象的属性有一个奇怪的问题

My Objective-C设置如下属性:
[textObject setValue:0.0 forKey:@“fontSize”]

我的Swift对象(
textObject
)具有此属性的自定义setter/getter

   var fontSize: CGFloat? {
      get {
         return internalTextGraphic?.fontSize 
      }
      set {
            internalTextGraphic?.fontSize = newValue
      }
   }
但是,如果我在
集合中设置断点,它将永远不会被命中

我有Objective-C对象也得到了同样的调用,我只是实现了
-setFontSize
,执行正确进入

为什么我不能通过
-setValueForKey
进入我的
set
方法? 我已100%确认
textObject
存在且类型正确

编辑
Martin R是正确的,我必须使a型非可选。这是我的工作代码:

   var fontSize: CGFloat {
      get {
         var retFontSize: CGFloat = 0.0
         if let fontSize = internalTextGraphic?.fontSize {
            retFontSize = fontSize
         }
         return retFontSize
      }
      set {
         if let textGraphic = internalTextGraphic {
            textGraphic.fontSize = newValue
         }
      }
   }

原因是Swift可选结构或枚举(在您的例子中是
CGFloat?
) 在Objective-C中不可表示(并且您不会看到该属性 在生成的
“Project Swift.h”
头文件中)。这一点变得更加明显 如果你标记了这个属性 显式地使用
@objc
,您将得到错误消息

error: property cannot be marked @objc because its type cannot be represented in Objective-C 错误:属性无法标记为@objc,因为其类型无法在Objective-C中表示 如果将属性类型更改为非可选的
CGFloat
然后KVC按预期工作。它还可以与可选的 类类型,例如
NSNumber?

“Swift可选项在Objective-C中不可表示”-好吧,这对于可选类/协议类型是不正确的,但是对于结构/枚举是正确的,CGFloat就是其中之一。