创建单例的两种方法
class MyClass {
static let singleton1 = MyClass()
static let singleton2: MyClass = {
let instance = MyClass()
// setup code
return instance
}()
private init() {}
}
[备注]:苹果官方推荐创建单例的方式
定义整型的平方
extension Int {
var square: Int { self * self }
}
print(10.square)
print(10.square.square)
定义二维数组
struct D2Array {
let rows: Int, colums: Int
var grid: [Int]
init(rows: Int, colums: Int) {
self.rows = rows
self.colums = colums
grid = Array(repeating: 0, count: rows * colums)
}
subscript(row: Int, col: Int) -> Int{
get {
return grid[row * colums + col]
}
set {
grid[row * colums + col] = newValue
}
}
}
跳出指定循环
label1: for x in 0..<5 {
label2: for y in (0..<5).reversed() {
if x == y {
break label1 // break 后面指定这个标签,当条件成立就跳出该标签的外循环
}
print(x, y)
}
}