美文网首页
第一个Swift程序

第一个Swift程序

作者: 写啥呢 | 来源:发表于2016-08-06 13:51 被阅读0次

    第一个Swift程序

    print("Hello, world!")
    //默认情况下printf()函数输出后会自动换行,如果不希望换行,可以通过指定terminator参数设定自己的是否换行
    print("Hello, world!",terminator: "")
    

    变量和常量

    let apples = 3
    let oranges = 5
    let appleSummary = "I have \(apples) apples."//转译字符用法
    let fruitSummary = "I have \(apples + oranges) pieces of fruit."
    
    

    元组

    用一个变量或一个常量保存多项信息

    let stu: (id: Int, name: String,gender: Bool,age: Int) = (1001,"王大锤",true,23
    )
    let (_,j, _, k) = stu //下划线表示不要()省略和忽略元组的第一项和第三项
    //用元组交换两个变量的值
    var x = 5 , y = 10
    (x,y) = (y,x)
    

    运算符

    // 算数运算符 + - *    / %
    //关系运算符 == != > >= < <=
    //短路运算符 && ||
    字符串的连接
    var string1 = "hello"
    var string2 = "world"
    string1 = string1 + " " + string2
    三元条件运算符
    //let a = 5 , b = 10
    //let c = a < b ? a : b
    

    分支结构

    游戏举例说明switch case

    func name(a:Int)->String{
        var msg: String
        
        switch a{
            
        case 1:
            msg="石头"
        case 2:
            msg="剪刀"
        case 3:
            msg="布"
            
        default:
            msg="输入错误"
        }
        return msg
    }
    func compare(a:Int,b:Int)->(String,Int,Int){
        var msg1: String
        var humanWin: Int = 0
        var win = 0
        if a==b{
            msg1="平局"
            win = 0
            humanWin = 0
        }
        else if  a==1&&b==2 || a==2&&b==3 || a==3&&b==1{
            msg1 = "你赢了"
            win = 0
            humanWin = 1
        }
        else{
            msg1 = "电脑赢了"
            win = 1
            humanWin = 0
        }
        return (msg1,humanWin,win)
        
    }
    

    if else 说明

    //计算某年的某个月有多少天
    //
    print("请输入年份:",terminator: " ")
    
    let year = inputInt()
    print("请输入月份",terminator: " ")
    let month = inputInt()
    let day: Int
    if year > 0 && month>=1 && month<=12{
        if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
            day = 31
        }
        else if month != 2{
            day = 30
        }
    //    else if year % 4 == 0 && year % 100 != 0 || year % 400 == 0 {
    //        day = 29
    //    }
    //    else {
    //        day = 28
    //    }
        else {day = year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ? 29 : 28}
        print("day=\(day)")
    }
    else{
        print("输入错误")
    }
    

    循环结构

    while 循环--有可能一次都不执行

    var i = 0
    while i < 10 {
        print("\(i)+\"\"Hello, World!")
        i += 1
    }
    

    repeat while 循环自少要执行一次循环体内容

    var i = 1
    repeat {
        print("\(i).hello,world")
     i += 1
    }while i <= 10
    

    for 循环

    for _ in 1..<10{//_ 下划线表示实参可以省略
        print("hello,world")
    }
    for i in 1...10{
        print("\(i).hello,world")
    }
    

    数组

    //1.创建一个空数组
    var array1 = [String]()
    var array2:[Int] = []
    var array3 = ["hello","world"]
    var array4 = [Int](count: 100, repeatedValue: 1)
    //修改元素
    array3[1...1]=["www"]
    print(array3)
    
    //2.向数组中添加元素
    array1.append("strawberry")//append追加 insert 插入
    array1.append("pear")
    array1 += ["pear"]
    array1.insert("waxberry", atIndex: 0)
    array1.insert("watermelon", atIndex: 2)
    array1.insert("lemon", atIndex: array1.count)
    print(array1)
    
    //3.从数组中删除元素全是 .remove(xxxx)
    array1.removeAll() //元素全部删除完,并回收空间
    print(array1)
    array1.removeAll(keepCapacity: true)//true只删除元素不会删除空间
    array1.removeAtIndex(3)//
    array1.removeFirst(100) //删除前100个元素
    array1.removeRange(<#T##subRange: Range<Int>##Range<Int>#>)//删除的范围
    
    //4.数组的复制
    var array1 = ["hello","world"]
    var array2 = array1
        array2[0] = "aaaaaa"
    //第二种写法
    var array3 = array1[1..<array3.count]
    
    //5.数组的元素合并成新数组(数组的+运算)
    var array1
    var array2
    var array3 = array1 + array2
    
    //6.获取数组元素的个数
    var array1 = ["hello","world"]
    print(array1.count)
    
    //7.对数组中的元素进行遍历
    for index in 0..<array3.count{
        //[]是对数组进行的下表运算(取出指定位置的元素)
        print(array3[index])
        if index == 1{
            array3[index] = "hhh"
        }
    }
    print(array3)
    //只读循环,在循环中不能修改数组中的元素
    for str in array3{
        print(str)
    }
    

    小游戏总结

    分支加循环的应用:

    猜值游戏

    var thyAnswer: Int
    var counter = 0
    let answer = Int(arc4random_uniform(100)) + 1
    repeat {
        counter += 1
        print("请输入你猜的数字:",terminator:"")
         thyAnswer = inputInt()
        if thyAnswer > answer{
            print("小一点")
        }
        else if thyAnswer < answer{
            print("大一点")
        }
        else {
            print("恭喜你,猜对了,你总共猜了\(counter)次")
        }
    }while thyAnswer != answer
    if counter > 7 {
        print("你的智商该充值")
    }
    

    for循环的应用:

    百钱买白鸡游戏 ocr图片识别软件
    GET: 穷举法,穷尽所有可能性直到找到正确答案

    for x in 0...20{
        for y in 0...33{
            let   z = 100 - x - y
                if   5 * x + 3 * y + z / 3 == 100 && z % 3 == 0{
                    print("公鸡:\(x),母鸡:\(y),小鸡:\(z)")
            }
        }
    }
    

    分鱼游戏

    循环分支语句的练习

    var total = 1
    var bool  = true
    while bool{
        // 用当次循环时total的值作为鱼的总数
        var fish = total
        // 假设鱼的数量足够五个人分
        var isEnough = true
        //通过循环模拟五个人分鱼的过程
        for _ in 1...5 {
    //        检查剩下的与是否够分
            if (fish - 1) % 5 == 0 {
                fish = (fish - 1) / 5 * 4
            }
            else{
    //            如果鱼不够分就将isEnough赋值为false并提前结束分鱼的循环
                isEnough = false
                bool = true
            }
        }
        if isEnough{
            print(total)
            bool = false
        }
        total += 1
    }
    

    数组的应用:提高代码质量

    func roll() ->Int{
        return  Int(arc4random_uniform(6))+1
    }
    
    //定义一个放整数的数组(6个元素,初始值都为0)
    var f = [Int](count: 11, repeatedValue: 0)//var f: [Int]
    for _ in 0..<600000{
        let face = roll() + roll()
        f[face - 2] += 1
    }
    for i in 0..<f.count{
        print("\(i+2)点摇出了\(f[i])次")
    }
    

    用图片做出动画效果

    //核心代码:
    var imageView: UIImageView!
     let screenHeight = self.view.bounds.size.height
    
            imageView = UIImageView(frame: CGRectMake(0, screenHeight / 2 - 50, 75, 100))
            // imageView.backgroundColor = UIColor.clearColor()
            // imageView.image = UIImage(named: "runner0")
            imageView.animationImages = [
                UIImage(named: "runner0")!,
                UIImage(named: "runner1")!,
                UIImage(named: "runner2")!,
                UIImage(named: "runner3")!,
                UIImage(named: "runner4")!,
                UIImage(named: "runner5")!
            ]
            imageView.animationDuration = 0.6
            self.view.addSubview(imageView)
            imageView.startAnimating()
            timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "runForward", userInfo: nil, repeats: true)
    
    imageView.animationImages = []如果用了这句话那么下面那句话也得用
    imageView.startAnimating()//不要这句话程序会报错
    
    
    
        func runForward() {
            var frame = imageView.frame//图片的另一个属性
            frame.origin.x += 12
            imageView.frame = frame//这句话必须写不然图片不会移动的
            if frame.origin.x > self.view.bounds.size.width {
                frame.origin.x = -75
                imageView.frame = frame
            }
        }
    

    剪刀石头布用case 语句写法 加 元组

    
    //剪刀1石头2布3
    
    //repeat{
    //    let machine = Int(arc4random_uniform(3)) + 1
    //    print("请出拳:",terminator:" ")
    //    let me = inputInt()
    //    if me > 0 && me < 4{
    //        switch (machine,me){
    //        case (1,1),(2,2),(3,3):
    //            print("平局")
    //        case (1,2),(2,3),(3,1):
    //            print("ren赢")
    //        default:
    //            print("ren输")
    //        }
    //    }
    //else{
    //        print("输入错误")
    //    }
    //}while true
    

    相关文章

      网友评论

          本文标题:第一个Swift程序

          本文链接:https://www.haomeiwen.com/subject/tgsksttx.html