ssnau / ios-dev Goto Github PK
View Code? Open in Web Editor NEWios-dev docs
ios-dev docs
_tl;dr: 如果你是Swift 1.2以上,使用class constant,否则使用nested struct以兼容更旧版本。
class SingletonA {
static let sharedInstance = SingletonA()
init() {
println("AAA");
}
}
这个方案支持懒初始化
,因为swift会懒初始化它的类级常量,并且由于我们用的是let
赋值,所以这是线程安全的。
Class constants
在Swift 1.2引入的。如果你需要支持更早版本,则需要使用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.
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 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)
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
本质上是一个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 ?? ""
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.