Swift基础语法

//: Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

let a : Int = 10
let b = 20.3
let c = Double(a) + b

let view = UIView()
view.backgroundColor = UIColor.blueColor()
view.center = CGPointMake(20, 30)
let btn : UIButton = UIButton()

if Double(a) < b {
    print("a 小")
} else {
    print("b 小")
}

func online(age:Int){
    guard age > 18 else{
        print("年龄太小")
        return
    }
    guard age < 60 else{
        print("年龄太大")
        return
    }
    print("可以上网")
}
online(32)



let sex = 1

switch sex {
case 0,1:
    print("男")
default:
    print("其他")
}


let n = 10
let m = 20
let opration = "*"
switch opration {
    case "+":
        print(n + m)
    case "-":
        print(n-m)
    case "*":
        print(n * m)
    case "/":
        print(n/m);
    default:
    print("啥都不做")
}


let score = 65
switch score {
case 0..<60:
    print("不及格")
case 60..<80:
    print("及格")
case 80..<90:
    print("良好")
case 90...100:
    print("优秀")
default:
    print("非人类")
}


for i in 0...10 {
    print(i)
}

for _ in 0..<10 {
    print("hello world")
}


var j = 0
while j < 10{
    j+=10;
    print(j)
}


repeat {
    j += 1
} while j < 100



// 定义字符串
let str2 = "hello world"

for c in str2.characters {
    print(c)
}

// 字符串拼接
let result = str + str2

// 字符串和其他标识符的拼接
let age = 19
let name = "ldh"
let height = 178

let info = "my name is \(name), age is \(age), height is \(height)"

// 字符串的格式化
let min = 3
let second = 04
let timeStr = String(format: "%02d:%02d", arguments:[min, second])

// 字符串的截取
let urlString = "www.baidu.com"

// 将String转换成NSString类型 string as NSString
let header = (urlString as NSString).substringToIndex(3)
let middle = (urlString as NSString).substringWithRange(NSMakeRange(4, 5))
let footer = (urlString as NSString).substringFromIndex(10)


/**********     数组    ***************/
// 不可变数组
let array = ["lpy","ldh","ls","lwy","mpf","tzy"];

// 可变数组
// var arrayM = Array()
var arrayM = [String]()

// 增
arrayM.append("gsj")
arrayM.append("ldh")
arrayM.append("ryy")

// 删
arrayM.removeAtIndex(0)

// 改
arrayM[0] = "haha"


// 获取下标元素
arrayM[1]


// 遍历
for i in 0..()
var dictM = [String : AnyObject]()


// 增
dictM["height"] = 1.83

// 删
dictM.removeValueForKey("height")

// 改
dictM["name"] = "ryy"

// 查
dictM["name"]


// 遍历字典
for key in dictM.keys {
    print(key)
}

for value in dictM.values {
    print(value)
}

for (key,value) in dictM {
    print(key,value)
}



/********************   元组    **********************/
let userInfo = ("ldh", 18, 189)
userInfo.0
userInfo.1
userInfo.2


let userInfo1 = (name : "ldh", age : 19 , height : 1.98)
userInfo1.name
userInfo1.age
userInfo1.height


let (name1, age1, height1) = ("ldh", 19, 1.98)
name1
age1
height1



/************************   可选类型   *****************************/
class Person1 : NSObject {
    var name : String?
    var age  : Int?
}

// 常规定义方法
// var name3 : Optional

// 语法糖
var name3 : String?

// 给可选类型赋值
name3 = "ldh"

// 从可选类型中取值
print(name3)

print(name3!) // 强制解包,存在风险

// 经常使用的解包方法
if let name3 = name3 {
    print(name3)
}


let url : NSURL? = NSURL(string: "https://www.baidu.com")

if let url = url {
    let request = NSURLRequest(URL: url)
}


/****************************     函数    ***************************************/

// 无参数 无返回值
func test () {
    print("无参数 无返回值")
}
test()

// 无参数 有返回值
func test2() -> String {
    return "无参数,有返回值"
}
print(test2())


// 有参数  无返回值
func call(phoneNum:String) -> Void {
    print("电话号码为\(phoneNum)")
}
call("110")


// 有参数  有返回值
func plus(num1 : Int, num2 : Int) -> Int {
    return num1 + num2
}

plus(12, num2: 15)




let x = 3
let y = 20.3
let result5 = Double(x) + y


func sum2(num1 : Int , num2 : Int) -> Int {
    return num1 + num2
}

sum2(123, num2: 123)

// 内部参数和外部参数
func sum3(num1 num1 : Int, num2 : Int) -> Int {
    return num1 + num2
}

sum3(num1: 154, num2: 14)


// 默认参数
func makeCoffee (coffeeName : NSString = "雀巢") -> String {
    return "制作了一杯\(coffeeName)"
}

makeCoffee("拿铁")
makeCoffee("猫屎")
makeCoffee()


// 可变参数
func sum(num : Int...) -> Int{
    var result = 0
    for n in num {
        result += n
    }
    return result
}

sum(1,2,3,45)



// 指针类型 
var m1 = 20
var n1 = 30

func swapNum(inout m : Int, inout n : Int) {
    let temp = n
    m = n
    n = temp
}

swapNum(&m1, n: &n1)


// 函数的嵌套
func test1() {
    func test2() {
        print("test2调用了")
    }
    print("test1调用了")
    test2()
}

test1()


/*************************   类  ****************************/

// 类的定义
class Person: NSObject {
    var age : Int = 0
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
}

let p = Person()
p.setValuesForKeysWithDictionary(["age" : 18, "name" : "ldh"])


class Student: NSObject {
    
    var age : Int = 0
    var name : NSString?
    
    var mathScore : Double = 0.0
    var chineseScore : Double = 0.0
    
    // 定义计算属性 :通过别的方式计算得到的结果的属性,称之为计算属性 
    var averageScore : Double {
        return (mathScore + chineseScore) * 0.5
    }
    
    // 定义类属性 : 类属性 是和整个类相关的属性,而且通过类名进行访问
    static var courseCount : Int = 0
    
}

// 给类属性进行赋值
Student.courseCount = 2

// 创建对象
let stu = Student()

// 给对象进行赋值
stu.name = "ldh"
stu.chineseScore = 80.0
stu.mathScore = 70.0

print(stu.age)

if let name = stu.name {
    print(name)
}

let averageScore = stu.averageScore



// 构造函数
class Person2 : NSObject {
    
    var name : String? {
        
        // 属性即将改变时监听
        willSet {
            print(name)
            print(newValue)
        }
        
        // 属性已经改变时进行监听
        didSet {
            print(name)
            print(oldValue)
        }
        
    }
    var age  : Int = 0
    
    override init() {
        print("-----")
    }
    
    // 自定义构造函数
    init(name : NSString, age : Int) {
        self.name = name as String
        self.age = age
    }
    
    init(dict : [String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
}


let p3 = Person2()
let p4 = Person2(name: "ldh", age: 13)
print(p4.age)
if let name = p4.name {
    print(name)
}


let p5 = Person2(dict: ["name": "ldh", "height" : 193, "age" : 20])
if let name = p5.name {
    print(name)
}
print(p5.age)







你可能感兴趣的:(Swift基础语法)