Swift 使用 日常笔记

//-------------------
var totalPrice: Int = 0 {
        willSet(newTotalPrice) { //参数使用new+变量名且变量名首地址大写
            println("准备将totalPrice值(原值为:\(totalPrice))设为: \(newTotalPrice)")
            //to do somthing before set.
      
        }
      
        didSet {
            if totalPrice > oldValue  {
                println("设置后新值比旧值增加了\(totalPrice - oldValue)")
                
            }
            
        }
      
    }
准备将totalPrice值(原值为:0)设为: 5
设置后新值比旧值增加了5
5

/使用#来把变量名提升了具有外部参数名作用的变量名,这样就不用再写一次外部参数名(在外部参数名与变量名相同时使用)  
    func setComputerConfig(#cpu:String,disk:String,mem:String,mon:String)  
    {  }

多参数方法
func addNumbers(numbers: Int...) ->Int {
        var totle = 0
        for number in numbers {
            totle += number
        }
        return totle
    }


常量参数
func constantParameter(var version: String) -> String {
        version = "版本号是:" + version
        return version;
    }
var  version = "4.0.0"
        var  ver = constantParameter(version)
        println(ver)
        println(version)
版本号是:4.0.0
4.0.0

   //函数作为返回值
    func testfunctionReturn(instruction : String) -> (Int,Int) -> Int
    {
        func Multiplication(a:Int,b:Int) ->Int
        {
            return a * b
        }
        
        return Multiplication
    }



//自动闭包类型
    //调用simpleAssert(testNumber % 2 == 0, "testNumber isn't an even number.")
    func simpleAssert(condition: () -> Bool, message: String) {
        if !condition() {
            println(message)
        }
    }

用来声明的:
“ class, deinit, enum, extension, func, import, init, let, protocol, static, struct, subscript, typealias, var.”
用于子句的:
“ break, case, continue, default, do, else, fallthrough, if, in, for, return, switch, where, while.”
表达式和类型的:
“ as, dynamicType, is, new, super, self, __COLUMN__, __FILE__, __FUNCTION__, __LINE__”
//特殊语境使用的:
“didSet, get, inout, mutating, override, set, unowned, unowned(safe), unowned(unsafe), weak , willSet”
http://blog.csdn.net/fengsh998/article/details/32133809
通知
 NSNotificationCenter.defaultCenter().postNotificationName("Notification1", object: nil)


 private var  observer : NSObjectProtocol!

observer = NSNotificationCenter.defaultCenter().addObserverForName("Notification1", object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: { (note:NSNotification!) -> Void in
            self.contentChangeNotification(note)
        });
private extension ViewController {
    func contentChangeNotification(notification: NSNotification) {
        println("1111")
        var text  = btn.titleLabel!.text! as NSString
        if text.isEqualToString("打开") {
            self.navigationItem.prompt = nil
                    btn.setTitle("关闭", forState: .Normal)
            
        } else {
            self.navigationItem.prompt = "测试显示";
           //演示1 s 执行
            let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC)))
            dispatch_after(popTime, dispatch_get_main_queue(), { () -> Void in
                self.navigationItem.prompt = "测试显示";
            });
        }
    }
    
}

GCD
async表明异步运行,block代表的是你要做的事情,queue则是你把任务交给谁来处理了
dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
 dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.value), 0), { () -> Void in
                var  url = NSURL(string: "http://s.qdcdn.com/cl/10911573,800,450.jpg")
                var  imgData = NSData(contentsOfURL: url!)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                      imageView.image = UIImage(data: imgData!)
                });
              
            });

 
线程队列,串行队列,会依次执行,
var  myQueue = dispatch_queue_create("com.inlee.ce0", DISPATCH_QUEUE_SERIAL)
            
            dispatch_async(myQueue, { () -> Void in
                println("0")
                var  url = NSURL(string: "http://img.lanrentuku.com/img/allimg/1311/13853799337947.jpg")
                var  imgData = NSData(contentsOfURL: url!)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    imageView.image = UIImage(data: imgData!)
                });
            });
            
            dispatch_async(myQueue, { () -> Void in
                 println("1")
                var  url = NSURL(string: "http://img.lanrentuku.com/img/allimg/1311/13853799337947.jpg")
                var  imgData = NSData(contentsOfURL: url!)
                if (imgData != nil){
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        imageView2.image = UIImage(data: imgData!)
                    });
                
                }
            });
            
            dispatch_async(myQueue, { () -> Void in
                println("2")
                var  url = NSURL(string: "http://media.vector4free.com/normal/chick.jpg")
                var  imgData = NSData(contentsOfURL: url!)
                if (imgData != nil){
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        imageView3.image = UIImage(data: imgData!)
                    });
                    
                }
                
            });



并行队列
 Concurrent queue(global dispatch queue):
