【问题标题】:Objective C syntax to assign a value to a variable property in Swift在 Swift 中为变量属性赋值的 Objective C 语法
【发布时间】:2020-05-28 05:02:10
【问题描述】:

我目前的项目是在 Objective C 中,我想在 Swift 中对其进行新的实现。

在我的 Objective C 类中,我需要为我的 swift 变量属性分配一个值,但我不知道执行此操作的语法。我想这样赋值。

self.pollBarGraph = [[PollBarGraphView alloc] initWithFrame:self.view.frame];

//I want to replace this with obj-c syntax to make it work
        self.pollBarGraph.dataEntries =
        [
           BarEntry(score: 100, title: "A"),
           BarEntry(score: 35, title: "B"),
           BarEntry(score: 55, title: "C"),
           BarEntry(score: 3, title: "D"),
           BarEntry(score: 10, title: "E")
        ]

PollBarGraph 是我在其中添加的 Swift 文件:

class BarEntry: NSObject {
        let score: Int
        let title: String

        init(score: Int, title: String) {
            self.score = score
            self.title = title
        }
    }

    @objc open var dataEntries: [BarEntry] = []{
        didSet {
            //my code
        }
    }

如何使用 Objective C 语法将值分配给我的 Swift 变量?

【问题讨论】:

    标签: objective-c swift bridging-header


    【解决方案1】:

    首先,您不需要didSet,因为您在分配时已经拥有该值。设置值后,您可以使用 didSet 做一些额外的副作用,例如一些计算,使某些东西无效等。但这里不是这种情况。

    所以首先你需要在你的 swift 代码中正确地指定你的类,例如

    class BarEntry: NSObject {
        let score: Int
        let title: String
    
        @objc init (score: Int, title: String) {
            self.score = score
            self.title = title
        }
    }
    
    class PollBarGraphView : UIView {
        @objc open var dataEntries = [BarEntry]()  // default: empty array
    }
    

    不要忘记通过@objc 公开您的BarEntry.init。 要在Objective C中使用它,语法如下:

    PollBarGraphView *pb = [[PollBarGraphView alloc] initWithFrame:self.view.frame];
    pb.dataEntries = @[
                        [[BarEntry alloc] initWithScore:1 title:@"A"],
                        [[BarEntry alloc] initWithScore:2 title:@"B"],
                        [[BarEntry alloc] initWithScore:3 title:@"C"]
                      ];
    

    【讨论】:

    • 感谢您的帮助和教导!我是 Swift 新手,您的回答对理解 swift 和 objc 互操作性有很大帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 2012-02-02
    • 2016-06-15
    • 2014-08-05
    • 2020-06-27
    • 1970-01-01
    相关资源
    最近更新 更多