码迷,mamicode.com
首页 > 编程语言 > 详细

Swift 5.X——Array

时间:2019-11-09 15:42:49      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:import   ios   ble   tin   替换   uikit   bool   app   index   

1.数组的基本操作

import UIKit

var a:[Int] = [1,2,3,4]
print(a)//[1, 2, 3, 4]
for index in 0..<a.count{
    print(a[index])//1234
}

var b = ["hello","world","123"]//涉及到类型推断
print(b)//["hello", "world", "123"]
b+=["iOS","MacOS"]//字符串的拼接
print(b)//["hello", "world", "123", "iOS", "MacOS"]
b.insert("apple", at: 1)//字符串的插入
print(b)//["hello", "apple", "world", "123", "iOS", "MacOS"]
print(b.contains("hello"))//true。元素的查找
b.replaceSubrange(0...1, with: ["123","456"])//元素替换
print(b)//["123", "456", "world", "123", "iOS", "MacOS"]
b.remove(at: 0)//元素的删除
print(b)//["456", "world", "123", "iOS", "MacOS"]

var c:Array<Double> = [1.1,2.2,3.3]//范型为Double
print(c)//[1.1, 2.2, 3.3]
c[0] = 5.5//元素的修改
print(c)//[5.5, 2.2, 3.3]
c.append(6.6)
print(c)//[5.5, 2.2, 3.3, 6.6]

var d = Array(repeating: -1, count: 3)
print(d)//[-1, -1, -1]  

2.数据的排序

import UIKit

var a = [1,2,3,4,5,6]
a.sort(by: {(s1,s2)->Bool in
    if (s1>s2) {
        return true
    }else{
        return false
    }
})
print(a)//[6, 5, 4, 3, 2, 1]。元素的倒序排列

var b = [1,3,2,7,5]
b.sort()//数据的元素排序
print(b)//[1, 2, 3, 5, 7]

3.数组的过滤

import UIKit

var a = [1,2,3,4,5,6]
var b = a.filter({(item)->Bool in
    if (item != 3) {
        return true//
    }else{
        return false
    }
})
print(a)//[1, 2, 3, 4, 5, 6]
print(b)//[1, 2, 4, 5, 6]

4.数组的比较

import UIKit

var a = [1,2,3]
var b = [1,2,3]
var c = [4,5,6]
print(a==b)//true
print(a==c)//false

  

Swift 5.X——Array

标签:import   ios   ble   tin   替换   uikit   bool   app   index   

原文地址:https://www.cnblogs.com/yangyh26/p/11826038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!