微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift 15 分钟

代码加注释,30分钟大概浏览下swift 的基本语法


/*
能用常量的尽量用常量,能自动判别类型的就让它自动判别,可提高可读性
*/
let message = "Hello World" // 用let定义常量
var score = 30              // 用var定义变量,自动判断类型
let num: Int = 20           // 指定常量类型为Int

let priceInferred = 19.99   //带小数的数字认为Double 类型
let priceExplicit: Double = 19.99   //Double 类型
let price: Float = 19.99    //Float 类型
let flag: Bool = true   // Bool 类型
let arr : [Double] = [1.2,2.3,4.3]    // 数组
let arr2 = [2,5,6,3]                 // 数组
let arr3 = 0..<10                       // 范围
let arr4 = ("hello",2,5)              // 元组,可以是不同的数据类型
let dict : [String: Int] = [ "key1": 3,"key2": 4,"key3": 5]    //字典,相当于map
let val1 = Int(dict["key1"]!)

// 值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换
var p : Double = Double(price)
for i in arr {                          // for-in 循环
    println("element: \(i)")
}

for i in 0...2 {    // 0..<2不包含2,0...2包含2
    println("element: \(i)")
}

for (key,value) in dict {
    println("key is \(key),value is \(value)")
}

var n = 2
while n < 2 {
    n = n * 2
}
do {
    n = n * 2
} while n < 5


if price < 40 {
    println("price is \(price)")    // 在字符串中使用\()来解析变量,函数等等
} else if price > 50 && price < 80 {
    println("score is \(score)");
} else {
    println("score is \(score)")
}

// 一个可选的值可能是一个具体的值或者是nil
let optStr : String? = "hello"
// 在if语句中,条件必须是一个布尔表达式,你可以一起使用if和let来处理是否为nil
//如果变量的可选值是nil,条件会判断为false,大括号中的代码会被跳过。
//如果不是nil,会将值赋给let后面的常量
if let flag = optStr {
    println(flag)
}
// 运行switch中匹配到的子句之后,程序会退出,不需要break
let animal = "wild dog"
switch animal {
case "bird":
    "bird"
case "mouse","cat":
    "mouse or cat"
case let pet where pet.hasSuffix("dog"):
    "dog"
default:
    "pet"
}

func greet (name : String) -> String {
    return "hello \(name)"
}

//返回元组
func getNumber () -> (Double,Double,String) {
    return (2.3,4.5,"hello")
}

// 不定参数
func sumNumber(num : Int...) -> Int {
    var sum = 0
    for n  in num {
        sum += n
    }
    return sum
}
// 闭包
func addExtraFive(n : Int) -> Int{
    var x = 5
    func add() {
        x += n
    }
    add()
    return x;
}
let y = addExtraFive(10)

//传入函数
func compare(n1:Int,n2:Int,equal: (Int,Int) -> Int)
    -> Int {
    return equal(n1,n2)
}

func makeFunc(n : Int) -> (Int -> Int) {
        func addNumber(n : Int) -> Int{
            return 1 + n
        }
        return addNumber
}

//匿名函数参数
compare(1,{(number:Int,num2 : Int)-> Int in
    let result = 3 * number
    return result
})

//当一个函数作为最后一个参数传给一个函数的时候,它可以直接跟在括号后面
compare(1,3) {(number:Int,num2 : Int)-> Int in
    let result = 3 * number
    return result
}

class A {          // 定义类A
    func calc(n1:Int,n2:Int) -> Int{
        return n1 + n2
    }
}

class B : A {       //定义类B,继承类A
    var seconds: Double = 0.0   //声明成员属性必须要初始化
    var score : Int           //使用init函数来初始化
    var price : Double?       //声明optional的成员属性不需要初始化
    var mount : Int = 0{
        didSet {                // after set a new vale
            println("mount changed from \(oldValue) to \(self.mount)")
        }
        willSet {               // before set a new value
            println("before change mount from \(self.mount) to \(newValue)")
        }
    }
    //定义 被计算的属性(computed property). -  do not have storage in the instance
    //setter方法没有将被设置的值定义一个名称,将会认地使用newValue这个名称来代替
    var minutes : Double{
        set {
            self.seconds = newValue * 60
        }
        get {
            return seconds / 60
        }
    }
    
    init(score : Int) {         //构造函数
        self.score = score         //用self指定本对象
    }
    
    /*重写父类方法*/
    override func calc(n1:Int,n2:Int) -> Int {
        return n1 + n2
    }
  
}

let objB = B(score: 30)     //创建B对象

objB.calc(32,n2: 34)

// 枚举
enum Day {
    case Monday,Tuesday,Wednesday,Thursday,Friday
    case Saturday,Sunday
    func print() {
        switch self {
        case .Monday,.Thursday,.Wednesday,.Friday:
                println("workday")
        case .Saturday,.Sunday:
                println("weekend")
        default:
            println("unkown")
        }
        self
    }
}

enum Constant {
    case Result(String)
}

var rs = Constant.Result("success")

// 结构体,结构体是传值,类是传引用
struct DayType {
    var day : Day
    var name : String
}

var type = DayType(day: Day.Monday,name: "workday")

// 接口
protocol Person {
    func speak()
}

class Chinese : Person {
    func speak() {
        println("speak Chinese")
    }
}

// 泛型

func execute<T> (s : T ) {
    println(s)
}

class Calculator<T> {
    func toString(t1 : T,t2 : T) -> String {
        return "\(t1)  \(t2)"
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