微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift 3.0 (一)

转载自:酷走天涯(文中部分错误修改 如发现请告知)

基本数据类型

let myConstant = 42

  • 使用var 定义变量
var myVariable = 42
myVariable = 50
  • 如果有初始化,你可以指定变量类型或者让系统自己去推断
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
  • 如果没有初始化,你要必须指定变量类型
var numb:Double
  • 在Swift 中,字符串是基本类型
let label = "The width is "
width = 94
  • 如何实现数据之间的相互转换
let 94
let widthLabel:String = String(width)
  • 使用最简单的方式将其他数据类型变成字符串
let apples = 3
let oranges = 5
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
  • 数组也是基本类型,不再是OC中的引用类型了
var shoppingList = ["catfish","water",152)">"tulips",152)">"blue paint"]
shoppingList[1] = "bottle of water"
let emptyArray = [String]()
 let emptyArray:[String] = []
  • 字典也是基本类型
var occupations = [
"Malcolm": "Captain",152)">"Kaylee": "Mechanic",]
  • 将数组清空
var shopingList1 = ["1",152)">"2"]
 shopingList1 = [] // 如果你这个类型,是系统可以推断的类型,你可以这样清空数组或者初始化
let emptyDictionary = [String: Float]()
let emptyDictionary:[String: Float] = [:]
  • 清空字典
dictionary = [1:"2"]
dictionary = [:]

可选值

let nickName: String? = nil

"?" :你的变量可能为nil,或者你可能将nil赋值给它,需要给变量定义的时候加上"?",否则一旦你将nil赋值给没有加"?"的变量,编译就会报错。
举个例子理解一下,我们假如有一个盒子,盒子是一个存在的物体,Swift不允许有空值出现,那我们怎么办呢?就需要把空值装到一个盒子里面,系统检查的时候,发现有一个盒子,哦好的,检测通过,但是如果你把盒子打开系统就会报错。

运行下面的代码:

let nickName: String? = "酷走天涯"
print(nickName)

结果:

Optional("酷走天涯")

发现有个Optional 就说明这个变量被包着,那么怎么才能不让它包裹着呢? 很简单,给变量加一个"!"

print(nickName!)

运行:

酷走天涯


我们还有一种解包的方式

String? = nil
let fullName: String = "XUJIE"
let informalGreeting = "Hi \(nickName ?? fullName)"
print(informalGreeting)

运行
Hi XUJIE

如果第一个解包值发现为nil,则使用第二值

控制流

  • for ... in 循环
// 遍历数组
let individualscores = [75,43,152)">103,152)">87,152)">12]
var teamscore = 0
for score in individualscores {
  if score > 50 {
      teamscore += 3
} else {
    teamscore += 1
}
}
print(teamscore)
// 遍历 字典
let interestingNumbers = [
"Prime": [2,152)">3,152)">5,152)">7,152)">11,152)">13],152)">"Fibonacci": [1,152)">8],152)">"Square": [4,152)">9,152)">16,152)">25],]
var largest = for (kind,numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
 }
 // 还可以这样使用循环
  var total = 0
 for i in 0..<4 {
   total += i
 }
 print(total)
  • Switch
let vegetable = "red pepper"
switch vegetable {
case "celery":
    print("Add some raisins and make ants on a log.")
"cucumber",152)">"watercress":
    "That would make a good tea sandwich.")
case let z where z.hasSuffix("pepper"):
    "Is it a spicy \(z)?")
default:
    "Everything tastes good in soup.")
}

注意 z 什么 随便写个变量名就可以了

  • while 循环
var n = 2
  while n < 100 {
n = n * 2
}
print(n)
  • repeat ...while
var m = 2
  repeat {
  m = m * 2
} while m < 100
print(m)

