Giter Club home page Giter Club logo

ios-dev's People

Watchers

 avatar  avatar

ios-dev's Issues

Swift单例模式

Swift单例模式

原文

_tl;dr: 如果你是Swift 1.2以上,使用class constant,否则使用nested struct以兼容更旧版本。

方案 A: Class constant

class SingletonA {

    static let sharedInstance = SingletonA()

    init() {
        println("AAA");
    }

}

这个方案支持懒初始化,因为swift会懒初始化它的类级常量,并且由于我们用的是let赋值,所以这是线程安全的。

Class constants在Swift 1.2引入的。如果你需要支持更早版本,则需要使用nested struct的方式。

方案 B: Nested struct

class SingletonB {

    class var sharedInstance: SingletonB {
        struct Static {
            static let instance: SingletonB = SingletonB()
        }
        return Static.instance
    }

}

Here we are using the static constant of a nested struct as a class constant. This is a workaround for the lack of static class constants in Swift 1.1 and earlier, and still works as a workaround for the lack of static constants and variables in functions.

常用Snippets

读取文件

    func readFileAsText(fileName: String) -> String {
        let f = fileName as NSString;
        let path = NSBundle.mainBundle().pathForResource(f.stringByDeletingPathExtension, ofType: f.pathExtension)
        do {
            let text = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
            return text
        } catch _ {
            return "";
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        print(readFileAsText("words.txt"))
    }

swift的函数参数

Swift 2中的函数参数遵守如下规则:

  • 函数的第一个参数是没有外部名称的。
  • 所有其他参数的内部/外部共享一个名称。
  • #的简写方式不再支持。如果你希望第一个参数的外部名称与内部名称一致,那么就把这个名称写两遍吧。
  • 所有参数的外部名称都能被override
  • 你可以使用_来取消外部名称。
// Please note that internalNameOne and internalNameTwo are the
// parameters accessible in the myFunction scope. That is, of course,
// the internal parameter names

// Standard behaviour
func myFunction(internalNameOne: Int, internalNameTwo: Int) {}
myFunction(1, internalNameTwo: 2)

// Second parameter with different external name
func myFunction(internalNameOne: Int, externalNameTwo internalNameTwo: Int) {}
myFunction(1, externalNameTwo: 2)

// This is how # used to work for the first parameter
func myFunction(internalNameOne internalNameOne: Int, externalNameTwo internalNameTwo: Int) {}
myFunction(internalNameOne: 1, externalNameTwo: 2)

// First and second parameters have different external parameter names
func myFunction(externalNameOne internalNameOne: Int, externalNameTwo internalNameTwo: Int) {}
myFunction(externalNameOne: 1, externalNameTwo: 2)

// Bonus: omitting external parameter names
func myFunction(internalNameOne: Int, _ internalNameTwo: Int) {}
myFunction(1, 2)

修改UserAgent

UIWebView的UserAgent会从UserDefaults中读,所以在新建一个UIWebView之前修改UserDefaults即可。

class SecondViewController: UIViewController {

    var webview: UIWebView?

    override func viewWillAppear(animated: Bool) {
        let ua = UIWebView().stringByEvaluatingJavaScriptFromString("navigator.userAgent")!
        print("get ua \(ua)")
        NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": " \(ua) HAHA\(arc4random())"])

        // 将老的容器干掉
        if let wv = webview {
            wv.removeFromSuperview();
        }
        print("create new webview")
        // 创建新的容器
        webview = UIWebView(frame: CGRect(x: 0, y: 0, width: 200, height: 500))
        view.addSubview(webview!)

        webview?.loadRequest(NSURLRequest(URL: NSURL(string: "http://localhost:8000/x")!))

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
     //   let ua = webview.stringByEvaluatingJavaScriptFromString("navigator.userAgent += ' HBBBB'")!
     //   NSUserDefaults.standardUserDefaults().registerDefaults(["userAgent": "\(ua) HHHHBBBB"])

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

Optional

Optional本质上是一个Enum

enum Optional<T> {
  case None
  case Some(T)
}

let x: String? = nil 
// 相当于
let x = Optional<String>.None

let x: String= "hello"
// 相当于
let x = Optional<String>.Some("hello")

var y = x!  // 强制unwrap一个nil会抛异常
// 相当于
switch x {
  case .Some(let val): y = value
  case .None: /* Throw Error */
}

let x: String? = ....
if let y = x {
  // do something
}
// 相当于
switch x {
  case .Some(let y): // do something with y
  case None: break;
}

var display: UILabel?;
if let label = display {
  if let text = label.text {
    let x = text.hashValue
  }
}
// 相当于
if let x = display?.text?.hashValue {
  // ..
}

let s: String? = ...
if s != nil {
  display.text = s
} else {
  display.text = ""
}
// 相当于
display.text = s ?? ""

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.