美文网首页
swift学习~~~~

swift学习~~~~

作者: marlonxlj | 来源:发表于2017-11-08 15:47 被阅读22次
//: Playground - noun: a place where people can play

//swift4 3天 学会

import UIKit
import Foundation

/**
 * 第一天 面向过程编程:基本语法
 * 第二天 面向对象编程:对象的属性
 * 第三天 主要协议属性:协议相关
 */
//一、常量

//let a : Double = 3.132
//
//
//print(a)

//二、变量
//var a = 5

//三、值的类型和类型推断
//var age : Int = 18//这里的类型Int 可以不写

//四、浮点
//var price = 6.6

//五、类型安全,会自行的进行类型的推断自动的帮你做一些转换的工作,更加的智能
//var price = 3.6
//
//price = 5
//
//print(price)

//六、bool,只有true和false
//var money = true
//money = false

//七、元组tuple:定义变量的一个组合
//一般形式:(3,"天", "swift", "4.0")
//前缀形式:(day:3, unit:"天",lang:"swift",version:"4.0")

//var (x,y,z) = (4,5,6)
//x
//y
//z

//var className = (day:3, unit:"天", lang:"swift",version:"4.0")
//className.version
//className.day
//className.unit

//八、可选类型:optional,代表变量可能有值的情况
//形式:var 变量:类型?,默认是无值(nil)
//var addr : String? = "四川成都市高新区"

//九、基础操作符:+ - * /

//十、字符串和字符
//字面量 "A,B,C"
//var a = ""
//var b = " "
//a.isEmpty
//b.isEmpty
//var a: Character = "我"
//var b: Character = "天"
//let c = "明天会更好"
//c.characters
//for word in c {
//    print(word)
//}
//连接
//let a = "BB"
//let b = "guirld"
//let c = "AA"
//
//var famus = a + b + c
//
//let numBer = "1"
//
//famus.append(numBer)

//插值
//let name = "老王"
//let type = "GD"
//let number = 15
//let price = 166.6
//
//let noticeInfo = "\(name)sir,您购买了\(type)\(number)的往返票,需要支付\(price * 2)元"
//
//print(noticeInfo)

//十一、集合:
//分为有序可重复 -- 数组 Array
//无序不重复 -- set
// 无序不重复-- 字典
//批量处理集合中的元素,for in

//数组
let array : [Int]
//元素3,重复10次
//无序
array = [Int](repeatElement(3, count: 10))

//有序
let array2 = Array(0...5)
//
var places = ["beijing","shanghai","chengdu"]
places.contains("chengdu")


//places.count
//places.isEmpty

places.append("chongqi")

let haiwaiPlace = ["NewYork","London"]

places += haiwaiPlace

places[4]

//插入:insert
places.count
places.insert("西藏民", at: 3)

places.count

//移除:remove
places.remove(at: 2)

集合set,适合存储具有唯一性的数据,如用户名、身份证号码、护照

let cardNum : Set = [1,2,3,4,5,56]

var citys: Set = ["shangdong","beijing","wuhan"]

citys.count
//cardNum.isEmpty
citys.insert("BBBB")

//citys.remove("BBBB")

citys.contains("wuhan")

//转换成数组
let cityArray = citys.sorted()


字典:键值对,[键类型:值类型]

定义的两种方式
var a : Dictionary<String, String>
var b : [String : String]
var airports = ["PNG":"天府机场","PNN":"天津机场","PGG":"重庆机场"]

airports["HOT"] = "红山机场"

airports["HOT"] = "大水机场"

airports["HOT"] = nil

//airports

//字典的键和值进行数组分离
let codes = [String](airports.keys)
let airport = [String](airports.values)


swift
var tmp = 36

switch tmp {
case 35...40:
    print("天气非常火热,强力制冷启用")
case 25...34:
    print("气温合适,空调制冷模式启动")
case 19...24:
    print("除湿模式")
case 0...18:
    print("制暖模式")
default:
    print("室外已经超过本空调的控制范围")
}

元组匹配

函数:
形式:func 函数名(参数1:类型,参数2:类型..)->返回结果的类型
调用:var 变量名称 = 函数名(变量1,变量2,...)

func add(x: Int, y: Int) ->Int{

    return x + y;
}

var z = add(x: 3, y: 5)


func add(x: Int, increment: Int = 2) ->Int{
    return x + increment
}

add(x: 3)

add(x: 3, increment: 5)

函数类型
func mutiply(x: Int, y: Int) -> Int{
    return x * y
}

func calc(x: Int, y: Int, mehtod: (Int, Int) -> Int) ->Int{
    return mehtod(x, y)
}

func add(x: Int, y: Int) -> Int{
    return x + y
}

calc(x: 3, y: 5, mehtod: mutiply)
calc(x: 2, y: 4, mehtod: add)

