在@ swift中@ property / @ synthesize等效 [英] @property/@synthesize equivalent in swift

查看:756
本文介绍了在@ swift中@ property / @ synthesize等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们曾经声明 property 在类之间传递数据,如下所示:

We used to declare property to pass data between classes as following:

.h file (interface file)
@property (nonatomic) double topSpeed;

.m file (implementation file)
@synthesize topSpeed;

现在没有界面类,如何在 .swift 类之间传递数据?

Now there is no interface class, how to pass data between .swift classes ?

推荐答案

Swift没有区别属性和实例变量之间(即属性的底层存储)。要定义属性,只需在类的上下文中声明一个变量。

Swift provides no differentiation between properties and instance variables (i.e, the underlying store for a property). To define a property, you simply declare a variable in the context of a class.

swift类只是一个ClassName.swift文件。

A swift class is simply a ClassName.swift file.

您将类和属性声明为

class SomeClass {

  var topSpeed: Double
  var aStrProperty: String
  var anIntProperty: Int

  //Initializers and other functions

}

您可以通过点表示法访问属性值。从Xcode6 beta 4开始,还有访问修饰符( public internal private )在Swift中。默认情况下,每个属性都是 internal 请点击此处了解详情。

You access property values via dot notation. As of Xcode6 beta 4, there also are access modifiers (public, internal and private) in Swift. By default every property is internal. See here for more information.

有关详细信息,请参阅 Swift编程指南

For more information, refer to the Swift Programming Guide:


存储的属性和实例变量



如果您有使用Objective-C的经验,您可能知道它提供
两种方法来存储值和引用作为类实例的一部分。
除了属性之外,您还可以使用实例变量作为存储在属性中的值的后备
存储。

Stored Properties and Instance Variables

If you have experience with Objective-C, you may know that it provides two ways to store values and references as part of a class instance. In addition to properties, you can use instance variables as a backing store for the values stored in a property.

Swift将这些概念统一到单一财产声明。
Swift属性没有相应的实例变量,
不会直接访问属性的后备存储。这种
方法避免了在不同的
上下文中如何访问值的混淆,并将属性的声明简化为单个
权威语句。有关该属性的所有信息(包括其
名称,类型和内存管理特性)都在
单个位置中定义,作为类型定义的一部分。

Swift unifies these concepts into a single property declaration. A Swift property does not have a corresponding instance variable, and the backing store for a property is not accessed directly. This approach avoids confusion about how the value is accessed in different contexts and simplifies the property’s declaration into a single, definitive statement. All information about the property—including its name, type, and memory management characteristics—is defined in a single location as part of the type’s definition.

这篇关于在@ swift中@ property / @ synthesize等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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