Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Swift Cheat Sheet [1] — Basic Types大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

常量和变量 Varibales var myInt = 1 //inexplicit type var myExpliciTint : Int = 1 // explicit type var x = 1, y = 2, z = 3 //declare multiple Integers myExpliciTint = 3 // set to another Integer value Const

常量和变量

Varibales

var myInt = 1 //inexplicit type
var myExpliciTint : Int = 1 // explicit type
var x = 1,y = 2,z = 3 //declare multiple Integers
myExpliciTint = 3 // set to another Integer value

Constants

let myInt = 1
myInt = 2 //compile-time error !!!

常量和变量的命名

let π = 3.14159
let 你好 = "你好世界"
let ���� = "dogcow" //可以用任何字符作为常量或变量名,包括Unicode字符

可选类型

可选类型,暗示常量或者变量可以没有值。

let possiblenumber = "123"
let convertednumber = Int(possiblenumber)
// convertednumber 被推测为类型 "Int?", 或者类型 "optional Int"

nil

可以给可选变量赋值为nil来表示它没有值.

var serverResponseCode: Int? = 404
// serverResponseCode 包含一个可选的 Int 值 404
serverResponseCode = nil
// serverResponseCode 现在不包含值

如果你声明一个可选常量或者变量但是没有赋值,它们会自动被设置为nil

var surveyAnswer: String?
// surveyAnswer 被自动设置为 nil

注意:

if 语句以及可选值的强制解析(forced unwrapping)

使用if语句和nil比较来判断一个可选值是否包含值
当你确定可选类型确实包含值之后,你可以在可选的名字后面加一个感叹号(!)来获取

var convertednumber : Int? = 10
if convertednumber != nil{
    print("convertednumber has an Integer value of \(convertednumber!)")
}
// 输出 "convertednumber has an Integer value of 10"

可选绑定(option binding)

使用可选绑定(optional binding)来判断可选类型是否包含值,如果包含就把值赋给一个临时常量或者变量。可选绑定可以用在if和while语句中,这条语句不仅可以用来判断可选类型中是否有值,同时可以将可选类型中的值赋给一个常量或者变量

一个示例解析

  • 例:

    let possiblenumber = “123”
    if let actualnumber = Int(possiblenumber){
    print(“\’(possiblenumber)\’ has an Integer value of (actualnumber)”)
    }else{
    print(“\’(possiblenumber)\’ Could not be convered to an Integer”)
    }

  • 解释这个示例:
    如果Int(possiblenumber)返回的可选Int包含一个值,创建一个叫做actualnumber的新常量并将可选包含的值赋给它。
    如果转换成功,actualnumber常量可以在if语句的第一个分支中使用。它已经被可选类型包含的值初始化过,所以不需要再使用!后缀来获取它的值。在这个例子中,actualnumber只被用来输出转换结果。

包含多个可选绑定在条件判断语句中

if let firstnumber = Int("4"),secondnumber = Int("42") where firstnumber < secondnumber
{
    print("\(firstnumber) < \(secondnumber)")
}
// prints "4 < 42"

隐式解析可选类型(implicitly unwrapped optionals)

在Swift构造的过程中,当可选类型第一次赋值之后,就可以确定之后一直有值。这种情况下,可选类型的可选状态被定义为隐式解析可选类型。把可选类型后边的问号改为叹号。

let possibleString: String? = "An optional String."
let forcedString: String = possibleString! // 需要惊叹号来获取值

let assumedString: String! = "An implicitly unwrapped optional String."
let implicitString: String = assumedString  // 不需要感叹号

分号

//Swift不强制要求在语句结尾处使用分号,当然,也可以按照自己的习惯添加
//当在同一行内写多条独立的语句时,必须要用分号!
let cat = "��";print(cat)

整数

整数范围

使用min和max属性获取整数的最小值和最大值

let minValue = UInt8.min // minValue 为 0,是 UInt8 类型
let maxValue = UInt8.max  // maxValue 为 255,是 UInt8 类型

Int

  • 在32位平台上,int和Int32长度相同。
  • 在64位平台上,int和Int64长度相同。
  • Int足够用了。

UInt

  • 在32位平台上,UInt和UInt32长度相同。
  • 在64位平台上,UInt和UInt64长度相同。
  • 尽量不要使用UInt

浮点数

  • Double表示64位浮点数,至少15位小数点。当你需要存储很大或者很高精度的浮点数时请使用此类型。
  • Float表示32位浮点数,至少6位小数点。精度要求不高的话可以使用此类型。

String

操作符+

var myString = "a"
let myImmutableString = "c"
myString += "b" // ab
myString = myString + myImmutableString //abc
myImmutableString += "d" //compile-time error!!!

