Swift4.0特性

2019-03-14  本文已影响0人  找不到工作的iOS

变量声明

let testOne = 20
var testTwo = 30
let stringOne = "123"
let stringOne:String = "123"
let testOne = 20
var testTwo : Double = 30;
var Three = testOne + Int(testTwo)
var Four = Double(testOne) + testTwo
print(testOne,testTwo)
print("值一:\(testOne),值2:\(testTwo)")

类型转换

let testOne = 20
let testTwo = testOne as? Double // 无法转化
var stringOne : String?
var testArray = ["1234","5678"]
testArray[1] = 456

var testArray = ["1234","5678"]
var testArrayTwo = testArray as? Array<any>
testArrayTwo![1] = 456

数组

let arrayOne = ["123","456"]
var mutableArray = ["123","456"]
mutableArray.append("789")

var arrayThree = Array<String>();
var arrayFour = Array<Any>();

var arrayFive = [any]()

字典

var dic = [
"key":"value",
"key":"value",
]

var dicTwo = [String:String]()
dicTwo["keyOne"] = "valueOne"

var dicThree = Dictionary<String:String>()
dicThree ["keyOne"] = "valueOne"

if (dic.isEmpty) {
}

循环

for index in 1...5 {

}
for index in 1..<5 {

}
for _ in 1...5 {

}
var names = ["1","2","3","4"]
for number in names {

}

for (index,number) in names.enumerated {

}

