swift研究

1、let dic = responseData as! Dictionary<AnyHashable, Any>

let dic:NSDictionary = responseData as! Dictionary<AnyHashable ,Any>

这代码有什么区别

2、var previewView:UIView? = nil

我们生明一个变量的时候可以设置为选择类型也可以设置为强制类型,但是创建的时候必须这样

self.previewView =UIView.init(frame:CGRect(x:0,y:64,width:320,height:300))

3、私有变量用fileprivate,私有方法前面加一个_  

4、throw :do {

            input = tryAVCaptureDeviceInput(device: backCamera)

        } catchlet error1asNSError {

            error = error1

            input = nil

       }

5、describing

6、convenience

disignated init method(指定的初始化方法)

class classA {

    let numA: Int 

    init(num: Int){

       numA = num

    }

}


class ClassB: ClassA {

    let numB: Int 

    override init (num:Int){

      numB = num + 1

      super.init(num: num)

   }

}

swift 中不加修饰的init方法都需要在方法中保证所有非Optional实例变量被赋值初始化,而在子类中也强制(显示或者隐式的)调用super版本的designated初始化。被初始化的对象总是可以完成完整的初始化的。

在上面的代码中,注意在init 里我们可以对let 的实例常量进行赋值,这是初始化方法的重要特点。在swift中let 声明的值是常量,这对于构建线程安全的API十分有用。二因为Swift的init 只可能被调用一次,因此在init中我们可以为常量进行赋值,而不会引起任何线程安全的问题的

convenience

在init前加上convenience关键字的初始化方法,这类方法是Swift初始化中的“二等公民”,只作为补充和提供使用上的方便。所有的convenience初始化方法都必须调用同一个类中的disignated初始化完成设置,另外convenience的初始化的方法是不能被子类重写或者是从子类中以super的方式调用的。只有在子类中实现了重写了父类convenience方法所指的init方法的话,我们在子类就也可以使用父类的convenience方法,如果我们在子类中实现了指定初始化方法的重写,那样,在子类中即使没有实现convenince 的初始化方法,我们仍然还是可以用这个方法来完成子类初始化。

最后,对于某些我们希望子类中一定实现designanted初始化方法,我们可以通过添加required关键字进行限制,强制子类对这个方法重写实现。这样做的最大的好处是可以保证依赖某个designated初始化方法的convenience一直可以被使用  来源作者:http://swifter.tips/init-keywords/

7、用文件画出来的变量不能放在闭包里面

8、我们有时需要转化,比如将int转为string,但是我们不知道那个int是不是为nil,于是系统会将String(a),切换为String(describing:a),导致转换过来的字符串多加了一个describing,怎么办呢,首先,要明白系统为什么会加,因为系统不确定a是不是有值,a是一个选择类型的,只要我们确定了a是有值的(guard或者if let -方法等),系统便会不加describing了。

9、swift的一些注意事项

(1)nil不能参与计算

(2)swift int 不要声明一个选择类型,直接赋值。

(3)bool值要声明加did

(4)SDWebImageDownloader 加载更新image一定要换到主线程

(5)调用了imageView.sd_setImage(with: someUrl,

          placeholderImage: someImage,

                 completed: someCompletitionBlock)

这个方法,会出现一个莫名的错误,这个问题也找到答案,是因为,在SDWebImage 的oc转换为swift的时候,两个oc方法会转为相同的方法,所以当我们调用这个方法时,系统不知道选哪个,就出现“Ambiguous use of 'sd_setImage(with:placeholderImage:completed:)’”错误

解决方法:

mageView.sd_setImage(with: someUrl,

          placeholderImage: someImage,

                   options: [], 

                 completed: someCompletitionBlock)

可以在options处加一个空数组

具体参考:https://stackoverflow.com/questions/38949214/ambiguous-use-of-sd-setimagewithplaceholderimagecompleted-with-swift-3

(6)给nil发消息有些事没问题的,比如hidden, button = nil,button.hidden = yes,oc和swift都行。

10、swift 编程遇到的部分坑

问题1:#selector' refers to a method that is not exposed to Objective-C swift 3

solution:@objcpublicprotocol OperatecellDelegate:NSObjectProtocol {

    func editAddress(indexPath:NSIndexPath)

    func deleteAddress(indexPath:NSIndexPath)

    func setDefaultAddress(indexPath:NSIndexPath)

}


问题2:argument of #selector doosn not refer to an ‘@objc’ method ,property ,or initializer

