zoukankan      html  css  js  c++  java
  • Swift函数

    函数定义

    使用 func 定义一个函数。调用函数使用他的名字加 上小括号中的参数列表。使用 -> 分隔参数的名字和 返回值类型。

    函数声明:

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. <span style="font-size:14px;">func greet(name: String, day: String) -> String {  
    2. return "Hello (name),today is (day)."  
    3.    
    4. </span>  

    函数调用:greet("Bob", "Tuesday")

    无返回值函数

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. <span style="font-size:14px;">func sayGoodbye(personName: String) {  
    2. println("Goodbye, (personName)!")  
    3. }  
    4. sayGoodbye("Tony")</span>  

    多返回值函数

    使用元组类型返回多个值:

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. <span style="font-size:14px;">func count(string: String) -> (vowels: Int, consonants:Int, others: Int) {  
    2. var vowels = 0,consonants = 0, others= 0 for character in string {  
    3. switch String(character).lowercaseString {  
    4. case "a","e", "i","o", "u":  
    5. ++vowels  
    6. case "b","c", "d","f", "g", "h", "j", "k", "l", "m","n", "p","q", "r","s", "t", "v", "w","x", "y", "z":  
    7. ++consonants default:  
    8. ++others  
    9. }  
    10. }   
    11. return (vowels, consonants, others)  
    12. }  
    13. let total = count("somearbitrary string!")   
    14. println("(total.vowels) 元音 , (total.consonants) 辅 音")</span>  

    嵌入函数

    函数嵌套: 相当于函数指针

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. <span style="font-size:14px;">func chooseStepFunction(backwards: Bool) ->(Int) -> Int {  
    2. func stepForward(input: Int) -> Int { return input  
    3. + 1 }  
    4. func stepBackward(input: Int) -> Int { return input  
    5. - 1 }  
    6. return backwards ? stepBackward : stepForward  
    7. }  
    8. var currentValue = -4  
    9. let               moveNearerToZero                    =  
    10. chooseStepFunction(currentValue> 0)  
    11. while currentValue != 0{  
    12. println("(currentValue)... ")   
    13. currentValue = moveNearerToZero(currentValue)  
    14. }</span>  

    Swift交流讨论论坛论坛:http://www.cocoagame.net

    欢迎加入Swift技术交流群:362298485

  • 相关阅读:
    Python2+appinum基础操作封装
    appinum+python环境搭建
    Python学习-pymysql(一)
    小程序onShow事件获取options方法
    css中content-box和border-box当宽度为百分比时的位置区别,vw和%区别
    JavaScript
    canvas入门基础,七巧板、五角星、粒子时钟等
    JavaScript 自适应轮播图
    css使用padding-bottom百分比进行提前占位,防止抖动
    Dreamweaver配色方案
  • 原文地址:https://www.cnblogs.com/iOS-Blog/p/3807307.html
Copyright © 2011-2022 走看看