Swift

Swift有一个好处就是不用在每行结尾加;

但是一行有多个语句是就要加上;

但当你在同一行书写多条语句时,必须用分号隔开:

let定义常量

var定义变量

lazy延迟存储属性必须用var

var定义变量带getset方法的叫计算属性

override重写属性的时候也要加上

final的类不能被继承

final的属性不能被重写

weak 弱引用防止循环引用

unowned无主引用

属性观察器willSetdidSet

willSet在设置新的值之前调用

didSet在新的值被设置之后立即调用

willSetdidSet观察器在属性初始化过程中不会被调用

常量可以没有初始值

但是只能赋值一次

Swift定义变量的时候会根据初始化的值自动判断变量的类型

但是也可以强制指定

后面加上 : 类型

1
2
let implicitDouble = 70.0
let explicitDouble: Double = 70

数字转字符串

1
2
3
let label = "The width is"
let width = 94
let widthLabel = label + String(width)
1
2
3
4
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

多行内容"""内容"""

1
2
let quotation = """I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit.""""

数组和字典在Swift中用的都是 []

1
2
3
4
5
6
7
8
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

数组的最后一个元素不用加逗号

而且Swift默认数组都是可变的可以一直append

初始化一个空数组和字典

1
2
let emptyArray: [String] = []
let emptyDictionary: [String: Float] = [:]

也可以这样前提是类型比较简单

1
2
shoppingList = []
occupations = [:]

Swift字典的key没有类型限制可以是整型或字符串

但是必须是唯一的

1
2
3
4
5
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var someVar = someDict[1]
print( "key = 1 的值为 \(someVar)" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )

修改字典的值updateValue(forKey:) 或者直接修改

1
2
3
4
5
6
7
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var oldVal = someDict.updateValue("One 新的值", forKey: 1)
var someVar = someDict[1]
print( "key = 1 旧的值 \(oldVal)" )
print( "key = 1 的值为 \(someVar)" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )
1
2
3
4
5
6
7
8
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var oldVal = someDict[1]
someDict[1] = "One 新的值"
var someVar = someDict[1]
print( "key = 1 旧的值 \(oldVal)" )
print( "key = 1 的值为 \(someVar)" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )

删除字典的KeyremoveValueForKey() 或者直接置为空

1
2
3
4
5
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
var removedValue = someDict.removeValue(forKey: 2)
print( "key = 1 的值为 \(someDict[1])" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )
1
2
3
4
5
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
someDict[2] = nil
print( "key = 1 的值为 \(someDict[1])" )
print( "key = 2 的值为 \(someDict[2])" )
print( "key = 3 的值为 \(someDict[3])" )

数组遍历

带索引的

1
2
3
4
5
6
7
8
var someStrs = [String]()
someStrs.append("Apple")
someStrs.append("Amazon")
someStrs.append("Runoob")
someStrs += ["Google"]
for (index, item) in someStrs.enumerated() {
print("在 index = \(index) 位置上的值为 \(item)")
}

不带索引的

1
2
3
4
5
6
7
8
var someStrs = [String]()
someStrs.append("Apple")
someStrs.append("Amazon")
someStrs.append("Runoob")
someStrs += ["Google"]
for item in someStrs {
print(item)
}

数组合并也比OC简单

类型一样的话直接加就行了

1
2
3
4
5
6
7
8
var intsA = [Int](repeating: 2, count:2)
var intsB = [Int](repeating: 1, count:3)

var intsC = intsA + intsB

for item in intsC {
print(item)
}

遍历字典

1
2
3
4
5
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

for (key, value) in someDict {
print("字典 key \(key) - 字典 value \(value)")
}

数组的长度还是count没有变

Swift还加了一个判断为空的函数isEmpty

字典也是一样

count 代表字典里键值的个数

isEmpty则是判断字典是否为空

接下来就是循环和判断了

Swiftif后面必须跟一个布尔值的表达式

不能像之前OC一样可以用对象

1
2
3
4
5
6
7
8
9
10
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)

???Swift新增的内容

?代表的是变量可以为空

对应的还有一个!代表不可能为空

??代表如果当前值为空可以设置一个默认值

有点a ? b : c的意思

Switch就比较厉害了

支持任意类型的数据以及各种比较操作

这一点就像if else if else

1
2
3
4
5
6
7
8
9
10
11
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}

OC不一样的是不用在case里面写break

for inOC差不多

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (_, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
// 输出 "25"

while变化的不太多

1
2
3
4
5
6
7
8
9
10
11
var n = 2
while n < 100 {
n *= 2
}
print(n)

var m = 2
repeat {
m *= 2
} while m < 100
print(m)

唯一改变的就是条件增加了一范围

1
2
3
4
5
var total = 0
for i in 0..<4 {
total += i
}
print(total)

..<不包含0

要想包含0就得改成...

方法基本全改了

func后面跟方法名

(参数名:参数类型)里面传参数

->后面跟返回值

1
2
3
4
func greet(_ person: String, on day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0

for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}

return (min, max, sum)
}
let statistics = calculateStatistics(scores:[5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)

没有返回值的函数

1
2
3
4
func runoob(site: String) {
print("菜鸟教程官网:\(site)")
}
runoob(site: "http://www.runoob.com")

而且方法里面还可以在写一个方法

虽然感觉这样作用不是很大

1
2
3
4
5
6
7
8
9
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()

除此以外函数还可以当做参数也可以当做一个返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(list: numbers, condition: lessThanTen)
1
2
3
4
5
6
7
8
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)

默认都是对象方法

class func表示的是类方法

或者这样static func

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Math
{
class func abs(number: Int) -> Int
{
if number < 0
{
return (-number)
}
else
{
return number
}
}
}

struct absno
{
static func abs(number: Int) -> Int
{
if number < 0
{
return (-number)
}
else
{
return number
}
}
}

let no = Math.abs(number: -35)
let num = absno.abs(number: -5)

print(no)
print(num)

接下来就是Swift中的Block了在Swift中称为闭包

感觉只是换了一个名字而已

闭包里面有一个关键字in

in就是用来隔离参数和方法体的

闭包常见的形式

1
2
3
4
5
6
7
//有参数有返回值
let testOne: (String, String) -> String = {(str1, str2) in return str1 + str2}
print(testOne("one", "two"))
//没有参数有返回值可以直接省略 "in"
let testTwo: () -> String = {return "test闭包"}
//没有参数没有返回值
let testThree: () -> Void = {print("test闭包")}

还可以把参数和返回值都省略掉

如果语句比较简单的话

闭包会把这个语句的值当做结果返回

对象和类就比较简单了

1
2
3
4
5
6
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}

Swift属性和方法都用点语法

1
2
3
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

有一个方法变了

就是deallocSwift中变成了deinit

每个类最多只能有一个析构函数deinit

1
2
3
deinit{

}

如果子类要继承父类并要重写父类的方法

需要用添加override否则就会报错

1
2
3
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}

枚举改动不大但是里面可以添加方法了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
enum Rank: Int {
case ace = 1
case two, three, four, five, six, seven, eight, nine, ten
case jack, queen, king
func simpleDescription() -> String {
switch self {
case .ace:
return "ace"
case .jack:
return "jack"
case .queen:
return "queen"
case .king:
return "king"
default:
return String(self.rawValue)
}
}
}

如果 switch 知道枚举的类型也可以直接用点语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 定义枚举
enum DaysofaWeek {
case Sunday
case Monday
case TUESDAY
case WEDNESDAY
case THURSDAY
case FRIDAY
case Saturday
}

var weekDay = DaysofaWeek.THURSDAY
weekDay = .THURSDAY
switch weekDay
{
case .Sunday:
print("星期天")
case .Monday:
print("星期一")
case .TUESDAY:
print("星期二")
case .WEDNESDAY:
print("星期三")
case .THURSDAY:
print("星期四")
case .FRIDAY:
print("星期五")
case .Saturday:
print("星期六")
}

Swift的注释与OC的差不多

单行//

多行

/* */

但是Swift新增了一个新的功能

可以注释里面嵌套注释

1
2
3
/* 这是第一个多行注释的开头
/* 这是嵌套的第二个多行注释 */
这是第一个多行注释的结尾 */

Swift关键字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
break	case	continue	default
do else fallthrough for
if in return switch
where while

class deinit enum extension
func import init internal
let operator private protocol
public static struct subscript
typealias var