可以同时运行多个任务,每个任务的启动时间是按照加入queue的顺序,结束的顺序依赖各自的任务.使用dispatch_get_global_queue获得.

var myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
            dispatch_async(myQueue, { () -> Void in
               NSThread.sleepForTimeInterval(6)
                println("6")
            });
            dispatch_async(myQueue, { () -> Void in
                NSThread.sleepForTimeInterval(4)
                println("4")
            });
            dispatch_async(myQueue, { () -> Void in
                NSThread.sleepForTimeInterval(1)
                println("1")
            });

1
4
6
http://blog.csdn.net/wildfireli/article/details/18668897
dispatch_group_async的使用
var queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
            var group = dispatch_group_create()
            dispatch_group_async(group, queue, { () -> Void in
                NSThread.sleepForTimeInterval(6)
                println("6")
            });
            
            dispatch_group_async(group, queue, { () -> Void in
                NSThread.sleepForTimeInterval(3)
                println("3")
            });
            
            dispatch_group_async(group, queue, { () -> Void in
                NSThread.sleepForTimeInterval(1)
                println("1")
            });
            
            dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
               println("完成!")
            });
1
3
6
完成!
map
//map函数可以让我们表达我们想要实现的目标的同时不用关心它背后发生了什么,这可以减轻我们理解代码的难度

 let numbers = [1,2,3]
 let doubledNumbers = numbers.map {$0 * 2 }
  println(doubledNumbers)
[2, 4, 6]
//--------
  let num = Optional(815)
        println(num)
        let transNum = num.map {$0 * 2}.map {$0 % 2 == 0}
        println(transNum)
Optional(815)
Optional(true)
//———
func map< U>(transformFunction: T -> U) -> Container< U>
T是当前的元素类型,U是将要返回的元素类型。通过这种方法我们可以实现诸如将一个字符串数组的每个字符串长度映射到一个整型数组中。
//------------
 let jsArr = ["abc", "12", "n", "klomj"]
        let jsArr2 = jsArr.map {$0.uppercaseString}
        let jsArr3 = jsArr.map {($0 as NSString).length}
        println(jsArr2)
        println(jsArr3)
[ABC, 12, N, KLOMJ]
[3, 2, 1, 5]



swift 异常处理
 NSSetUncaughtExceptionHandler(<#CFunctionPointer<NSUncaughtExceptionHandler>#>)

  NSSetUncaughtExceptionHandler(exceptionHandlerPtr)


//———
需要新建一个OC类,桥架该头文件
// volatile的作用: 作为指令关键字,确保本条指令不会因编译器的优化而省略,且要求每次直接读值.
//关键字“extern”,表示此函数是外部函数


@interface ExceptinHandler : NSObject
volatile void exceptionHandler(NSException *exception);
extern NSUncaughtExceptionHandler *exceptionHandlerPtr;
@end
#import "ExceptinHandler.h"
@implementation ExceptinHandler
volatile void exceptionHandler(NSException *exception) {
    // Do stuff
}
NSUncaughtExceptionHandler *exceptionHandlerPtr = &exceptionHandler;
@end


id方法
 private struct Constants {
        static let sharedManager = LocationManager()
    }
    
public class var sharedManager: LocationManager {
        return Constants.sharedManager
    }

 //1
  class var sharedInstance: LibraryAPI {
    //2
    struct Singleton {
      //3
      static let instance = LibraryAPI()
    }
    //4
    

 
 静态常量的声明
类似OC中 #define 
public struct HUDAssets {
    public static let rotationLockImage = HUDAssets.bundledImage(named: "rotation_lock")
internal static func bundledImage(named name: String) -> UIImage {
        let bundleIdentifier = "com.NSExceptional.PKHUD"
        return UIImage(named: name, inBundle: NSBundle(identifier: bundleIdentifier), compatibleWithTraitCollection: nil)!
    }
}
调用
HUDAssets.ringerMutedImage
 
public struct Tool {
    public static let greenColor = UIColor(red: 35.0/255.0, green: 153.0/255.0, blue: 73.0/255.0, alpha: 0.8)
} 

属性的set/get
public var userInteractionOnUnderlyingViewsEnabled: Bool {
        get {
            return !window.userInteractionEnabled
        }
        set {
            window.userInteractionEnabled = !newValue
        }
    }

private let backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(white:0.0, alpha:0.25)
        view.alpha = 0.0;
        return view;
    }()
// 
private var currentAlbumData : (titles:[String], values:[String])?
if  (currentAlbumData != nil) {}
可以改成
if let albumData = currentAlbumData {}
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor(), NSFontAttributeName:UIFont(name: "AvenirNextCondensed-DemiBold", size: 22.0)!]

 

你可能感兴趣的:(Swift 使用 日常笔记)