Swift 3.0 (一)

Swift 3.0 (一),第1张

概述转载自:酷走天涯(文中部分错误已修改 如发现请告知) 基本数据类型 使用 let 定义常量 let myConstant = 42 使用 var 定义变量 var myVariable = 42myVariable = 50 如果有初始化,你可以指定变量类型或者让系统自己去推断 let implicitInteger = 70let implicitDouble = 70.0let expl

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

基本数据类型 使用 let 定义常量
let myConstant = 42

使用var 定义变量
var myVariable = 42myVariable = 50
如果有初始化,你可以指定变量类型或者让系统自己去推断
let implicitInteger = 70let implicitDouble = 70.0let explicitDouble: Double = 70
如果没有初始化,你要必须指定变量类型
var numb:Double
在Swift 中,字符串是基本类型
let label = "The wIDth is "wIDth = 94
如何实现数据之间的相互转换
let 94let wIDthLabel:String = String(wIDth)
使用最简单的方式将其他数据类型变成字符串
let apples = 3let oranges = 5let 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不允许有空值出现,那我们怎么办呢?就需要把空值装到一个盒子里面,系统检查的时候,发现有一个盒子,哦好的,检测通过,但是如果你把盒子打开系统就会报错。

运行下面的代码:

@H_419_226@let nickname: String? = "酷走天涯"print(nickname)

结果:

Optional("酷走天涯")

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

print(nickname!)

运行:

酷走天涯


我们还有一种解包的方式

@H_419_226@String? = nillet 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 = 0for 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 < 100print(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 = 10add() {    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 = 0func 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,tencase 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.acelet 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 = aprint(protocolValue.simpleDescription)
扩展

例子:给Int 添加一个协议

extension Int: ExampleProtocol {"The number \(self)"}    adjust() {        self += 42    }}print(7.simpleDescription)
错误 *** 作 定义一个错误枚举
PrinterError: Error {case outOfPapercase noTonercase 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的灵活性,优秀的设计模式,从上面的内容体现不出来,我会在后面几篇文章中,阐述它的高级用法!

总结

以上是内存溢出为你收集整理的Swift 3.0 (一)全部内容,希望文章能够帮你解决Swift 3.0 (一)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1062795.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存