1、数组
// 定义不可变数组
let array:[String] = ["1", "2", "3", "4"]
print(array)
// 定义可变数组
var mutArray = ["one", "two", "three", "four"]
print(mutArray)
// 修改数组元素值
mutArray[0] = "1";
print(mutArray)
// 根据范围修改元素值
mutArray[1...3] = ["2", "3", "4"]
print(mutArray)
// 增加元素
mutArray += ["five", "six”];
print(mutArray)
2、字典
let dict = ["one":1, "tow":2, "three":3]
// 字典遍历
for (key, value) in dict{
print("key:\(key), value:\(value)")
}
// 字典取值,可能值的使用
let value:Int? = dict["four"];
if value != nil{
print(value!);
}else{
print("没有该值")
}
3、控制语句
let value = 10;
if value > 5{
print("a>5")
}else{
print("a<5")
}
// case中可以为区间值,可以多个值,每个case后默认带break
switch value {
case 0:
print("0");
case 1, 2, 3:
print("1 or 2 or 3")
case 4...10:
print("range(4, 10)")
default:
print("other....")
}
4、循环
最简单的for循环
for item in 1...5{
print(item)
}
5、函数与闭包
完整写法:
let closures : (Int,Int)->Int = {
(a:Int,b:Int) in
return a + b;
}
print(closures(1, 2));
简化为:
let closures : (Int, Int) -> Int = {
return $0 + $1;
}
print(closures(1, 2));
无返回值
let closures : (Int, Int) -> () = {
(a:Int, b:Int) in
print("\(a), \(b)");
}
closures(1, 2);
无参数有返回值
let closures : ()->(String) = {
return "colsures...";
}
print(closures());
无参数无返回值
let closures : ()->() = {
print("closures...");
}
closures()
简化为:
let closures = {
print("closures...");
}
closures()
举个栗子:
override func viewDidLoad() {
super.viewDidLoad()
sa_repeat(count: 3, task:{
print("Hello")
})
// 可以美化为以下格式
sa_repeat(count: 3) {
print("Hello")
}
}
// 函数定义
func sa_repeat(count:Int, task:()->()){
for _ in 0..<count{
task();
}
}
6、类
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let bicycle = Bicycle();
print(bicycle.description);
let car = Car();
print(car.description);
let pcar = ParentsCar();
pcar.speed = 80
print(pcar.description)
}
}
class Vehicle {
// properties属性
// Stored Properties 储值属性
var numberOfWheels = 0
// Computed Properites 算值属性
var description : String {
get{
return "Bicycle有\(numberOfWheels)个轮子"
}
set{
// 可以与储值属性交互,如果没有set方法则为只读算值属性
}
}
// initalizers 初始化
init() {
}
// methods方法
}
class Bicycle : Vehicle {
override init() {
super.init();
numberOfWheels = 2;
}
}
class Car : Vehicle {
var speed = 120.0;
override init() {
super.init();
numberOfWheels = 4;
}
// 计算属性覆盖
override var description: String{
get{
return super.description + ", 每小时行驶\(speed)公里"
}
set{
}
}
}
class ParentsCar : Car {
override init() {
super.init()
}
// 储值属性覆盖(属性观察)
override var speed: Double{
willSet{
print(newValue)
}
didSet{
print(oldValue)
}
}
}
输出结果:
Bicycle有2个轮子
Bicycle有4个轮子, 每小时行驶120.0公里
80.0
120.0
Bicycle有4个轮子, 每小时行驶80.0公里
7、结构体
7.1、结构体与类的区别:
- 结构体存储在栈中,类存储在堆中
- 结构体赋值是值传递,类传递引用
- 结构体不能继承,而类可以被继承
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let p = Point(x:1, y:2)
print(p)
let s = Size(width: 100, height: 200)
print(s)
let r = Rect(origin: p, size: s)
print(r)
}
struct Point {
var x, y: Double
// 修改内部属性的方法需要加mutating关键字
mutating func modify(x:Double){
self.x = x;
}
}
struct Size {
var width, height: Double
}
struct Rect {
var origin: Point
var size: Size
// 计算属性,直接返回为get属性
var area: Double {
return size.width * size.height;
}
// 方法与函数中的方法及函数都类似
func someMethod(){
// coding...
}
}
}
8、枚举值
import UIKit
enum Day: Int{
case Monday = 1
case Tuesday = 2
case Wednesday = 3
case Thursday = 4
case Friday = 5
case Saturday = 6
case Sunday = 7
}
enum SpecialChar: Character {
case Tab = "\t"
case Return = "\n"
case Dot = "."
}
enum Direction {
case North, South, East, West
}
enum TrainStatus {
case OnTime
case Delayed(Int)
// 枚举中还可以有初始化方法
init(){
self = .OnTime
}
// 可以有算值属性
var description: String{
switch self {
case .Delayed(let min):
return "晚点\(min)分钟"
default:
return "整点"
}
}
func method(){
print("enmu method...")
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let day = Day.Tuesday
print(day.rawValue)
let dot = SpecialChar.Dot
print(dot.rawValue)
let direction = Direction.West;
// print(Direction.rawValue) // 报错
let label = UILabel()
label.textAlignment = NSTextAlignment.right;
// 可直接简写为
label.textAlignment = .right;
// 火车晚点(40分钟)
let status = TrainStatus.Delayed(40)
status.method()
print(status.description)
}
}
9、扩展(Extensions)
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.description();
10.sa_repeat {
print("Hello Swift!")
}
}
}
extension ViewController {
func description(){
print("ViewController....")
}
}
// 扩展系统类|系统数据类型的方法,任意扩展
extension Int {
func sa_repeat(closures:()->()){
for _ in 0...self{
closures()
}
}
}
10、泛型
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var s = Stack<String>();
s.push(ele: "4")
s.push(ele: "6")
print(s)
s.pop()
print(s)
}
}
struct Stack<T>{
var elements = [T]()
mutating func push(ele: T){
elements.append(ele)
}
mutating func pop(){
elements.removeLast();
}
}
运行结果
Stack<String>(elements: ["4", "6"])
Stack<String>(elements: ["4"])