首页 > 代码库 > Swift基础之方法实战

Swift基础之方法实战

1.和之前一样

2.代码

  1 //  2 //  ViewController.swift  3 //  SwitfLesson_exam  4 //  5 //  Created by 薛雨仑 on 14-10-7.  6 //  Copyright (c) 2014年 Dylan. All rights reserved.  7 //  8   9 import UIKit 10  11 class ViewController: UIViewController { 12  13     override func viewDidLoad() { 14         super.viewDidLoad() 15          16         // 1. 17         // Change Two temper 18         // 2种元组的初始化 19         var a = "Alice" 20         var b = "Dylan" 21         var myType = (a, b) 22          23         var name:String 24         var family:String 25         (name, family) = ("Alice", "Dylan") 26          27         // test func change 28         swap(&a, with: &b) 29         println(a) 30         println(b) 31          32         // 2. 33         // print String 34         // test func flexString 35         println(flexStrings(s1:"Alice ", s2: "Dylan")) 36          37         // 3. 38         // sumAny 39         // test func sumAny 40         println(sumAny(1, 2, 3)) 41          42         // 4. 43         // countFrom 44         // test func countFrom 45         countFrom(from: 1, to: 5) 46     } 47      48     /** 49     1. fun change 50     交换2个任意对象的值 51     */ 52     func swap<T>(inout a:T, inout with b:T) { 53         (a, b) = (b, a) 54     } 55      56     /** 57     2. func flexStrings 58     输出字符串 59     */ 60     func flexStrings(s1:String = "", s2:String = "") ->String { 61         return s1 + s2 == "" ? "none" : s1+s2 62     } 63      64     /** 65     3. func sumAny 66     */ 67     func sumAny(anys: Any...) ->String { 68         return String( 69             (anys.map({item in 70                 switch item { 71                 case "" as String, 0 as Int: 72                     return -10 73                 case let s as String where s.toInt() > 0: 74                     return s.toInt()! 75                 case is Int: 76                     return item as Int 77                 default: 78                     return 0 79                 } 80             }) as [Int]).reduce(0, combine: { 81                 $0 + $1 82             }) 83         ) 84     } 85      86     /** 87     4. func countFrom 88     */ 89     func countFrom(#from: Int, to:Int) { 90         println(from) 91         if from < to { 92             countFrom(from: from + 1, to: to) 93         } 94     } 95  96     override func didReceiveMemoryWarning() { 97         super.didReceiveMemoryWarning() 98         // Dispose of any resources that can be recreated. 99     }100 101 102 }

 

Swift基础之方法实战