欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Swift 学习笔记 博客分类: swift Swift 

程序员文章站 2024-02-10 11:32:34
...

sw i f t 作为苹果新的开发语言,相比Object-C相对好理解,项目需要因此需要学习一下,特此写下此笔记

 

Swift 学习建议参考苹果开发者中心文档:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-ID1

 

代码:

//
//  main.swift
//  swiftlearn
//
//  Created by YoungStream on 16/3/23.
//  Copyright © 2016年 mugutu. All rights reserved.
//

import Foundation

print("Hello, World!")

//定义变量
var myVar = 42
myVar = 35

var myVar2: Double = 30.345

var myStr:String = "Hello Swift!"

//定义一个常量,没有指明类型时,编译器根据初始值自动推断出myConst是一个整数
let myConst = 43
//定义一个常量并声明类型
let myConst2: Double = 30.0

let myFloat: Float = 4.0
// Int8整型常量或者变量能够存储的数值是-128到127,而UInt8整型常量或者变量能够存储的
//数值范围是0到255.当编译的时候,数值越界是不会自动得到合适的值的,而且会编译出错。
//let t1: UInt8 = -1

/*
 整型雨浮点类型的转换
*/
let three = 3
// 转换three为整型
let pi = Double(three) + 0.14569

let integer = Int(3.1415926)

print("This A Value : "+String(integer))
//array数组
var shoppingList = ["one","two","three"]

shoppingList[0] = "once again"

var occupations = [
    "one"   :"Mom",
    "two"   :"Lily",
    "three" :"Tom"
]
occupations["four"] = "Jack";

//初始化空数组
let emptyArray = [String]()
//初始化空字典
let emptyDictionary = [String:Float]()


//==Control Flow== 流程控制 if else for

let individualScores = [75,43,103,87,12]

var tempScore = 0;
for score in individualScores {
    if score > 50 {
        tempScore += 3;
    } else {
        tempScore += 1;
    }
}

var optionalString:String? = "Hello"
print(optionalString == nil)

var optionName:String? = nil
//var optionName:String? = "John Appleseed"

var greeting = "Hello!"
if let name = optionName {
    greeting = "Hello, \(name)"
} else {
    greeting = "Hello,YoungStream"
}
print(greeting)


let nickName: String? = nil
let fullName: String = "Young Stream"
let informalGreeting = "Hi \(nickName ?? fullName)"

print("infomalGreeting : "+informalGreeting)

//Switch Case
let vegetable = "red pepper"

switch vegetable {
case "celery":
    print("This is celelry")
case "cucumber","watercress":
    print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
    print("It is a spicy \(x)?")
default:
    print("Swicth Case Default Print")
}

//for each pai value
let interestingNumbers = [
    "Prime": [2,3,5,7,11,13],
    "Fibonacci": [1,1,2,3,5,8],
    "Square":[1,4,9,16,25]
]

var largest = 0

for(kind,numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
    print("key : "+kind)
}

print("The Max Value : "+String(largest))
//While Repeat

var n = 2
while n < 100 {
    n = n * 2
}
print("While N Value : "+String(n))

var m = 2
repeat {
    m = m * 4
} while m < 100

print("Repeat M Value : "+String(m))

var total = 0
for i in 0..<4 {
    total += i
}
print("For ..< Value : "+String(total))

//== Functions and Closures ==
print("=== Functions and Closures ===")

//func FunctionName(paramName:paramType ...) -> returnType {Function Body}
func greet(name:String,day:String) ->String {
    return "Hello \(name), today is \(day)."
}

print("Function greet return Value: "+greet("Bob",day:"Tuesday"))

//使用元组返回多个值
func calculateStatistics(scores:[Int]) -> (min: Int,max: Int,sum: Int) {
    var min = scores[0]
    var max = scores[0]
    var sum = 0
    
    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        
        sum += score
    }
    return (min,max,sum)
}
var calcuReturn = calculateStatistics([1,2,3,4,5,6,7,8,9,10])
print("Function calculateStatistics return Value : max => "+String(calcuReturn.max)+", min => "+String(calcuReturn.0)+", sum => "+String(calcuReturn.sum))
//函数嵌套 Function Nested
func returnFifteen() -> Int {
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}
print("Function Nested At. returnFifteen Return Value : "+String(returnFifteen()))

//Function Return Another Function
func makeIncrementer() -> ((Int) -> Int) {
    func addOne(number:Int) -> Int {
        return 1 + number
    }
    return addOne
}
var increment = makeIncrementer()

print("Return Function's Return Value : "+String(increment(7)))
//Function use Another Function as Parameter 函数使用应一个函数作为参数

func hasAnyMatches(list:[Int],condition:(Int) ->Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}


func lessThanTen(number:Int) -> Bool {
    return number < 10
}

var numbers = [20,19,18,12]
print("Function hasAnyMatches Return Value : "+String(hasAnyMatches(numbers,condition:lessThanTen)))

numbers.map({
    (number:Int) -> Int in
    let result = 3 * number
    return result
})

let sortedNumbers = numbers.sort{$0 > $1}
print("Closures Sorted Numbers Result[闭包函数SortedNumbers结果]")
print(sortedNumbers)


let mappedNumbers = numbers.map({number in 3 * number})
print("Numbers Map Result : "+String(mappedNumbers))

print("Add Total : "+String(tempScore))
print(occupations[shoppingList[1]])
print("Hello Swift :\(myVar) , \(myStr), \(myConst),\(integer)")

//Objects and Classes

class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides"
    }
}

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

print("Shape Instance Description : "+shapeDescription)

class NamedShape {
    var numberOfSides: Int = 0
    var name: String
    
    init(name:String) {
        self.name = name;
    }
    
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

class Square: NamedShape {
    var sideLength:Double
    
    init(sideLength:Double,name:String) {
        self.sideLength = sideLength
        super.init(name:name)
        numberOfSides = 4
    }
    
    func area() -> Double {
        return sideLength * sideLength
    }
    
    override func simpleDescription() -> String {
        return "A square sides of length \(sideLength)."
    }
}

let test = Square(sideLength:5.2,name:"my test square")
test.area()
test.simpleDescription()


class EquilateralTriangle: NamedShape {
    var sideLength: Double = 0.0
    
    init(sideLength: Double,name: String) {
        self.sideLength = sideLength
        super.init(name:name)
        numberOfSides = 3
    }
    
    var perimeter: Double {
        get {
            return 3.0 * sideLength
        }
        set {
            sideLength = newValue / 3.0
        }
    }
    
    override func simpleDescription() -> String {
        return "An equilateral triangle with sides of length \(sideLength)."
    }
}

var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")

print(triangle.perimeter)
triangle.perimeter = 9.9
print(triangle.sideLength)

 

相关标签: Swift