swift语法

/* // 数组操作 // 定义初始化方法1

var arrayInt : [Int] = [1,3,4]

// 定义初始化方法2 var array1 : [Int] array1 = [55,66]

// 定义初始化方法3 var arrayStr = String

array1.append(32) print(array1[2]) array1[0]=333 //print(array1[1]) //遍历数组 for item in array1 { print("array1= (item)") }

//arrayStr=["dd","ddd"] arrayStr.append("Apple") arrayStr.append("banana") //同时获取数组的值和索引 for (index, item) in arrayStr.enumerated() { print("index= (index) value = (item)") }

//字典()

var dic :[String:String] dic = ["4":"afasdgsa","dd":"asfasdf"] //dic.append("4444":"asfasfas")

dic["4"] = "fff" var tempDicV = dic["4"]

print("(tempDicV!)") print("___")

var somDic1 :[Int:String] = [3:"ddd" , 4:"44444"] for (key,value) in somDic1.enumerated() { print("key =(key) value=(value)") } let arrayKey = Int let arrayValue = String print("*") print(arrayKey[1]) print(arrayValue[1]) print("__")

// 可选类型 // 定义方法1 var optionalA: Int? optionalA = 44

// 定义方法2 var optionalB: Optional optionalB = 55 //定义加初始化 var optionalC: Int? = 4

// 强制解析! var c1 = optionalC! print(c1)

//可选绑定:与if while等一起使用,会自动对可选类型的值进行判断并赋值给一个常量或者变量

var mystr :String? = "ddd" if let str1 = mystr { print(str1) } //自动解析,声明时加!,则会自动解析 /* var optionalD:String! optionalD = "dddd"

*/ let myString1:String! = "Hello, Swift!" let str1 = myString1

print("stringValue2:(str1!)")

//闭包

let studname = {print("dd")} studname() let divide = {(va1:Int,va2:Int) ->Int in return va1 - va2 } let s = divide(29,10) print(s) // 闭包做参数 let names = ["AT", "AE", "D", "S", "BE"]

func backwards(s1: String, s2: String) -> Bool { return s1 > s2 } var reversed = names.sorted(by: backwards) print(reversed) // 省略参数的闭包 var recersed1 = names.sorted(by: {$0>$1}) // 运算符函数 var reversed2 = names.sorted(by: >) print(reversed2)

//闭包,可以在其定义的上下文中捕获常量或者变量, func makeIncreamentor (forIncrement amout: Int) -> () -> Int { var runT = 0 func incrementor () -> Int { runT += amout return runT } return incrementor } // 调用时: inByten是常量,因函数和闭包是引用类型,所以常量指向的闭包的引用,任然可以增加其捕获的变量值 let inByten = makeIncreamentor(forIncrement: 10) print(inByten()) print(inByten()) print(inByten())

//枚举 enum DayWeek { case Sunday case Monday case FIrday }

var week = DayWeek.FIrday

switch week { case .Sunday: print("dd") case .Monday: print("fd") case .FIrday: print("dffg")

} // 相关值,可以各个值类型不同 enum DayWeek1 { case Sunday(String) case Monday(Int) case FIrday(Float) }

var week1 = DayWeek1.FIrday(3.33)

switch week1 { case .Sunday: print("dd") case .Monday: print("fd") case .FIrday: print("dffg (week1)")

} // 原始值 就是指定枚举的类型,然后赋值

//构造体struct:可以定义属性,添加方法,通过复制的方式在代码中传递,所以值不可修改

struct studentMark { var mark1 = 100 var mark2 = 200 var mark3 = 500

} var marks = studentMark() marks.mark3 = 4444 print("ff (marks.mark3)")

struct studentMark1 {

 var mark4: Int

 init(mark: Int) {
    self.mark4 = mark

 }

} var marks1 = studentMark1(mark:99) print("ff (marks1.mark4)")

