learn swift grammar

common

import Foundation
typealias i8 = Int8
typealias i16 = Int16
typealias i32 = Int32
typealias i64 = Int64
typealias isize = Int
typealias u8 = UInt8
typealias u16 = UInt16
typealias u32 = UInt32
typealias u64 = UInt64
typealias usize = UInt
typealias f32 = Float
typealias f64 = Double
typealias char = Character
typealias string = String
typealias Option = Optional
typealias bool = Bool
typealias Codable = Decodable & Encodable
typealias Debug = CustomDebugStringConvertible
typealias VecDeque = BidirectionalCollection
typealias Vec = Collection
public enum Results<T> {
case OK(T)
case Err(T)
}
public enum Err: Error {
case notEqual(String)
}
func assertEqual<T:Equatable>(_ result1:T,_ result2:T)->Result<String,Error>{
if result1 == result2 {
return Result.success("expected \(result1) found \(result2)")
}else{
return Result.failure(Err.notEqual("expected \(result1) found \(result2)"))
}
}
func assertEq<T:Equatable>(_ result1:T,_ result2:T){
let result = assertEqual(result1,result2)
switch result {
case .success:
print("\(result)")
break
case .failure:
print("\(result)")
break
}
}
// assertEq(threeSum([-1, -1, -1, -1, 2, 1, -4, 0], target: 0),[[-1, -1, 2], [-1, 0, 1]])

basic