as dynamicType false is
nil self Self super
true _COLUMN_ _FILE_ _FUNCTION_
_LINE_

associativity convenience dynamic didSet
final get infix inout
lazy left mutating none
nonmutating optional override postfix
precedence prefix Protocol required
right set Type unowned
weak willSet

Swift变量和运算符一定要加一个空格

NSLog也变成了print

Swift没有了++--

只能num = num + 1或者num = num - 1

但是+= -= *= /= %=都还在

Swift 打印常量和变量

打印常量

1
2
3
var stringA = "菜鸟教程:"
stringA += "http://www.runoob.com"
print( stringA )

打印变量

1
2
3
4
5
var varA   = 20
let constA = 100
var varC:Float = 20.0
var stringA = "\(varA) 乘于 \(constA) 等于 \(varC * 100)"
print( stringA )

字符串的连接也特别的简单

直接用+连接就行了比OC要好

1
2
3
4
let constA = "菜鸟教程:"
let constB = "http://www.runoob.com"
var stringA = constA + constB
print( stringA )

也可以直接用+=来拼接字符串

两个字符串比较也直接用=就可以直接比较

1
2
3
4
5
6
7
8
var varA   = "Hello, Swift!"
var varB = "Hello, World!"

if varA == varB {
print( "\(varA) 与 \(varB) 是相等的" )
} else {
print( "\(varA) 与 \(varB) 是不相等的" )
}

遍历字符串

1
2
3
for ch in "Runoob" {
print(ch)
}

字符串的长度变成了count

Swift还加了一个判断字符串是否为空的函数isEmpty

===!==Swift中新增的两个运算符

===是恒等运算符

如果两个常量或者变量引用同一个类实例则返回 true

!==是不恒等运算符

如果两个常量或者变量引用不同一个类实例则返回 true

Swift类型转换

类型判断is

检查一个实例是否属于特定子类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Subjects {
var physics: String
init(physics: String) {
self.physics = physics
}
}

class Chemistry: Subjects {
var equations: String
init(physics: String, equations: String) {
self.equations = equations
super.init(physics: physics)
}
}

class Maths: Subjects {
var formulae: String
init(physics: String, formulae: String) {
self.formulae = formulae
super.init(physics: physics)
}
}

let sa = [
Chemistry(physics: "固体物理", equations: "赫兹"),
Maths(physics: "流体动力学", formulae: "千兆赫"),
Chemistry(physics: "热物理学", equations: "分贝"),
Maths(physics: "天体物理学", formulae: "兆赫"),
Maths(physics: "微分方程", formulae: "余弦级数")]


let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("实例物理学是: \(samplechem.physics)")
print("实例方程式: \(samplechem.equations)")


let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("实例物理学是: \(samplemaths.physics)")
print("实例公式是: \(samplemaths.formulae)")

var chemCount = 0
var mathsCount = 0
for item in sa {
// 如果是一个 Chemistry 类型的实例,返回 true,相反返回 false。
if item is Chemistry {
++chemCount
} else if item is Maths {
++mathsCount
}
}

print("化学科目包含 \(chemCount) 个主题,数学包含 \(mathsCount) 个主题")

转型和强制转型

as?as!

不确定的时候用as?

确定类型一定正确的情况下用as!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Subjects {
var physics: String
init(physics: String) {
self.physics = physics
}
}

class Chemistry: Subjects {
var equations: String
init(physics: String, equations: String) {
self.equations = equations
super.init(physics: physics)
}
}

class Maths: Subjects {
var formulae: String
init(physics: String, formulae: String) {
self.formulae = formulae
super.init(physics: physics)
}
}

let sa = [
Chemistry(physics: "固体物理", equations: "赫兹"),
Maths(physics: "流体动力学", formulae: "千兆赫"),
Chemistry(physics: "热物理学", equations: "分贝"),
Maths(physics: "天体物理学", formulae: "兆赫"),
Maths(physics: "微分方程", formulae: "余弦级数")]


let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("实例物理学是: \(samplechem.physics)")
print("实例方程式: \(samplechem.equations)")


let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("实例物理学是: \(samplemaths.physics)")
print("实例公式是: \(samplemaths.formulae)")

var chemCount = 0
var mathsCount = 0

