在Swift中创建与Objective-C等效的Getter和Setter [英] Creating an Objective-C equivalent Getter and Setter in Swift

查看:141
本文介绍了在Swift中创建与Objective-C等效的Getter和Setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下Swift中的Objective-C代码等效于什么?

What is the equivalent of the following Objective-C code in Swift?

@property (nonatomic, assign, getter = isOpen) BOOL open;

具体来说,如何在Swift中声明一个变量以使用自定义名称来合成吸气剂?

Specifically, how does one declare a variable in Swift to synthesize the getter with a custom name?

此外,您随后如何覆盖getter和setter的实现?

Furthermore, how can you subsequently override the implementation of the getter and setter?

推荐答案

您的假设很接近,但是有些事情可以更改.我会尽力帮助您尽可能接近Objective-C版本.

Your assumption was close, but a few things could be changed. I will try to help you get as close as possible to the Objective-C version.

首先,nonatomicassign无关紧要.剩下

First of all, the nonatomic and assign are irrelevant in swift. That leaves us with

@property (getter = isOpen) BOOL open;

由于swift中的属性只是实例变量,因此swift的翻译如下.

Since properties in swift are just instance variables, the swift translation would be as follows.

var open:Bool

尽管它具有与Objective-C版本相同的基本功能,但缺少命名的getter(isOpen).不幸的是,目前尚无直接翻译可迅速解决.您可以使用自定义的getter和setter.

Although this has the same basic functionality as the Objective-C version, it is lacking the named getter (isOpen). Unfortunately, there is no direct translation to swift for this (yet). You could use a custom getter and setter.

var open:Bool {
    get {
        // custom getter
    }
    set {
        // custom setter
    }
}

一个相当粗略的解决方法是制作一个另一个函数,该函数实际上称为isOpen,将充当吸气剂.

A rather crude work around would be to make another function literally called isOpen that would act as a getter.

func isOpen() -> Bool { return self.open }

总而言之,您所要问的只是一点点可能,但是希望在以后的swift版本中可以成为现实.

In conclusion, what you are asking is only slightly possible, but hopefully in later releases of swift can become a reality.

这篇关于在Swift中创建与Objective-C等效的Getter和Setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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