CocoaPods trunk is moving to be read-only. Read more on the blog, there are 17 months to go.

SugarString 1.0.1

SugarString 1.0.1

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Apr 2017
SwiftSwift Version 3.0
SPMSupports SPM

Maintained by ooppstef.



  • By
  • Charles

Sugar

Sugar is a beautiful syntactic sugar for String in Swift3.Idea from Ruby.Fully tested.

Three parts of String:

  • Operators:subscription with Range,Tuple,Index,Key;-,*,/
  • Regular Expresstion: gsub,scan,match,=~
  • literal converted to resource:date,color,image,bundle path,nib and more.

Have fun with sugar!

Requirements

Swift3

Installation

Available through CocoaPods

pod 'SugarString'

Usage

import SugarString

Details

Operators

subscription with Range(start ..< end)
let str = "0123456789"
str[0 ..< 3] //=> "123"
var str = "0123456789"
str[0 ..< 3] = "abc" //=> (str = "abc3456789")
subscription with Tuple(location,length)
var str = "0123456789"
str[(5,10)] //=> "abcde"
var str = "0123456789"
str[(3,7)] = "abcde" //=> str = "012abcde"
subscription with index
let str = "0123456789"
str[0] //=> "0"
var str = "0123456789"
str[0] = "A" //=> str1 = "A123456789"
subscription with key
let url = "https://google.com?a=b&c=d"
url["a"] //=> "b"
let string = "abcdef"
string["a"] //=> nil
operator: -
"000111000" - "0" //=>"111"
"aa aabbccdd" - "aa" //=> " bbccdd"
"123" - "abc" //=> "123"
operator: *
"abc" * 3 //=> "abcabcabc"
"" * 3 //=> ""
operator: /
"1,2,3" / "," //=> ["1","2","3"]
"1 2 3" / " " //=> ["1","2","3"]
"1 2 3" / "," //=> nil

Regular Expresstion

operator: =~
let str = "0123456789\n  abcef"
str =~ "0" //=> true
str =~ "A" //=> false
str =~ "^0\\d*\\s*.*f$" //=> true
gsub
var string = "0123456789\n  abcef"
string.gsub(reg: "^0\\d*\\s*.*f$", replacement: "") //=> string = ""

string = "0123456789\n  abcef"
string.gsub(reg: "[359]", replacement: "TTT") //=> string = "012TTT4TTT678TTT\n  abcef"
scan

it returns [(String?, NSTextCheckingResult)]?

let string = "0123456789\n  abcef"
let array = string.scan(reg: "\\d") //=> array = [0,1,2,3,4,5,6,7,8,9]
match
let string = "0123456789\n  abcef"
result = string.match(reg: "\\d+") //=> "0123456789"

Resources

Some convenience functions with literal.

Date

Try to get date with 2 default formats,then try convert to TimeInterval to get date

//default format 1
"2020-01-01".date() //=> Date:2020-01-01

//default format 2
"2020-01-01 00:00:00".date() //=> Date 2020-01-01 00:00:00

//timeinterval
"1577808000".date() //=> 2020-01-01 00:00:00
"-1".date() //=> nil

//format with parameter
"2020/01/01".date(format: "yyyy/MM/dd") //=> 2020/01/01
Color
"255 255 255".color()    //=> white
"255,255,255".color()   //=> white
"#ffffff".color()       //=> white
"0x000000".color()      //=> black
"000000".color()        //=> black
"00FF00".color()        //=> green

"1255 255 255".color()  //=> nil
"-1,-1,-1".color()      //=> nil