Swift语法初见
http://c.biancheng.net/cpp/html/2424.html
类型的声明:
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
注:如果初始值没有提供足够的信息(或者没有初始值),那你需要在变量后面声明类型,用冒号分割。
数值转换:
let label = "The width is"
let width = 94
let widthLabel = label + String(width)
注:值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换。
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
注:有一种更简单的把值转换成字符串的方法:把值写到括号中,并且在括号之前写一个反斜杠。
数组、字典的初始化和赋值
var emptyArray = NSMutableArray.init()
var emptyArray1 = NSMutableArray()
emptyArray[0] = "00000";
emptyArray[1] = "11111";
emptyArray.add("22222")
var emptyDictionary = NSMutableDictionary()
emptyDictionary["1"] = 67788
emptyDictionary["2"] = "67788"
emptyDictionary.setValue("sss", forKeyPath: "key")
控制流
let vegetable = "cucumber"
switch vegetable {
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(x)?"
default:
let vegetableComment = "Everything tastes good in soup."
}
注:支持任意类型比较;支持多个条件匹配;不需要break,因为只运行一个case; 除非case覆盖所有可能,否则default不可缺失
let interestingNumbers:NSDictionary = ["Prime": [2, 3, 5],"Fibonacci": [1, 1, 8],"Fibonacc": [1, 1, 8]]
for (a,b) in interestingNumbers{
print(a)
print(b)
}
输出:Fibonacci [1, 1, 8] Prime [2, 3, 5]
for c in interestingNumbers{
print(c)
}
输出:(key: "Fibonacci", value: [1, 1, 8]) (key: "Prime", value: [2, 3, 5])
注:for in 遍历字典时,两个变量表示 key,value,一个变量表示 key-value键值对
for i in 0...1 {
interestingNumbers.object(forKey: interestingNumbers.allKeys[i])
}
for i in 0..<2 {
interestingNumbers.object(forKey: interestingNumbers.allKeys[i])
}
函数和闭包
func greet(nameOut name:String,_ day:String) -> String{
return "Hello \(name), today is \(day)."
}
greet(nameOut:"sss","sss")
注:1,区分内部和外部参数名 2,返回值的方式
func greet1(names:Int...) -> (a:Int,b:String,c:String){
let a = names[0]
let b = "ss"
let c = "aaa"
return (a,b,c)
}
greet1(names: 1,2,3)
func makeIncrementer() -> ( (Int) -> Int ) {
func addOne(number:Int) ->Int {
return 1+number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
注:1,函数可作为返回值
func hasAnyMatches(list: [Int],condition:(Int)->Bool) -> Bool{
for item in list{
if condition(item){
return true
}
}
return false
}
func lessThanTen(number:Int) -> Bool {
return number < 10
}
var number = [20, 19, 7, 12]
hasAnyMatches(list:number,condition:lessThanTen)
注:1,函数可作为参数
let numbers = [10,20,30]
numbers.map({
(number: Int) -> Int in
let result = 3 * number
let aiia = "ssss"
return result
})
let mappedNumbers = numbers.map { number in number/2
}
print (mappedNumbers)
class Shape {
var name = "aa"
let numberOfSides = 0
init(name:String) {
self.name = name
}
func simpleDescription(name:String) -> String {
return "A shape with \(numberOfSides) sides."
}
func funcInFunc(name:String)->((Int) -> (Int)){
func addSelf(number:Int)->Int{
return 1+number
}
return addSelf;
}
}
Shape(name:"bb")
let p = Shape(name:"aa").funcInFunc(name:"sss")
p(20)
注:1,函数可作为返回值
numbers.map({
(number:Int)->Int in
var aa = number
let num = number % 2
if(num == 1){
aa = 0
}
print(aa)
return aa;
})
class ShapeChild: Shape
{
override func simpleDescription(name: String) -> String{
return "A shape with \(numberOfSides) sides."
}
var sideLength: Double = 0.0
var perimeter:Double{
get{
return 3.0 * sideLength
}
set{
sideLength = newValue/3.0
}
}
var per:Int = 0{
willSet{
print("newValue : \(newValue)")
}
didSet{
print("oldValue : \(oldValue)")
}
}
}
var triangle = ShapeChild(name:"bb")
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength = 4.0
triangle.perimeter
triangle.per = 1
triangle.per = 2
注:1,重写父类方法 用 override关键字 2,属性可以有get set方法,oldValue、newValue是默认参数
枚举与结构体
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.Ace
let aceRawValue = ace.rawValue
注:使用enum来创建一个枚举 rawValue为自动去取方法
var optionalSquare: Rank? = Rank.Ace
optionalSquare = nil
optionalSquare = Rank.Five
注:如果?之前的值是nil,?后面的东西都会被忽略,并且整个表达式返回nil
enum ServerResponse {
case Result(String, String)
case Error(String)
}
let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")
switch success {
case let .Result(sunrise, sunset):
let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Error(error):
let serverResponse = "Failure... \(error)"
}
注:一个枚举成员的实例可以有实例值。相同枚举成员的实例可以有不同的值。创建实例的时候传入值即可。
实例值和原始值是不同的:枚举成员的原始值对于所有实例都是相同的,而且你是在定义枚举的时候设置原始值。
protocol printSelf{
var selfStr:String{get}
mutating func printSelf()
}
class desk:printSelf{
var selfStr: String = "a desk"
func printSelf() {
print(selfStr)
}
}
struct phone:printSelf{
var selfStr: String = "a phone"
func printSelf() {
print(selfStr)
}
}
desk()
phone()
注:类、枚举和结构体都可以实现接口。其中类是引用类型,枚举和结构体是值类型
在值类型的实例方法中,也可以直接修改self属性值。 mutating关键字用来标记一个会修改结构体或枚举属性值的方法
泛型
func repeatFunc<T>(item: T, times: Int) -> [T] {
var result = [T]()
for _ in 0...times {
result.append(item)
}
return result
}
repeatFunc(item:"knock",times:4)