函数和闭包

  • 定义函数
  • func greet(person: String,day: String) -> String {
    return "Hello \(person),today is \(day)."
    }
    greet(person: "Bob",210)">day: "Tuesday")
    • 缺省参数名
    func greet(_ person: String,152)">_ day: String) -> 
    }
    greet("John",152)">"Wednesday")
    • 返回值可以是元祖类型
    func calculateStatistics(scores: [Int]) -> (min: Int,210)">max: Int,210)">sum: Int) {
    min = scores[0]
    max = scores[sum = in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }
    
    return (min,210)">max,210)">sum)
    }
    let statistics = calculateStatistics(scores: [100,152)">9])
    print(statistics.sum)
    print(statistics.2)
    • 定义多个类型相同的参数
    func sumOf(numbers: Int...) -> Int {
    var sum = in numbers {
        sum += number
    }
      return sum
    }
    sumOf()
    sumOf(numbers: 42,152)">597,152)">12)
    returnFifteen() -> Int {
    var y = 10
    add() {
        y += 5
    }
    // 方法内部定义方法,声明周期为方法
    add()
    return y
    }
    returnFifteen()
    func makeIncrementer() -> ((Int) -> Int) { func addOne(number: Int) -> Int {
            return 1 + number
    }
    return addOne
    }
    var increment = makeIncrementer()
    increment(7)
    hasAnyMatches(list: [Int],condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
    }
    lessthanTen(number: Int) -> Bool {
        return number < 10
    }
    var numbers = [20,152)">19,152)">12]
    hasAnyMatches(list: numbers,condition: lessthanTen)

    对象和类

    class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        "A shape with \(numberOfSides) sides."
    }
    }
    NamedShape {
        var numberOfSides: Int = 0
        var name: String
        // 初始化方法
        init(name: String) {
           self.name = name
        }
        // 成员方法定义
        simpleDescription() -> String {
           "A shape with \(numberOfSides) sides."
        }
    }
    • 继承
    Square: NamedShape {
      var sideLength: Double  // 如果不是可选类型 必须在初始化方法中初始化
    
      init(sideLength: Double,name: String) {
        self.sideLength = sideLength
        super.init(name: name) // 调用父类的初始化方法
        numberOfSides = 4 // 给父类属性赋值之前必须先调用父类的初始化方法
      }
    
      area() ->  Double {
          return sideLength * sideLength
      }
    
        // 重写父类方法
        override String {
            "A square with sides of length \(sideLength)."
        }
      }
    • setter 和 getter
    EquilateralTriangle: NamedShape {
    var sideLength: Double = 0.0  // 定一个属性
    init(sideLength: Double,name: String) {
        self.sideLength = sideLength
        super.init(name: name)
        numberOfSides = 3
    
    }
     // 这个是setter 和geterr方法的定义
      var perimeter: Double {
        get {
             3.0 * sideLength
        }
        set {
            sideLength = newValue / 3.0
        }
        }
    
    override func simpleDescription() -> String {
        "An equilateral triangle with sides of length \(sideLength)."
    }
    }
    class TriangleAndSquare {
      // 定一个三角形对象
      var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
      }
      // 定一个一个正方形对象
      var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength
        }
      }
      // 通过检测属性,我们让两个对象的边保持一样长
      init(size: Double,name: String) {
        square = Square(sideLength: size,name: name)
        triangle = EquilateralTriangle(sideLength: size,name: name)
      }
      }
      var triangleAndSquare = TriangleAndSquare(size: 10,name: "another test shape")
      print(triangleAndSquare.square.sideLength)
      print(triangleAndSquare.triangle.sideLength)
      triangleAndSquare.square = Square(sideLength: 50,152)">"larger square")
      print(triangleAndSquare.triangle.sideLength)

    运行结果

    10.0
    10.0
    50.0

    枚举类型

    • 定义
    enum Rank: Int { // Int 设置枚举值的类型
    // 定义枚举值设置值
    case ace = 1
    // 可以case 后面一次定义多个枚举值
    case two,three,four,five,six,seven,eight,nine,ten
    case jack,queen,king
    
    // 定义函数 如果多人合作的时候,可以使用这个让别人更加了解你定义的属性的含义
    String {
        switch self { // self 就是这个枚举本身
            case .ace:
                "ace"
            case .jack:
                "jack"
            case .queen:
                "queen"
            case .king:
                "king"
            default:
                return String(self.rawValue)
        }
    }
    }
    // 使用
    let ace = Rank.ace
    let aceRawValue = ace.rawValue

    问题1 如何想OC 一样使用 | 或操作呢?

    结构体

      struct Card { // 定义结构体 var rank: Rank var suit: Suit // 结构体内可以定义方法 "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } }
      • 使用
      let threeOfSpades = Card(rank: .three,suit: .spades)
      let threeOfSpadesDescription = threeOfSpades.simpleDescription()

      协议

        protocol ExampleProtocol { var simpleDescription: String { get } mutating adjust() }
        SimpleClass: ExampleProtocol {
         "A very simple class."
         var anotherProperty: 69105
         adjust() {
              simpleDescription += " Now 100% adjusted."
         }
        }
        SimpleStructure: "A simple structure"
         " (adjusted)"
         }
        }
        let protocolValue: ExampleProtocol = a
        print(protocolValue.simpleDescription)

        扩展

        例子:给Int 添加一个协议

        extension Int: ExampleProtocol {
        "The number \(self)"
        }
            adjust() {
                self += 42
            }
        }
        print(7.simpleDescription)

        错误操作

        PrinterError: Error {
        case outOfPaper
        case noToner
        case onFire
        }
        send(job: Int,toPrinter printerName: String) throws -> if printerName == "Never Has Toner" {
            throw PrinterError.noToner
        }
        "Job sent"
        }
        • 捕捉异常
        do {
        let printerResponse = try send(job: 1040,toPrinter: "Bi Sheng")
        print(printerResponse)
        } catch {
        print(error)
        }
        1440,152)">"Gutenberg")
            catch PrinterError.onFire {
            print("I'll just put this over here,with the rest of the fire.")
        } catch let printerError as PrinterError {
            "Printer error: \(printerError).")
        } catch {
              print(error)
        }

        总结

        Swift 的基本语法已经了解完毕,但这只是些简单的东西,如果Swift只是这些东西,那我们就没有学习的必要了,Swift的灵活性,优秀的设计模式,从上面的内容体现不出来,我会在后面几篇文章中,阐述它的高级用法!

        版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

    相关推荐