solution:

let tap:UITapGestureRecognizer =UITapGestureRecognizer(target:self, action:#selector(tappedView()))

change to 

let tap:UITapGestureRecognizer =UITapGestureRecognizer(target:self, action:#selector(tappedView)) 

tappedview without ()

问题3 if dict?["code"].intergvalue ==100 {}

value of type ‘any’ has no member ‘intergvalue’

solution:

if dict?["code"] as! Int ==100 { }

问题4arr  add adding 区别

问题5:

wrong:init(userInfo:Dictionary<AnyHashable Any>)

solution:

init(userInfo:Dictionary<AnyHashable,Any>) 

问题6:

Empty collection literal requires an explicit type” error on Swift3

var contentArr = [Any]()

solution 加一个强制类型 ,具体现在暂时不明

问题7:知识记录

if let dic  = dict?["value"] as! [AnyHashable: Any]?, let addr = dic["addrid"]as! String? {


问题8:属性文本增加一个链接

 NSAttributedStringKey.link: String(format:"markcontent://%d/%d", Int(plist[pidx].markId)!, pidx),

11、as、as? 、as!区别

1as 作用

(1)从派生类转换为基类,向上转型

class Animal{}

class tiger:Animal{}

let tiger = Tiger()

let animal = tiger as Animal

(2)消除二义性,数值类型转换

let age = 42 as CGFloat

let accurateAge = 43.0 as Int

(3)switch 语句中进行模式匹配

如果不知道一个对象是什么类型,你可以通过switch语法检测它的类型,并且尝试在不同的情况下使用对应的类型进行相应的处理

switch animal {

     case let cat as Tiger

}

2、as! 使用场合

向下转型时使用,这是强转,如果转换失败,会报错

3、as? 使用场合

as? 和as! 操作符的转换规则完全一样。但是as? 如果转换不成功的时候便会返回一个nil对象。成功的话返回可选类型值,需要我们拆包使用,由于as?在转换失败的时候也不会出现错误,所以对于如果能确保100%会成功的转换则可使用as!,否则as?

参考文章:

http://www.hangge.com/blog/cache/detail_1089.html

12、警告解决方法

return result not used  --------->意思是返回的结果根本没有被用到

13、let myNSRange =NSRange(location:0, length:1)       

 let myotherNSRange =NSRange(location:1, length:4)

nsrange写法



1Writing Swift code is interactive(交互式的) and fun, the syntax is concise(简明的) yet expressive(贵的), and Swift includes modern features developers love.

swift是互动的有趣的,语法是简洁明了,swift包含开发者喜爱的现在特征。

2、Swift code is safe by design, yet also produces software that runs lightning-fast.

Swift code是设计安全的,这样也生产一些运行非常快速的软件。

3The protocol can then be adopted(被采纳) by a class, structure, or enumeration to provide an actual implementation of those requirements. 

协议能被类、结构、枚举继承以便提供这些方法的实现。

4、If a protocol requires a property to be gettable and settable, that property requirement can’t be fulfilled by a constant stored property or a read-only computed property. If the protocol only requires a property to be gettable, the requirement can be satisfied by any kind of property, and it’s valid for the property to be also settable if this is useful for your own code.

如果一个协议需要一个属性,就是如果写了一个强制方法,我们需要赋一个初始值。

4、swift面向协议是精髓

5、实例方法和类方法的区别就是static

6、研究throw,exception,以及do try catch的运行模式

7、为什么,服务器返回时0.11,mJ转换之后打印那个模型,确实0.1,去取model.value 有是0.11

8、当然你也可以增加@discardableResult声明,告诉编译器此方法可以不用接收返回值。

9attriStr.append(NSAttributedString(string: " ", attributes: [NSAttributedStringKey.font: UIFont(name: "PingFangSC-Medium", size: 12)!]))

为什么要加叹号 因为这种字体可能不存在

10pulic private的区别@objc var _customContent:String = "" 默认是public

11、怎么删掉public都能调用,因为默认就是public

12、但是方法就不一样,如果要想被外部调用,前面就必须加上public

13、要想能被外部oc调用,方法或者属性前面要加上@objc

14、pulic class里面方法都能调用,是的,但是那些生命了fileprivate 或者声明了private的方法和属性不能被调用

声明了public的类里面没有关键字也能被调用。

15、(data.name ?? "") + " "     

data.name ?? "" + " “

这两个语法有区别,要特别注意。









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值