// Number
var int = 10
var float = 12.15
//Boolean
var have = true
var have_not = false
//print type of value
var numberOfPets = 4
print(type(of: numberOfPets))
var numberOfPetsDouble: Double = 4
print(type(of: numberOfPetsDouble))
var inchesDouble = 4.1243
print(type(of: inchesDouble))
var inchesFloat: Float = 4.1243
print(type(of: inchesFloat))
// String
var hstr = "hello world "
hstr.append("to the world")// push
//convert number to string by radix
let s0 = String(1635999) // returns "1635999"
let s1 = String(1635999, radix: 10) // returns "1635999"
let s2 = String(1635999, radix: 2) // returns "110001111011010011111"
let s3 = String(1635999, radix: 16) // returns "18f69f"
let s4 = String(1635999, radix: 16, uppercase: true) // returns "18F69F"
let s5 = String(1635999, radix: 17) // returns "129gf4"
let s6 = String(1635999, radix: 36) // returns "z2cf"
print("s3:\(s3)")
//String start_with,end_with
let is_start_with = "/demo".hasPrefix("/")
let is_end_with = "demo/".hasSuffix("/")
let long_string = """
is_start_with /:\(is_start_with)
is_end_with /:\(is_end_with)
"""
print(long_string)
//push string
var s7 = ""
s7.write("write") //like rusts push_str()
s7.append("append ") //like rusts push_str()
s7.append("🌍") //like rusts push() char
print("s7:\(s7)")
//slice string get prefix 前面的元素
var ss7 = s7.prefix(1)
print("ss7:\(ss7)")
//slice string get suffix 后面的元素
var ss8 = s7.suffix(1)
print("ss8:\(ss8)")
//split string
print("\(s7.split(separator: " "))") //["writeappend", "🌍"]
print("\(s7.split(separator: " ",maxSplits:0))") //["writeappend"]
print("\(s7.split(separator: " ",omittingEmptySubsequences:false))")  //["writeappend", "🌍"] 不省略空
let s8 = "Hello!"
let bytes = s8.utf8CString
print(bytes)// Prints "[72, 101, 108, 108, 111, 33, 0]"
// reverse string
let w = "Backwards"
for char in w.reversed() {
print(char, terminator: "")
}
var ns1 = String("demo")
let numbers = 0...9
let shuffledNumbers = numbers.shuffled()
print("\(shuffledNumbers)")
//Array
var emptyAray = [String]()
var names = ["John", "Sansa", "Theon", "Jaime"]
names.insert("Varys", at: 2) //insert
names.append("Robb") //push back
names.remove(at: 3) //remove at index of 2
let words = ["apple", "orange", "banana"]
print("\(words.count)")
let new_names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = new_names.randomElement()!
let str = words.joined(separator:" : ")//json array to string
//Dictionaries
var emptyDict = [Int:Double]()
var capitalCities = ["Russia":"Moscow",
"Canada": "Ottawa", "France": "Paris"]
capitalCities["Germany"] = "Berlin"
capitalCities["Canada"] = "Toronto"
print(capitalCities)
for city in capitalCities{
print("The capital city of \(city.key) is \(city.value).")
}
//if else
var n = 10;
if n<9{
print(n);
}
else if n==10{
print("is \(10)");
}
else {
}
//simplified ifelse statement
let age = 25
let haveCar = age>28 ? true:false
print("have \(haveCar)")
//swich
var country = "Sweden"
switch country {
case "Germany":
print("This country is in Europe")
case "Sweden":
print("This country is in Europe")
case "USA":
print("This country is in North America")
case "India":
print("This country is in Asia")
case "Egypt":
print("This country is in Africa")
default:
print("Sorry i don't know the continent of this country")
}
let testscore = 80
var grade:Character
switch testscore {
case 90...100:
grade = "优"
case 80..<90:
grade = "良"
case 60..<80:
grade = "中"
case 0..<60:
grade = "差"
default:
grade = "无"
}
print("Grade = \(grade)")
// Loop
//for in loop
let listOfNames = ["John", "Sansa", "Theon","Jaime", "Robb", "Thyrion"]
for name in listOfNames {
print("listOfNames:\(name)")
}
//while loop
var startValue = 1
let endValue = 10
while startValue <= endValue {
print("startValue \(startValue)")
startValue += 1
}
//repeat-while-loop
var m = 2
repeat{
m*=2
}while m<10
print("m is: \(m)")
//Function
func ourFirstFunction() {
print("I love Swift!")
}
ourFirstFunction()
func sayHi(from name:String){
print("Hi \(name)")
}
func sayHi1(name:String){
print("Hi \(name)")
}
sayHi(from:"Andrew")
sayHi1(name:"Andrew")
func doubleTheInput(inputValue: Int) -> Int {
return inputValue*2
}
print("Double the input:\(doubleTheInput(inputValue:5))")
// Classes
class Car {
let horsepower = 100
let color = "red"
var numberOfCarDoors = 4
}
let myCar = Car()
// myCar.colour = "blue" //will error because let means that is constant value
myCar.numberOfCarDoors = 6
print("my car numberOfCarDoors :\(myCar.numberOfCarDoors)")
class NewCar {
let horsepower:Int
let color:String
let numberOfCarDoors:Int
init(horsepower: Int, color: String,numberOfCarDoors: Int) {
self.horsepower = horsepower
self.color = color
self.numberOfCarDoors = numberOfCarDoors
}
func engineOn() {
print("Engined turned on.")
}
func engineOff() {
print("Engine turned off.")
}
}
let myNewCar = NewCar(horsepower: 120, color:"green", numberOfCarDoors: 4)
print("my new car horsepower:\(myNewCar.horsepower)")
myNewCar.engineOn()
myNewCar.engineOff()
//Class Inheritance (对象继承)
class Person {
var firstName: String
var lastName: String
init(firstName: String, lastName: String){
self.firstName = firstName
self.lastName = lastName
}
func greetings() {
print("Hi, my name is \(firstName) \(lastName)!")
}
}
//Employee 继承Person class
class Employee: Person {
var staffNummer: Int
init(staffNummer: Int, firstName: String,lastName: String) {
self.staffNummer = staffNummer
super.init(firstName: firstName,lastName: lastName)//继承必须使用super.init()类初始化父类
}
func identity() {
print("First name \(firstName), Lastname \(lastName), Staff Number \(staffNummer)")
}
}
let christine = Employee(staffNummer: 780,firstName: "Christine", lastName: "Mayer")
christine.greetings() //调用父类的方法
christine.identity() //调用自己的方法
//Class overriding 重载 (替换父类的方法)
class Student:Person {
var stuId:String
init(stuId:String,firstName:String,lastName:String) {
self.stuId = stuId
super.init(firstName:firstName,lastName:lastName)
}
func sayStuId(){
print(stuId)
}
// overriding greetings
override func greetings() {
print("Hello, how are you?") //We override the function of the superclass
}
}
let ryan = Student(stuId:"1820012",firstName:"Andrew",lastName:"Ryan")
ryan.sayStuId()
ryan.greetings()
//Optionals 跟Rust的Option 一样
var ourFirstOptional: Int?
ourFirstOptional = 4
if let insideValue = ourFirstOptional { //just like rusts if let statement
print(insideValue)
} else {
print("Optional contains nil")
}
var studentOptional:Student?;
studentOptional?.sayStuId() //Nothing will happen
studentOptional?.greetings()//Nothing will happen
studentOptional = Student(stuId:"1820012",firstName:"Andrew",lastName:"Ryan")
studentOptional?.sayStuId() //will print id
//implment stack
struct Stack<T> : ExpressibleByArrayLiteral, CustomDebugStringConvertible {
var debugDescription: String {
get {
return "Stack: \(storage)"
}
}
typealias Element = T
private var storage: [T] = []
public init(arrayLiteral elements:Element...) {
self.storage = elements
}
mutating func push(_ item:T) {
storage.insert(item, at: 0)
}
mutating func pop() -> T? {
guard storage.count > 0 else { return nil }
return storage.remove(at: 0)
}
}
//栈 先进后出
var stack = Stack<i8>()
for i in 0...5{
stack.push(i8(i))
}
print("pop from stack:\(stack.pop()!)")
print("\(stack)")
learnArgument()
learnInput()
learnDir()
learnJSON()
learnTime()
learnSets()
learnResult()

