大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > IOS技巧 > Swift基础之方法实战

Swift基础之方法实战

关键词:实战基础方法Swift  阅读(507) 赞(16)

[摘要]本文是对Swift基础之方法实战的讲解,对学习IOS苹果软件开发有所帮助,与大家分享。

1.和之前一样

2.代码

 //
 //  ViewController.swift
 //  SwitfLesson_exam
 //
 //  Created by 薛雨仑 on 14-10-7.
 //  Copyright (c) 2014年 Dylan. All rights reserved.
 //
 
 import UIKit
 
 class ViewController: UIViewController {
 
     override func viewDidLoad() {
         super.viewDidLoad()
         
         // 1.
         // Change Two temper
         // 2种元组的初始化
         var a = "Alice"
         var b = "Dylan"
         var myType = (a, b)
         
         var name:String
         var family:String
         (name, family) = ("Alice", "Dylan")
         
         // test func change
         swap(&a, with: &b)
         println(a)
         println(b)
         
         // 2.
         // print String
         // test func flexString
         println(flexStrings(s1:"Alice ", s2: "Dylan"))
         
         // 3.
         // sumAny
         // test func sumAny
         println(sumAny(1, 2, 3))
         
         // 4.
         // countFrom
         // test func countFrom
         countFrom(from: 1, to: 5)
     }
     
     /**
     1. fun change
     交换2个任意对象的值
     */
     func swap<T>(inout a:T, inout with b:T) {
         (a, b) = (b, a)
     }
     
     /**
     2. func flexStrings
     输出字符串
     */
     func flexStrings(s1:String = "", s2:String = "") ->String {
         return s1 + s2 == "" ? "none" : s1+s2
     }
     
     /**
     3. func sumAny
     */
     func sumAny(anys: Any...) ->String {
         return String(
             (anys.map({item in
                 switch item {
                 case "" as String, 0 as Int:
                     return -10
                 case let s as String where s.toInt() > 0:
                     return s.toInt()!
                 case is Int:
                     return item as Int
                 default:
                     return 0
                 }
             }) as [Int]).reduce(0, combine: {
                 $0 + $1
             })
         )
     }
     
     /**
     4. func countFrom
     */
     func countFrom(#from: Int, to:Int) {
         println(from)
         if from < to {
             countFrom(from: from + 1, to: to)
         }
     }
 
     override func didReceiveMemoryWarning() {
         super.didReceiveMemoryWarning()
         // Dispose of any resources that can be recreated.
     }
 
 
 }


相关评论