// 类 class: 是一种通用且灵活的结构体。是引用类型,使用=== 判断两个厂里是否引用同一个类实例,但注意需要重写==方法 class Equatable{

} class SampleClass: Equatable { let myProperty: String init(s:String){ myProperty = s } } func ==(lhs:SampleClass, rhs:SampleClass) -> Bool { return lhs.myProperty == rhs.myProperty } let sp1 = SampleClass(s: "44")

let sp2 = sp1 if sp1 === sp2 { print("adasasdgasdgds") } else{ print("**") }

//属性: 将值与特定的类,结构体,枚举关联,分为存储属性和计算属性(不能有存储属性))

//lazy 表示一个延迟存储属性,只要在第一次被调用时才会调用其初始值 // 计算属性:通过get方法获取值,set方法设置值 class Sample { lazy var no = number1() var no1 = 0.0, no2 = 0.0 var length = 300.0, breadth = 100.0 var middle:(Double,Double) { get { return (length / 2, breadth / 2) } set( ax) { no1 = ax.0 - length / 2 no2 = ax.1 - breadth / 2 }
} } class number1 { var name = "runby" } var firstSample = Sample() print(firstSample.no.name) var secondSample = Sample() secondSample.middle = (0.0,100.0) print(secondSample.no1 ) print(secondSample.no2 )

// 只读计算属性 class Film { var head = "" var duration = 0.0 var metinfo: [String:String] { return [ "head": self.head, "duration": "(self.duration)" ] }

} var movice = Film() movice.head = "ddd" movice.duration = 5.555 print(movice.metinfo["head"]!)

 print(movice.metinfo["duration"]!)

//属性观察器:监控和响应属性值的变化,涉及的方法有willset didset 都是在设置新的值的时候会调用,初始化时不会调用

class Samplepgm { var test:Int=0

var counter: Int=0 {
    willSet(newTotal) {
        print("a")
    }
      didSet {
          if counter > oldValue {
              print(">")
          } else {
              print("<")
          }
      }

}

} var testS = Samplepgm() print("__") testS.test = 5; testS.counter = 99

// 类型属性:写在类最外层的{}内,是类定义的一部分,通过类本身获取(记住不是类实例获取),static 用来定义值类型的类型属性,class用于为类定义类型属性 print("__") struct studmarkss { static let markCount = 100 static var totalCount = 0 var InternalMarks: Int = 0 { didSet{ if InternalMarks > studmarkss.markCount { print("ddd"); InternalMarks = studmarkss.markCount }

     }
 }

} var stu1 = studmarkss() var stu2 = studmarkss() stu1.InternalMarks = 98 print(stu1.InternalMarks) stu1.InternalMarks = 120 print(stu1.InternalMarks) stu2.InternalMarks = 86 print(stu2.InternalMarks)

// swift 的函数参数可以有一个局部名称(在函数内部使用)和一个外部名称(在函数调用时使用)

class mutiplication { var count: Int = 0

  func incrementBy( no1: Int, no2:Int) {
       count = no1 * no2
       print(count)
  }
   func incrementBy1(_ no1: Int, _ no2:Int) {
       count = no1 * no2
       print(count)
  }
  func incrementBy2(f no1: Int, _ no2:Int) {
       count = no1 * no2
       print(count)
  }

} let counter = mutiplication() counter.incrementBy(no1: 800, no2: 3) counter.incrementBy(no1: 700, no2: 4)
counter.incrementBy1( 700, 4) counter.incrementBy2( f:700, 4)

// swift 中结构体和枚举是值类型,无法在实例方法中修改属性值,如果需改变,需使用关键字mutating写方法

struct areaT {
    var length = 1
    var breadth = 1
    func area () -> Int {
        return length * breadth
    }
     mutating func scaleBy (res: Int) {
          length *= res
          breadth *= res 
          print(length)
          print(breadth)
     }
}
var testArea = areaT()
testArea.length = 10
testArea.breadth = 12
print("\(testArea.area())") 

