Swift3.0学习笔记-The Basics(对比Java)

       根据苹果官网的顺序学习Swift语言:

https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309


        Swift是为iOS,macOS,watchOS和tvOS应用开发设计的一种新的语言。 Swift参考了很多C和Object-C语言的做法。
       Swift实现了所有C和OC的基础数据类型, 包括整型Int,Double和Float作为浮点数类型,布尔类型Bool,字符串类型String。而且Swift提供了3种主要并且功能强大的集合类型,包括Array,Set和Dictionary。
       跟C语言类似,Swift使用变量存值和通过变量取值。 Swift还实现了常量数据类型,即值不可更改,而且比C语言常量要更可靠。一般在你不希望值被篡改时使用常量,从而使得Swift语言更安全、清晰。

        除了熟悉的数据类型, Swift还提供了OC没有的数据类型,例如元组。元组可以创建和传值多个变量。
       Swift
还提供可能数据类型,处理变量没赋初值的情况。Optional可能有值也可能没值,没值时等于nil这个nilOCnil不同,Swiftnil可以赋给任意数据类型,这是Swift一个核心特性。

       Swift是类型安全的语言,即Swift会确定每个变量的数据类型。如果一个参数是String类型,那么无法赋Int型赋值给它。类似的,你无法将可选字符串类型赋值给字符串类型。数据类型检查在编码阶段就会被Xcode检查出来并提示错误。


下面用SwiftJava逐一说明基本语法:

let用于声明常量(类似于Java的final关键字),var用于声明变量(Java中无类似关键字)

/** 常量和变量 let做常量 var做变量**/

let ConstantValue ="constant" //常量,隐式String类型。不可修改

var value = "value"          //变量,编译器会根据之类型设置变量类型

value = "modify"     //修改value变量

//ConstantValue = "modify"   //这句会报错,常量不能修改

print("No1:"+ value)


final String ConstantValue = "constant";
String value = "value";
value = "modify";
System.out.println("No1:" + value);
说明:Swift没有分号、以换行符为一句代码的结束符;Java以分号作为一句代码的结束符。Swift可以不像Java那样显式的声明变量类型,初值的类型就是参数类型。

let lable = "the width is "

let width = 94

let widthLable = lable+ String(width)

print(widthLable)    //the width is 94

 
  
 
  
String lable = "the width is";
int width = 94;
String widthLable = lable + width;
System.out.println(widthLable);
说明:在Swift语言中整型和字符串类型拼接时,要先将整型转换为字符串类型。(Swift是类型安全的)

var x=0.0, y=0.0, z=0, strValue="test"//声明多个变量,以逗号分隔,隐式的根据值设置变量类型。x和y是Int型,z是Double型,strValue是String型

var red, green, blue:Double  //red green blue都是Double类型

var welcomeMessage:String   //: Swift里是type of的意思,即指定数据类型

welcomeMessage = strValue

