Swift Language Learning No.2: two-dimensional arrays

Source: Internet
Author: User
Tags assert

In the tutorial before learning a two-dimensional array, the original inside a lot of knowledge points are not very understanding, and then after some information to find, basically understand thoroughly, do a summary of it.

The usual, the first code:

Class Array2d<t> {Let     columns:int let     rows:int     var array:array<t?>     init (columns:int, Rows:int) {         self.columns = columns         self.rows = rows         array = array<t?> (count:rows * columns, Repeatedva Lue:nil)     }     subscript (Column:int, row:int), T?  {         get {             return array[(Row * columns) + column]         }         Set (NewValue) {             array[(Row * columns) + column] = NewValue         }}}     

In fact, in general, this custom class is very similar to the template class in C + +, for example, using T to represent arbitrary data types, but only in Swift? To represent the optional type, the optional and non-optional types have been described in the previous blog post and are not repeated here.

It should not be difficult to understand whether a two-dimensional array is actually a one-dimensional array, except that the value of the element is determined by two parameters. So there are 3 variables in the class, namely the number of rows, the number of columns, and the one-dimensional array used to store the data.

Then two functions, one is the init initialization function, and the other is the subscript function, we have to look at the two functions separately.

init function

Init a two-dimensional array requires two parameters, the number of rows and columns, the first two lines of code is very simple, the value of the formal parameter passed to the two private variables of the instantiated class, and to store the data array, you have to use the Swift soundtrack of the array class to build. For more information on the swift array class, please poke: here

Let's focus on the init (count:repeatedvalue:) function of the array.

First on the code:

Init (count:repeatedvalue:) constructs an array with a given number of elements, each initialized to the same value. Declarationinit (Count:int, repeatedvalue:t) discussionthe resulting array'll has count elements in it, each initialize D to the same value provided as the value for repeatedvalue.for example:let Numericarray = Array (Count:3, Repeatedvalue: ()//Numericarray is [all] let Stringarray = Array (Count:2, repeatedvalue: "Hello")//Stringarray is ["Hello", "H Ello "]
From the two chestnuts, it is easy to understand, count represents the size of the array, Repeatedvalue represents the initialized value, here means that all the values are the same, when I first saw this function, because the tutorial is written in the Repeatedvalue is nil, I thought it was possible to allow the array to have duplicate values. Knowing the details of Swift's official documentation, the meaning of this function is understood correctly.

Again reminds me, must not take for granted, cannot above his business, not clear the matter, must read down the information to make clear.

subscript Function

When I first saw this function, I was confused by Swift's grammar. What symbol is,->? Although this function can be read or written in terms of content, what is the exact wording?

After reviewing the official documents, I understand thoroughly and want to understand the complete subscript function, please poke here

The use of the subscript function is introduced as soon as it goes up:

classes, structures, and enumerations can define subscripts, which is shortcuts for acces Sing the member elements of a collection, list, or sequence. You use the subscripts to set and retrieve values by index without needing separate methods for setting and retrieval. For example, you access elements in an Array instance as Somearray[index] and elements in a Dictionary instance as Somedic Tionary[key]. You can define multiple subscripts-a single type, and the appropriate subscript overload-to-use are selected based on T He type of index value you pass to the subscript. Subscripts is limited to a single dimension, and you can define subscripts with multiple input parameters to suit R custom type ' s needs. 
subscripts enable you to query instances of a type by writing one or more values in square brackets after the instance Nam E. Their syntax is similar to both instance method syntax and computed property syntax.  You write subscript definitions with the Subscript keyword, and specify one or more input parameters and a return type, in The same is instance methods. Unlike instance methods, subscripts can be read-write or read-only. This behavior are communicated by a getter and setters in the same-as for computed properties:
That is, you can define the subscript function as read-write or read-only mode, we see both set and get are read-write mode, if you want to read-only mode, do not write the Get keyword is:

As with read-only computed properties, can drop the Get keyword for read-only subscripts:subscript (index:int)-I NT {    //return an appropriate subscript value here}
Let's continue to look at a few examples of using the subscript function, in fact the definition is defined, when used, and normal array usage, a pair of "[]" can be

Structural Body
struct Timestable {let    multiplier:int    subscript (index:int), Int {        return multiplier * index    }}let threetimestable = timestable (multiplier:3) println ("six times three is \ (Threetimestable[6])")//Prints "six times three is 18 "

The subscript function of the struct is to return the input parameter multiplied by the private variable in the struct, so it is easy to understand the value of the example.

Dictionary
var numberoflegs = ["Spider": 8, "Ant": 6, "cat": 4]numberoflegs["bird"] = 2

Finally, look at the official documents given in the two-dimensional array of source code, is not the same as in the tutorial?

struct Matrix {Let    rows:int, Columns:int    var grid: [Double]    init (rows:int, columns:int) {        self.rows = Rows        self.columns = columns        Grid = Array (count:rows * columns, repeatedvalue:0.0)    }    func INDEXISVALIDF Orrow (Row:int, column:int), Bool {        return row >= 0 && row < rows && column >= 0 && Amp Column < columns    }    subscript (Row:int, column:int), Double {        get {            assert (  Indexisvalidforrow (Row, Column:column), "Index Out of Range")            return grid[(Row * columns) + column]        }        Set {            assert (Indexisvalidforrow (row, Column:column), "Index Out of Range")            grid[(Row * columns) + column] = newval UE        }}    }

But the matrix here returns the number of double types, and in our tutorial we use the template T. See here there should be no more explanation, about the two-dimensional array of all the content is at a glance?


Swift Language Learning No.2: two-dimensional arrays

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.