闭包:函数的简写形式,省去函数名,把参数和返回值放入花括号中
var city = ["zhengzhou","xiamen","hefei","nanchang"]

var cityRank1 = city.sorted()

func daoxu( a : String, b : String) -> Bool{
    return a > b
}

var cityRank2 = city.sorted(by: daoxu)

var cityRank3 = city.sorted { (a, b) -> Bool in
    return a > b
}

var cityRank4 = city.sorted{ $0 > $1 }

print(cityRank4)


枚举
定义和使用
enum Weather{
    case sunny
    case cloundy
    case rainy
    case snow
    case froggy
}

使用
Weather.cloundy

var todayWeather = Weather.sunny
switch todayWeather {
case .cloundy:
    print("今天天气多云")
case .sunny:
    print("天气明亮")
default:
    print("天气未知")
}

第二天: 面向对象
/**
 * 基因:属性和方法(变量和函数)
 * 繁殖:完全克隆和基因交换(继承和变异)
 * 结构体struct class和enum的区别,什么情况下使用哪个?
 * 自定义对象的时候使用struct,系统提供的使用class
 */

/**
 * 属性是一个类/结构体/枚举关联的变量
 * 属性:
 * - 实例属性: 实例化后才能使用
 * - 存储属性: 保存单个类型的变量
 * - 计算属性:由其它属性计算得出的.由getter和setter组成
 */

class person {
    var id = ""
    var money = 0
}

let mm = person()
mm.id = "2322"
mm.money = 233
struct moveX{
    var x = 0, y = 0
}

enum moveForword{
    case walk
    case run
    case qi
    case chuansong
}

class xiaoming: person{
    var 人物坐标 = moveX()
    var 人物移动方式 = moveForword.walk

    var 当前坐标 : moveX{
        get {
            switch 人物移动方式 {
            case .walk:
                人物坐标.x += 1
                人物坐标.y += 1
            case .run:
                人物坐标.x += 3
                人物坐标.y += 3
            case .qi:
                人物坐标.x += 10
                人物坐标.y += 10
            case .chuansong:
                人物坐标.x += 100
                人物坐标.y += 100
            }
            return 人物坐标
        }

        set {
            人物坐标 = newValue
        }
    }
}

var fashi = xiaoming()
fashi.人物坐标

类型属性:属于类型固有的,实例不能调用,不用实例化
对于类,计算型的类型属性,前面加关键字class可被子类重写override
结构体和枚举,关键字static
class 生命体{
   class var 遗传方式: String{
        return "DNA"
    }
}

生命体.遗传方式

class Human: 生命体{
   override class var 遗传方式: String{
        return "ABC"
    }
}

Human.遗传方式

实例方法

enum Monster : Int {
    case sheep = 10, cat = 50, snake = 100
}
struct ExpTimes {
    var open = false
    var times = 1
}
class RmbPlayer{
    var exp = 0
    var expTimes = ExpTimes()

    func idle() {
        exp += 500
        print("挂机成功1次!总验证为\(exp)")
    }

    func kill(monster: Monster, expTimes: Int){

        exp += (monster.rawValue * expTimes)

        print("当前总验证为\(exp)")
    }
}

var xiaoming = RmbPlayer()
xiaoming.idle()
//xiaoming.kill(monster: Monster.cat, expTimes: 2)

var mming = RmbPlayer()
mming.idle()
mming.kill(monster: .cat, expTimes: 2)

类型方法:静态方式
class Player {
    static var nick = "xlj"

    class func server(){
        print("\(nick),您在深圳A区")
    }
}

Player.server()

class ShangHaiPlayer : Player {
    override static func server (){
        print(nick,"您在上海B区")
    }
}

ShangHaiPlayer.server()

下标: 计算属性:subscript可以忽略set(只读)
常见的用法:字典、数组、集合

var array = [1,2,3]
array[0]

var dic = [1:"A",2:"B",3:"C"]
dic[2]

struct Cyle {
    func area(radius: Double) -> Double{
        return Double.pi * pow(radius, 2)
    }

    subscript(radius: Double) -> Double{
        return Double.pi * pow(radius, 2)
    }
}

let cyle = Cyle()

cyle.area(radius: 3)
cyle[3]

继承: class之间
 子类可以继承父类的属性和方法

class Viechle{
    var speed = 0
    var desc : String{
        return "时速是\(speed)km/h"
    }

    func makeNoise() {

    }
}

class Bike : Viechle{

    var hasBasket = false
}

let aBike = Bike()
aBike.speed = 30
aBike.desc

//子类可以根据需要来修改继承的属性和方法(就是多态)

class CRH: Viechle{
    override func makeNoise() {

    }
}

初始化:描述类/结构体/枚举实例化时,属性如何给初始值的方式.形式:init(){}.此方法称这为构造器
1. 类的定义没有给属性默认的值,则必须在init中指定
class RoomTemp{
    var season : String
    var temp : Int