for item in sa {
// 类型转换的条件形式
if let show = item as? Chemistry {
print("化学主题是: '\(show.physics)', \(show.equations)")
// 强制形式
} else if let example = item as? Maths {
print("数学主题是: '\(example.physics)', \(example.formulae)")
}
}

AnyAnyObject的类型转换

AnyObject可以代表任何class类型的实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Subjects {
var physics: String
init(physics: String) {
self.physics = physics
}
}

class Chemistry: Subjects {
var equations: String
init(physics: String, equations: String) {
self.equations = equations
super.init(physics: physics)
}
}

class Maths: Subjects {
var formulae: String
init(physics: String, formulae: String) {
self.formulae = formulae
super.init(physics: physics)
}
}

// [AnyObject] 类型的数组
let saprint: [AnyObject] = [
Chemistry(physics: "固体物理", equations: "赫兹"),
Maths(physics: "流体动力学", formulae: "千兆赫"),
Chemistry(physics: "热物理学", equations: "分贝"),
Maths(physics: "天体物理学", formulae: "兆赫"),
Maths(physics: "微分方程", formulae: "余弦级数")]


let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("实例物理学是: \(samplechem.physics)")
print("实例方程式: \(samplechem.equations)")


let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("实例物理学是: \(samplemaths.physics)")
print("实例公式是: \(samplemaths.formulae)")

var chemCount = 0
var mathsCount = 0

for item in saprint {
// 类型转换的条件形式
if let show = item as? Chemistry {
print("化学主题是: '\(show.physics)', \(show.equations)")
// 强制形式
} else if let example = item as? Maths {
print("数学主题是: '\(example.physics)', \(example.formulae)")
}
}

var exampleany = [Any]()
exampleany.append(12)
exampleany.append(3.14159)
exampleany.append("Any 实例")
exampleany.append(Chemistry(physics: "固体物理", equations: "兆赫"))

for item2 in exampleany {
switch item2 {
case let someInt as Int:
print("整型值为 \(someInt)")
case let someDouble as Double where someDouble > 0:
print("Pi 值为 \(someDouble)")
case let someString as String:
print("\(someString)")
case let phy as Chemistry:
print("主题 '\(phy.physics)', \(phy.equations)")
default:
print("None")
}
}

Any可以表示任何类型,包括方法类型(function types)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Subjects {
var physics: String
init(physics: String) {
self.physics = physics
}
}

class Chemistry: Subjects {
var equations: String
init(physics: String, equations: String) {
self.equations = equations
super.init(physics: physics)
}
}

class Maths: Subjects {
var formulae: String
init(physics: String, formulae: String) {
self.formulae = formulae
super.init(physics: physics)
}
}

let sa = [
Chemistry(physics: "固体物理", equations: "赫兹"),
Maths(physics: "流体动力学", formulae: "千兆赫"),
Chemistry(physics: "热物理学", equations: "分贝"),
Maths(physics: "天体物理学", formulae: "兆赫"),
Maths(physics: "微分方程", formulae: "余弦级数")]


let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("实例物理学是: \(samplechem.physics)")
print("实例方程式: \(samplechem.equations)")


let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("实例物理学是: \(samplemaths.physics)")
print("实例公式是: \(samplemaths.formulae)")

var chemCount = 0
var mathsCount = 0

for item in sa {
// 类型转换的条件形式
if let show = item as? Chemistry {
print("化学主题是: '\(show.physics)', \(show.equations)")
// 强制形式
} else if let example = item as? Maths {
print("数学主题是: '\(example.physics)', \(example.formulae)")
}
}

// 可以存储Any类型的数组 exampleany
var exampleany = [Any]()

exampleany.append(12)
exampleany.append(3.14159)
exampleany.append("Any 实例")
exampleany.append(Chemistry(physics: "固体物理", equations: "兆赫"))

for item2 in exampleany {
switch item2 {
case let someInt as Int:
print("整型值为 \(someInt)")
case let someDouble as Double where someDouble > 0:
print("Pi 值为 \(someDouble)")
case let someString as String:
print("\(someString)")
case let phy as Chemistry:
print("主题 '\(phy.physics)', \(phy.equations)")
default:
print("None")
}
}

Swift 扩展

