Swiftは日常メモを使います.

17557 ワード

//-------------------
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)!]