Swift学习笔记

Swfit

Swift初见

第一个HelloWorld
printf("hello,Swift")

简单值

用let声明常量,var声明变量

var myVariable = 42
myVariable = 50
let myConstant = 42

声明时类型可选,在__变量后面声明类型__,用冒号分割

let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70

创建一个隐式常量,类型为Float,值为4
let explicitFloat:Float = 4
值永远不会隐式转换为其他类型,如果需要类型转换,需要进行显示转换

//
//  main.swift
//  helloworld
//
//  Created by 张扬 on 15/5/10.
//  Copyright (c) 2015年 张扬. All rights reserved.
//

import Foundation

//let explicitFloat:Float = 4;

let lable = "The width is ";

 //// 需要注意的是,如果声明的常量为Int型,那么在转换时直接使用String(width)就可以将width的值显示转换为String
 //// 但是如果声明的常量为Double型或Float型,则使用String(width)编译器会报错,
 //// 需要在width前加入stringInterpolationSegment:

let width = 4;
//let width : Int = 4;

//let width : Float = 4;
//let width : Double = 4 ;

//let widthLable = lable + String(stringInterpolationSegment: width);
let widthLable = lable + String(width);

println(widthLable);

如果去掉String,则会报Binary operator '+' cannot be applied to operands of type 'String' and 'int'这个错误
这个显示类型转换看上去有点眼熟String widthLable = (String)Object这时Java中强制类型转换,与Swift中显示转换是不一样的,如果习惯性的给String加()会报错,大致意思是编译器认为语句在")"已经结束,但是后面还有一个width,所以需要在后面加";"

如果声明的常量为Int型,那么在转换时直接使用String(width)就可以将width的值显示转换为String,貌似是因为String(Int),调用的时String的init()方法,而String(Float/Double)则需要调用String的stringInterpolationSegment方法。

还有一种简单的办法,可以将值转换为字符串

let apple = 3;
let orange = 7 ;
let fruit = "I have \(apple + orange) piece of fruits";
println(fruit);

//// exercise
let width = 4.0;
let height = 3.0;
let squre = "The squre is \(width * height) cm * cm"
println(squre);

let height : Float = 185.34;
let name = "John"
let sayhello = "hello " + name+", I`m \(height) cm";
println(sayhello);


使用[]创建数组和字典,通过下表或键(key)访问元素。

//// 下标从0开始
var shoppingList = ["fish","meat","apples","water","blue paint"];
var first = "The first of list is "+shoppingList[0];

var numberList = [0,1,2,3,4,5,6,7,8,9];
var second = "The second of numberList is \(numberList[1])";

var doubleList = [1.53,2.55,4.25];
var third = "The third of numberList is \(doubleList[2])";

var weekList = [
    "Monday": 1,
    "Wensday": "2",
    "Thusday": 3
];

//var monday = weekList[1];

var monday = weekList["Monday"];
var wendsday = weekList["Wensday"];

println("monday  = \(monday)");
println("wendsday = \(wendsday)");

// Array types are now written with the brackets around the element type
// let emptyArr = String[]();
// 声明一个空数组
let emptyArr = [String]();
let emptyDic = Dictionary<String,Float>();


//println(doubleList);
//println(third);


//println(second);
//println(numberList);

//println(first);
//println(shoppingList);

你可能感兴趣的:(swift)