• swift学习笔记5


    五、集合

    数组

    1、泛型 Array<类型>

    2、简化[类型]

    var myAr:Array<String>

    var names:[String]

    myArr = Array<String>()

    names = Array<String>(count:10,repeatedValue:"heri")

    nums = Array<Int>(count:100,repeatedValue:0)

    var values = ["2","3","4","o"]

    println(names[1])

    name[0]="spring"

    for var i=0;i <values.count;i++

    {
    println(values[i])

    }

    for v in values

    {
    println(v)

    }

    添加元素

    var languages = ["swift"]

    languages.append("Go")

    languages +=["Ruby"]

    插入元素

    languages.insert("R",atIndex:0)

    let subRange = languages[1..<4]

    languages[2...4] = ["c++","php"]

    清空

    languages[0..<languages.count] = []

    删除

    languages.removeAtIndex(2)

    languages.removeLast()

    languages.removeAll()

    字典

    1、泛型 

    2、简化

    var myDict : Dictionary<String,String>

    var health:[String,String]

    构造器

    myDict = Dictionary<String,String>()

    health = ["身高":"180","体重":"70","血压":"90/120"]

    读取 var height = health["身高"]

    var emptyDict :[String:Double]=[:]

    health["体重"]= 80

    添加新的key - value对

    var result = health.updateValue("50",forkey:"腰围")

    desc 默认代表 value

    var seasons = ["spring":"春暖花开","summer":"夏日炎炎"]

    for (season,desc)in seasons

    {

    println("(season) -->(desc)")

    }

    var keys = Array(seasons.keys)

    var values = Array(seasons.values)

    删除

    var languages = ["swift":900,"php":340,"oc":48]

    languages.removeValueForKey("php")

    languages["oc"]=nil

    languages.removeAll()

    实战例子: 记录字符串中每个字符出现的次数,并且对比哪个出现最多

    let str = "renhairui is a best man xhahahaxxxxx"

    var status :[Character:Int] =[:]

    for ch in str

    {

    if num !=nil

    {

    var num = status[ch]

    status[ch] = num! +1

    }else{

    status[ch] = 1

    }

    }

    println(status)

    var maxOccurs = 0

    for occurs in Array(status.values)

    {

    if occurs >maxOccurs

    {

    maxOccurs = occure

    }

    for (ch,occurs)in status

    {

    if occurs == maxOccurs

    {

    println("出现最多的字符:(ch),出现次数:(occurs)次")

    }

    }

    }

  • 相关阅读:
    物联网市场碎片化严重 物联网网关设计挑战重重
    物联网市场碎片化严重 物联网网关设计挑战重重
    物联网市场碎片化严重 物联网网关设计挑战重重
    越做越大的行李寄存生意,老板竟是3个95后
    互联网人失业理由排行榜,每一个都戳破职场真相
    读小说赚钱吗?这个年入百万
    BI驾驶舱的必备知识
    2019开源BI软件排行榜
    主流的开源bi工具
    企业为什么需要BI决策系统?
  • 原文地址:https://www.cnblogs.com/heri/p/4471498.html
Copyright © 2020-2023  润新知