//
// main.swift
// swift_test
//
// Created by collonn on 14-6-9.
// Copyright (c) 2014年 ___abc___. All rights reserved.
//
import Foundation
//这是单行注释
//var用来声明变量,变量的值是可以修改的
//let用来声明常量,一但赋值后,就不能再修改了
/*这是多行注释1
/*这是多行注释2*/
这是多行注释3*/
//整形
var a1 = 1;
var a2:Int = 2;//推荐使用,32位平台上Int=Int32,在64位平台上Int=Int64
var a3:Int8 = 3;
var a4:Int16 = 4;
var a5:Int32 = 5;
var a6:Int64 = 6;
var a7:UInt = 7;
var a8:UInt8 = 8;
var a9:UInt16 = 9;
var a10:UInt32 = 10;
var a11:UInt64 = 11;
println("a1=\(a1), a2=\(a2), a3=\(a3), a4=\(a4), a5=\(a5), a6=\(a6), a7=\(a7), a8=\(a8), a9=\(a9), a10=\(a10), a11=\(a11)")
//浮点型
var b1 = 1.1;//这样声明时,默认总是Double类型
var b2:Double = 1.2;
var b3:Float = 1.3;
var b4 = 1 + 1.1//这样声明时,默认总是Double类型
println("b1=\(b1), b2=\(b2), b3=\(b3)")
//整数和浮点数都可以被额外的零填充,并且可以包含下划线,以增加可读性
let b5 = 000123.456
let b6 = 1_000_000
let b7 = 1_000_000.000_000_1
println("b5=\(b5), b6=\(b6), b7=\(b7)")
//bool型
var c1 = true;
var c2 = false;
var c3:Bool = true
println("c1=\(c1), c2=\(c2), c3=\(c3)")
//字符串型
var d1 = "Swift"
var 姓名 = "冰冻火山"
println("d1=\(d1), 姓名=\(姓名)")
println("Hello, " + d1 + ", " + 姓名)
//用一行代码,声明不同的基本类型的变量
var e1 = 1, e2 = 1.1, e3 = true
println("e1=\(e1), e2=\(e2), e3=\(e3)")
var f1 = 1; var f2 = 1.1; var f3 = true; var f4 = "Swift"; let f5 = "Apple"
println("f1=\(f1), f2=\(f2), f3=\(f3), f4=\(f4), f5=\(f5)")
//类型转换
var g1 = 1
var g2 = 1.1
var g3 = Double(g1) + g2
var g4 = g1 + Int(g2)
var g5 = "1.1"
var g6 = g5 + String(g1)
println("g3=\(g3), g4=\(g4), g5=\(g5), g6=\(g6)")
//元组类型
var tuple = (name: "Swift", age: 4)
println("name=\(tuple.name), age=\(tuple.age)")
var (_name, _age) = tuple
println("name=\(_name), age=\(_age)")
var (_name2, _) = tuple
println("name2=\(_name2)")
var (_, _age2) = tuple
println("age2=\(_age2)")
var (name, age) = ("Swift", 4)
println("name=\(name), age=\(age)")
tuple = ("Swift", 4)
println("name=\(tuple.0), age=\(tuple.1)")
//可选类型
var h1:Int? //h1是Int类型,但此时h1的值是未知的,即默认值nil
println("h1=\(h1)")
var h2:Int? = 1 //h1是Int类型,但此时h1的值是1,但不知道以后的值是什么
println("h2=\(h2), h2=\(h2!)")
var h3:Int! = 1 //h1是Int类型,并且明确的知道h1的值以后也是1
println("h3=\(h3)")
var h4 = "Swift".toInt()
print("h4可选类型是否包含一个特定的值?")
if(h4) {
print("yes")
} else {
print("no")
}
print("\n")
var h5 = "123".toInt()
print("h5可选类型是否包含一个特定的值?")
if(h5) {
println("yes")
} else {
println("no")
}
print("\n")
//使用断言调试
var j1 = 123
assert(j1 == 123)
assert(j1 == 123, "j1 must be 123")
看代码学习 Apple Swift (一) 基本数据类型
最新推荐文章于 2024-03-09 21:51:37 发布