zoukankan      html  css  js  c++  java
  • swift 小练习

    //: Playground - noun: a place where people can play
    
    import UIKit
    
    var str = "Hello, playground"
    var myVariable = 42
    myVariable = 50
    let myConstant = 42
    let intNum:Int=80
    
    let floatNum:Float=4
    
    let label="hello,world"
    let widthLabel=label+String(intNum)
    //还有更简单的方法来在字符串中包含值:以小括号来写值,并用反斜线("")放在小括号之前。例如:
    let apples=3
    let oranges=5
    let appleSummary="I have (apples) apples"
    let fruitSummary="I have (apples+oranges) pieces of fruit."
    
    var shoppingList=["c","d","e","a"]
    shoppingList[1]="bottle"
    var occupations=["key1":"aa","key2":"bb"]
    occupations["key3"]="cc"
    
    
    let emptyArray=[String]()
    let emptyDictionary=Dictionary<String,Float>()
    
    let individualScores=[75,43,103,87,12]
    var teamScore=0
    for score in individualScores
    {
        if(score>50)
        {
            teamScore+=3
        }
        else
        {
            teamScore+=1
        }
    }
    teamScore
    
    var optionalString:String?="Hello"
    optionalString==nil
    
    var optionalName:String?="john appleseed"
    var greeting="Hello!"
    if let namae=optionalName
    {
        greeting="hello,(namae)"
    }
    
    
    let vegetable="red pepper"
    switch vegetable
    {
    case "celery":
        let vegetableComment="add some"
    case "cucumber","watercress":
        let vegetableComment="that would"
    case let x where x.hasSuffix("pepper"):
        let vegetableComment="Is it a spicy (x)"
    default:
        let vegetableComment="Everything tastes good in soup"
    }
    
    
    
    let interestingNumbers=[
        "prime":[2,3,5,7,11,13],
        "Fibonacci": [1,1,2,3,5,8],
        "Square": [1,4,9,16,25],
    ]
    
    var lagest=0
    
    for(kind,numbers) in interestingNumbers
    {
        for number in numbers
        {
            if(lagest<number)
            {
                lagest=number;
            }
        }
    }
    lagest
    
    func  greet(name:String,day:String)->String
    {
        return "Hello (name),today is (day)"
    }
    
    greet("liran", day: "周三")
    
    // 使用元组(tuple)来返回多个值
    
    func getGasPrices()->(Double,Double,Double)
    {
        return (3.59,3.69,3.79)
    }
    getGasPrices()
    //函数可以接受可变参数个数,收集到一个数组中。
    
    func sumOf(numbers:Int...)->Int
    {
        var sum=0
        for number in numbers
        {
            sum+=number
        }
        return sum
    }
    
    sumOf()
    
    sumOf(1,2,3,4,1)
    
    
    //练习
    //编写一个函数计算其参数的平均值。
    
    func average(numbers:Int...)->Int
    {
        var sum=0
        for number in numbers
        {
            sum+=number
        }
        return sum/numbers.count
    }
    
    average(5,10,15,20,25)
    
    
    //函数可以嵌套。内嵌函数可以访问其定义所在函数的变量。你可以使用内嵌函数来组织代码,避免过长和过于复杂。
    
    func returnFifteen()->Int
    {
        var y=10
        
        func add()
        {
            y+=5
        }
        
        add()
        
        return y
        
    }
    
    returnFifteen()
    
    //函数是第一类型的。这意味着函数可以返回另一个函数。
    //prame mark
    func makeIncrementer()->(Int->Int)
    {
        func addOne(number:Int)->Int
        {
            return 1+number
        }
        
        return addOne
    }
    
    var increment=makeIncrementer()
    increment(7)
    
    //一个函数可以接受其他函数作为参数。
    
    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,7,12]
    hasAnyMatches(numbers, condition: lessThanTen)
    
    //函数实际是闭包的特殊情况,你可以写一个闭包而无需名字,只需要放在大括号中即可。可使用in 到特定参数和主体的反悔值
    
    numbers.map { (number:Int) -> Int in
        let result=3*number
        return result
    }
    
    //对象与类
    // 使用class 可以创建一个类。一个属性的声明则是在类里作为常量或变量声明的,除了是在类的上下文中。方法和函数也是这么写的
    class Shape
    {
        var numberOfSides=0
        func simpleDescription()->String
        {
            return "A shape with (numberOfSides) sides."
        }
    }
    //通过在类名后加小括号来创建类的实例。使用点语法来访问实例的属性和方法
    
    var shape=Shape();
    shape.numberOfSides=7
    var shapeDepription=shape.simpleDescription()
    
    //这个版本的shape 类有些重要的东西不在: 一个构造器来在创建实例时设置类,使用init来创建一个
    class NamedShape
    {
        var numberOfSide:Int=0
        var name:String
        
        init(name:String)
        {
            self.name=name
        }
        
        func  simpleDescription()->String
        {
            return "A shape with (numberOfSide) sides"
        }
    }
    //注意self 用来区分name属性和name参数。构造器的生命跟函数一样,除了会创建类的实例,每个属性
    //都需要赋值,无论在声明里还是在构造器里
    //使用deinit 来创建 一个熹构器,来执行对象销毁时的清理工作
    //子类包括其超类的名字,以冒号分割。在继承标准跟类时无需声明,所以你可以忽略超类
    //子类的方法可以通过标记override 重载超类中的实现,而没有override 的会被编译器看作是错误
    
    class Square: NamedShape {
        var sideLength:Double
        
        init(sideLength:Double,name:String)
        {
            self.sideLength=sideLength
            super.init(name: name)
            numberOfSide=4
        }
        
        
        func area()->Double
        {
            return sideLength * sideLength
        }
        
        override func simpleDescription() -> String {
            return "A square with sides of length (sideLength)"
        }
    }
    
    let test=Square(sideLength: 5.2, name: "my test square")
    test.area()
    test.simpleDescription()
    //练习
    //编写另一个NamedShape的子类叫做Circle,接受半径和名字到其构造器,实现area和simpleDescription 方法
    
    class Circle: NamedShape {
        var radius:Double
        init(radius:Double,name:String)
        {
            self.radius=radius
            super.init(name: name)
            numberOfSide=5
        }
        
        func area()->Double
        {
            return  3.14159 * radius * radius
        }
        
        override func simpleDescription() -> String {
            return "A circle with sides of length (numberOfSide)"
        }
        
        var perimeter:Double
            {
            get
            {
                return 3.1 * radius
            }
            set
            {
                radius=newValue / 3.1
            }
        }
    }
    
    // 7 枚举与结构
    
    enum Rank:Int
    {
        case Ace=1
        case Two,Three,Four,Five,Six,Seven,Eight
        case Jack,Queen,King
        
        func simpleDescrition()->String
        {
            switch self
            {
            case.Ace:
                return "ace"
            case.Jack:
                return "jack"
            case.Queen:
                return "queen"
            default:
                return String(self.rawValue)
            }
        }
    }
    
    
    //func count(String:String)->(vowels:Int,constants:Int,others:Int)
    //{
    //    var vowels=0,constants=0,others=0
    //    
    //    for character in String
    //    {
    //        switch String(character).lowercaseString
    //        {
    //            case "a","e","i":
    //                ++vowels
    //            case "b","c","d":
    //                ++constants
    //            default:
    //            ++others
    //        }
    //    }
    //    
    //    return(vowels,constants,others)
    //}
    
    
    func swapTwoInts(inout a:Int,inout b:Int)
    {
        let temporaryA=a
        a=b
        b=temporaryA
    }
    
    var someInt=3
    var anotherInt=107
    swapTwoInts(&someInt, b:&anotherInt)
    print("someInt is now (someInt), and anotherInt is now (anotherInt)")
    
    //函数类型
    //每一个函数都有特定的函数类型,由函数的形参类型和返回类型组成。
    func addTwoInts(a:Int,b:Int)->Int
    {
        return a+b
    }
    
    func multiplyTwoInts(a:Int,b:Int)->Int
    {
        return a*b
    }
    
    func printHelloWorld()->()
    {
        print("hello world")
    }
    
    //使用函数类型
    var mathFunction:(Int,Int)->Int=addTwoInts
    
    print("result: (mathFunction(2,3))")
    
    mathFunction=multiplyTwoInts
    print("result: (mathFunction(2,3))")
    
    let anotherMathFunction=addTwoInts
    print("result: (anotherMathFunction(2,b: 3))")
    //作为形参类型的函数类型
    //您可以使用一个函数类型,作为另一个函数的形参类型
    func printMathResult(mathFunction:(Int,Int)->Int,a:Int,b:Int)
    {
        print("Result: (mathFunction(a,b))")
    }
    
    printMathResult(addTwoInts, a: 3, b: 5)
    
    ////作为返回类型的函数类型
    ////你可以将一个函数类型作为另一个函数的返回类型,你可以在返回函数的返回肩头后立即编写一个完整的函数类型来实现
    //func stepFoward(input:Int)->Int
    //{
    //    return input+1
    //}
    //
    //func stepBackWard(input:Int)->Int
    //{
    //    return input-1
    //}
    //
    //func chooseStepFunction(backwards:Bool)->(Int)->Int
    //{
    //    return backwards ? stepFoward:stepBackWard
    //}
    //
    //var currentValue=3
    //let moveNearerToZero=chooseStepFunction(currentValue>0)
    //
    //moveNearerToZero(3)
    
    //嵌套函数
    //  嵌套函数默认对外界隐藏的,但仍然可以通过他们包裹的函数调用和使用它。 enclosing function也可以返回
    //一个嵌套函数,以便在其他作用域中使用嵌套函数
    func chooseStepFunction(backwards:Bool)->(Int)->Int
    {
        func stepForward(input:Int)->(Int){return input+1}
        
        func stepBckward(input:Int)->(Int){return input-1}
        
        return backwards ? stepBckward : stepForward
    }
    
    var currentValue = -4
    let moveNearerToZero=chooseStepFunction(currentValue>0)
    
    
    
    while currentValue != 0   {
        print("(currentValue)")
        currentValue=moveNearerToZero(currentValue)
    }
    print("zero")
    
  • 相关阅读:
    SpringMVC 下载本地文件
    Spring MVC 自定义转换器
    Struts,Hibernate,Spring经典面试题
    SpingMVC 执行的流程
    SpringMVC 应用配置
    SpringMVC特点
    Struts2学习
    mysql免安装配置
    mysql免安装版设置密码
    《金色梦乡》金句摘抄(六)
  • 原文地址:https://www.cnblogs.com/xinshijie/p/5611315.html
Copyright © 2011-2022 走看看