for value in array.reversed() {


var dic = ["key1":"1","key2":"2","key3":"3"]
for (key,value) in dic {
}
for charac in "hello"{
}
repeat {
count = count + 1
} while count < 5

while count < 5 {
}

元祖

let http404 = (404,"error")
print(http404.0,http404.1)
let(statusCode,statusDes) = http404
print(statusCode,statusDes)

let(statusCode,_) = http404
let http200Status = (status:200,des:"success")
print(http200Status.status,http200Status.des)

条件语句 if

let testStr = "123"
if testStr {
}
let testStr:<String>? = "123"
if let condtion = testStr {
  print("condtion is ture")
}

if testStr != nil {

}

条件语句 switch

let characterTest:Character = "1"
switch characterTest {
   case "1","一":
  print(characterTest)
  fallthrough
   case "2":
 print(characterTest)
   case "3":
 print(characterTest)
  default:
print("not")
}
let num = 3000
var str:String
switch num{
   case 0...9:
  str = "个"
   case 10...999:
 str = "百"
   case 1000...9999:
 str = "千"
  default:
print("万")
}
let point = (1,1)
switch point{
   case (0,0):
  print("在原点")
   case (0,_):
 print("x")
   case (_,0):
 print("y")
  case (-2...2,-2...2)
 print("要求范围内")
   default:
print("不在轴上")
}
let point = (3,0)
switch point{
   case (let x,0):
  print("在x轴的位置:\(x)")
   case (0,let y):
  print("在x轴的位置:\(y)")
   case (let x,let y):
 print("point:\(x) \(y)")
   default:
print("不在轴上")
}
let point = (3,0)
switch point{
   case let(x,y):
 print("point:\(x) \(y)")
   default:
print("不在轴上")
}

方法

fun testMethod() {
  print("testMethod")
}
testMethod()
fun testMethod(number1:Int, number2:Int) -> Int {
  return number1 + number2
}
testMethod(number1:2,number2:8)
fun testMethod(numberArray:Array<Int>) -> (max:Int,min:Int,sum:int) {
  return (100,1,101)
}
testMethod([1,2,3])
fun testMethod(fristStr str1:String ,secondStr str2:String) -> String {
  return str1 + str2;
}
testMethod(fristStr:"123",secondStr:"456");
fun testMethod(_str1:String ,_str2:String) -> String {
  return str1 + str2;
}
testMethod("123","456");
fun testMethod( str1:String ,str2:String = “abc”) -> String {
  return str1 + str2;
// "123abc"
}
testMethod(str1:"123");
fun testMethod( argNumbers:Int ...) -> Int {
  var sum = 0
  for number in argNumbers {
       sum += number
  }
 return sum;
}
testMethod(argNumbers :1,2,3,4,5,6,7);
fun swap( inout num1:Int, inout num2:Int.)  {
  var temp = num1
  num1 = num2
  num2 = temp 
}
var numberOne = 1
var numberTwo = 9
swap(num1:&numberOne, &num2:numberTwo)
func testMethod(num1:Int,num2:Int) -> Int {
  return num1 + num2
}
var methodVar : (Int,Int)->Int = testMethod
methodVar(1,2)
func testMethod(num1:Int,num2:Int) -> Int {
  return num1 + num2
}
func testMethodTwo(parameterMethod:(Int,Int)->Int, _ parameter1:Int,_ parameter2:Int)  {
   let result = parameterMethod(parameter1,parameter2)
}
func testone (p:Int,p2:Int)- {
}
func testtwo (p:Int,p2:Int)- {
}
func testMethodThree(_ condition:Bool) -> (Int,Int)->Int {
       return condition? testone : testtwo 
}
func testMethodThree(_ condition:Bool) -> (Int,Int)->Int {
      func testone (p:Int,p2:Int)- {
      }
       func testtwo (p:Int,p2:Int)- {
       }
       return condition? testone : testtwo 
}
let _testLock = NSLock.init()
var _testCount = 0

// 做一个线程安全
var testCount : Int {
     set {
      _testLock.lock()
       defer {
       _testLock.unlock()
       }
       _testCount = newValue
     }
     get {
      _testLock.lock()
       defer {
       _testLock.unlock()
       }
      return _testCount;
     }
}

闭包

func testMethod (num1:Int,num2:Int) -> Bool {
     return num1 > num2
}
let names = [1,2,3,4,5]
let nameSortFour = names.sorted(by:testMethod)
let names = [1,2,3,4,5]
let nameSortFour = names.sorted  {(num1,num2) in num1 > num 2}
print(nameSortFour) // 5 4 3 2 1
let names = [1,2,3,4,5]
// 写法1
let nameSortFour = names.sorted () {
   return $0 > $1
}
// 写法2
let nameSortFour = names.sorted  {$0 > $1}
func testMethod (styleMethod:()->()) {
   styleMethod()
}
// 正规写法
testMethod(styleMethod:{
  print("闭包调用")
})
func testMethod (styleMethod:()->()) {
   styleMethod()
}
// 编译器会提示的省略版本(当函数只有闭包一个参数时)
testMethod {
  print("闭包调用")
}
func testMethod (_ styleMethod:()->()) {
   styleMethod()
}
testMethod ({
  print("闭包调用")
})
var nameMethod = ((Int) -> String)?

override func viewDidLoad () {
   super.viewDidLoad()
   self.title = "testName"
 
   weak var weakSelf = self
   nameMethod = { num in
     return weakSelf?.title ?? ""
  }
  print(nameMethod!(1))

  deinit {
     print("delloca")
  }
}
func testMethod( closure:@escape ()->void) {

   DispatchQueue.main.async {
      closure()
   }

}

枚举

func 枚举() {
  enum CompassPoint {
     case North
     case West
     case  East
     case South
  }
  print(CompassPoint.North)

  var direction = CompassPoint.North
  direction = .South

  let directionTow : CompassPoint = .West

  switch (directioTow) {
      case: .North
      print("北")
      case: .West
      print("西")
  }
}
 enum CompassPoint {
     case North = 2
     case West // 3
     case  East // 4
     case South // 5
  }
 enum CompassPoint {
     case North(String,Int)
     case West (Double)
     case  East // 4
     case South // 5
  }
var directionOne = CompassPoint.North("北方",2)
var directionTwo = CompassPoint.West(3.0)

switch (directionOne ) {
  case .North(let direction, let number) :
  print("方向\(direction) 数字\(number)")
  case .West(let doubleNum) :
  print("浮点数\(doubleNum)")
}
 enum CompassPoint {
     case North = 1
     case West 
     case  East 
     case South 
  }
let direction = CompassPoint(rawValue;1) // North
let direction = CompassPoint(rawValue;5) // nil
}

