Swift初探
来自: http://my.oschina.net/xinxingegeya/blog/608514
Swift初探
Xcode 7.2
下面swift一些基本的语法。把这些代码写下来,发现swift和一些语言很像,比如javascript和scala。如果对这些语言比较熟悉的话,一看代码就会懂。
总的来说swift的语法还是比较fashion。好评~~~
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let name = "hello world" //编译器会自动推断类型,该类型是Int let implicitInt = 70 //编译器会自动推断类型,该类型是double let implicitDouble = 10.0 //定义一个常量,并指定类型为double let explicitDouble: Double = 70 let height:Float = 5 let label = "the width is" let width = 90 //值永远不会被隐式转换为其他类型,这里使用String 显式转换一个字符串 let widthLable = label + String(width) print(widthLable) let apples = 3 let oranges = 5 // \(apples)是一种简单的方式来转换字符串 let appliSummary = "I have \(apples) apples;" let fruitSummary = "I have \(apples + oranges) pieces of fruits;" //创建一个数组 let shoplist = ["catfish","water","tulips","blue paint"]; //使用[String]表明是一种数组类型 var shoppingList: [String] = ["Eggs", "Milk"] //使用下标来访问数组元素 print(shoplist[1]) //创建一个空数组 let emptyArray = []; print(emptyArray) //创建一个空的数组 let emptyStringArray = [String]() print(emptyStringArray) let individualScores = [12,12,13,25] var teamScore = 0 //swift中基本的for循环控制流 for score in individualScores { if score > 13{ teamScore += 3 } else{ teamScore += 1 } } print(teamScore) //使用?表示该变量的值是可选的 var optionalString:String? = "hello" optionalString = nil var optionalName:String? = nil var greeting = "Hello!" //如果变量的可选值是 nil,条件会判断为 false,大括号中的代码会被跳过。如果不是nil, //会将值赋给 let 后面的常量,这样代码块中就可以使用这个值了。 if let name = optionalName { greeting = "Hello,\(name)" } else { greeting = "Hello everyone" } //switch语法 let vegetable = "red pepper" 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." } let vegetable2 = "watercress" //switch必须有一个default switch vegetable2{ 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." } //定义字典数组 let interestingNumbers = [ "prime":[2,3,5,7], "fibonacci":[1,1,2,3,5,8], "square":[1,4,9,16,25] ] var largest = 0 //遍历数组 //字典类型的元素需要两个变量来表示每个键值对 for (kind,numbers) in interestingNumbers{ for number in numbers{ if number > largest{ largest = number } } } print(largest) //1...3 是 Closed Range Operator => 1 2 3 var sum = 0 for i in 1...3{ sum += i } print(sum) sum = 0 //1..<3 是 Half-Open Range Operator => 1 2 for i in 1..<3 { sum += i } print(sum) //函数的定义 //使用右向箭头表示返回值 func greet(name:String, day:String) ->String{ return "Hello \(name),today is \(day)"; } greet("LiYi", day: "2016-1-1") greet("world",day: "2016-1-1") //函数返回类型为元组 func getGasPrices() -> (Double,Double,Double){ return (3.56,3.23,3.21) } getGasPrices() //swift的可变参数列表 func sumOf(numbers:Int...)->Int{ var sum = 0 for number in numbers{ sum += number } return sum } sumOf() sumOf(42,597,12) //在函数内部定义一个函数 func returnFifteen() -> Int { var y = 10 func add() { y += 5 } //调用函数内部的函数 add() return y } returnFifteen() //=========函数作为返回值 //定义一个函数,返回值是一个函数类型 //函数类型是 (Int -> Int) ,表示该函数接收一个入参Int,返回值是Int func makeIncrementer() -> (Int -> Int){ func addOne(number:Int)->Int{ return 1 + number } return addOne } var increment = makeIncrementer() increment(1) //定义一个函数 makeAdd ,其返回值也是一个函数类型, //(Int,Int) -> Int 表示返回类型,是一个接收两个Int参数,返回Int的函数 func makeAdd()-> (Int,Int) -> Int { func add(a:Int ,b:Int) -> Int{ return a + b } return add; } var add = makeAdd() add(1,2) //=========函数作为参数 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 } hasAnyMatches([20,19,7,12], condition: lessThanTen) var numbers = [20,19,7,12] //(number:Int) -> Int 是一个匿名闭包的入参和返回值 //使numbers数组中的元素都变成了三倍 numbers.map( { (number:Int) -> Int in let result = 3 * number return result } ) //map 函数 numbers.map( { (number:Int) -> Int in if number % 2==0{ let result = 3 * number return result } else { return 0 } } ) //filter 函数 numbers.filter({ (number:Int) -> Bool in return number % 2 == 0 }) //类的定义 class Shape{ //定义一个常量 let happy = true //定义一个变量 var numberOfSides = 0 func simpleDscription() -> String{ return "A shape with \(numberOfSides) sides" } func toHappy()->Bool{ return happy } } //创建类的实例 var shape = Shape() shape.numberOfSides = 10 shape.simpleDscription() shape.toHappy() //定义类的构造函数 class NamedShape{ var numberOfSides:Int = 0 var name: String //定义类的构造函数 init(name:String){ self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides" } } var namedShape = NamedShape(name: "hello world") namedShape.name namedShape.simpleDescription() //继承 类的继承 class Square : NamedShape{ var sideLength : Double init(sideLength: Double ,name :String){ self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double{ return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength)" } } let test = Square(sideLength: 5.12, name: "my test square") test.area() test.simpleDescription() class EquilateralTriangle : NamedShape{ var sideLength : Double = 0.0 init(sideLength: Double, name: String){ self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } //定义属性的setter 和 getter 方法 var perimeter : Double { get{ return 3.0 * sideLength } set{ sideLength = newValue / 3.0 } } override func simpleDescription() -> String { return "An equilateral triagle with sides of length \(sideLength)" } } var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") triangle.perimeter triangle.perimeter = 9.9 triangle.sideLength //定义一个类,类中有一个函数 class Counter { var count: Int = 0 //该方法的第二个参数有两个参数名 //第一个参数名是numberOfTimes,给方法的外部调用者使用 //第二个参数名是times,给方法内部使用 func incrementBy(amount:Int,numberOfTimes times: Int){ count += amount * times } } //创建一个实例 var counter = Counter() counter.incrementBy(2, numberOfTimes: 7) //定义一个枚举 //枚举原始值的类型是Int,所以你只需要设置第一个原始值。 //剩下的原始值会按照顺序赋值。你也可以使用字符串或者浮点数作为枚举的原始值。 enum Rank: Int { //指定该枚举实例的原始值为1 case Ace = 1 case Two ,Three ,Four , Five , Six ,Seven , Eight ,Nine ,Ten case Jack,Queen,King func simpelDescription() -> String{ switch self{ case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queue" case .King: return "king" default: return String(self.rawValue) } } } let ace = Rank.Ace //调用 rawValue 方法 let aceRawValue = ace.rawValue ace.simpelDescription() //定义不需要原始值的枚举 enum Suit { case Spades,Hearts,Diamonds,Clubs func simepleDescription ()-> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } } let hearts = Suit.Hearts let heartsHashValue = hearts.hashValue let heartDescription = hearts.simepleDescription() //创建一个结构体 struct Card { var rank : Rank var suit : Suit func simpleDescription() -> String { return "The \(rank.simpelDescription()) of \(suit.simepleDescription())" } } //使用 struct 来创建一个结构体。 //结构体和类有很多相同的地方,比如方法和构造器。 //它们结构体之间最大的一个区别就是,结构体是传值,类是传引用。 let threeOfSpades = Card(rank: .Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription() //该枚举也不需要原始值 //一个枚举成员的实例可以有实例值。 //相同枚举成员的实例可以有不同的值。 //创建实例的时候传入值即可。 //实例值和原始值是不同的:枚举成员的原始值对于所有实例都是相同的 //而且你是在定义枚举的时候设置原始值。 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") //success是一个枚举实例 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来声明一个接口 protocol ExampleProtocol{ var simpleDescription : String { get } mutating func adjust() } //类、枚举和结构体都可以实现接口 class SimpleClass: ExampleProtocol{ var simpleDescription :String = "a very simple class" var anotherProperty : Int = 123 func adjust() { simpleDescription += " now 100% adjusted" } } var a = SimpleClass() a.adjust() let desc = a.simpleDescription //该结构体实现协议 struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "a very simple structure" //mutating 关键字用来标记一个会修改结构体的方法 mutating func adjust(){ simpleDescription += " (adjusted)" } } // 枚举继承协议 enum SimpleEnum: ExampleProtocol{ case First(String) case Second(String) //属性的get方法 var simpleDescription:String{ get{ switch self{ case let .First(text): return text default: return "hi" } } } mutating func adjust(){ print("description: hi") } } var s = SimpleEnum.First("dingding") s.simpleDescription s.adjust() //使用 extension 来为现有的类型添加功能,比如添加一个计算属性的方法。 //你可以使用扩展来给任意类型添加协议 //甚至是你从外部库或者框架中导入的类型 extension Int : ExampleProtocol{ var simpleDescription : String { return "the number \(self)" } mutating func adjust() { self += 42 } } 7.simpleDescription // 定义一个泛型函数 func repeatItem<T>(item : T,times: Int) -> [T] { //定义一个空的数组 var result = [T]() for i in 0...times { //数组元素的追加 result.append(item) } return result } repeatItem(3, times: 4)
============END============
本文由用户 seqn0777 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!