Those years, learn the pits that Swift trod

Source: Internet
Author: User
Tags serialization
those years, learn the pits that Swift trod

The recent learning of Swift, I thought that many of the grammar and OC are different, and are using the same cocoa framework, the same API, but more or less still some pits in, in order to avoid the next step, write down here, later found a new pit, will slowly be added here

[TOC] where's the 1.main file? the code in MAIN.M in OC can be automatically generated by the @uiapplicationmain tag to make a note of the @uiapplicationmain in Appdelegate, and realize main by itself, but no one does. To implement the following code is the function of the main file in OC

Uiapplicationmain (PROCESS.ARGC, process.unsafeargv, Nil, Nsstringfromclass (appdelegate))
2. How to create a class object from a string. When you print an object in Swift, you will find that there is always a namespace in front of the type. + class name in Swift, a string-generated class object needs to be spliced into such a format to successfully generate class attention, namespaces without special symbols, or cannot get controller classes
Gets the namespace, in the Info.plist file is the executable files let
nameSpace = Nsbundle.mainbundle (). infodictionary![" Cfbundleexecutable "] as! String
//stitching into fixed format let
controller:anyclass = nsclassfromstring (NameSpace + "." + controllername)!
Create Object let
Viewcontroller = (Controller as! Uiviewcontroller.type). Init ()
the Any,anyobject,anyclass in the 3.Swift represent what they are respectively. Anyobject: equivalent to the ID in OC, representing all class type data, all inherited and NSObject classes implicitly implement the 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 through Anyobject, because many of Swift's data types can be automatically converted to the data types in OC, which have been converted to the object type of OC within the system.

anyclass: Class type (meta type) used to represent any class

  Typealias Anyclass = Anyobject.type
  . Type is used to get the meta type of the class, for example, Person.type represents the meta type that gets the
  person. Self if invoked by the class name, then you can get the type of the class, which is to get yourself
4. How to crawl the exception in the Swife. Grabbing an exception in Swift requires do,catch,try these three keywords here's an example of JSON serialization
do{let
            path =/.. Path.. /Let
            data =/... Turn data. ///The 
            compiler will ask you to implement anomaly detection, so add a try field
            //outer parcel do,catch before serialization, and obviously mistakes naturally go catch let           
            Dicarr = Try Nsjsonserialization.jsonobjectwithdata (data, options:NSJSONReadingOptions.MutableContainers)

        }catch
        {
            //If an exception is thrown it will come to catch

        }
5. How to define a global printing method in SwiftSince Swift has no macros, we cannot define it directly in Appdelegate as OC, where all can be used to determine debug and release status with generic parameters. In Build settings find Swift Compiler-custom flags in the debug of other Swift flags add two fields "-D" "DEBUG" code direct judgment on the line
Func hjslog<t> (message:t)
{
    #if DEBUG
        print ("\ (Message)")

    #endif
}
6. In swift, how to write a single case. In Swift, there are two ways in which a single example is written in terms of OC thinking.
     static var oncetoken:dispatch_once_t = 0
    static var instance:networktools?

    Class Func Sharenetworktools ()-> networktools
    {

        dispatch_once (&oncetoken) {()-> Void in
            print ( "I was called")
            instance = Networktools ()
        } return

        instance!
    }
The other is that Swift's pure writing is in Swift, let itself will only be created once, and can use this attribute let is thread safe
static Let Instance:networktools = Networktools ()
    class func sharenetworktools ()-> networktools
    {
        return Instance
    }
7. How to privatize the Click event method in SwiftGenerally we do not expose the method will be added in front of private but for example button click Method, just add private is not enough because Swift's method call is decided at compile time and click event method because it is from the Runloop compiler will not compile it together, Only call at run time, this is the way the OC is called so we need to add @objc before the method.
button click Handle
    @objc private func Composeclick () {

    } '
8. How to lazy load in swiftThere are special keywords for lazy loading in swift
Lazy load a imageview
private 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 simple, just define it in front of the class.
@objc
Protocol Visitorviewdelegate:nsobjectprotocol
{
  //Click on the Register button
  optional func Visitorviewdidregisterbtnclick (Visitview:visitorview)
  //Click on the login button
  optional func visitorviewdidloginbtnclick (Visitview:visitorview)
}
Agent properties need to be set to weak to prevent circular references
Weak var delegate:visitorviewdelegate?
When invoking the proxy method, the agent as an optional attribute has helped us prevent the possibility that the agent does not exist we also need to use the optional attribute to prevent the implementation of the method is not implemented of course, in the determination of the implementation of the premise can unpack
Registered handle
  @objc private func Registerclick () {
delegate? visitorviewdidregisterbtnclick! (self)
  }
  Login handle
  @objc private func Loginclick () {delegate? Visitorviewdidloginbtnclick? (self)
  }
10. How to write classifications in SwiftI just turned around from OC and I ran into the question of how to write categories in Swift. It's easy to write categories in swift Extension is a category in Swift. For example, add a category to Uibarbuttonitem and create a new uibarbuttonitem+ Extension.swift file
Import uikit

extension uibarbuttonitem
{
    convenience init (target:anyobject?,action:selector,image: String) {let

        btn = UIButton (type:UIButtonType.Custom)
        btn.setimage (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 forced 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. The general satisfaction of this demand is abstract Type or abstract functionIn the face of this situation, to ensure that subclasses implement these methods, and that methods in the parent class are not incorrectly invoked, we can use fatalerror to force throw errors in the parent class to ensure that the developers who use the code notice that they must implement the relevant methods in their subclasses:
Class MyClass {  
    func methodmustbeimplementedinsubclass () {
        FatalError ("This method must be overridden in subclasses")
    }

Class Yourclass:myclass {  
    override func Methodmustbeimplementedinsubclass () {
        print ("YourClass implemented This method")
    }

class Theirclass:myclass {  
    func someothermethod () {

    }
}

YourClass (). Methodmustbeimplementedinsubclass ()  
//YourClass implemented the method

Theirclass (). Methodmustbeimplementedinsubclass ()  
//This method must be overridden in a subclass
Not only for the use of similar abstract functions can choose FatalError, for everything else we do not want others to call, but also have to implement the method, we should use FatalError to avoid any possible misunderstanding. For example, the parent class indicates that one of the Init methods is required, but your subclass will never use this method to initialize, and it can be used in a similar way, and the widespread use (and the widely hated) of Init (Coder:nscoder) is an example. In subclasses, we tend to write
Required Init (coder:nscoder) {  
  fatalerror ("Nscoding not Supported")
}
12. Use guard and FatalError in Swift to throw exceptionsIn the rigorous development will often use the assertion that the previous article introduced FatalError to throw the error of the article to introduce the guard and fatalerror with the use of the assertion effect
Guard Let Safevalue = Criticalvalue else {
  fatalerror ("Criticalvalue cannot is nil here")
}
Somenecessaryoperation (Safevalue)
I would have thought if I could do that.
If let Safevalue = criticalvalue {
  somenecessaryoperation (safevalue)
} else {
  fatalerror ("Criticalvalue Cannot be nil ")
}
Or
if Criticalvalue = = Nil {
  fatalerror ("Criticalvalue cannot is nil here")
}
somenecessaryoperation ( criticalvalue!)

But see some blogs that say:

This flatten C

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.