标签:swift

浏览模式: 标准 | 列表 | 图文
swift srand(time(NULL))

swift srand(time(NULL))

随机数在OC中真心简单啊 srand(time(null)),可是这样的代码到了 Swift中就行不通了

首先:swift没有null,time(nil)出来的又是 int,但 srand 的传入参数 又是Uint32.。。所以好让人纠结

不过网上还是有高手,他们说,你可以这样:srand(UInt32(time(nil))),看上去和原来的OC几乎一样,当然 他还提出了

But consider to use arc4random() or its variants instead. From http://nshipster.com/random/:

arc4random does not require an initial seed (with srand or srandom), making it that much easier to use.
arc4random has a range up to 0x100000000 (4294967296), whereas rand and random top out at RAND_MAX = 0x7fffffff (2147483647).
rand has often been implemented in a way that regularly cycles low bits, making it more predictable.
For example,

let x = arc4random_uniform(10)
generates a random number in the range 0 ... 9.

可是还有人说:

let time = UInt32(NSDate().timeIntervalSinceReferenceDate)
srand(time)
print("Random number: \(rand()%10)")

得,还是能用就成

swift pragma mark

swift pragma mark

众所周知,大家在OC中对代码进行逻辑组织 用的是#pragma mark - ,生成分隔线

用#pragma mark 函数说明,来生成一个函数的说明X
但在swift中,这个语法就不支持了,毕竟它是属于C的语法,于是就有了新的一些语法,如:// MARK: // FIXME // TODO: 等
// MARK: - 生成分隔线
// MARK: 说明
别忘了那个冒号。。。
参考 :http://stackoverflow.com/questions/24017316/pragma-mark-in-swift
UIActionSheetView和UIAlertView

UIActionSheetView和UIAlertView

笔记

这两个View都有一个参数 :otherButtonTitles,在OC中的时候,如果这个参数 不设置就是otherButtonTitles:nil,
如果有多个参数 ,就是otherButtonTitles: @"first" , @"second" , nil
就因为这个nil,害得我在swift里走了弯路
在写swift的时候,我也是otherButtonTitles:nil的时候直接就报错了,说是不能转成String,再看了一下方法,果然人家写的就是otherButtonTitles:String?
那怎么办?想了一阵,那我不写这个参数行不行?最后果然OK。那么,如果是多个button咋整?
放弃nil吧?otherButtonTitles:"abc","def","ghi"
果然编译通过。。。原代码中的nil真是吓坏我了
我在看精通IOS开发第6版。初学。100页还没看完。不过我是全部用swift写的,好累啊@
IOS开发笔记(swift)二

IOS开发笔记(swift)二

1、 如何获取字符串的长度:

在判断长度是否大于0的时候,if [xxx length ] > 0 就行了。而如果直接用swift,就不能写 if xxx.length > 0 了。因为xxx没有length这个方法。
有两个办法:
  1. if countElements(xxx) > 0
  2. if xxx.utf16count > 0
2、swift的delegate不象oc那样一个个的标注,只要在class头上写明就OK了
比如 class ViewController : UIViewController , UIActionSheetDelegate {

}
就能直接用UIActionSheetDelegate中的方法了。然后他们的delegate写self即可

刚开始学。不知道对错,目前就这样先纯做笔记,当然 你也可以delegate: nil 这样代表你这个控件 就不再接受委托了
swift initwithnibname

swift initwithnibname

本篇是个笔记

在参考oc代码的时候,有一个initWithNibName方法,在使用swift重写的时候,发现,如果super.init,就会报错,参考了网上很多代码,有人说,重写init方法。不能用override,要用required,结果也是无效

所幸stackflow上面已经有人提出了,说是不能用 init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) 这种方法,只能用 init(NSCoder),网上也有很多人写了例子。

但好象每一个版本的xcode 测试版都不太正常,所以,有的例子就是:func init(coder code:NSCoder!),但实际在使用的时候发现它有提示,说是必须要required,而且NSCoder!不要加感叹号。

于是我最后的代码就是:

required init(coder decoder: NSCoder){
super.init(coder: decoder)
}

搞定

参考:

1、http://blog.johnregner.com/post/93071481303/ios-programming-in-swift-chapter-1

2、http://stackoverflow.com/questions/25267907/initwithnibname-does-not-implement-superclass-swift