learnArgument

import Foundation
// get arguments
func learnArgument(){
let args = CommandLine.arguments
if args.count != 2 {
print("Usage: cmd")
} else {
let name = args[1]
print("Name: \(name)")
}
}

learnInput

import Foundation
/// Inputs
var cin: String {
readLine()!
}
var cinArray: [Character] {
Array(cin)
}
extension String {
func str2(separator: Character = " ") -> (String, String) {
let a = split(separator: separator).map { String($0) }
precondition(a.count == 2)
return (a[0], a[1])
}
func strs(separator: Character = " ") -> [String] {
split(separator: separator).map { String($0) }
}
func int() -> Int {
guard let v = Int(self) else {
fatalError()
}
return v
}
func int2(separator: Character = " ") -> (Int, Int) {
let a = split(separator: separator).map { Int($0)! }
precondition(a.count == 2)
return (a[0], a[1])
}
func int3(offset: Int = 0, separator: Character = " ") -> (Int, Int, Int) {
let a = split(separator: separator).map { Int($0)! + offset }
precondition(a.count == 3)
return (a[0], a[1], a[2])
}
func int4(separator: Character = " ") -> (Int, Int, Int, Int) {
let a = split(separator: separator).map { Int($0)! }
precondition(a.count == 4)
return (a[0], a[1], a[2], a[3])
}
func int5(separator: Character = " ") -> (Int, Int, Int, Int, Int) {
let a = split(separator: separator).map { Int($0)! }
precondition(a.count == 5)
return (a[0], a[1], a[2], a[3], a[4])
}
func int6(separator: Character = " ") -> (Int, Int, Int, Int, Int, Int) {
let a = split(separator: separator).map { Int($0)! }
precondition(a.count == 6)
return (a[0], a[1], a[2], a[3], a[4], a[5])
}
func ints(separator: Character = " ") -> [Int] {
split(separator: separator).map { Int($0)! }
}
func float() -> Float {
guard let v = Float(self) else {
fatalError()
}
return v
}
func float2(separator: Character = " ") -> (Float, Float) {
let a = split(separator: separator).map { Float($0)! }
precondition(a.count == 2)
return (a[0], a[1])
}
func float3(separator: Character = " ") -> (Float, Float, Float) {
let a = split(separator: separator).map { Float($0)! }
precondition(a.count == 3)
return (a[0], a[1], a[2])
}
func float4(separator: Character = " ") -> (Float, Float, Float, Float) {
let a = split(separator: separator).map { Float($0)! }
precondition(a.count == 4)
return (a[0], a[1], a[2], a[3])
}
func floats(separator: Character = " ") -> [Float] {
split(separator: separator).map { Float($0)! }
}
func double() -> Double {
guard let v = Double(self) else {
fatalError()
}
return v
}
func double2(separator: Character = " ") -> (Double, Double) {
let a = split(separator: separator).map { Double($0)! }
precondition(a.count == 2)
return (a[0], a[1])
}
func double3(separator: Character = " ") -> (Double, Double, Double) {
let a = split(separator: separator).map { Double($0)! }
precondition(a.count == 3)
return (a[0], a[1], a[2])
}
func double4(separator: Character = " ") -> (Double, Double, Double, Double) {
let a = split(separator: separator).map { Double($0)! }
precondition(a.count == 4)
return (a[0], a[1], a[2], a[3])
}
func doubles(separator: Character = " ") -> [Double] {
split(separator: separator).map { Double($0)! }
}
}
func learnInput(){
let in_string = cin
let in_string_arr = in_string.strs(separator:" ")
print("in_string_arr: \(in_string_arr)")
}

