Last active
August 29, 2015 14:24
-
-
Save safecat/ba5f79f9c1f15ba30701 to your computer and use it in GitHub Desktop.
Swift 函数学习
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //: Playground - noun: a place where people can play | |
| import UIKit | |
| var str = "Hello, playground" | |
| // 函数和返回值 | |
| func getUserName(id: Int) -> String { | |
| return "xxy"; | |
| } | |
| getUserName(1); | |
| // 外部参数 | |
| func getUserName(ById id: Int) -> String { | |
| return "xxy"; | |
| } | |
| getUserName(ById: 1); | |
| // 简写外部参数 | |
| // 已经被 Swift 2.0 弃用了 | |
| // 返回tuple类型 | |
| func getUserInfo(ById id: Int) -> (name: String, age: Int) { | |
| return ("xxy", 21); | |
| } | |
| var info = getUserInfo(ById: 1); | |
| print(info.age, appendNewline: false) | |
| // 参数默认值 | |
| func getUserAge(name: String = "xxy") -> Int { | |
| return 1; | |
| } | |
| getUserAge(); | |
| // 可变参数 | |
| func getUserNames(ByIds ids : Double ...) -> [String] { | |
| return ["xxy", "yyx", "xyy"]; | |
| } | |
| getUserNames(ByIds: 1,2,3); | |
| // 变量参数 | |
| func getUserAge(var id : Int) ->Int { | |
| id++ // 如果参数前不加var,这句将会报错 | |
| return 1 | |
| } | |
| getUserAge(1); | |
| // IO参数 | |
| func addLastName(inout name : String) { | |
| name = name + " " + "Xie" | |
| } | |
| var a = "Xuyang" | |
| addLastName(&a) | |
| print(a, appendNewline: false) | |
| // 函数复制 | |
| func sortBook(book1 : String, book2 : String) -> Int { | |
| return book1.compare(book2).rawValue | |
| } | |
| var sortAnimal:(String, String) -> Int = sortBook; | |
| sortAnimal("cat", "dog"); | |
| sortBook("dog", book2: "cat") | |
| //sortBook("dog", "cat") //会报错 | |
| // 返回函数 | |
| func aaa() -> (String, String) -> Int { | |
| return sortBook; | |
| } | |
| // 嵌套函数 | |
| func bbb() -> () -> Void { | |
| func sortPeople(){} | |
| return sortPeople; | |
| } | |
| // 函数第二个参数 | |
| // 在 Swift 2.0 中,从第二个参数开始,参数名即为external name。 | |
| func eee(seg1 : String, seg2 : String) {} | |
| eee("a", seg2: "b"); | |
| func fff(seg1 : String, _ seg2 : String) {} | |
| fff("a", "b") | |
| // 可选 tuple 返回值 | |
| func ddd(tupleIsNil tupleIsNil:Bool) -> (seg1:String, seg2:Int)? { | |
| return tupleIsNil ? nil : ("aaa", 1); | |
| } | |
| ddd(tupleIsNil: true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment