In those years, learn swift to step over the pit

Source: Internet
Author: User
Tags mutex

Recently learning Swift, this thought much is the grammar and OC different, and are all using the same cocoa framework, the same API, but more or less still some pits in, in order to avoid further stepping, here to write down, later found a new pit, will slowly add here

[TOC]

1.main file where are we going?
    • Code in MAIN.M in OC, automatically generated by @uiapplicationmain tag
    • Can be appdelegate in the @uiapplicationmain, the implementation of the main, but generally no one to do so
    • Implementing the following code is the function of the main file in OC
UIApplicationMain(Process.argc, Process.unsafeArgv, nil, NSStringFromClass(AppDelegate))
2. How do I create a class object from a string?
    • When you print an object in Swift, you will find that there is always a + in front of the type 命名空间 .类名
    • Generating a class object in Swift with a string will need to be stitched into such a format to successfully generate the class
    • Note that namespaces do not add special symbols, or you cannot get the Controller class
//获取命名空间,在info.plist文件里就是Executable filelet nameSpace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String//拼接成固定格式let controller:AnyClass = NSClassFromString(nameSpace + "." + controllerName)!//创建对象let viewController = (controller as! UIViewController.Type).init()
What do the Any,anyobject,anyclass in 3.Swift represent respectively?
    • anyobject: equivalent to the ID in OC, representing all data of class type, all inheriting and NSObject classes implicitly implement protocol Anyobject protocol, so he can represent all class types
    • Any: All basic data types and enum/struct can be represented by any

      Note: There are times when you will find that the basic data type or enum/struct is saved via Anyobject and will not be an error because many of the data types in Swift can be automatically converted to the data types in OC, and they have been converted to OC object types within the system.

    • Anyclass: The class type (meta-type) used to represent any class

        typealias AnyClass = AnyObject.Type  .Type用于获取类的元类型, 例如Person.Type就代表着获取Person的元类型 .self如果通过类名调用, 那么可以获取该类的类型, 说白了就是获取自己
4. How do I crawl exceptions in Swife?
    • Fetching exceptions in Swift requires do,catch,try of these three keywords
    • Here's an example of JSON serialization
do{            let path = /..路径../            let data =/..转data../ //编译器会要求你实行异常检测,于是在序列化前面添加try字段 //外部包裹do,catch,显而易见出错自然会走catch let dicArr = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) }catch { // 如果抛出异常就会来到catch }
5. How to define a global printing method in Swift
    • Because Swift does not have macros, we cannot define them like OC.
    • Write directly in the appdelegate, it can be used anywhere, anyway.
    • To use generic pass-through parameters
    • How to determine the debug and release status?
    • Find Swift Compiler-custom Flags in Build settings
    • Add two fields to the debug of other Swift flags
    • "-D"
    • "DEBUG"
    • Direct judgment in the code.
func HJSLog<T>(message: T){ #if DEBUG print("\(message)") #endif}
6. In swift, how do I write a single case?
    • In Swift, the Singleton is written in two ways
    • One is to write according to OC's thinking
     0    static var instance: NetworkTools?    class func shareNetworkTools() -> NetworkTools { dispatch_once(&onceToken) { () -> Void in print("我被调用了") instance = NetworkTools() } return instance! }
    • The other is Swift's pure notation.
    • In Swift, let itself is created only once, and this feature can be used
    • Let is thread-safe
static let instance: NetworkTools = NetworkTools()    class func shareNetworkTools() -> NetworkTools { return instance }
7. How to privatize the Click event method in Swift
    • Generally we do not expose the method will be added in the previousprivate
    • But for example button click Method, private Just add is not enough
    • Because Swift's method invocation is determined at compile time.
    • And the Click event method is due to be from Runloop
    • The compiler does not compile it together, only at run-time calls, which are called by OC
    • So we're going to need to add that in front of the method@objc
//按钮点击handle    @objc private func composeClick(){ }`
8. How to lazy load in swift
    • Special keywords for lazy loading in swift
///懒加载一个imageViewprivate lazy var icon:UIImageView = {        let imageV = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon")) return imageV }()
9. Agreement in Swift (protocol)
  • Defining a protocol in Swift is also simple
  • You just need to define it before the class.
    @objcprotocol VisitorViewDelegate:NSObjectProtocol{ //点击注册按钮 optional func visitorViewDidRegisterBtnClick(visitView: VisitorView) //点击登录按钮 optional func visitorViewDidLoginBtnClick(visitView:VisitorView)}
  • Proxy properties need to be set to weak to prevent circular referencing
    var delegate:VisitorViewDelegate?
  • When invoking the proxy method, the proxy as an optional attribute has helped us to prevent the possibility that the agent does not exist
  • We also need to use optional attributes to prevent the method from being implemented
  • Of course, it is possible to unpack the package if the implementation is determined
    ///注册handle  @objc private func registerClick(){delegate?.visitorViewDidRegisterBtnClick!(self) } ///登录handle @objc private func loginClick(){ delegate?.visitorViewDidLoginBtnClick?(self) }
10. How to write a classification in Swift
    • I've just been transferred from OC and I've come across a question of how to write a classification in Swift
    • It's easy to write a category in Swift
    • extensionis the classification in Swift
    • For example, add a category to Uibarbuttonitem
    • Create a new Uibarbuttonitem+extension.swift file
ImportUikitextensionuibarbuttonitem{convenience init (target:anyobject?,action:selector,image:string) {Let btn =UIButton (type: uibuttontype. Custom) btnsetimage (UIImage (named:image), forstate: uicontrolstate. Normal) btn. SetImage (UIImage (named:image + "_highlighted"), Forstate: uicontrolstate. Highlighted) btn. AddTarget (Target, action:action, forcontrolevents: uicontrolevents. Touchupinside) self. Init (CUSTOMVIEW:BTN)}}          
11. Why is it often mandatory to implement Init (Coder:nscoder)
    • Because there is no direct such abstract function syntax support in OBJECTIVE-C and Swift
    • However, there are times when we do not want others to call a method, but have to expose it.
    • It is the abstract type or abstract function that generally satisfies this requirement.
    • In the face of this situation, to ensure that subclasses implement these methods, and that the methods in the parent class are not called incorrectly, we can use fatalerror to force throwing errors in the parent class to ensure that the developers using the code notice that they have to implement the relevant methods in their own subclasses:
ClassMyClass {FuncMethodmustbeimplementedinsubclass() {FatalError ("This method must be overridden in a subclass")}}Classyourclass: myclass {override func methodmustbeimplementedinsubclass< Span class= "Hljs-params" > () {print ( "YourClass implemented this method")}}< Span class= "Hljs-class" >class theirclass: myclass {func someothermethod () {}}YourClass (). Methodmustbeimplementedinsubclass () //YourClass implemented the method //This method must be overridden in a subclass    
    • Not only for the use of similar abstract functions can choose FatalError, for all other things we do not want others to call, but we have to implement the method, we should use FatalError to avoid any possible misunderstanding. For example, if the parent class indicates that an Init method is required, but your subclass will never use this method to initialize it, it can be used in a similar way, and the widespread use (and the widely hated) init (Coder:nscoder) is an example. In subclasses, we tend to write
required init(coder: NSCoder) { fatalError("NSCoding not supported")}
12. Using guard with FatalError to throw exceptions in Swift
  • Assertions are often used in rigorous development.
  • The previous article introduced fatalError to throw an error
  • This is the way to introduce guard the fatalError use of mates to achieve the effect of assertions
    let safeValue = criticalValue else {  fatalError("criticalValue cannot be nil here")}someNecessaryOperation(safeValue)
  • I thought I if could have achieved that.
    if let safeValue = criticalValue {  someNecessaryOperation(safeValue)} else {  fatalError("criticalValue cannot be nil here")}
  • Or
    if criticalValue == nil {  fatalError("criticalValue cannot be nil here")}someNecessaryOperation(criticalValue!)
  • But I see some blogs that say:

    This flatten code otherwise enters an if let block and exits prematurely in the context of the relevant environment, rather than entering the else code block. Even when you do not capture a value (guard let), this pattern also forces premature exit during compilation. In the second if example, although the code is flattend like a guard, a destructive error or other process that returns some non-exiting (or an illegal state based on an exact instance) will cause crash. When a premature exit occurs, the Guard statement will detect the error in time and remove it from the else block. (The blogger really sucks)

  • So, it's better to use a guard.

    13. What did the mutex become like in Swift?
  • How the mutex is written in Swift
  • Mutex lock in OC:
@synchronized(self) {    //需要执行的代码块}
    • Mutual exclusion lock in Swift
objc_sync_enter(self)//需要执行的代码块objc_sync_exit(self)
    • As for the other multi-threaded API and the same as before, just a few perform this kind of API, Apple has removed the
14. How to avoid circular references when self is referenced in Swift
    • In OC, we need to use self for the code block, we can pay the self to other variables directly, and then make the empty after use in the block, or like the following weak reference self to avoid circular references:
      __weak typeof(self) weakSelf = self;
    • So what do we do to this in swift?
    • Very simple, look at the following code
      //这里用gcd举例不好,毕竟系统的块不会造成循环引用,这里就勉强的学一下怎么改吧dispatch_async(dispatch_get_global_queue(0, 0)) {[unowned self] () -> Void in self.view //添加自己的代码 }
    • You just need to add it in the closure. [unowned self]



Wen/Yo _json (Jane book author)
Original link: http://www.jianshu.com/p/b5c87824e33c
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

In those years, learn swift to step over the pit

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.