    init(season: String, temp: Int) {
        self.season = season
        self.temp = temp
    }
}

let temp1 = RoomTemp(season: "Sprint", temp: 20)


2. 结构体定义不需要指定属性默认的值,因为默认提供一个包含甩的属性初始化的构造器
struct RoomTemp{
    var season : String
    var temp : Int
}

let temp2 = RoomTemp(season: "summer", temp: 30)

3. 便利构造器: 可以通过对主构造器的包装,实现便利的初始化
class Food{
    var name : String

    //主构造器
    init(name: String) {
        self.name = name
    }

    //便利构造器
   convenience init() {
        self.init(name: "mianshi")
    }
}

let food = Food()


4.可失败构造器: 针对有可能初始化失败,返回nil,初始化一张图片,如果图片不存在,则初始化失败
struct Animal {
    let name: String

    init?(name: String) {

        if name.isEmpty{
            print("没有给动物命名")
            return nil
        }

        self.name = name

    }
}
let cat = Animal(name: "cat")

错误处理
 1. 可选类型仅处理值缺失,错误处理可以针对不同的出错原因对不同的应对N
 2. 一个函数可以throws关键字,表示可以处理错误,这个函数的调用者可以捕获catch这个错误进行应对
 3. 当你调用抛出错误的函数,必须加上try关键字
 4.处理更细分的错误情况,错误类型必须遵从ErrorType协议
 5. 有时候仅关心结果有无,可以使用try?或try!来忽略错误细节


协议:方法、属性或一段功能
属性协议:要求遵从者实现以指定的名称实现属性,但具体实现是实例属性或类属性并不关心
1. 可以指定要求实现getter或getter+setter,必须定义为变量
protocol FileAccessPriority{
    var readOnly: Bool{get}//实例
    var readWirte: Bool {get set}
}

protocol AccessUrl{
    //static类型属性,或class
    static var link: String{get}
}

2. 遵从实例属性协议1

protocol FullName {
    var fName: String{ get}
    var gName : String{get }
}

struct Student : FullName {

    var fName: String
    var gName : String

}

struct Teacher : FullName {
    var fName: String
    var gName : String

}

var student1 = Student(fName: "小明", gName: "王")
student1.fName
student1.gName

//3. 遵从实例属性协议2
class SomeBody : FullName{
    var title : String?
    var name : String
    init(title: String?, name: String) {
        self.title = title
        self.name = name
    }

    var gName: String{
        return name
    }

    var fName: String{
        return title ?? "无名人"
    }

    var desc: String {
        return self.fName + self.gName
    }

}

var someBody1 = SomeBody(title: "大明", name: "凤凰网")
someBody1.fName
someBody1.gName
someBody1.desc


方法协议:定义时没有花括号执行体,实现仅要求名称相同
类型方法协议: 前缀总是static
protocol Amethod{
   //如果不加前缀是实例方法,加前缀是类型方法
   static func foo()
}
class A: Amethod{

    //如果不想让子类覆盖父类就使用static,如果想让子类对父类进行覆盖使用class
    static func foo() {
        print("AAAA")
    }
}

//实例方法协议
protocol RandomGeneratable{
    func randomNumber() -> Int
}

struct RandomNumber : RandomGeneratable{
    func randomNumber() -> Int {
        return Int(arc4random())
    }
}


struct RandomNumberInSix : RandomGeneratable{
    func randomNumber() -> Int {
        return Int(arc4random()) % 6 + 1
    }
}

let rad = RandomNumber()
rad.randomNumber()

let rad1 = RandomNumberInSix()
rad1.randomNumber()

枚举 mutating
protocol SwitchTable {
   mutating func onOff()
}

enum MySwitch : SwitchTable{
    mutating func onOff() {
        switch self {
        case .off:
            self = .on

        default:
            self = .off
        }
    }

    case on, off
}



//变异方法协议

//构造方法协议
protocol A {
    init(a : Int)
}

struct B : A {
    init(a: Int) {

    }
}

class C : A {
    required init(a: Int) {

    }
}

协议作为代理
protocol RandomGeneratable{
    func randomNumber() -> Int
}

struct RandowNumber: RandomGeneratable{
    func randomNumber() -> Int {
        return Int(arc4random())
    }
}

class TenRandomNuber : RandomGeneratable{
    func randomNumber() -> Int {
        return Int(arc4random()) % 10 + 1
    }
}

struct Dice{
    var sides : Int
    var randomNuber : RandomGeneratable

    func play() -> Int{
        return self.randomNuber.randomNumber() % sides + 1
    }
}

let adic = Dice(sides: 6, randomNuber: TenRandomNuber())

adic.play()

protocol Role {
    var name : String { get set }
}

protocol Player{
    var role: Role {get}
   mutating func play()
}

