Last active
December 27, 2017 05:55
-
-
Save tkdmaf/2276cf96528c1da925e83ccde3f54fb6 to your computer and use it in GitHub Desktop.
Playground get state string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
enum MyContain { | |
case before | |
case after | |
case between | |
} | |
class MyState { | |
static private var instance:MyState? | |
private var contains:[(min:Int,max:Int,string:String,contain:MyContain)] = [ | |
(min:0,max:0,string:"zero",contain:.between), | |
(min:0,max:10,string:"one",contain:.after), | |
(min:11,max:20,string:"two",contain:.between), | |
(min:21,max:30,string:"three",contain:.between), | |
(min:31,max:40,string:"four",contain:.between), | |
(min:41,max:50,string:"five",contain:.before), | |
(min:50,max:Int.max,string:"Limit",contain:.between) | |
] | |
static func shared() -> MyState { | |
if instance == nil { | |
instance = MyState() | |
} | |
return instance! | |
} | |
func state(_ value:Int) -> String?{ | |
for item in contains { | |
if self._getString(value: value, min: item.min, max: item.max, contain: item.contain) { | |
return item.string | |
} | |
} | |
return nil | |
} | |
private func _getString(value:Int,min:Int,max:Int,contain:MyContain) -> Bool{ | |
switch contain { | |
case .before: | |
return value >= min && value < max | |
case .after: | |
return value > min && value <= max | |
case .between: | |
return value >= min && value <= max | |
} | |
} | |
} | |
let str = MyState.shared().state(31) | |
//output | |
// four |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
let state:[(range:[Int],name:String)] = [ | |
(range:Array(0...10),name:"one"), | |
(range:Array(11...20),name:"two"), | |
(range:Array(21...30),name:"three"), | |
(range:Array(31...40),name:"four"), | |
(range:Array(41..<50),name:"five") | |
] | |
let number = 11 | |
let string = state.filter { | |
$0.range.index(of: number) != nil | |
} | |
let str = state.flatMap { (range,string) -> String? in | |
if range.index(of: number) != nil { | |
return string | |
} | |
return nil | |
} | |
print(string) | |
print(str) | |
//output | |
// [(range: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], name: "two")] | |
// ["two"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment