swift开源库iOS分享世界swift开发技巧

MG--Swift3.x进阶语法学习2

2017-03-14  本文已影响218人  Mg明明就是你
let myCustomViews = self.subViews.flatMap { 
          $0 as MyCustomView 
}
NSArray<MyCustomView *> *myCustomViews = (NSArray<MyCustomView *> *) [self.subViews filteredArrayUsingPredicate: [NSPredicate predicateWithBlock:^BOOL(id _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {                     
           return [evaluatedObject isKindOfClass:[MyCustomView class]];            
        }]
];



  • 1.数组的初始化

  • 2.进制转换>

String(12, radix: 16)   // 十进制转16进制
String(12, radix: 8)   // 十进制转8进制
String(12, radix: 2)   // 十进制转2进制
String(12, radix: 4)   // 十进制转4进制
进制转换结果
// 数字转化后的字母是否需要大小写 
 // str设置为“1 c”。如果你喜欢——即“1 C”。,大写
String(28, radix: 16, uppercase: true)  // 打印结果:"1C"
String(18, radix: 16, uppercase: true)  // 打印结果:"12"
// 字符串转化  (转换回一个整数——记住,可选!)
let int = Int("1C", radix: 16)          // 打印结果:28
其他进制的转化
let scores = [5, 3, 6, 1, 3, 5, 3, 9, 6] // 数组
let scoresSet = Set(scores)              // 集合,从打印结果看出不会重复,且集合是无序的
let uniqueScores = Array(scoresSet)      // 从集合中创建一个数组
数组和集合的转化
enum Color {
        case Unknown
        case Blue
        case Green
        case Pink
        case Purple
        case Red
}
enum Color {
            case Unknown, Blue, Green, Pink, Purple, Red
}
  • 创建一个结构体,有名字和color。它会自动生成构造方法

struct Boy {
        let name: String
        let color: Color
}
  - 如何使用:我们不需要使用UIColor. Pink,可以直接.Pink
let 明哥 = Boy(name: "明哥", color: . Green)
let 路西 = Boy(name: "My Girl Friend", color: . Purple)
它会自动生成构造方法 举个🌰
  • Raw values

enum Planet: Int {  // 枚举
            case Mercury = 1 ,Venus ,Earth ,Mars ,Unknown
}
let ttt = Planet.Earth.rawValue  // 是可选值,不一定有
let mars = Planet(rawValue: 4) ?? Planet.Unknown  // 打印Mars
let mars1 = Planet(rawValue: 7) ?? Planet.Unknown  // 打印Unknown 
  • 值得注意的是:枚举:如果枚举没有指定类型

enum Color {
             case Unknown, Blue, Green, Pink, Purple, Red
}
let pink = Color.Pink. rawValue   // 这样会报错,需改为Color.Pink. hasValue
  // 改为Color.Pink. hasValue == 打印出来的是3 // 从结果可以看出,也就是说默认会从0开头算起
改为Color.Pink. hasValue == 打印出来的是3
  • 枚举:指定是String类型

enum Color: String {
             case Unknown, Blue, Green, Pink, Purple, Red
}
MYColor.Pink.rawValue // 打印出来是"Pink"
枚举:指定是String类型


 let names = ["Dabitha", "Taylor", "Ahomas", "Ximothy", "Hobias", "Tyler"]    names.sorted()
    let numbers = [5, 3, 1, 9, 5, 2, 7, 8]
    let lowest = numbers.min() // 找出最小值1 
    let highest = numbers.max() // 找出最大值9
    numbers.sorted() //排序 
打印结果
let names = ["Dabitha", "Taylor", "Ahomas", "Ximothy", "Hobias", "Tyler"]
let sortNames = names.sorted {
        print("Comparing \($0) and \($1)")
        if ($0 == "Ximothy") {
            return true
        }  else {
            return $0 < $1
        }
}
print(sortNames)
数组排序
  • 操作符重载

struct Dog: Comparable {
        var breed: String
        var age: Int
}
func <(lhs: Dog, rhs: Dog) -> Bool {
        return lhs.age < rhs.age
}
func ==(lhs: Dog, rhs: Dog) -> Bool {
        return lhs.age == rhs.age
}
- ####控制器viewDidLoad()方法中
override func viewDidLoad() {
        super.viewDidLoad()
        let poppy = Dog(breed: "Poodle", age: 5)
        let rusty = Dog(breed: "Labrador", age: 2)
        let rover = Dog(breed: "Corgi", age: 11) 
        let dogs = [poppy, rusty, rover] 
        let newDogs = dogs.sorted()
        print("排序前:\(dogs)")
        print("=============") 
        print("排序后:\(newDogs)")
    }
打印结果
  • 数组的增加、删除和插入

let poppy = Dog(breed: "Poodle", age: 5)
let rusty = Dog(breed: "Labrador", age: 2)
let rover = Dog(breed: "Corgi", age: 11)
var dogs = [poppy, rusty, rover]
let beethoven = Dog(breed: "St Bernard", age: 8)dogs += [beethoven] // 拼接一个数组等价于dogs.append(contentsOf: [beethoven])
dogs.append(Dog(breed: "xiaohua", age: 3)) // 拼接一个元素
 let popDog = dogs.popLast()
print("打印popDog = \(popDog)")
let removeDog = dogs.removeLast()
print("打印removeDog = \(removeDog)")
- 打印删除.png
// newElement: 要插入的元素  at: 要插入的位置
// dogs.insert(<#T##newElement: Element##Element#>, at: <#T##Int#>)
dogs.insert(Dog(breed: "huazai", age: 4), at: 0)
let array2 = Array<Int>(1...1000000)
let array3 = ContiguousArray<Int>(1...1000000)
var start = CFAbsoluteTimeGetCurrent()
array2.reduce(0, +)   // 50500000
var end = CFAbsoluteTimeGetCurrent() - start
print("array Took \(end) seconds")
start = CFAbsoluteTimeGetCurrent()
array3.reduce(0, +)   // 50500000
end = CFAbsoluteTimeGetCurrent() - start
print("ContiguousArray  Took \(end) seconds")
打印时间,差不多是2倍.png


var set1 = Set<Int>([1, 2, 3, 4, 5]) // 5, 2, 3, 1, 4 集合的无序性和不重复性
var array1 = Array(set1) // 5, 2, 3, 1, 4
var set2 = Set(array1)   // 5, 2, 3, 1, 4
for number in set1 {
         print(number)  // 5, 2, 3, 1, 4
}
for number in set1.sorted() {
         print(number) // 1, 2, 3, 4, 5
}

奇怪的是Set有popFirst(),没有popLast(),而数组恰恰相反,我想知道Why?

let spaceships1 = Set(["Serenity", "Nostromo", "Enterprise"])
let spaceships2 = Set(["Voyager", "Serenity", "Executor"])
let union = spaceships1.union(spaceships2) // 并集
let intersection = spaceships1.intersection(spaceships2) // 交集
let difference = spaceships1.symmetricDifference(spaceships2) // 除交集以外的集合
两个集合.png 并集.png 交集.png 除交集以外的集合.png
• A.isSubsetOf(B): returns true if all of set A's items are also in set B.
• A.isSupersetOf(B): returns true if all of set B's items are also in set A.
• A.isDisjointWith(B): returns true if none of set B's items are also in set A.
• A.isStrictSubsetOf(B): returns true if all of set A's items are also in set B, but A and B are not equal
• A.isStrictSupersetOf(B): returns true if all of set B's items are also in set A, but A and Bare not equal
#### 翻译:####
•A.isSubset(of: B):返回true,A是B的子集,A和B是可以是一样的。
•A.isSuperset(of: B):返回true,A是B的父集, A和B是可以是一样的。
•A.isDisjoint(with:B):返回true,A子集的任何一个元素都不包含在B集合中。
•A.isStrictSubsetOf(B):返回true,A是B的子集,但A和B是不一样的,两者不能等价
•A.isStrictSupersetOf(B):返回true,如果A的所元素也在设置在B中,并且A元素中的个数小于B中元素的个数,也就是A和B是不一样的,两者不能等价
var spaceships1 = Set(["Serensdaity", "Nostromo", "Enterprise"])
let spaceships2 = Set(["Voyager", "Serenity", "Executor"])
let spaceships = Set(["Voyager", "Serenity"])
spaceships.isSubset(of: spaceships2)        // true
spaceships.isSuperset(of: spaceships2)      // false
spaceships1.isDisjoint(with: spaceships2)   // trues
paceships.isStrictSubset(of: spaceships2)   // true
spaceships.isSuperset(of: spaceships2)      // false
结果图.png
let spaceships1 = Set(["Serenity", "Nostromo", "Enterprise"])
let spaceships2 = Set(["Voyager", "Serenity", "Star Destroyer"])
let spaceships3 = Set(["Galactica", "Sulaco", "Minbari"])
let spaceships1and2 = spaceships1.union(spaceships2)
spaceships1.isSubsetOf(spaceships1and2)         // true
spaceships1.isSubsetOf(spaceships1)             // true
spaceships1.isSubsetOf(spaceships2)             // false
spaceships1.isStrictSubsetOf(spaceships1and2)   // true
spaceships1.isStrictSubsetOf(spaceships1)       // false
spaceships1and2.isSupersetOf(spaceships2)       // true
spaceships1and2.isSupersetOf(spaceships3)       // false
spaceships1and2.isStrictSupersetOf(spaceships1) // true
spaceships1.isDisjointWith(spaceships2)         // false
var spaceships = ["Serenity", "Nostromo", "Enterprise"]
spaceships += ["Voyager", "Serenity", "Star Destroyer"]
spaceships += ["Galactica", "Sulaco", "Minbari"]
let countedSet = NSCountedSet(array: spaceships)
print(countedSet.count(for: "Serenity")) // 2,虽然不会重复出现,但是他可以统计到出现了几次
print(countedSet.count(for: "Sulaco"))   // 1
打印截图.png
扫一扫,关注我.jpg
上一篇 下一篇

猜你喜欢

热点阅读