protocol GameDelegate{
    func start(with player: Player) -> Int
    func rolePK(with player: Player, armed: Bool) ->Int
    func end(with player:Player) -> Int
}

struct GameAgent: GameDelegate {
    func start(with player: Player) -> Int {

        print(player.role.name,"开始游戏,获得经验值:200")
        return 200

    }

    func rolePK(with player: Player, armed: Bool) -> Int {

        if armed {
            print(player.role.name,"开始PK,您有wepen,获得经验值:500")
            return 500
        }else{

            print(player.role.name, "开始,获得验证值:250")
            return 250
        }
    }

    func end(with player: Player) -> Int {
        print(player.role.name, "正常退出,获得验证值:1000")
        return 1000
    }
}

struct MirPlayer : Player{

    var exp: Int
    var gameAgen: GameAgent?

    var role: Role
   mutating func play() {
    if let gameAgents = gameAgen {
        print("您使用了代练")
        exp += gameAgents.start(with: self)
        exp += gameAgents.rolePK(with: self, armed: true)
        exp += gameAgents.end(with: self)
    }else{
        print("没有代经练,不能自动升级")
        }
    }
}

let role = Role()
let playe1 = MirPlayer(exp: 0, gameAgen: nil, role: role)
playe1.plae()

协议扩展
let a = 1

protocol ShowHint{
    func hint() -> String
}

extension Int : ShowHint{
    func hint() -> String {
        return "AAA:\(self)"
    }
}

a.hint()

struct Lessono{
    var name : String
    var description: String {
        return "课程名:" + name
    }
}

//1.description
extension Lessono : CustomStringConvertible{}

extension ShowHint where Self: CustomStringConvertible {
    func hinit2()-> String{
        return "我是一个能显示成字符串的类型" + self.description
    }
}

1.hinit2()

let array = [1,2,3,4]

extension Collection where Iterator.Element : CustomStringConvertible{
    func newDesc() -> String{
        let itemAsText = self.map{$0.description}

        return "该集合元素数目是\(self.count),元素值是"+itemAsText.joined(separator: ",")
    }
}

array.newDesc()

协议集合
let array:[CustomStringConvertible] = [1,2,3,"hello"]

for element in array {
    print(element)
}

协议的继承
protocol MyPrintable: CustomStringConvertible, CustomPlaygroundQuickLookable{

}

struct MyContent{
    var text : String
    var mycustomtext : String
}

extension MyPrintable {
    var customPlaygroundQuickLook: PlaygroundQuickLook{
        return PlaygroundQuickLook.text("默认高新园区")
    }
}

extension MyContent : MyPrintable{
    var description: String{
        return self.text
    }
}

let mycontent1 = MyContent(text: "内容", mycustomtext: "保留文字")
mycontent1.description

类专用协议:可以把协议限制在class类型(让结构体和枚举无法使用),加关键字class到协议继承列表的第一位
protocol OnleyForClass : class, CustomPlaygroundQuickLookable, CustomStringConvertible{

}

class Mytext : OnleyForClass
{
    var description: String{
        return "aa"
    }

    var customPlaygroundQuickLook: PlaygroundQuickLook{
        return PlaygroundQuickLook.text("AA")
    }
}


协议组合
protocol Ageable {
    var age : Int {get}

}

protocol Nameable{
    var name : String {get}
}

struct Student : Ageable, Nameable{
    var age: Int
    var name: String
}

struct Teacher: Ageable, Nameable{
    var age: Int
    var name: String
    var title : String
}

func wish(someone: Ageable & Nameable){
    print("祝", someone.name, someone.age, "生日快乐!")
}

let stu1 = Student(age: 10, name: "多多")
let teach1 = Teacher(age: 30, name: "mm", title: "小海")

wish(someone: stu1)
wish(someone: teach1)

协议检查和转换:使用is和as类型转换操作符来检查协议遵从与否,或转成特定的协议
protocol Slogan{
    var desc: String {get}
}

protocol Coder : Slogan{
    var name : String {get set}
}

struct JavaCode : Coder{
    var name: String
    var desc: String
    {
        return "666666"
    }
}

struct JSCode : Coder{
    var name: String
    var desc: String
    {
        return "88888"
    }
}

struct NewBie{
    var name : String
}

let java1 = JavaCode(name: "momo")
let js1 = JSCode(name: "xiaoke")
let new = NewBie(name: "jing")

let coders = [java1, js1, new] as [Any]

for coder  in coders {
    if let coder = coder as? Coder{
        print(coder.name,coder.name)
    }else{
        print("不是一个同类")
    }

    if let newbi = coder as? NewBie {
        print("你是菜鸟",newbi.name)
    }
}


相关文章

网友评论

      本文标题:swift学习~~~~

      本文链接:https://www.haomeiwen.com/subject/yhkymxtx.html