第一个:泛型 交换方法 N多文章都copy烂了 增强了一个泛型类型的判断
- var a = 0
- var b = 1
- var aStr = "a"
- var bStr = "b"
- print(a,b,aStr,bStr)
- swapValues(a: &a,b: &b)
- swapValues(a: &aStr,b: &bStr)
- print(a,bStr)
- let date = NSDate() //类型转字符串的方法
- print(NSStringFromClass(type(of: date)))
- print(NSStringFromClass(object_getClass(date)!))
- /// 泛型交换方法
- ///
- /// :param:
- /// :returns: void
- func swapValues <T> ( a:inout T,b:inout T) {
- let temp = a
- a = b
- b = temp
- if T.self == type(of: Int()) {
- print("数字交换")
- }else {
- print("字符串交换")
- }
- }
- /// 查找数字位置
- ///
- /// :param:
- /// :returns: void
- func findIndex<T: Equatable> (_ array: [T],_ valueToFind: T) -> Int? {
- for (index,value) in array.enumerated(){
- if value == valueToFind { //如果没指定S:Equatable 这句话会编译不通过
- return index
- }
- }
- return 0
- }
第二个: 类中如何使用泛型 支持多个泛型
- class Stack<Element,Dacai> {
- var containers = [Element]()
- var containers2 = [Dacai]()
- func push(e: Element) {
- containers.append(e)
- }
- func pop() -> Element {
- return containers.removeLast()
- }
- func dcpush(e: Dacai) {
- containers2.append(e)
- }
- func dcPop() -> Dacai {
- return containers2.removeLast()
- }
- }
第三个:protocol中 mutating关键词干嘛的
- protocol Vehicle {
- var numberOfWheels: Int {get}
- var color: UIColor {get set}
- mutating func changeColor()
- }
- struct MyCar: Vehicle {
- let numberOfWheels = 4
- var color = UIColor.blue
- mutating func changeColor() {
- color = .red
- } //mutating 会报这个错误 Cannot assign to property: 'self' is immutable
- }
- class MyFerrari: Vehicle {
- let numberOfWheels = 4
- var color = UIColor.red
- func changeColor() { //类中实现的协议 没有任何问题
- color = .black
- }
- }
第四个:扩展协议 where 的用法 关联类型
- protocol Father {
- }
- protocol Son : Father{
- }
- class FatherClass: Father {
- }
- class SonClass: Son {
- }
- protocol Container {
- associatedtype ItemType
- }
- extension Container where ItemType: Father {
- var b: Int {return 100}
- }
- extension Container where ItemType: Son {
- var b: Int {return 200}
- }
- class TestClass: Container {
- typealias ItemType = SonClass //这里指定泛型的类型
- }
- let myCass = TestClass()
- print (myCass.b)
第五个:实战WHERE的用法 协议 加载xib
- protocol NibLoadable {
- }
- extension NibLoadable where Self : UIView {
- static func loadFromNib(_ nibname : String? = nil) -> Self {
- let loadName = nibname == nil ? "\(self)" : nibname!
- return Bundle.main.loadNibNamed(loadName,owner: nil,options: nil)?.first as! Self
- }
- }
第六个:为什么swift要面向协议开发本质是什么 例子: 我们有3个控制器vc1 vc2 vc3 都要有showError的方法 1:第一种做法 写3个方法 是不是很恶心呢 2:第二种做法 父亲类不就行了吗 我们一下这样带来的问题,继承了fu类的是不是都需要这个方法