Swift 4 Cheat Sheet and Quick Reference

本文介绍了Swift编程语言的基础知识,包括类实现、方法定义、实例创建与使用、枚举类型、变量声明与类型介绍、控制流结构、字符串操作、数组与字典的使用等核心概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

## Class Implementation

```swift
class MyClass : OptionalSuperClass, OptionalProtocol1, OptionalProtocol2 {
    var myProperty:String
    var myOptionalProperty:String? 
    // More properties...
    
    // Only need override if subclassing
    override init() {
        myProperty = "Foo" 
    }
    // More methods...
}
```

## Methods

```swift
func doIt() -> Int { 
    return 0
}
func doIt(a:Int) -> Int {
    return a
}
func doIt(a:Int, b:Int) -> Int {
    return a+b
}    
```

## Creating/Using an Instance 

```swift
var a = MyClass() 
a.myProperty 
a.doIt() 
a.doIt(a:1) 
a.doIt(a:2, b:3)
```

## Enums 

```swift
enum CollisionType: Int { 
    case player = 1
    case enemy = 2
}
var type = CollisionType.player
```

## Declaring Variables 

```swift
var mutableDouble:Double = 1.0 
mutableDouble = 2.0

let constantDouble:Double = 1.0 
// constantDouble = 2.0 // error

var mutableInferredDouble = 1.0 

var optionalDouble:Double? = nil
optionalDouble = 1.0
if let definiteDouble = optionalDouble {
    definiteDouble
}
```

## Variable types 

|types|value|
|:-|:-|
|Int|1, 2, 500, 10000|
|Float,Double|1.5, 3.14, 578.234|
|Bool|true, false|
|String|"Kermit", "James"|
|ClassName|UIView, UIButton, etc|

## Control Flow 

```swift
var condition = true 
if condition {
} else {
}

var val =5 
switch val { 
case 1:
    "foo"
case 2: 
    "bar"
default:
      "baz"
}

// omits upper value, use ... to include
for i in 0..<3 { }
```

## String Quick Examples 

```swift
var personOne = "Ray"
var personTwo = "Brian"
var combinedString = "\(personOne): Hello, \(personTwo)!"

var tipString = "2499"
var tipInt = Int(tipString)

tipString = "24.99"
var tipDouble = Double(tipString)
```

## Array Quick Examples 

```swift
var person1 = "Ray"
var person2 = "Brian"
var array:[String] = [person1, person2]
array.append("Waldo")

for person in array {
    print("Person: \(person)")
}
var waldo = array[2]    
```

## Dictionary Quick Examples 

```swift
var dict:[String: String] = ["Frog": "Kermit", "Pig": "Ms. Piggy", "Weirdo": "Gonzo" ]
dict["Weirdo"] = "Felipe"
dict["Frog"] = nil // delete frog

for (type, muppet) in dict {
    print("type: \(type), muppet: \(muppet)")
}
```

## Reference

[https://koenig-media.raywenderlich.com/uploads/2014/06/RW-Swift-Cheatsheet-0_8.pdf](https://koenig-media.raywenderlich.com/uploads/2014/06/RW-Swift-Cheatsheet-0_8.pdf)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值