Skip to content

Instantly share code, notes, and snippets.

@kingcos
Last active April 8, 2017 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingcos/60d5da73730622e0821277e7e3b41d90 to your computer and use it in GitHub Desktop.
Save kingcos/60d5da73730622e0821277e7e3b41d90 to your computer and use it in GitHub Desktop.
Swifter Tips - 3 - Notes: http://www.jianshu.com/p/85dbf5a524e8
func random(in range: Range<Int>) -> Int {
return Int(arc4random_uniform(UInt32(range.count))) + range.lowerBound
}
for _ in 0..<5 {
let range = Range<Int>(1...6)
print(random(in: range))
}
enum MyEnum {
case value1, value2, value3
}
func check(someValue: MyEnum) -> String {
switch someValue {
case .value1:
return "OK"
case .value2:
return "Maybe OK"
default:
fatalError("Should NOT show!")
}
}
enum ImageName: String {
case imageA = "image_a"
}
extension UIImage {
convenience init!(imageName: ImageName) {
self.init(named: imageName.rawValue)
}
}
let img = UIImage(imageName: .imageA)
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class MyClass {
@objc func callMe() {
print("Hi")
}
}
let object = MyClass()
Timer.scheduledTimer(timeInterval: 1.0,
target: object,
selector: #selector(MyClass.callMe),
userInfo: nil,
repeats: true)
import UIKit
import PlaygroundSupport
let label = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: 400.0, height: 200.0))
label.backgroundColor = .white
label.font = UIFont.systemFont(ofSize: 32.0)
label.textAlignment = .center
label.text = "maimieng.com"
PlaygroundPage.current.liveView = label
import UIKit
let num = Double.nan
if num.isNaN {
print("num is NaN")
}
// OUTPUT:
// num is NaN
func printLog<T>(_ message: T,
file: String = #file,
method: String = #function,
line: Int = #line) {
#if DEBUG
print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)")
#endif
}
import UIKit
protocol EnumeratableEnum {
static var allValue: [Self] { get }
}
enum Suit: String {
case spades = "黑桃"
case hearts = "红桃"
case clubs = "草花"
case diamonds = "方片"
}
extension Suit: EnumeratableEnum {
static var allValue: [Suit] {
return [.spades, .hearts, .clubs, .diamonds]
}
}
for suit in Suit.allValue {
print(suit)
}
// OUTPUT:
// spades
// hearts
// clubs
// diamonds
import UIKit
func tailSum(_ n: UInt) -> UInt {
func sumInternal(_ n: UInt, current: UInt) -> UInt {
if n == 0 {
return current
} else {
return sumInternal(n - 1, current: current + n)
}
}
return sumInternal(n, current: 0)
}
tailSum(100000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment