美文网首页
Swift语法备忘录1-Simple Values

Swift语法备忘录1-Simple Values

作者: 叶子扬 | 来源:发表于2018-01-06 15:59 被阅读0次

    这句代码已经是一个完整的程序了

    print("Hello World")
    

    let 声明恒量 编译期不需要知道类型,但是必须正确的赋值
    var 声明变量

    自动类型推断这个恒量的类型,另外,也在冒号后面指定类型

    let implicitFloat:Float = 4
    print(implicitFloat)
    

    不能含蓄的进行类型转换,需要明确的指定类型

    let label = "the width is "
    let width = 94
    let labelWidth = label + String(width)
    print(labelWidth)
    

    拼接不同类型的变量

    let oldFloat = 4.0
    let Jack = "Jack"
    let jackOld = "jack is \(oldFloat) years old"
    print(jackOld)
    

    """ 连续的三个双引号表示换行

    let apples = 3
    let oranges = 5
    let quotation = """
    I said "I have \(apples) apples."
    And then I said "I have \(apples + oranges) pieces of fruit."
    """
    print(quotation)
    

    使用圆括号和方括号创建数组和字典([]),使用索引获取或者赋值,允许子啊末尾添加一个逗号

    var shoppingList = ["catfish", "water", "tulips", "blue paint"]
    print(shoppingList)  ["catfish", "water", "tulips", "blue paint"]
    shoppingList[1] = "bottle of water"
    print(shoppingList)  ["catfish", "bottle of water", "tulips", "blue paint"]
    
    var occupations = [
        "Malcolm": "Captain",
        "Kaylee": "Mechanic",
    ]
    occupations["Jayne"] = "Public Relations"
    print(occupations)
    

    初始化空的数组和字典,需要使用初始化格式

    let emptyArrar = [String]()
    let emptyDic = [String: Float]()
     如果消息可以推断出来,就不用指定类型了, 比如,给新变量赋值,或者函数传参
    shoppingList = []
    occupations = [:]
    print(shoppingList)
    print(occupations)
    

    相关文章

      网友评论

          本文标题:Swift语法备忘录1-Simple Values

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