learnDir()

import Foundation
func learnDir(){
let homeDir = NSHomeDirectory()
let userName = NSUserName()
if let home_user = NSHomeDirectoryForUser("andrew"){
print("\(homeDir),\(userName),\(home_user)")
}
let pwd = URL(fileURLWithPath: "./")
print("\(pwd)")
}

learnJSON

import Foundation
struct Employeer: Codable {
var name:String
var id: Int
var mToy:Toy
}
struct Toy:Codable {
var name:String
}
extension Employeer:Debug {
var debugDescription: String {
return name + "(" + String(id) + "): " + mToy.name
}
}
func learnJSON(){
/// encode instance to jsonString
let toyA = Toy(name: "Teddy Bear")
let employeeA = Employeer(name: "EmployA", id:1, mToy:toyA)
let jsonEncoder = JSONEncoder()
let jsonData = try? jsonEncoder.encode(employeeA)
// jsonData contains an unreadable representation of employeeA
print("jsonData: \(String(describing:jsonData))")
let jsonString = String(data: jsonData!, encoding: .utf8)
print("jsonString: \(String(describing:jsonString))")
/// decode jsonString to instance
let jsonDecoder = JSONDecoder()
let employeeADecoded = try? jsonDecoder.decode(Employeer.self, from: jsonData!)
print(employeeADecoded!)//result
/*
jsonData: Optional(54 bytes)
jsonString: Optional("{\"name\":\"EmployA\",\"id\":1,\"mToy\":{\"name\":\"Teddy Bear\"}}")
EmployA(1): Teddy Bear
*/
}

learnTime

