7. Swift 有趣的代码.png

创建单例的两种方法

  1. class MyClass {
  2. static let singleton1 = MyClass()
  3. static let singleton2: MyClass = {
  4. let instance = MyClass()
  5. // setup code
  6. return instance
  7. }()
  8. private init() {}
  9. }

[备注]:苹果官方推荐创建单例的方式

定义整型的平方

  1. extension Int {
  2. var square: Int { self * self }
  3. }
  4. print(10.square)
  5. print(10.square.square)

定义二维数组

image.png

  1. struct D2Array {
  2. let rows: Int, colums: Int
  3. var grid: [Int]
  4. init(rows: Int, colums: Int) {
  5. self.rows = rows
  6. self.colums = colums
  7. grid = Array(repeating: 0, count: rows * colums)
  8. }
  9. subscript(row: Int, col: Int) -> Int{
  10. get {
  11. return grid[row * colums + col]
  12. }
  13. set {
  14. grid[row * colums + col] = newValue
  15. }
  16. }
  17. }

跳出指定循环

  1. label1: for x in 0..<5 {
  2. label2: for y in (0..<5).reversed() {
  3. if x == y {
  4. break label1 // break 后面指定这个标签,当条件成立就跳出该标签的外循环
  5. }
  6. print(x, y)
  7. }
  8. }