testArea.scaleBy(res:6) // 实例方法:呗类型的某个实例调用的方法 // 类型方法:简称类方法,是被类型本身调用的方法,使用关键字static // 类使用关键字class 来允许自雷重写父类的实现方法

class Math { class func abs(number: Int) -> Int { if number < 0 { return (-number) } else { return number } } } class absno { static func abs (number: Int) -> Int { if number < 0 { return (-number) } else { return number } } } let no = Math.abs(number:-10) let num = absno.abs(number:-9) print(" (no) (num)")

// 下标脚本:允许通过里面后【】里传入一个或者多个索引对象来对实例进行访问和赋值 //关键字subscript struct subexample { let decrementer: Int subscript(index: Int) -> Int { return decrementer / index } } let division = subexample(decrementer: 100)

print("100 除以 9 等于 (division[9])") print("100 除以 2 等于 (division[2])") print("100 除以 3 等于 (division[3])") print("100 除以 5 等于 (division[5])") print("100 除以 7 等于 (division[7])")

struct subEx { let dec: Int subscript(index: Int) -> Int { return dec / index } } let devEx = subEx(dec: 100) print ("(devEx[2])")

class daySofaweek { private var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "saturday"] subscript (index: Int) -> String { get { return days[index] } set(newValue) { days[index] = newValue } } } var p = daySofaweek() print(p[3]) p[1]="ddd" print(p[1])

 var numberOfLegs = ["spider": 8,"ant": 6, "cat": 4]
 numberOfLegs["bird"] = 2
 print(numberOfLegs)



 class Matrix {
   final  var test: Int = 6;
   var length:Double?
     let rows: Int, columns: Int
     var print2: [Double]
     init(){
         self.rows = 0
          self.columns = 0;
          print2 = Array(repeating: 0.0, count: rows * columns)
     }
      init(rows: Int, columns: Int) {
          self.rows = rows
          self.columns = columns;
          print2 = Array(repeating: 0.0, count: rows * columns)
      }
       subscript (row: Int, column: Int) -> Double{
           get {
               return print2[(row * columns) + column]
           } 
            set {
              print2[(row * column) + columns] = newValue
            }
       }
       func show() {
           print("dddd")
       }
 }
 var mat = Matrix(rows:4, columns:4)
 mat[1, 1] = 3.0
 mat[2, 3] = 9.998
 print("\(mat.print2)")

 // 重写,关键字 override,是对继承父类的方法或者属性的定制功能
 //防止重些 关键字final
  class myMatrix: Matrix {
      override func show() {
          super.show()
          print("ff")
      }
  }
  var testMat = myMatrix(rows:4, columns:2)
   testMat.show()

print("(testMat.print2)")

//常量的值在构造过程结束前都可以初始化 class test { let a1: Int init(){ self.a1 = 55 } } var t = test() print(t.a1)

//默认构造器:无父类,所有属性都有默认值,自动获得一个为所有属性设置默认值的默认构造器

//结构体的逐一成员构造器:结构体的所有存储型属性提供了默认值,且没有定制构造器,则会自动获得一个逐一成员构造器

// 值类型的构造器代理:构造器可以通过调用其他构造器来完成实例的部分构造过程,叫构造器代理

struct Size { var width = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 }

struct Rect {

var origin = Point() var size = Size() init() {} init(origin: Point, size: Size) { self.origin = origin self.size = size }

 init(center: Point, size: Size) {
       let originX = center.x - (size.width / 2)
       let originY = center.y - (size.height / 2)
       let point = Point(x: originX, y: originY)
      self.init(origin: Point(x: originX, y: originY), size: size)
   }

} let basicRect = Rect() let oriRect = Rect(center: Point(x: 3.0, y: 3.3), size: Size(width: 5.0, height: 5.0)) print(oriRect.origin.y ) print(oriRect.origin.x ) print(oriRect.size.width ) print(oriRect.size.height)

