美文网首页
swift基础一

swift基础一

作者: 喜剧收尾_XWX | 来源:发表于2021-03-31 17:11 被阅读0次

    1.打印

    print("hello world")
    

    2.生命常量和变量

    • 使用let声明常量,var变量
            let age = 18
            var name = "xingweixin"
            name = "fmy"
            var height:Double = 172.0 //后边加类型
            height = 160.0
            print(age)
            print(name)
            print(height)
            print("name:\(name)  age:\(age) height:\(height)")
    

    3.if语句

    let contentHeight = 40
    let hasHeader = true
    var rowHeight = contentHeight
    if hasHeader {
        rowHeight = rowHeight + 50
    } else {
        rowHeight = rowHeight + 20
    }
    

    4.for循环

    //方式一
    for index in 1...5 {
        print("\(index) * 5 = \(index * 5)")
    }
    //方式二a..<b
    let names = ["Anna", "Alex", "Brian", "Jack"]
    let count = names.count
    for i in 0..<count {
        print("第 \(i + 1) 个人叫 \(names[i])")
    }
    //方式三
    for name in names[2...] {
        print(name)
    }
    // Brian
    // Jack
    
    for name in names[...2] {
        print(name)
    }
    // Anna
    // Alex
    // Brian
    //方式四
    for name in names[..<2] {
        print(name)
    }
    // Anna
    // Alex
    
    

    5.字符串

    • 初始化
    var emptyString = ""               // 空字符串字面量
    var anotherEmptyString = String()  // 初始化方法
    // 两个字符串均为空并等价。
    
    • 判断为空
    if emptyString.isEmpty {
        print("Nothing to see here")
    }
    
    • 字符串的可变性
    var variableString = "Horse"
    variableString += " and carriage"
    // variableString 现在为 "Horse and carriage"
    
    let constantString = "Highlander"
    constantString += " and another Highlander"
    // 这会报告一个编译错误(compile-time error) - 常量字符串不可以被修改。
    
    //在 Objective-C 和 Cocoa 中,需要通过选择两个不同的类(NSString 和 NSMutableString)来指定字符串是否可以被修改
    
    • 拼接字符串
    let string1 = "hello"
    let string2 = " there"
    var welcome = string1 + string2
    // welcome 现在等于 "hello there"
    
    var instruction = "look over"
    instruction += string2
    // instruction 现在等于 "look over there"
    
    let exclamationMark: Character = "!"
    welcome.append(exclamationMark)
    // welcome 现在等于 "hello there!"
    
    

    相关文章

      网友评论

          本文标题:swift基础一

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