结构体与类的区别

struct testStruct {
   var name = "ken"
   var age = 9
}
var structOne = testStruct()
let structTwo = structOne
structOne.age = 10
print(stuctTwo.age) // 还是9
struct testStruct {
   var name = "ken"
   var age = 9
}
var testStructTwo =  testStruct(name:"sun",age:15)

运算符 === 与 ==

  1. === 表示两者是否引用同一对象
var classOne = EOClass()
var classTwo = EOClass()
if classOne === ClassTwo {
   print("引用同一对象")
}
  1. == 值类型的判断
var str1= “111”
var str2= “111”
if str 1== str2 {
   print("两个值相等")
}
  1. swift的所有基础类型是值类型(拷贝行为)Int Double String Bool Array Dictionary

属性

lazy var

subscript下标运算

struct TestTable{
    subscript(index:Int) -> String {
      return ""
    }
    subscript(key:String) -> String {
      return ""
    }
}
var testTable = TestTable()
var value = testTable[1]
var value2 = testTable["key"]

继承

class OneClass {
     func method () { 

     }
}
class SubClass : OneClass {
    override func method() {

    }
}
class OneClass {
    final  func method () { 

     }
}
class SubClass : OneClass {
    override func method() {

    }
}

构造

var oneTest = ClassOne()
var oneTest = ClassOne.init()
class OneClass {
   init (name:String) {
   }
}
var testClass = OneClass() // 这样就不行了
var testClass = OneClass(name:"111")
var testClass = OneClass,init(name:"111") //正式写法
class OneClass {
   let name:String
   init (name:String) {
      self.name = name
   }
}
class SubClass : OneClass {
     override init (name:String) {
       super.init(name:name)
    }
}
class OneClass {
   let name:String
   init (name:String) {
      self.name = name
   }
}
class SubClass : OneClass {
     var subname
     override init (name:String) {
       subname = "" 
       super.init(name:name)// 为了安全放在最后
    }
}
protocol OneProtocol {
   func method()
   var name:String {get set} // 表示可读可写
   static func classMethod()
   mutating func changeProperty()
}
class TwoClass:OneProtocol {
      func method() {
            // 实现
      }
      name:String = "123"
     static func classMethod {

     }
    func changeProperty {

    }
}
// 有父类
class TwoClass:OneClass:OneProtocol {

}
protocol OneProtocol {
}
protocol TwoProtocol {
}
class TestClass {
  var delegate:OneProtocol?
  var delegate2:(OneProtocol & TwoProtocol)
}
@objc protocol TwoProtocol {
   @objc optional func testMethod()
}
class TestClass:TwoProtocol {
    func testMethod {
     print("实现了可选方法")
    }
}
override viewDidLoad() {
   let testClass = TestClass()
   (testClass as TwoProtocol) .testMethod?() // ? 如果有实现协议的方法,就执行
}
func swapTwoInt(_ num1:inout Int ,_ num2:inout Int) {
    let temp = num1
    num1 = num2
    num2 = temp
}
func swapTwo<T>(_ num1:inout T,_ num2 inout T) {
    let temp = num1
    num1 = num2
    num2 = temp
}

swapTwo(&num1,&num2)
swapTwo(&str1,&str2)
struct Vector2D {
   var x = 2
   var y = 3

   static func + (left:Vector2D ,right:Vector2D) -> Vector2D  {
    return Vector2D (left.x + right.x , left.y + right.y)
  }
   static prefix func ++ (left: inout Vector2D ) {
    left.x = left.x + 1
    left.y = left.y + 1
  }
  static func += (left:inout Vector2D , right:Vector2D ) {
     left = left + right
  }
}
override func viewDidLoad() {
    var Vector1 = Vector2D ()
    var Vector2 = Vector2D ()
    var Vector3 = Vector1 + Vector2

    ++Vector3 
    Vector3 =+ Vector1 
}
上一篇下一篇

猜你喜欢

热点阅读