// 类的继承和构造过程 //类的构造器有制定构造器和便利构造器两种,前者是必须的,后者是可选的,便利构造器可调用制定构造器

// 制定构造器 print("_") class mainClass { var no1: Int init(no1: Int) { self.no1 = no1 } } class SubClass : mainClass { var no2:Int //指定构造器 init(no1: Int, no2: Int) { self.no2 = no2 super.init(no1: no1) } // 便利构造器 override convenience init(no1:Int) { self.init(no1:no1, no2: 0) } } let res = mainClass(no1: 10) let subRes = SubClass (no1: 10, no2: 20) print(res.no1) print(subRes.no1)

// 可失败构造器 就是加了? 跟可选效果类似

enum TempUnit { case ke, ce, ph init?(sy: Character) { switch sy { case "K": self = .ke case "C": self = .ce default: return nil } } }

let f = TempUnit(sy:"K")

let f1 = TempUnit(sy:"H") if(f1 != nil) { print("b") } else { print("c")
}

//析构函数: 在类的实例被释放前会自动立即调用,关键字deinit。只适用于类类型,类对象置空时引用计数会减一 var counter = 0 class BaseClass1 { init () { counter += 1; } deinit{ counter -= 1 } } var show: BaseClass1? = BaseClass1() print(counter) print(counter) show = nil print(counter)

print("__")

class Person { var residence: Residence? }

class Residence { var rooms = Room // 只读计算属性 var numberOfRooms: Int { return rooms.count } // 对象的下标语法 subscript(i: Int) -> Room { return rooms[i] } func printNumberOfRooms() { print("房间号为 (numberOfRooms)") } // 定义可选类类型 var address: Address? }

// Room 定义一个name属性和一个设定room名的初始化器 class Room { let name: String init(name: String) { self.name = name } }

// 模型中的最终类叫做Address class Address { var buildingName: String? var buildingNumber: String? var street: String? func buildingIdentifier() -> String? { if (buildingName != nil) { return buildingName } else if (buildingNumber != nil) { return buildingNumber } else { return nil } } } let johh = Person()

let house = Residence() house.rooms.append(Room(name:"keting")) house.rooms.append(Room(name:"keting1")) johh.residence = house

let addr = Address() addr.buildingName = "The Larches" addr.street = "Laurel Street" johh.residence?.address = addr

johh.residence?.printNumberOfRooms()

if let street = johh.residence?.address?.street { print(street) } else { print("b") } if ((johh.residence?[0].name) != nil) { print("(johh.residence![0].name)") } else { print("b") }

// ARC实例 class person { let name: String init(name: String) { self.name = name print("chushihua") } deinit{ print("deinit") } } var ref1: person? var ref2: person? var ref3: person? print("___0") ref1 = person(name: "rr") print("___") ref2 = ref1 print("___1") ref3 = ref1 print("___2") ref1 = nil print("___3") ref2 = nil print("___4")

// 弱引用weak
 class SubModule {
     let number: Int
     init(num: Int) {self.number = num}
    deinit 
    {
           print("sub")
    }
       weak var topic: Module? // 弱引用另一个对象         
 }

class MyModule { let str: String init(name: String) { self.str = name } deinit { print("MyModule") } // 捂住引用实例unowned unowned var mainModule: Module? } class Module { let name: String init(name: String) { self.name = name } var sub:SubModule? var myMo: MyModule? deinit { print("main") } }

  var top: Module? = Module(name: "fdg")
  var sub1: SubModule? = SubModule(num: 4)
  var customModel:MyModule? = MyModule(name:"dd")
  top!.sub = sub1
  sub1!.topic = top
  customModel!.mainModule = top
  top!.myMo = customModel
  top = nil
  sub1 = nil
  customModel = nil

