nonocast / me

记录和分享技术的博客
http://nonocast.cn
MIT License
20 stars 0 forks source link

学习 MacOS 开发 (Part 10: 继续学习Swift语法) #247

Open nonocast opened 2 years ago

nonocast commented 2 years ago

Snippets 1

struct User {
  var name: String?
}

let user = User(name: "nonocast")
print(user.name!)

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"
let x: Int? = 7
print(x!)
struct Resolution {
    var width = 0
    var height = 0
}

let vga = Resolution(width: 640, height: 480)
print(vga.width)

struct为值拷贝,class为引用拷贝。

protocol Namable {
  var name: String? { get set }
}

struct User : Namable {
  var name: String?
}