print("welcomeMessage:"+ welcomeMessage//welcomMessage:test


double x=0.0, y=0.0;
int z=0;
String strValue = "test";
double red, green, blue;
String welcomeMessage;
welcomeMessage = strValue;
System.out.println("welcomMessage:" + welcomeMessage);
说明:在Swift语言中,一行代码可以声明多种数据类型,而Java只能声明一种;Swift里的冒号空格对应的英文解释是type of,即后面是数据类型、前面是变量名;

let apples = 3

let oranges = 5   //Int

let appleSummary ="I have \(apples) apples"

let fruitSummary ="I have \(apples+oranges) pieces of fruit"

print("fruitSummary"+ fruitSummary)

final int apples = 3;
final int oranges = 5;
final String appleSummary = "I have " + apples + " apples";
final String fruitSummary = "I have" + (apples+oranges) + " piece of fruit";
System.out.println("fruitSummary" + fruitSummary);

说明:在Swift中字符串里添加整型变量时用\(Int)方式,例如\(apples)。


var tmp1 = 1;

var tmp2 = 2.1;

var tmp3: Double

tmp3 = Double(tmp1) +tmp2     //Swift是类型安全语言,编译器不会修改参数类型。tmp1是整型,需要强转为Double才能相加。

int tmp1 = 1;
double tmp2 = 2.1;
double tmp3;
tmp3 = tmp1 + tmp2;
说明:Swift是类型安全语言,Java不是类型安全语言;在Swift中要先强转tmp1为Double型才能与tmp2相加,而在Java中编译器会直接将tmp1的值转换为double型,不用显式的强转。Swift和Java的强转方法有区别,Swifit是Double(tmp1),即参数外加圆括号;Java是(double)tmp1,即关键字外加括号。

//类型转换

let meaningOfLife = 42  //Int型译

let pi=3.14159  //有小数时默认数据类型总是为Double型,而不是Float

let anotherPi = 3 + 0.14159    //3Int型,0.14159Double型,所以anotherPiDouble

let resultPi = pi -anotherPi   //resultPi是Double型

print("pi result:"+ String(resultPi)) //0.0


//进制,下面4个参数都是十进制的17

let dcimalInteger = 17      //十进制

let binaryInteger = 0b10001 //二进制,以0b开头

let octalInteger = 0o21     //八进制,以0o开头

let hexadecimalInteger = 0x11  //十六进制,以0x开头


//数字写法

let paddingDouble = 000123.456  //可以在数字前边加0

let oneMillion = 1_000_000     //西方写法一百万,Int1000000,以_为占位符,方便理解位数

let justOverOneMillion = 1_000_000.000_000_1

let oneMillion1 = 100_0000   //中国写法,100

let oneMillionJava = 1000000;  //Java和C的写法,100

说明:在数字里下划线是占位符,没有任何意义,只是为了提高可读性。 这个设计很赞,再也不用数0了


//数字越界编译器会检查,如果出现越界时编译报错

//let cannotBeNegative: UInt8 = -1   //这样写会提示错误!

说明:Xcode和Android Studio都会检查值的范围,如果越界会给出错误提示。


//自定义关键字,类似于C语言的typedef

typealias IntType =Int    //IntType等同于Int

var typeTest1: IntType    //typeTest1Int

typeTest1 = 10

var typeTest2: Int

typeTest2 = 10

print("typealias result:"+ String(typeTest2-typeTest1)) //typealias result:0

说明:在Java中没有类似功能关键字。


//布尔值

let orangesAreOrange = true //Bool

let turnipsAreDelicious = false

if turnipsAreDelicious {

    print("Mmm, tasty turnips")

} else {

    print("Eww, trunips are horrible")

}


let i = 1

if i ==1 {

    print("this will be executed")  //this will be execute

}


final boolean orangeAreOrange = true;
final boolean turnipsAreDelicious = false;
if (turnipsAreDelicious) {
    System.out.print("Mmm, tasty turnips");
} else {
    System.out.print("Eww, trunips are horrible");
}
final int i = 1;
if (i == 1) {
    System.out.println("this will be executed");
}
说明:Swift的布尔关键字是Bool,等同于Java的boolean。 if的用法也都一致, 区别是Swift if判断语句没有圆括号。

//键值对

let http404Error = (404,"Not Found")//http404Error是键值对(Int, String)类型

let (statusCode, statusMsg) = http404Error   //参数statusCode,statusMsg是值http404Error的类型

print("The status code is\(statusCode)"//The status code is 404

print("The status Message is\(statusMsg)")

let (justStatusCode, _) =http404Error  //只需要一个值时,另一个可以用_做占位符

print("The status code is\(justStatusCode)")

print("The status code is\(http404Error.0)")//使用下标取值,"The status code is 404"

说明:类似于Java的Map,但Swift的键值对用法更加灵活方便。下划线可以作为占位符。


//Optional 不确定类型?

let possibleNumber = "123"

let convertNumber =Int(possibleNumber)   //这时convertNumberInt?

let possibleNumber1 = "abc"

let convertNumber1 =Int(possibleNumber1//这时convertNumber1Int?型,值为nil

if convertNumber !=nil {

    print("convertNumber:"+ String(describing:convertNumber))

    

if convertNumber1 ==nil {

    print("convertNumber1 is nil"//convertNumber1 is nil

}

说明:Optional类型是指变量可能没赋初值的情况, 这时值是nil。 nil的含义就是没值,在Swift里不是指针;Java里没有类似数据类型。

//nil 不是指针,可以赋值给任何数据类型,类似于Java没赋初值的情况

var serverResponseCode: Int? = 404 //声明加赋值404

serverResponseCode = nil

var nilInt: Int

//nilInt = nil      //提示错误,nil不能赋给Int

说明:对于基本数据类型,不能赋值为nil;可选数据类型(?)可以赋值为nil。


//确定数据类型!即肯定有值

let possibleString: String? ="an optional String"

let forcedString: String =possibleString!

let assumedString:String! = "An implicitly unwrapped optional String"

let implicitString: String  =assumedString   //不需要感叹号

说明:?和!在Swift中类似,区别是?可能为ni,而!不可能为nil, ?指可能的数据类型,!是肯定的数据类型。 换句话说,Optional(?)类型可能存在空值nil的情况,而!指任何时候参数里都有值。


//如果possibleNumber是个数字,那么赋值给actualNumber,actualNumberInt

if let actualNumber =Int(possibleNumber) {

    print("possibleNumber has an Interger value of\(actualNumber)")

} else {

    print("possibleNumber could not be converted to Integer")

}

说明:如果possibleNumber由数字组成的字符串,例如”123“, 那么if会为真;否则为假。

/** 数组使用[]创建一个数组或字典,通过indexkey获取对应的之**/

var shoppingList = ["catfish","water", "tulips"]  //String数组,含有3个值

shoppingList[1] ="bottle of water"   //修改第2个值

var occupations = [

    "key1":"value1",

    "key2":"value2",

occupations["key1"] ="modify value1"

var someStrs = [String]()   //String类型的空数组

var someStrs1: [String] = ["first","second"]


String[] shoppingList = {"catfish", "water", "tulips"};
shoppingList[1] = "bottle of water"; //通过下标修改值
//使用HashMap实现...
String[] someStrs = new String[3];
String[] someStrs1 = {"first", "second"};
说明:Swift声明数组的方式跟Java类似, 区别是Swift对关键字加方框,而Java是对值加方框;occupations类似于Java的new HashMap()


小结:
       1、Swift声明参数分为显示和隐式的方法, 而Java只能是显式。
       2、Swift的nil并不是空指针,可以理解为空值。 因为它可以赋值给Optional类型。
       3、Swift对数字添加了下划线作为占位符,提高了可读性;
       4、Swift是类型安全语言,Int和Double型不能直接加减乘除;而Java是可以的。

附参考代码:
//
//  main.swift
//  swiftdemo
//
//  Created by brycegao on 16/11/5.
//  Copyright © 2016年 brycegao. All rights reserved.
//

import Foundation

print("The Basics")
//https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309

var tmp1 = 1;
var tmp2 = 2.1;
var tmp3: Double
tmp3 = Double(tmp1) + tmp2

/** 常量和变量 let做常量 var做变量**/
let ConstantValue = "constant"  //常量,隐式String类型。不可修改
var value = "value"          //变量,编译器会根据之类型设置变量类型
value = "modify"      //修改value变量
//ConstantValue = "modify"   //这句会报错,常量不能修改
print("No1:" + value)

let lable = "the width is "
let width = 94
let widthLable = lable + String(width)
print(widthLable)     //the width is 94

var x=0.0, y=0.0, z=0, strValue="test" //声明多个变量,以逗号分隔,隐式的根据值设置变量类型
var red, green, blue: Double  //red green blue都是Double类型
var welcomeMessage: String   //: 在Swift里是type of的意思, 即指定数据类型
welcomeMessage = strValue
print("welcomeMessage:" + welcomeMessage)  //welcomMessage:test

let apples = 3
let oranges = 5    //Int型
let appleSummary = "I have \(apples) apples"
let fruitSummary = "I have \(apples+oranges) pieces of fruit"
print("fruitSummary" + fruitSummary)

var iTest1: Int     //在32位平台下等同于Int32, 64位平台下等同于Int64
var iTest2: Int64
iTest2 = 3

//类型转换
let meaningOfLife = 42   //Int型译
let pi=3.14159   //有小数时默认数据类型总是为Double型,而不是Float
let anotherPi = 3 + 0.14159     //3是Int型,0.14159是Double型,所以anotherPi是Double型
let resultPi = pi - anotherPi
print("pi result:" + String(resultPi))  //0.0

//进制
let dcimalInteger = 17       //十进制
let binaryInteger = 0b10001  //二进制
let octalInteger = 0o21      //八进制
let hexadecimalInteger = 0x11  //十六进制

//数字写法
let paddingDouble = 000123.456   //可以在数字前边加0
let oneMillion = 1_000_000     //西方写法一百万,Int型1000000,以_为占位符,方便理解位数
let justOverOneMillion = 1_000_000.000_000_1
let oneMillion1 = 100_0000    //中国写法,100万
let oneMillionJava = 1000000; //Java/C的写法,100万

//数字越界 编译器会检查,如果出现越界时编译报错
//let cannotBeNegative: UInt8 = -1   //这样写会提示错误!

//整型和浮点型转换, 强转语法如Double(value)
let three = 3 //Int型
let pointOneFourOneFiveNine = 0.14159 //Double型
let pi1 = Double(three) + pointOneFourOneFiveNine   //pi是Double型


//自定义关键字,类似于C语言的typedef
typealias IntType = Int    //IntType等同于Int
var typeTest1: IntType    //typeTest1是Int型
typeTest1 = 10
var typeTest2: Int
typeTest2 = 10
print("typealias result:" + String(typeTest2-typeTest1))  //typealias result:0

//布尔值
let orangesAreOrange = true  //Bool型
let turnipsAreDelicious = false
if turnipsAreDelicious {
    print("Mmm, tasty turnips")
} else {
    print("Eww, trunips are horrible")
}

let i = 1
if i == 1 {
    print("this will be executed")   //this will be execute
}

//键值对
let http404Error = (404, "Not Found") //http404Error是键值对(Int, String)类型
let (statusCode, statusMsg) = http404Error
print("The status code is \(statusCode)")  //The status code is 404
print("The status Message is \(statusMsg)")
let (justStatusCode, _) = http404Error  //只需要一个值时,另一个可以用_做占位符
print("The status code is \(justStatusCode)")
print("The status code is \(http404Error.0)") //使用下标取值,"The status code is 404"


//不确定类型?
let possibleNumber = "123"
let convertNumber = Int(possibleNumber)    //这时convertNumber是Int?型
let possibleNumber1 = "abc"
let convertNumber1 = Int(possibleNumber1)  //这时convertNumber1是Int?型,值为nil
if convertNumber != nil {
    print("convertNumber:" + String(describing: convertNumber))
}
    
if convertNumber1 == nil {
    print("convertNumber1 is nil")  //convertNumber1 is nil
}

//nil 不是指针,可以赋值给任何数据类型,类似于Java没赋初值的情况
var serverResponseCode: Int? = 404  //声明加赋值404
serverResponseCode = nil
var nilInt: Int
//nilInt = nil      //提示错误,nil不能赋给Int型


//确定数据类型! 即肯定有值
let possibleString: String? = "an optional String"
let forcedString: String = possibleString!
let assumedString: String! = "An implicitly unwrapped optional String"
let implicitString: String  = assumedString   //不需要感叹号


//如果possibleNumber是个数字, 那么赋值给actualNumber, 且actualNumber是Int型
if let actualNumber = Int(possibleNumber) {
    print("possibleNumber has an Interger value of \(actualNumber)")
} else {
    print("possibleNumber could not be converted to Integer")
}

/** 数组 使用[]创建一个数组或字典,通过index或key获取对应的之**/
var shoppingList = ["catfish", "water", "tulips"]   //String数组,含有3个值
shoppingList[1] = "bottle of water"   //修改第2个值
var occupations = [
    "key1": "value1",
    "key2": "value2",
]
occupations["key1"] = "modify value1"

var someStrs = [String]()    //String类型的空数组
var someStrs1: [String] = ["first", "second"]


你可能感兴趣的:(Swift基础)