   class HTMLEle {
       var name: String
     let text: String?
    var  someValue: String {
        get {
            return "dd"
        }
        set(str) {
             self.name = str
        }
    }
    lazy var asHTML: () -> String = {
       [unowned self] in // 闭包的无主引用和弱引用,避免循环引用

        if let text = self.text {
            return self.text!  + "--------"
        }
        else {
            return "-------"
        }
    }
    init(name: String, text: String? = nil) {
    self.name = name
    self.text = text
}
 deinit {
    print("\(name) is being deinitialized")
}
   }
   var pa: HTMLEle? = HTMLEle(name: "P", text: "dddd")
   print(pa!.asHTML())
   print(pa!.someValue)
   pa = nil
   // swift的语言类型转化可以判断实例的类型,也可以检测实例是否属于其父类或者子类的实例

   // is 用于检测值的类型,as用于类型转化

   class SubJects {
        var physics: String
init(physics: String) {
    self.physics = physics
 }
   }
   class Chemistry: SubJects {
       var eq: String

       init(physics: String, eq: String) {
    self.eq = eq
    super.init(physics: physics)
}
   }

    class Math: SubJects {
         var forStr: String

init(physics: String, forStr: String) { self.forStr = forStr super.init(physics: physics) } }

     var sa = [
         Chemistry(physics:"wuli", eq:"hjh"),
          Math(physics: "shuxue", forStr: "dd"),
               Math(physics: "shuxue", forStr: "dd"),
         Chemistry(physics:"wuli", eq:"hjh")]

      for item in sa {
          if ( item is Chemistry){
              print("----")
          }  else  if ( item is Math){
              print("---yyyy)")
          }
      }

// 向下转化 for item in sa { if let show = item as? Chemistry { print("----") } else if let show = item as? Math { print("---yyyy)") } } print("*") // Any 表示任意类型,包括方法类型 // as? 必须与if while配合使用 //AnyObject 表示任何class类型的实例

var exArray = Any exArray.append(4) exArray.append(5.5) exArray.append("dd") exArray.append(Chemistry(physics:"wuli", eq:"hjh"))

for item2 in exArray { switch item2 { case let intV as Int: print("整型值为 (intV)") case let someString as String: print("(someString)") case let phy as Chemistry: print("ggg (phy.physics)") default: print("None") } }

// 扩展: extension // 协议protocal:规定了用于实现某一特定功能的方法和属性.协议可以继承 //任意满足协议要求的类型乘坐遵守这个协议 // 协议中可以指定属性,但不能是计算属性 // 协议中的构造器,需要加上required修饰符

protocol Classa {

var marks: Int { get set }
var result: Bool { get }

func attendance() -> String
func markssecured() -> String

}

class Classc: Classa { 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 stu1 = Classc() print(stu1.attendance())

protocol Classss { var marks2: Int { get set } } protocol Classd: Classss { var marks: Int { get set } var marks1: Int { get } func attendance1() -> String

}

class Classf: Classd { var marks: Int = 99 var marks1: Int = 44 var marks2: Int = 0 func attendance1() -> String { print("ff") return "ee" } }

let stu = Classf() stu.attendance1()

print("-----")

// 协议可可以是类型 protocol Generator { associatedtype members func next() -> members? }

var items = [10,20,30].makeIterator()

while let x = items.next() { print(x) } print("-----") for lists in [1,2,3].map( { i in i5}) { print(lists) } print("-----") print([100,200,300]) print([1,2,3].map({ i in i10}))

// 类专属协议: 在协议的继承列表中添加class关键字,表示协议只能适配到类类型 protocol TcpPro {

} protocol TcpProtocol: class, TcpPro { init(no1: Int) }

class MainC { var no1: Int init(no1: Int) { self.no1 = no1 }

}

class SubMain:MainC, TcpProtocol { var no2: Int init(no1: Int, no2: Int) { self.no2 = no2 super.init(no1: no1) } //协议中要求实现的便利构造器 required override convenience init(no1: Int) { self.init(no1: no1, no2: 0) } } let res = MainC(no1: 20) let show = SubMain(no1: 29, no2: 39) print(res.no1 ) print("---- - (show.no1) (show.no2)")

// 泛型:用于定制可重用的函数和类型
func swap(_ a: inout Int, _ b: inout Int ) {
    let temp = a
    a = b
    b = temp
}
func swapString(_ a: inout String, _ b: inout String ) {
    let temp = a
    a = b
    b = temp
}
 var num1 = 100, num2 = 300
  swap(&num1,&num2)
  print("---\(num1)====\(num2)")
  // 使用泛型T来替代类型就可以产生一个泛型方法或者类型<T>
   func SwapTwoValue<T> (_ a: inout T, _ b: inout T ) {
     let temp = a
    a = b
    b = temp
   }
   var n1 = "3333.98d"
   var n2 = "sdjasdfjdas"
    SwapTwoValue(&n1, &n2)
    print("---\(n1)====\(n2)")
    print("-------------")
     */

