Advertisement
Guest User

Swift String Extension

a guest
Nov 22nd, 2017
479
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.73 KB | None | 0 0
  1. extension String {
  2.     // LEFT
  3.     // Returns the specified number of chars from the left of the string
  4.     // let str = "Hello"
  5.     // print(str.left(3))         // Hel
  6.     func left(_ to: Int) -> String {
  7.         var t = to;
  8.         if (t > self.count) {
  9.             t = self.count;
  10.         } else if (t < 0) {
  11.             t = 0;
  12.         }
  13.         return "\(self[..<self.index(startIndex, offsetBy: t)])"
  14.     }
  15.    
  16.     // RIGHT
  17.     // Returns the specified number of chars from the right of the string
  18.     // let str = "Hello"
  19.     // print(str.left(3))         // llo
  20.     func right(_ from: Int) -> String {
  21.         var f = from;
  22.         if (f > self.count) {
  23.             f = self.count;
  24.         } else if (f < 0) {
  25.             f = 0;
  26.         }
  27.         return "\(self[self.index(startIndex, offsetBy: self.count-f)...])"
  28.     }
  29.    
  30.     // MID
  31.     // Returns the specified number of chars from the startpoint of the string
  32.     // let str = "Hello"
  33.     // print(str.left(2, 2))         // ll
  34.     func mid(_ from: Int, _ count: Int = -1) -> String {
  35.         var f = from;
  36.         if (f < 0) {
  37.             f = 0;
  38.         }
  39.         let x = "\(self[self.index(startIndex, offsetBy: f)...])"
  40.         return x.left(count == -1 ? x.count : count)
  41.     }
  42.    
  43.     // MIDAFTER
  44.     // Returns the substring that are found after the specified search string
  45.     // let str = "Hello"
  46.     // print(str.midAfter("e"))       // llo
  47.     func midAfter(_ search : String, _ count: Int = -1) -> String {
  48.         let r = self.range(of: search);
  49.         if (r == nil) {
  50.             return "";
  51.         }
  52.         let lb = r!.lowerBound;
  53.         let x = "\(self[lb...])".mid(1);
  54.         return x.left(count == -1 ? x.count : count)
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement