Thursday 2 February 2017

Working with string and character in Swift

In swift string is value type. In Swift string type is built from Unicode scalar values. A unicode scalar is a unique 21 bit number for a character.

To write an arbitrary scalar value , use \u{n}, where n is a 1-8 digit hexadecimal number with a value equal to a valid Unicode code point.
For example:
let dollar = "\u{24}"
let baby:Character = "\u{1f425}"

Using Extended grapheme cluster we can create a single character by many complex script characters.
An Extended grapheme cluster is a sequence of one or more unicode scalar  that produce a  single human readable character.
let eInCircle:Character = "\u{E9}\u{20DD}"

Will print "é⃝"


String indices: 

In swift different characters require different amount of memory  to store , so in order to determine the position of a character, we must iterate over each unicode scalar from start or end of that string .That's why string in swift can not be indexed by integer values.

A) To get the position of the first character , use the startIndex property of the string:
  var name = "Budha"
   
  To get the first character of the name,
   let firstChar =  name[name.startIndex]

B) The endIndex property  is position after the last character in the string. So to access the last character in the string, use:

let endIndex = name.endIndex
let lastChar = name[name.index(before: endIndex)]

C) To check the equality for string and character, we use ==(equal to ) and != (not equal  to )operator. Two string value will be considered equal if their Extended grapheme clusters are canonically equal. Extended grapheme clusters are canonically equal if they have the same linguistic meaning and appearance, even if they are composed from  different Unicode scalars behind the scenes.

1 comment:

  1. superb.....blog is much interesting which engaged me more.Spend a worthful time.keep updating more.
    SEO Companies in India

    ReplyDelete