     // 泛型的栈
      struct stack<T> {
          var items = [T]()
          // 方法加上mutating表示可以修改成员变量或者属性
          mutating func push (_ item: T) {
              items.append(item)
          }
           mutating func pop() -> T {
               return items.removeLast()
           }
      }
      extension stack {
           var topItem : T? {
               return items.isEmpty ? nil : items[items.count - 1]
           }
      }
       var stackOfString = stack<String>()
       stackOfString.push("a")
              stackOfString.push("2a333")
              print(stackOfString.items)
             print("_____")
             print("\((stackOfString.topItem)!)")
              let pops = stackOfString.pop()
              print("\(pops)")

//类型约束语法 func findIndex(ofString valueToFind: String, in array:[String]) -> Int? { for (index, value) in array.enumerated() { if value == valueToFind { return index } } return nil } let strings = ["google", "weibo", "taobao", "runoob", "facebook"] if let fIndex = findIndex(ofString: "runoob", in: strings) { print("(fIndex)") }

// 关联类: 关键字associatedtype设置关联类型实例, protocol Container { // 定义一个关联类型实例itemType associatedtype itemType // 定义协议方法 mutating func append( item: itemType) var count: Int { get } subscript(i: Int) -> itemType { get } } struct myStack: Container { var items = T mutating func push( item: T) { items.append(item) } mutating func pop() -> T { return items.removeLast() } var count: Int { return items.count } subscript(i: Int) -> T { return items[i]

      }
     mutating func append(_ item: T) {
         self.push(item)
      }

} var top = myStack() top.push("fdd") top.push("33fdd") top.push("refdd") print(top.count) top.append("ddd") print("-------------") print(top.items) print (top.pop()) //参数列表中通过where定义参数的约定 //Equatable 比较值相等的协议 extension Array: Container {} func allItemsMatch ( someContainer: C1, anotherContainer: C2) -> Bool where C1.itemType == C2.itemType, C1.itemType: Equatable { if someContainer.count != anotherContainer.count { return false } for i in 0..<someContainer.count { if someContainer[i] != anotherContainer[i] { return false } } return true }

print("ddddd") var tos = myStack() tos.push("google") tos.push("runoob") tos.push("taobao")

var aos = ["google", "runeeoob", "taobao"]

if allItemsMatch(tos, aos) { print("匹配所有元素") } else { print("元素不匹配") } // 访问控制 // public // internal: 自己可以访问源文件的任何实体,但是别人不能访问该模块中源文件的实体 // fileprivate: 文件内私有 // private :只能在类或者结构体的作用域内访问 // 默认是internal

chapter-9
JSRUN前端笔记, 是针对前端工程师开放的一个笔记分享平台,是前端工程师记录重点、分享经验的一个笔记本。JSRUN前端采用的 MarkDown 语法 (极客专用语法), 这里属于IT工程师。