import Foundation
extension Date {
/// 获取当前 秒级 时间戳 - 10位
var timeStamp : String {
let timeInterval: TimeInterval = self.timeIntervalSince1970
let timeStamp = Int(timeInterval)
return "\(timeStamp)"
}
/// 获取当前 毫秒级 时间戳 - 13位
var milliStamp : String {
let timeInterval: TimeInterval = self.timeIntervalSince1970
let millisecond = CLongLong(round(timeInterval*1000))
return "\(millisecond)"
}
}
func learnTime(){
//当前时间
let dformatter = DateFormatter()
dformatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
print("当前日期时间:\(dformatter.string(from: Date()))")
//TimeStamp 时间戳
let millisecond = Date().milliStamp
print("当前毫秒级时间戳是 millisecond == ",millisecond)
let timeStamp = Date().timeStamp
print("当前秒级时间戳是 timeStamp == ",timeStamp)
//将时间戳转为日期时间
let timeStamp1 = 1463637809
print("时间戳:\(timeStamp1)")
let timeInterval:TimeInterval = TimeInterval(timeStamp1)
let date = Date(timeIntervalSince1970: timeInterval)//转换为时间
let dformatter1 = DateFormatter()
dformatter1.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
print("对应的日期时间:\(dformatter1.string(from: date))")//格式话输出
//获取当前时区
let zone = NSTimeZone.system
print("zone = \(zone)")
//获取当前时区和GMT的时间间隔
let interval = zone.secondsFromGMT()
print("interval = \(interval)")// 当前时区和格林威治时区的时间差 8小时 = 28800秒
print("interval = \(interval/3600)")// 输出当前系统时区
//获取当前系统时间
let now = Date().addingTimeInterval(TimeInterval(interval))
print("now time = \(now)")// 是Date格式不是String
}
/**
输出结果
当前日期时间:2022年12月21日 00:42:10
当前毫秒级时间戳是 millisecond ==  1671554530990
当前秒级时间戳是 timeStamp ==  1671554530
时间戳:1463637809
对应的日期时间:2016年05月19日 14:03:29
*/

learnSets

import Foundation
func learnSets(){
var primes: Set = [2, 3, 5, 7,55]
if primes.isEmpty {
print("No primes!")
} else {
primes.insert(77)
print("We have \(primes.count) primes.")
}
let primesSum = primes.reduce(0, +)
let primeStrings = primes.sorted().map(String.init)
print("primesSum:\(primesSum)")
print("primeStrings:\(primeStrings)")
primes.remove(77)
primes.removeFirst()
if let index = primes.firstIndex(of:55){
primes.remove(at:index)
}
let smallNums = primes.filter { $0 < 5 }
print("smallNums:\(smallNums)")
// Tests whether primes is a subset of a Range<Int>
print(primes.isSubset(of: 0..<10))
// Prints "true"
// Performs an intersection with an Array<Int>
let favoriteNumbers = [5, 7, 15, 21]
print(primes.intersection(favoriteNumbers)) //集合的交集
}

learnResult

func getResult()->Results<String> {
Results.OK("ok")
}
func learnResult(){
print("\(getResult())")
}

impliment like pythons system function with swift

//python's os.system()
import Foundation
#if os(Linux)
func system(_ command: String) -> Void {
let task = Process()
task.executableURL = URL(fileURLWithPath: "/bin/sh")
task.arguments = ["-c", command]
do {
try task.run()
task.waitUntilExit()
} catch {
print("Error: \(error.localizedDescription)")
}
}
system("ls")
#elseif os(macOS)
func system(_ command: String) -> Void {
let task = Process()
task.executableURL = URL(fileURLWithPath: "/bin/sh")
task.arguments = ["-c", command]
do {
try task.run()
task.waitUntilExit()
} catch {
print("Error: \(error.localizedDescription)")
}
}
system("ls")
#elseif os(Windows)
func system_cmd(_ command: String) -> Void {
let task = Process()
task.executableURL = URL(fileURLWithPath: "cmd")
task.arguments = ["/c", command]
do {
try task.run()
task.waitUntilExit()
} catch {
print("Error: \(error.localizedDescription)")
}
}
system_cmd("ping dnrops.gitee.io")
func system_powershell(_ command: String) -> Void {
let task = Process()
task.executableURL = URL(fileURLWithPath: "powershell")
task.arguments = ["-Command", command]
do {
try task.run()
task.waitUntilExit()
} catch {
print("Error: \(error.localizedDescription)")
}
}
system_powershell("ping dnrops.gitee.io")
#else
let platform = "Unknown"
print("This operating system is not supported.")
#endif