Swift编程注释小记1(变量,函数,类)

--阅读The Swift Progrmaing Language 
--Swift 中的self 参考了Python, 也有函数式编程的影子,
import Foundation

//Varibal 变量和定义篇 ===============================================
println("Hello, World!")


//var 表示变量, let表示常量,所有的数据类型的的首字母是需要大写的
var myVariable = 42
myVariable = 50
let myConstant = 42

let explicitDouble: Double = 70

let lablel = "The width is "
let width = 40
let widthLable = lablel + String(width)

println(widthLable)


let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."

//两个整数相加时,任意一个不能为浮点数
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

//打印语句
println(appleSummary)
println(fruitSummary)

//array and dictionary
var shoppingList = ["catfish", "water","tulips","blue paint"]
shoppingList[1] = "bottle of water"

var occpations = [
    "Malcolm":"Captain",
    "Kaylee":"Mechanic",
]

occpations["Jayne"] = "Public Relations"

println(shoppingList)
println(occpations)

//create empty array and dictionary
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()


//for loop  statment must be bool type
let individualScores = [75,43, 103,87,12]
var tempScore = 0
for score in individualScores
{
    if score  > 50
    {
        tempScore += 3
    }
    else
    {
        tempScore += 1
    }
}
println(tempScore)


//for and let together use
var optionalString:String? = "Hello"
optionalString == nil

var optionalName : String? = "John Appleaseed"
var greeting = "Hello"
/* if name is nil the code int braces is skipped*/
if let name = optionalName
{
    greeting = "Hello ,\(name)"
}

//switch...case
//must need add default case and is no need to explicitly break
let vegetable = "red pepper"
switch vegetable
{
case "celery":
    let vegetableComment = "Add some raisions and make ants on a log"
case "cucumber", "watercress":
    let vegetableComment = "That would make a good tea sandwich"
case let x where x.hasSuffix("pepper"):
    let vegetable = "It it a spicy \(x)?"
default:
    let vegetableComment = "Everything tasts good is soup"
}

//for in providing a pair of name to user for key-value pair
let interestingNumbers = [
    "Prime" : [2,4,5,7,11,13],
    "Fibonacci" : [1,1,2,3,5,8],
    "Squear" : [1,4,5,16,25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest{
            largest = number
        }
    }
}
println("largest = \(largest)")

//while
var n = 2
while n < 100 {
    n = n * 2
}

var m = 2
do {
    m = m * 2
} while m < 100
println("n = \(n), m = \(m).")

//for i in 0..3  I think don't using this statment ,on method resoulation one Problem


//Function 篇 ====================================================
//func and closures,one return value
//“Use -> to separate the parameter names and types from the function’s return type.”
func greet(name:String,day:String) -> String{
    return "Hello \(name), today is \(day)."
}
let Return:String = greet("Bob", "Tues")
println("Return = \(Return)")

//func and closures ,Use a tuple to return multiple values from a function,rember is a tuple
func getGasPrices() -> (Double, Double, Double)
{
    return (3.58,4.23,45.234)
}
let MultipleReturn = getGasPrices()
println("MultipleReturn = \(MultipleReturn)")


// func and closures, functions can nested,就是可以在一个函数中定义多个函数,低层次中的函数可以使用上层次中的变量。
func returnFifteen() -> Int {
    var y = 10
    
    func add() {
        y += 5
    }
    add()
    return y
}

let result : Int  = returnFifteen()
println("result = \(result)")

//func and closures, first-class-type 
//意思就是一个函数可以当成值返回,so cool
func makeIncrementer() -> (Int -> Int) {
    func addOne(number :Int) -> Int {
        return 1 + number
    }
    return addOne
}
var increment = makeIncrementer()
println(increment(7))
println("---------------------------------")

//func and closures, A function can tak another function as one of ites argument
//一个函数可以作为一个参数其它函数使用
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, 18,7,12]
println(hasAnyMatches(numbers,lessThanTen))
// func and closures ,Use in to separate the argumnet and return type from the body
let mapValue = numbers.map({(number:Int) -> Int in
    let result = 3 * number
    return result
})

let tuple = [1,4,3,45,2]
sort(tuple) { $1 > $0}
println(tuple)
println("---------------------------------")

//Object and Classes define and declare =================================
//Object 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()
println(shapeDescription)
println("---------------------------------")

//object and class , important:an initializer to set up the class when an instance  create
//“Use deinit to create a deinitializer if you need to perform some cleanup before the object is deallocated.
class NamedShape {
    var numberOfSide : Int = 0
    var name: String
    
    //importmemt:
    init(name:String) {
        self.name = name
    }
    
    //deinit(){}
    func shapeDescription() -> String {
        return "A simple whith \(numberOfSide) sides"
    }
}
    //class initializer
var namedShape = NamedShape(name:"triganle")
namedShape.numberOfSide = 3
println(namedShape.shapeDescription())
println("---------------------------------")

//Object and class override
//
class Square : NamedShape {
    var sideLength : Double
    
    init(sideLength: Double, name:String) {
        self.sideLength = sideLength
        //super 代表父类初始化,也可以重新设置父类的变量值
        super.init(name:name)
        numberOfSide = 4
    }
    
    func area() -> Double {
        return sideLength * sideLength
    }
    //override shapeDescription method
    override func shapeDescription() -> String{
        return "A spuare whith sides of length \(sideLength)"
    }
}
let test = Square(sideLength : 5.2, name :"my test square")
println(test.shapeDescription())
println(test.area())
println("---------------------------------")

//object and class , get and set 
class EquilaterTriangle : NamedShape {
    var sideLength:Double = 0.0
    
    init(sideLength: Double, name : String) {
        self.sideLength = sideLength
        super.init(name:name)
        numberOfSide = 3
    }
    
    var perimter: Double {
    get {
        return 3.0 * sideLength
    }
    //use set newValue and return new Value
    set {
        sideLength = newValue / 3.0
    }
    }
    
    override func shapeDescription() -> String{
        return "An equilater triagle with sides of length \(sideLength)"
    }
}

var triangle = EquilaterTriangle(sideLength:10.5,name:"a triangle")
println(triangle.perimter)
println(triangle.perimter = 11)
println(triangle.shapeDescription())






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值