swift5.0 记录(1)
2021-05-24 本文已影响0人
rhc2008
import UIKit
//1
func minMax(array:[Int]) -> (min:Int,max:Int)? {
if array.isEmpty {//!!! array is empty
return nil
}
var min = array[0]
var max = array[0]
for value in array{
if value < min {
min = value;
}
if value > max {
max = value
}
}
return (min,max)
}
//if let minMax = minMax(array:[1,2,3,4,5]) {
// print("min is\(minMax.min),max is\(minMax.max)")
//}
//2.inout
var number = 10;
var another = 8
func swap(_ a:inout Int, _ b:inout Int) {
let t = a
a = b
b = t
}
//!!! no return value: ->()
let call : (inout Int, inout Int) -> () = swap
call(&number,&another)
//print(number,another)
//3. container function
func step(backward :Bool) ->(Int) ->Int {
func stepForward(step:Int) -> Int { return step + 1 }
func stepBackward(step:Int) -> Int { return step - 1 }
return backward ? stepBackward:stepForward
}
var step = -4
let stepCall = step(backward: step>0)
while step != 0 {
step = stepCall(step)
}
//print(step)
// 4.callParamters
func callParamters(a:Int) ->Int {
return a
}
func res(_ callback : (Int) -> Int, _ a:Int) {
print(callback(a))
}
//res(callParamters,1)
// 5.clouse
func makeIncreamenter(p:Int)-> () -> Int {
var to = 0
func increamenter() -> Int {
to += p
return to
}
return increamenter
}
let increateBy10 = makeIncreamenter(p: 10)
//print(increateBy10())//
var providers:[() -> String] = []
func customerProvider1(provider:@autoclosure @escaping() -> String) {
providers.append(provider)
}
func customerProvider2(provider: @escaping() -> String) {
providers.append(provider)
}
//?????
func customerProvider3(provider: @autoclosure() -> String) {
//providers.append(provider)
provider()
}
var names = ["a","b"];
customerProvider1(provider: names.remove(at: 0))
customerProvider2(provider: {names.remove(at: 0)})
//customerProvider3(provider: names.append("c"))
class clouseClass {
var x:String = "he"
func dosth() {
customerProvider1(provider: self.x) //
customerProvider3(provider: x)
}
}
//6.
let data = [1,1,2,3,5,8]
let nullData:[String?] = ["a",nil,"bi"]
//print(data.map {$0 * 10})
//print(data.filter({$0 > 4}))
//print(data.reduce(100) {$0 + $1 })
//print(nullData.compactMap( {$0} ))
//7. the link of program
let words = """
there are moments in life when you miss someone so much that u want to pick them from your
"""
let NON_WRODS = ["a","of","and","the","on"]
func wordkFrep(words:String) ->[String:Int] {
var wordDict:[String:Int] = [:]
let wordList = words.split(separator: " ")
wordList.map{$0.lowercased()}
.filter{!NON_WRODS.contains($0)}
.forEach{ wordDict[$0] = (wordDict[$0] ?? 0) + 1}
return wordDict
}
//print(wordkFrep(words: words))
let employe = ["neal","s","j","rich"]
func clearNames(names:[String]) -> String {
var joinedNames = ""
for name in names {
if name.count > 1 {
joinedNames += name.capitalized + ","
}
}
joinedNames.remove(at: joinedNames.index(before: joinedNames.endIndex))
return joinedNames
}
let result = employe.filter{$0.count > 1}
.map{$0.capitalized}
.joined(separator: ",")
//print(result)
// 并行,线程不安全
extension Array where Element:Any {
public func concurrentMap<T>(_ transform:(Element) -> T) -> [T] {
let n = self.count
if n == 0{
return []
}
var result = Array<T>()
result.reserveCapacity(n)
DispatchQueue.concurrentPerform(iterations: n) { (i) in
result.append(transform(self[i]))
}
return result
}
}
let result1 = employe.filter{$0.count > 1}
.concurrentMap{$0.capitalized}
.joined(separator: ",")
//print(result1)
//8 enum
//CaseIterable 可遍历
enum CompassPoint:CaseIterable {
case south
case north
case east
case west
}
//print(CompassPoint.allCases)
//print(CompassPoint.allCases.count)
//let direction = CompassPoint.west
//switch direction {
//case .south:print("s")
//case .north:print("n")
//case .east:print("e")
//case .west:print("w")
//}
//预设值
enum CompassPoint_v2:Int {
case south = 5
case north
case east
case west
static subscript(index:Int) -> CompassPoint_v2 {
get {
return CompassPoint_v2(rawValue:index) ?? south
}
}
}
let dir = CompassPoint_v2(rawValue: 9)
//print(CompassPoint_v2[2])
//print(dir)
enum ControlCharacter:String {
case tab = "\t"
case line = "\n"
}
//print(ControlCharacter.tab.rawValue)
//print(ControlCharacter.tab)
// 关联值
enum Barcode {
case upc(Int,Int,Int ,Int)
case qrCode(String)
}
var code = Barcode.upc(1, 2, 3, 4)
code = .qrCode("abce")
////print(code)
//switch code {
//case .upc(let a, let b, let c, let d):
// print("upc:\(a) \(b) \(c) \(d)")
//case.qrCode(let codeString):
// print("codeString:\(codeString)")
//}
// 递归 (1+3) * 4
indirect enum ArithmethicExpression {
case number(Int)
case add(ArithmethicExpression,ArithmethicExpression)
case mutilply(ArithmethicExpression,ArithmethicExpression)
}
let first = ArithmethicExpression.number(1)
let second = ArithmethicExpression.number(3)
let add = ArithmethicExpression.add(first, second)
let third = ArithmethicExpression.number(4)
let muliply = ArithmethicExpression.mutilply(add, third)
//print(multiply)
func eval(_ expression : ArithmethicExpression) -> Int {
switch expression {
case .number(let value):
return value
case .add(let left,let right ):
return eval(left) + eval(right)
case .mutilply(let left ,let right ):
return eval(left) * eval(right)
}
}
//print(eval(muliply))
//9 下标
struct Matrix {
let rows:Int
let coulmns :Int
var grid:[Double]
// grid[2,2] => [0,0,0,0]
init(rows:Int,columns:Int) {
self.rows = rows
self.coulmns = columns
grid = Array(repeating: 0, count: rows * columns)
}
subscript(row:Int,column:Int) -> Double {
get{
return grid[row * coulmns + column]
}
set {
grid[row * coulmns + column] = newValue
}
}
}
var matrix = Matrix(rows: 2, columns: 2)
matrix[0,0] = 9
matrix[1,1] = 8
// Matrix(rows: 2, coulmns: 2, grid: [9.0, 0.0, 0.0, 8.0])
//print(matrix,matrix[0,0])
// 10 class
class Person {
var age:Int
var name :String
init(name:String,age:Int) {
self.name = name
self.age = age
}
convenience init(age:Int) {
self.init(name:"[unnamed]",age:age)
}
}
class Teacher:Person {
var salary:Int
init(name:String,age:Int,salary:Int) {
self.salary = salary //!!! 放前面
//test() //!!! 'self' used in method call 'test' before 'super.init' call
//self.name = self.name + "teacher" //!!! 'self' used in property access 'name' before 'super.init' call
super.init(name: name, age: age)
test()
self.name = self.name + "teacher"
// self.salary = salary //!!! Property 'self.salary' not initialized at super.init call
}
// 重写了父类所有的指定初始化构造器,那么便利初始化器会被继承下来
override init(name:String,age:Int) {
self.salary = 5000
super.init(name: name, age: age)
}
convenience init(salary:Int) {
// self.salary = salary //!!! self' used before 'self.init' call or assignment to 'self'
self.init(name:"jack",age:20,salary:salary)
self.salary = salary
}
func test() {
print("test")
}
}
class Student:Person {
// 子类没有任何指定初始化器,就继承父类的指定初始化器
func test(){
}
}
// 必要初始化器,可失败初始化器
class Animal {
var sex:Int
var age :Int
required init(sex:Int) {
self.sex = sex
self.age = 0
}
init?(sex:Int,age :Int) {
if age > 200 {
return nil
}
self.age = age
self.sex = sex
}
}
//
class Men:Animal{
var height:Int
init(age:Int){
self.height = age
super.init(sex: 0)
}
required init(sex: Int) {
self.height = 10
super.init(sex: sex)
}
}
//var techer = Teacher(age: 20) //注掉:override init(name:String,age:Int) No exact matches in call to initializ
//techer = Teacher(name: "", age: 1)
//var stu = Student(age: 0)
//var men = Men(sex:0)
//var animal = Animal(sex: 0,age: 300);
// 继承 override
class Vehicle {
var currentSpeed:Int = 0
// 计算属性
var desc:String {
return "run at speed \(currentSpeed)"
}
// static 类型属性.对于类类理的计算类型属性,可以使用class关键字来许子类重写父类的实现
static var circle:Int {
return 100
}
class var pps:String {
return "100"
}
func makeNoise(){}
}
class Car:Vehicle {
var gear:Int = 0
override var desc: String {
return super.desc + "at gear \(gear)"
}
var circle:Int {
return 10
}
var pps:String {
return ""
}
}
//let array = [Vehicle(),Car()]
//print(type(of: array)) //Array<Vehicle>
//for item in array { // as 向下类型转换
// if let obj = item as? Car {
// print(obj.circle)
// }
//}
//11 extension
//可以向一个类型添加新的方法,但是不能重写已有的方法
// 添加计算属性
extension Double {
var km:Double {
return self / 1000.0
}
}
//let speed:Double = 12000.0
//print(speed.km)
//添加方法
extension Int {
func repeatTask(_ task:()->()) {
for _ in 0..<self {
task()
}
}
}
//3.repeatTask {
// print("hello")
//}
// 添加下标
extension Int {
subscript(digitIndex :Int ) ->Int {
get {
var base = 1
for _ in 0..<digitIndex {
base *= 2
}
return (self / base) * 10
}
}
}
//print(10[2])
// 添加内嵌类型
extension Int {
enum Kind{
case zero
case negative
case positive
}
var kind:Kind {
get {
switch self {
case 0:
return .zero
case let x where x > 0:
return .positive
default:
return .negative
}
}
}
}
//print(0.kind,8.kind,(-1).kind)
// 12 协议
protocol Named {var name:String{get}}
protocol Aged {var age:Int{get}}
struct People:Named,Aged {
var name:String
var age:Int
}
let p = People(name: "jack", age: 11)
func wish(to:Named & Aged) {
print("name \(to.name) age \(to.age)")
}
//wish(to: p)
protocol TextRepresentable {
var desc:String {get}
}
extension People:TextRepresentable {
var desc:String {
return "name \(name) age \(age)"
}
}
//print(p.desc)
//extension Array:TextRepresentable where Element:TextRepresentable {
// var desc:String {
// let itemDesc = self.map{$0.desc}
// return itemDesc.joined(separator: ",")
// }
//}
//let arr = [People(name: "zhang", age: 1),People(name: "lisi", age: 3)]
//print(arr.desc)
// 扩展协义本身
extension Collection where Iterator.Element:TextRepresentable {
var desc:String {
let itemDesc = self.map{$0.desc}
return itemDesc.joined(separator: ",")
}
}
let arr1 = [People(name: "zhang", age: 1),People(name: "lisi", age: 3)]
//print(arr1.desc)
func firstIndex<T:Equatable>(of valueToFind:T, in array:[T]) -> Int? {
for (index,value) in array.enumerated() {
if value == valueToFind { // confirm to Equatable
return index
}
}
return nil
}
let st = ["zhangsan","lisi","wang"]
print(firstIndex(of: "lisi", in: st) ?? "")