既然苹果放出了这样一个利器,身为iOS开发者的我也不能落下,APPLE为我们提供了两个文档The Swift Programming Language和Using Swift with Cocoa and Objective-C。他们一个是纯语言角度的介绍Swift,包括各种细节语法,另一个则是介绍怎么它怎么与Cocoa交互,如何使用它开发iOS和MAC应用,以及如何与现有的程序兼容。学习这样一门全新的技术我还是建议读第一手资料的,虽然现在网络上有好多中文版的资料了吧,但是苹果的文档写的很是通俗易懂,读起来也没有什么困难。而起自己之前有过脚本语言的经验,所以看起来也是很快。
//// ViewController.swift// HexConverter_swift//// Created by taowang on 7/24/14.// Copyright (c) 2014 Meilishuo. All rights reserved.//importUIKitclassViewController:UIViewController{@IBOutletvarbeforeConvertTextField:UITextField@IBOutletvarafterConvertTextField:UITextField@IBOutletvarsegmentControl:UISegmentedControloverridefuncviewDidLoad(){super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.self.segmentControl.addTarget(self,action:Selector("setTextFieldKeyboardType"),forControlEvents:UIControlEvents.ValueChanged)}overridefuncdidReceiveMemoryWarning(){super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}funcdecimalConvertedFromHexdecimal(hexdecimal:NSString)->NSString?{varsum:Int=0for(vari:Int=0;i<hexdecimal.length;i++){varc:unichar=hexdecimal.characterAtIndex(i)varnum:unichar=0;if(c>=65&&c<=70){num=c-55;}elseif(c>=97&&c<=102){num=c-87;}elseif(c>=48&&c<=57){num=c-48;}else{letalert=UIAlertController(title:"错误",message:"你提供了非法字符",preferredStyle:.Alert)alert.addAction(UIAlertAction(title:"知道了",style:.Cancel,handler:nil))self.presentViewController(alert,animated:true,completion:nil)self.beforeConvertTextField.text=""self.beforeConvertTextField.becomeFirstResponder()returnnil}lettmp=Int(pow(16,CDouble(hexdecimal.length-i-1)))sum=sum+Int(num)*tmp}returnNSString(format:"%d",sum)}funchexdecimalConvertedFromDecimal(decimal:NSString)->NSString?{varnum:Int=decimal.integerValue;varresult:NSMutableString=NSMutableString(capacity:0);while(num>0){vartmp=num%16;varc:unichar=48;if(tmp>9){c=97+unichar(tmp-10);}else{c=48+unichar(tmp);}letcharacter:NSString=NSString(format:"%c",c)result.insertString(character,atIndex:0)num/=16;}returnresult;}funcsetTextFieldKeyboardType(){self.beforeConvertTextField.resignFirstResponder()if(self.segmentControl.selectedSegmentIndex==0){self.beforeConvertTextField.keyboardType=.ASCIICapable;}else{self.beforeConvertTextField.keyboardType=.NumberPad;}self.beforeConvertTextField.becomeFirstResponder();}@IBActionfuncendEditing(sender:AnyObject){self.view.endEditing(true)}@IBActionfuncconvertButtonPressed(sender:AnyObject){if(""==self.beforeConvertTextField.text){varalert=UIAlertController(title:"提示",message:"你还没有填写被转换数字",preferredStyle:.Alert)alert.addAction(UIAlertAction(title:"知道了",style:.Cancel,handler:nil))self.presentViewController(alert,animated:true,completion:nil)return}self.beforeConvertTextField.resignFirstResponder()if(0==self.segmentControl.selectedSegmentIndex){self.afterConvertTextField.text=self.decimalConvertedFromHexdecimal(self.beforeConvertTextField.text)}else{self.afterConvertTextField.text=self.hexdecimalConvertedFromDecimal(self.beforeConvertTextField.text)}}}