1. Grammar points are verified using playfround. Xcode ->new->playground
import UIKit
var str = "Hello, playground"
/ / 1. Never, use guard
func myFatalError(a) -> Never {
print("!!!")
fatalError(a)// Failed to force termination
}
func mod(_ a: Int._ b: Int) -> Int {
guard b ! = 0 else {
myFatalError()
}
return a%b
}
//mod(a: 2, b: 0)
mod(2.3)
// 2. Implicitly selectable. Variables can carry nil, but normally should not carry nil
let a: Int! = 5
let b = a // b is Int?
let c: Int = a
let d = a + 0 // d is Int
#keyPath,forKeyPath
let superviewColor = #keyPath(UIView.superview.backgroundColor)
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
view.backgroundColor = UIColor.blue
view.addSubview(label)
// The value can be evaluated in either of the following ways
label.value(forKeyPath: superviewColor)
label.superview?.backgroundColor
// 4. Index obtains the key value
let arr = [10.20.30.40.50]
let i = arr.startIndex
let next = arr.index(after: i)
let before = arr.index(before: next)
let j = str.startIndex
let k = str.index(j, offsetBy: 5) // k = 5
str[k]
str[j..<k]
// 5. Define generic types, subclasses or protocol.pi to use
func square<T: FloatingPoint> (_ a: T) -> T { // T specifies the generic type
return (a).squareRoot()
}
let a: CGFloat = 4.0
let b: Float = 4.0
let d: Double = 4.0
square(a)
square(b)
square(d)
a * .pi
b * .pi
d * .pi
// 6
func findMin<T: FloatingPoint> (_ a: [T]) -> T? {
var res = T.infinity
for i in a {
res = i < res ? i : res
}
return res
}
findMin([3.4.5.-1.-4])
// 7.nan(not a number)
let myNan = Double.nan;
myNan > 0
myNan < = 0
if myNan.isZero {
print("nan")
}
myNan.isNaN
// 8. Trailing closure,map,?? Null conjunction operator
let arr = ["12"."16"."15"."no data"."19"."no data"."18"]
let temp = arr.map { Double($0) ?? .nan }
let temp1 = temp.filter { !$0.isNaN }
temp1
// 9. Custom infix operator?? , generic, @atuocloSure automatic closure
infix operator ?????
//func ???
(option: T? , defaultValue:() -> T) -> T {
func ????? <T>(option: T? , defaultValue:@autoclosure() - >T) - >T {
if let value = option {
return value;
}
return defaultValue();
}
func login(a) -> String? {
print("login...")
return nil;
}
// Parameter default value, force unpack (a!)
func loginGuest(_ a: String? = "bbb") -> String{
print("guest...\(a!)")
return "aaa"
}
//let flag = login() ??? "guest"
//let flag = login() ??? {"guest" }
let flag = login() ????? loginGuest()
// 10. Where 3.0 is removed, guard is specified
let vector = (4.0)
if case (let x, 0) = vector , x > 2 && x < 5 {
print("success")}func doMath(a: Int? .b: Int? .c: Int?). -> Int? {
guard let a = a, let b = b, let c = c,
a>0,b<0,c= =0 else {
return nil
}
return 0
}
//// 11. < Custom array comparison function
func <(t1: (Int.Int),t2: (Int.Int)) -> Bool {
print("score1 < score2")
return true;
}
let score1 = (23.10)
let score2 = (23.11)
score1 < score2
// 12. forin,[starIndex...] , the where, switch, value binding, fallthrough, continue to break, label jump
let numbers = [100.1.2.3.5.-10.-2]
var sum = 0
outer: for num in numbers[1.] where num > 0 {
switch num {
case let x where x = = 1:
sum + = num
continue // Continue the for loop
case let x where x = = 2:
fallthrough // Proceed with next case. If not, jump out of switch
case let x where x = = 3:
continue;
default:
break outer; / / out of the outer
}
sum + = num;
}
print("\(sum)")
// 13.inout uses address passing
var number = 10
func add(_ num: inout Int) {
num = 11
}
add(&number)
// 14. Function overloading -> Parameter name related. Print is independent of the return argument
func sum(_ :Int ,_ : Int){}func sum(a:Int ,b: Int){}func sum(a:Int , b: Int._: Int){}func sum(c: String...). {
// for item in c {
// print(item, separator: " ", terminator: "\t")
/ /}
print(1.0.2.0.3.0.4.0.5.0, separator: "...", terminator: "\n")
}
sum(1.3)
sum(a: 1, b: 3)
sum(a: 1, b: 3.4)
sum(c: "12"."34"."56")
// 15. Nested functions
func forward(_ forward: Bool)- > (Int) - >Int {
func next(_ input: Int) -> Int {
return input + 1
}
func previous(_ input: Int) -> Int {
return input - 1
}
return forward ? next : previous;
}
forward(true) (5)
forward(false) (5)
Enum Basic usage, associated value, original value
enum Direction {
case north
case south
case east
case west
}
//enum Direction {
// case north, south, east, west
/ /}
var dir = Direction.north
dir = Direction.west
dir = .east
print(dir)
enum Score {
case points(Int)
case grade(Character)}var score = Score.points(12)
//score = .grade("A")
let i = 0
switch score {
case let .points(i):
print(i,"points")
case let .grade(i):
print("grade",i)
}
/ / associated values
enum Date {
case digit(year: Int, month: Int, day: Int)
case string(String)}var date = Date.digit(year: 2020, month: 10, day: 26)
//date = .string("2020-10-26")
switch date {
case .digit(let year, let month, let day):
print(year,month,day,separator:"/")
case let .string(value):
print(value)
}
/ / the original value
enum Direction : String {
case north = "north1"
case south = "south1"
case east = "east1"
case west = "west1"
}
print(Direction.north.rawValue)
print(Direction.south.rawValue)
enum Direction1 : Int {
case north = 1
case south
case east = 5
case west
}
print(Direction1.north.rawValue)
print(Direction1.east.rawValue)
print(Direction1.west.rawValue)
// recursive ji
indirect enum ArithExpr {
case number(Int)
case sum(ArithExpr.ArithExpr)
case diff(ArithExpr.ArithExpr)}enum ArithExpr {
case number(Int)
indirect case sum(ArithExpr.ArithExpr)
indirect case diff(ArithExpr.ArithExpr)}func calculate(_ expr: ArithExpr) -> Int {
switch expr {
case let .number(value):
return value
case let .sum(left , right):
return calculate(left) + calculate(right)
case let .diff(left, right):
return calculate(left) - calculate(right)
}
}
let five = ArithExpr.number(5)
let four = ArithExpr.number(4)
let two = ArithExpr.number(2)
let sum = ArithExpr.sum(five, four)
let diff = ArithExpr.diff(five, two)
calculate(sum)
calculate(diff)
Copy the code