How to simplify the lengthy class instance initialization code in the standard library in Swift

Source: Internet
Author: User

Some children's shoes may not be known, and the abbreviated point symbol in Swift is valid for any static member of any type.

Let's actually write an example to look at:

import UIKitclass CFoo{    staticlet sharedInstance = CFoo()}struct SFoo{    staticlet sharedInstance = SFoo()}let foo:CFoo = .sharedInstancelet f:SFoo = .sharedInstance

As you can see in the code above, the Foo type is Cfoo, and cfoo happens to have a static property sharedinstance, so you can use the abbreviated point notation to complete the simplification. The f variable is similar to Foo.

It seems like just a little gimmick, no practical use, but not necessarily, in swift to deal with the traditional OBJC code, you can often see the C-style enumeration initialization code:

animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)

Isn't it annoying? We can write an extension to simplify the syntax (here's the Code excerpt):

extension CAMediaTimingFunction{    // 这个属性会在第一次被访问时初始化。    // (需要添加 @nonobjc 来防止编译器    //  给 static(或者 final)属性生成动态存取器。)    staticlet EaseInEaseOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)    // 另外一个选择就是使用计算属性, 它同样很有效,    // 但 *每次* 被访问时都会重新求值:    staticvar EaseInEaseOut: CAMediaTimingFunction {        // .init 是 self.init 的简写        return .init(name: kCAMediaTimingFunctionEaseInEaseOut)    }}

Then we can use it gracefully:

animation.timingFunction.EaseInEaseOut

How to simplify the lengthy class instance initialization code in the standard library in Swift

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.