0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

swift 的结构

Object

Three Flavors of Object Type

  • struct
  • enum
  • class

Variables

A variable is a name for an object. Technically, it refers to an object; it is an object reference.

all variables must be declared. If you need a name for something, you must say “I’m creating a name.” You do this with one of two keywords: let or var.

通过 let 或者 var 来声明变量

let one = 1
var two = 2

函数

上面的代码是不能够随便写的,需要放到函数体内. 最普通的声明方式就是:

func go() {
    let one = 1
    var two = 2
    two = one
}

Swift also has a special rule that a file called main.swift, exceptionally, can have executable code at its top level, outside any function body, and this is the code that actually runs when the program runs. You can construct your app with a main.swift file, but in general you won’t need to.

swift 同样有程序运行入口. 那就是 main.swift.

一个 swift 文件的构成:

  • 模块 import
  • 变量声明,
    • 直接声明的变量就是全局的.
  • 函数声明
  • 对象类型:类,枚举还有结构

作用域和生命周期

规则就是他们是否是同级可见或者更高层级可见.

  • 一个模块
  • 一个文件
  • 一个大括号

对象成员

在对象类型(类,结构还有枚举)里,往往定义在顶层的内容都有其特殊原因,这里拿一个类叫 Manny 来示范:

class Manny {
  let name = "manny"
  func sayName() {
    print(name)
  }
}

在这个代码里

  • name 它是定义在对象 Manny 顶层的. 我们将它称之为属性 (property).
  • sayName 这个函数同样也是定义在顶层,我们称之为对象方法.

凡是定义在顶层的都是作为对象的 成员 存在. 他们通常都是很重要的,因为他们定义了可以传递什么样的 消息 给这个对象.

命名空间

它同样也是作为作用域而存在, 一个命名空间内的属性是不能够随便让外界访问到. 它可以 同时用来防止命名冲突.

class Manny{
  class Klass {}
}

像这上面的写法就是很好地将类 Klass 隐藏在了 Manny 内部,这个时候 Manny 就是命名空间.
访问的时候可以通过 Manny.Klass 来访问.

模块

通常顶层的命名空间我们称之为模块, 其实你的 ios app 就是一个 module, 而各种 framework 也是 module, 通常顶层的 module 我们不需要在调它们成员的时候显式再来来打点调用.因为既然已经 import 了那它们顶层的模块已经就是可见的.

swift 本身就是定义在一个 module 之内 -- swift 模块.你的代码总是隐士的在引入 swift 模块. 你完全可以在一个 swift 文件里开头使用 import swift 作为开始,但是完全没有必要. 但是呢, 为什么说这个呢想想看我们从哪里定义的 print 方法呢,其实它就是定义在顶层的一个函数在 swift 模块里.你也可以写成这样子: Swift.print("hello, world")!

实例

对象类型(类,结构,枚举)他们都是可以被 实例化的. 也就是说当你定义一个对象的时候它本身只是一个 类型. 而实例化一个类型就是它它实例化得到一个实例.

如我定义一个 Dog 对象:

class Dog{
  func bark(){
    print("woof")
  }
}

其他敲响上面这些代码在程序中并没有发生什么,你只是描述了一个类型. 你想要一个实际的 Dog,你就需要创建一个. 那就是实例化.

在 swift 中如何实例化一个对象呢, 就是直接在对象名后面加上 括号, 它就是一个特殊的方法,传递了一个消息给对象创建一个实例出来:

let fido = Dog()

然后我们可以继续调用它的方法:

let fido = Dog()
fido.bark()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?