- 将下面的数组进行排序:
let fruits = [“apple”, “orange”, “pine”, “banana”]
let fruits = ["apple", "orange", "pine", "banana"]
let sortedFruits = fruits.sort(<)
print(sortedFruits)
- 找出下面数组中年龄大于20的人,并打印姓名:
let workers = [["name":"Zhangsan", "age":18],["name":"Lisi", "age":22],
["name":"Wangwu", "age":24],
["name":"Zhaoliu", "age":16]]
let workers = [
["name":"Zhangsan", "age":18],
["name":"Lisi", "age":22],
["name":"Wangwu", "age":24],
["name":"Zhaoliu", "age":16]
]
//struct(值类型): class(类)
//Int/Double: NSNumber
//String: NSString
//Array: NSArray/NSMutableArray
//Dictionary: NSDictionary/NSMutableDictionary
let result = workers.filter({
(w: [String:NSObject]) -> Bool in
if w["age"] as! Int > 20 {
return true
}
else {
return false
}
})
for w in result {
print(w["name"]!)
}
//简写
workers.filter({ $0["age"] as! Int > 20 }).forEach({
print($0["name"]!)
})
- 请编写代码判断以下数组中的元素是否唯一(没有重复数据):
let ids = [1, 9, 3, 7, 2, 3]
let ids = [1, 9, 3, 7, 2, 3]
for n in 0..<ids.count{
var flag = false
for i in (n+1)..<ids.count
{
if ids[n] == ids[i]
{
print( "该数组元素不唯一")
flag = true
break //结束所在的循环
}
}
if flag {
break
}
}
- 用map/filter/reduce将下面数组中小于60的分数挑出来,并连接成字符串,其中分数之间用逗号隔开:
let scores = ["30", "61", "59", "89", "99", "20"]
let scores = ["30", "61", "59", "89", "99", "20"]
//map: 转换类型
//filter: 过滤
//reduce: 合成一个
//forEach: 遍历
let r = scores.map({ Int($0)! }).filter({ $0 > 60 }).reduce("", combine: {
if $0 == "" {
return "\($1)"
}
return "\($0),\($1)"
})
print(r)
- 定义一个类表示圆,储存它的半径,需要使用时能够快速获取圆的面积,并能够知道半径改变的时机:
class Circle {
var radius: Double = 0 {
willSet {
print("\(radius) -> \(newValue)")
}
didSet {
print("改变完成")
}
}
var area: Double {
get {
return 3.14 * radius * radius
}
}
}
6.定义一个协议(protocol),里面包含一个printInfo的方法,然后让Int类型实现该协议(可以随便打印一些东西):
protocol X {
func printInfo()
}
//让一个已经存在的类型实现协议,只能通过extension
extension Int : X {
func printInfo() {
print("打印一些东西")
}
}
self:特指调用该方法的"对象"
typealias:给A类型起别名
typealias B = A