无法从Objective-C访问Swift 4类:“在类型对象上找不到属性” [英] Unable to access Swift 4 class from Objective-C: "Property not found on object of type"

查看:294
本文介绍了无法从Objective-C访问Swift 4类:“在类型对象上找不到属性”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用最新的Xcode 9 beta,我似乎完全无法访问Swift类的属性。甚至更奇怪,我可以访问类本身来实例化它或者其他什么,但完全无法访问它上面的属性。

Using the latest Xcode 9 beta, I'm seemingly completely unable to access properties on Swift classes. Even odder, I can access the class itself to instantiate it or whatever, but completely unable to access properties on it.

所以如果我有这个Swift类:

So if I have this Swift class:

import UIKit

class TestViewController: UIViewController {
    var foobar = true
}

我尝试这样做:

TestViewController *testViewController = [[TestViewController alloc] init]; // success
testViewController.foobar; // error

我究竟做错了什么?使用Xcode 9的新项目。

What exactly am I doing wrong? New project with Xcode 9.

推荐答案

在Swift 4中将Swift代码暴露给Objective-C的规则已经改变。试试这个:

The rules for exposing Swift code to Objective-C have changed in Swift 4. Try this instead:

@objc var foobar = true

作为优化,Swift 4中的 @objc 推断已经减少。例如,中的属性NSObject -derived类,例如你的 TestViewController ,将 no 更长时间推断 @objc 默认情况下(就像在Swift 3中一样)。

As an optimization, @objc inference have been reduced in Swift 4. For instance, a property within an NSObject-derived class, such as your TestViewController, will no longer infer @objc by default (as it did in Swift 3).

或者,您也可以将所有成员公开给Objective- C一次使用 @objcMembers

Alternatively, you could also expose all members to Objective-C at once using @objcMembers:

@objcMembers class TestViewController: UIViewController {
    ...
}

新设计详见< a href =https://github.com/apple/swift-evolution/blob/master/proposals/0160-objc-inference.md =noreferrer>相应的Swift Evolution提案。

这篇关于无法从Objective-C访问Swift 4类:“在类型对象上找不到属性”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