struct User {
var name: String?
}
let user = User(name: "nonocast")
print(user.name!)
let和var的区别:
12> var foo = 1
foo: Int = 1
13> foo = 2
14>
15> foo
$R0: Int = 2
16>
17> let bar = 1
bar: Int = 1
18> bar = 2
expression failed to parse:
repl.swift:17:1: note: change 'let' to 'var' to make it mutable
let bar = 1
^~~
var
error: repl.swift:18:1: error: cannot assign to value: 'bar' is a 'let' constant
bar = 2
^~~
repl.swift:17:1: note: change 'let' to 'var' to make it mutable
let bar = 1
^~~
var
- 定义变量时可以通过推测`var name = "hello"`,如果没有推导依据就需要通过冒号后显示表示类型
```swift
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
let emptyMessage: String
let message: String = "hello world"
String?表示optionals
let x: Int? = 7
print(x!)
如果不需要考虑继承优先考虑效率更高的struct
struct Resolution {
var width = 0
var height = 0
}
let vga = Resolution(width: 640, height: 480)
print(vga.width)
Snippets 1
error: repl.swift:18:1: error: cannot assign to value: 'bar' is a 'let' constant bar = 2 ^~~
repl.swift:17:1: note: change 'let' to 'var' to make it mutable let bar = 1 ^~~ var
struct为值拷贝,class为引用拷贝。
struct FrameView : View
,这里不是继承,View是protocol, 即protocol View
User(name: "nonocast")
,可以在new的过程中直接设置任意属性的值,不用写N个构造函数。class不支持。