Swift learning "Swift Programming Tour---subscripts subscript (16)

Source: Internet
Author: User
Tags instance method

Classes, structs, and enumerations can define subscripts, and he can quickly and easily access the elements of a collection (set,array,dict), and you can make use of subscripts to get and set the collection elements. You can define multiple subscripts for a type, which can be overloaded by the different index value types, and the number of indexed values may be multiple.

Grammar

Look at an example first

Subscript (index:int), Int {    get  {        //  return an appropriate Subscript valuehere    }    set(newvalue) {        //  perform A suitable setting actionhere    }}

It allows you to access and assign values to an instance by passing in one or more index values in the brackets behind the instance. Syntax is similar to the blending of instance methods and computed properties. Similar to defining an instance method, defining subscript uses the SUBSCRIPT keyword to explicitly declare the in parameter (one or more) and the return type. Unlike instance methods, subscripts can be set to read-write or read-only. This approach is somewhat like the getter and setter of computed properties:

The type of newvalue must be the same as the return type defined by subscript. The same as the computed attribute is the parameter declaration of the set newvalue even if not written, the default newvalue variable can still be used to access the newly assigned value in the set code block. As with read-only computed properties, you can write the code that should be written in the get code block directly in subscript:
Subscript (index:int), Int {     //

Swift learning "Swift Programming Tour---subscripts subscript (16)

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.