swift 关键词

2021-08-24  本文已影响0人  若水water
关键词
protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}
// 定义类 实现该协议
class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class"
    var anotherProperty: Int = 110
    // 在 class 中实现带有mutating方法的接口时,不用mutating进行修饰。因为对于class来说,类的成员变量和方法都是透明的,所以不必使用 mutating 来进行修饰
    func adjust() {
        simpleDescription += " Now 100% adjusted"
    }
}
// 定义 struct 实现该协议
struct SimpleStruct: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {
        simpleDescription += "(adjusted)"
    }
}
//在 enum 中 实现该协议
enum SimpleEnum: ExampleProtocol {
    case First, Second, Third
    var simpleDescription: String {
        get {
            switch self {
            case .First:
                return "first"
            case .Second:
                return "second"
            case .Third:
                return "third"
            }
        }

        set {
            simpleDescription = newValue
        }
    }
    
    mutating func adjust() {

    }
}

protocol Animal {
    associatedtype F: Food
    func eat(_ food: F)
}

struct Meat: Food { }
struct Grass: Food { }

struct Tiger: Animal {
    func eat(_ food: Meat) {
        print("eat \(food)")
    }
}

struct Sheep: Animal {
    func eat(_ food: Grass) {
        print("eat \(food)")
    }
}

struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}
//使用
 let times = TimesTable(multiplier: 3)
 let time = times[3]
 let type: Int = 3
        var name: String = ""
        switch type {
        case 1, 2, 3, 4, 5, 6:
            name += "\(type)"
            fallthrough
        case 8:
            name += "哈哈哈哈"
        case 9:
            name += "嗯~"
        default:
            name += "结束了"
        }
 func test(a: inout Int, b: inout Int)  {
        let num = a + b
        print(num)
    }
//使用
var a = 3
var b = 5
test(a: &a, b: &b)

image.png

改进:

class PHAssetController: PHBaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        getNumber()
    }

    @discardableResult
    func getNumber() -> Int {
        return 9;
    }
}
访问关键词
上一篇 下一篇

猜你喜欢

热点阅读