字符串插值\(value)

let count = 7
let message = "There are \(count) days in a week"

Bool值在if语句中的应用

let turnipsAreDelicIoUs = false
if turnipsAreDelicIoUs {
    print("Mmm,tasty turnips!")
}else {
    print("Eww,turnips are horrible.")
}

元组

元组(tuples)把多个值组合成一个复合值。元组内的值可以是任意类型,并不要求是相同类型。

创建一个元组

let http404Error = (404,"Not Found")
//let http404Error = (404,"Not Found")

分解元组内容

let http404Error = (404,"Not Found")
let (statusCode,statusmessagE) = http404Error
print(("The status code is \(statusCodE)"))
// 输出 "The status code is 404"
print("The status message is \(statusmessagE)")
// 输出 "The status message is Not Found"

用下划线_忽略一部分元组

如果你只需要一部分元组值,分解的时候可以把要忽略的部分用下划线(_)标记

let (justTheStatusCode,_) = http404Error
print("The status code is \(justTheStatusCodE)")
// 输出 "The status code is 404"

访问元组的单个元素

print("The status code is \(http404Error.0)")
// 输出 "The status code is 404"
print("The status message is \(http404Error.1)")
// 输出 "The status message is Not Found"

元组的单个元素命名

let http200Status = (statusCode: 200,description: "OK")

通过名字访问元组元素

print("The status code is \(http200Status.statusCodE)")
// 输出 "The status code is 200"
print("The status description is \(http200Status.description)")
// 输出 "The status message is OK"

类型别名

typealias AudioSample = UInt16
//使用typealias关键字来定义类型别名
var maxAmplitudeFound = AudioSample.min
//maxAmplitudeFound 现在是 0

类型转换

整数和浮点数

整数 to 浮点数

let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(threE) + pointOneFourOneFiveNine
// pi 等于 3.14159,所以被推测为 Double 类型

浮点数 to 整数

let IntegerPi = Int(pi)
// IntegerPi 等于 3,所以被推测为 Int 类型

整数和字符串

Int to String

let label = "The width is"
let width = 94
let widthLabel = label + String(width)// The width is 94

String to Int

code1:

var myString = "7" //7
var possibleInt = Int(myString) //7
print(possibleint) //"Optional(7)\n"

code2:

var myString1 = "banana" // "banana"
var possibleInt1 = Int(myString1) //nil
print(possibleInt1) // "nil\n"

PrinTing

let name = "Swift"
println("Hello")
pringln("My name is \(Name)")
print("See you")
print(later)
/*
    Hello
    My name is Swift
    See you later
*/

Logical Operators

var happy = true
var sad = !happy//logical NOT,sad = false
var everyoneHappy = happy && sad//logical AND,everyoneHappy = false
var someoneHappy = happy || sad //logical OR,someoneHappy = true

Functions

func iAdd(a:Int,b:Int,c:int) -> Int{
    return a + b + c
}
iAdd(1,b: 2,c: 3)//return 6


func eitherSide(n:int)-> (nMinusOne:Int,nPlusOne:int){
    return(n-1,n+1)
}
eitherSide(5)//(.0 4,.1 6)

Array

空数组

// Creates an empty array.
let emptyArray = [String]() // []

索引

var ratingList = ["Poor","Fine","Good","Excellent"]
ratingList[1] = "k"
ratingList // return ["Poor","OK","Excellent"]

拼接数组

var colors = ["red","blue"] //["red","blue"]
var moreColors: [String] = ["orange","purple"] //["orange","purple"]
colors.append("green") //["red","blue","green"]
colors += ["yellow"] //["red","green","yellow"]
colors += moreColors //["red","yellow","orange","purple"]

添加删除元素

var days = ["mon","thu"] 
var firstDay = days[0] // mon
days.insert("tue",aTindex: 1) // [mon,tue,thu]
days[2] = "wed"  // [mon,wed]
days.removeATindex(0)  //[tue,wed]

Dictionary

var days = ["mon": "monday","tue": "tuseday"]
days["tue"] = "tuesday" // change the value for key "tue"
days["wed"] = "Wednesday" // add a new Key/value pair

var moreDays: Dictionary = ["thu": "thursday","fri": "friday"]
moreDays["thu"] = nil // remove thu from the Dictionary
moreDays.removeValueForKey("fri") // remove fri from the Dictionary

大佬总结

以上是大佬教程为你收集整理的Swift Cheat Sheet [1] — Basic Types全部内容,希望文章能够帮你解决Swift Cheat Sheet [1] — Basic Types所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。