添加计算型属性和计算型静态属性

定义实例方法和类型方法

提供新的构造器

定义下标

定义和使用新的嵌套类型

使一个已有类型符合某个协议

不能重写方法

1
2
3
extension SomeType {
// 加到SomeType的新功能写到这里
}
1
2
3
extension SomeType: SomeProtocol, AnotherProctocol {
// 协议实现写到这里
}

添加属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
extension Int {
var add: Int {return self + 100 }
var sub: Int { return self - 10 }
var mul: Int { return self * 10 }
var div: Int { return self / 5 }
}

let addition = 3.add
print("加法运算后的值:\(addition)")

let subtraction = 120.sub
print("减法运算后的值:\(subtraction)")

let multiplication = 39.mul
print("乘法运算后的值:\(multiplication)")

let division = 55.div
print("除法运算后的值: \(division)")

let mix = 30.add + 34.sub
print("混合运算结果:\(mix)")

添加方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
extension Int {
func topics(summation: () -> ()) {
for _ in 0..<self {
summation()
}
}
}

4.topics({
print("扩展模块内")
})

3.topics({
print("内型转换模块内")
})

Swift协议

协议规定了用来实现某一特定功能所必需的方法和属性。

任意能够满足协议要求的类型被称为遵循(conform)这个协议。

类,结构体或枚举类型都可以遵循协议,并提供具体实现来完成协议定义的方法和功能。

1
2
3
protocol SomeProtocol {
// 协议内容
}
1
2
3
struct SomeStructure: FirstProtocol, AnotherProtocol {
// 结构体内容
}
1
2
3
class SomeClass: SomeSuperClass, FirstProtocol, AnotherProtocol {
// 类的内容
}

协议中的属性

必须指明是只读的还是可读可写的

在类型声明后加上{ set get }来表示属性是可读可写的

只读属性则用{ get }来表示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
protocol classa {
var marks: Int { get set }
var result: Bool { get }
func attendance() -> String
func markssecured() -> String
}

protocol classb: classa {

var present: Bool { get set }
var subject: String { get set }
var stname: String { get set }
}

class classc: classb {
var marks = 96
let result = true
var present = false
var subject = "Swift 协议"
var stname = "Protocols"
func attendance() -> String {
return "The \(stname) has secured 99% attendance"
}
func markssecured() -> String {
return "\(stname) has scored \(marks)"
}
}

let studdet = classc()
studdet.stname = "Swift"
studdet.marks = 98
studdet.markssecured()

print(studdet.marks)
print(studdet.result)
print(studdet.present)
print(studdet.subject)
print(studdet.stname)

协议中的方法

mutating关键字作为函数的前缀

写在func之前

表示可以在该方法中修改它所属的实例及其实例属性的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
protocol daysofaweek {
mutating func show()
}

enum days: daysofaweek {
case sun, mon, tue, wed, thurs, fri, sat
mutating func show() {
switch self {
case .sun:
self = .sun
print("Sunday")
case .mon:
self = .mon
print("Monday")
case .tue:
self = .tue
print("Tuesday")
case .wed:
self = .wed
print("Wednesday")
case .thurs:
self = .thurs
print("Wednesday")
case .fri:
self = .fri
print("Firday")
case .sat:
self = .sat
print("Saturday")
default:
print("NO Such Day")
}
}
}

var res = days.wed
res.show()

Swift 泛型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 定义一个交换两个变量的函数
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}

var numb1 = 100
var numb2 = 200

print("交换前数据: \(numb1) 和 \(numb2)")
swapTwoValues(&numb1, &numb2)
print("交换后数据: \(numb1) 和 \(numb2)")

var str1 = "A"
var str2 = "B"

print("交换前数据: \(str1) 和 \(str2)")
swapTwoValues(&str1, &str2)
print("交换后数据: \(str1) 和 \(str2)")

Swift 访问控制

public可以访问自己模块中源文件里的任何实体

别人也可以通过引入该模块来访问源文件里的所有实体

internal可以访问自己模块中源文件里的任何实体

但是别人不能访问该模块中源文件里的实体

fileprivate文件内私有

只能在当前源文件中使用

private只能在类中访问

离开了这个类或者结构体的作用域外面就无法访问

变量方法都可以用