repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lorentey/GlueKit | Sources/CompositeObservable.swift | 1 | 10676 | //
// CompositeObservable.swift
// GlueKit
//
// Created by Károly Lőrentey on 2016-10-09.
// Copyright © 2015–2017 Károly Lőrentey.
//
extension ObservableValueType {
public func combined<Other: ObservableValueType>(_ other: Other) -> AnyObservableValue<(Value, Other.Value)> {
return CompositeObservable(left: self, right: other, combinator: { ($0, $1) }).anyObservableValue
}
public func combined<A: ObservableValueType, B: ObservableValueType>(_ a: A, _ b: B) -> AnyObservableValue<(Value, A.Value, B.Value)> {
return combined(a).combined(b, by: { a, b in (a.0, a.1, b) })
}
public func combined<A: ObservableValueType, B: ObservableValueType, C: ObservableValueType>(_ a: A, _ b: B, _ c: C) -> AnyObservableValue<(Value, A.Value, B.Value, C.Value)> {
return combined(a, b).combined(c, by: { a, b in (a.0, a.1, a.2, b) })
}
public func combined<A: ObservableValueType, B: ObservableValueType, C: ObservableValueType, D: ObservableValueType>(_ a: A, _ b: B, _ c: C, _ d: D) -> AnyObservableValue<(Value, A.Value, B.Value, C.Value, D.Value)> {
return combined(a, b, c).combined(d, by: { a, b in (a.0, a.1, a.2, a.3, b) })
}
public func combined<A: ObservableValueType, B: ObservableValueType, C: ObservableValueType, D: ObservableValueType, E: ObservableValueType>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E) -> AnyObservableValue<(Value, A.Value, B.Value, C.Value, D.Value, E.Value)> {
return combined(a, b, c, d).combined(e, by: { a, b in (a.0, a.1, a.2, a.3, a.4, b) })
}
public func combined<Other: ObservableValueType, Output>(_ other: Other, by combinator: @escaping (Value, Other.Value) -> Output) -> AnyObservableValue<Output> {
return CompositeObservable(left: self, right: other, combinator: combinator).anyObservableValue
}
public func combined<A: ObservableValueType, B: ObservableValueType, Output>(_ a: A, _ b: B, by combinator: @escaping (Value, A.Value, B.Value) -> Output) -> AnyObservableValue<Output> {
return combined(a).combined(b, by: { a, b in combinator(a.0, a.1, b) })
}
public func combined<A: ObservableValueType, B: ObservableValueType, C: ObservableValueType, Output>(_ a: A, _ b: B, _ c: C, by combinator: @escaping (Value, A.Value, B.Value, C.Value) -> Output) -> AnyObservableValue<Output> {
return combined(a, b).combined(c, by: { a, b in combinator(a.0, a.1, a.2, b) })
}
public func combined<A: ObservableValueType, B: ObservableValueType, C: ObservableValueType, D: ObservableValueType, Output>(_ a: A, _ b: B, _ c: C, _ d: D, by combinator: @escaping (Value, A.Value, B.Value, C.Value, D.Value) -> Output) -> AnyObservableValue<Output> {
return combined(a, b, c).combined(d, by: { a, b in combinator(a.0, a.1, a.2, a.3, b) })
}
public func combined<A: ObservableValueType, B: ObservableValueType, C: ObservableValueType, D: ObservableValueType, E: ObservableValueType, Output>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, by combinator: @escaping (Value, A.Value, B.Value, C.Value, D.Value, E.Value) -> Output) -> AnyObservableValue<Output> {
return combined(a, b, c, d).combined(e, by: { a, b in combinator(a.0, a.1, a.2, a.3, a.4, b) })
}
}
private struct LeftSink<Left: ObservableValueType, Right: ObservableValueType, Value>: UniqueOwnedSink {
typealias Owner = CompositeObservable<Left, Right, Value>
unowned let owner: Owner
func receive(_ update: ValueUpdate<Left.Value>) {
owner.applyLeftUpdate(update)
}
}
private struct RightSink<Left: ObservableValueType, Right: ObservableValueType, Value>: UniqueOwnedSink {
typealias Owner = CompositeObservable<Left, Right, Value>
unowned let owner: Owner
func receive(_ update: ValueUpdate<Right.Value>) {
owner.applyRightUpdate(update)
}
}
/// An AnyObservableValue that is calculated from two other observables.
private final class CompositeObservable<Left: ObservableValueType, Right: ObservableValueType, Value>: _BaseObservableValue<Value> {
typealias Change = ValueChange<Value>
private let left: Left
private let right: Right
private let combinator: (Left.Value, Right.Value) -> Value
private var _leftValue: Left.Value? = nil
private var _rightValue: Right.Value? = nil
private var _value: Value? = nil
public init(left: Left, right: Right, combinator: @escaping (Left.Value, Right.Value) -> Value) {
self.left = left
self.right = right
self.combinator = combinator
}
deinit {
assert(_value == nil)
}
public override var value: Value {
if let value = _value { return value }
return combinator(left.value, right.value)
}
internal override func activate() {
assert(_value == nil)
let v1 = left.value
let v2 = right.value
_leftValue = v1
_rightValue = v2
_value = combinator(v1, v2)
left.add(LeftSink(owner: self))
right.add(RightSink(owner: self))
}
internal override func deactivate() {
left.remove(LeftSink(owner: self))
right.remove(RightSink(owner: self))
_value = nil
_leftValue = nil
_rightValue = nil
}
func applyLeftUpdate(_ update: ValueUpdate<Left.Value>) {
switch update {
case .beginTransaction:
beginTransaction()
case .change(let change):
_leftValue = change.new
let old = _value!
let new = combinator(_leftValue!, _rightValue!)
_value = new
sendChange(ValueChange(from: old, to: new))
case .endTransaction:
endTransaction()
}
}
func applyRightUpdate(_ update: ValueUpdate<Right.Value>) {
switch update {
case .beginTransaction:
beginTransaction()
case .change(let change):
_rightValue = change.new
let old = _value!
let new = combinator(_leftValue!, _rightValue!)
_value = new
sendChange(ValueChange(from: old, to: new))
case .endTransaction:
endTransaction()
}
}
}
//MARK: Operations with observables of equatable values
public func == <A: ObservableValueType, B: ObservableValueType>(a: A, b: B) -> AnyObservableValue<Bool>
where A.Value == B.Value, A.Value: Equatable {
return a.combined(b, by: ==)
}
public func != <A: ObservableValueType, B: ObservableValueType>(a: A, b: B) -> AnyObservableValue<Bool>
where A.Value == B.Value, A.Value: Equatable {
return a.combined(b, by: !=)
}
//MARK: Operations with observables of comparable values
public func < <A: ObservableValueType, B: ObservableValueType>(a: A, b: B) -> AnyObservableValue<Bool>
where A.Value == B.Value, A.Value: Comparable {
return a.combined(b, by: <)
}
public func > <A: ObservableValueType, B: ObservableValueType>(a: A, b: B) -> AnyObservableValue<Bool>
where A.Value == B.Value, A.Value: Comparable {
return a.combined(b, by: >)
}
public func <= <A: ObservableValueType, B: ObservableValueType>(a: A, b: B) -> AnyObservableValue<Bool>
where A.Value == B.Value, A.Value: Comparable {
return a.combined(b, by: <=)
}
public func >= <A: ObservableValueType, B: ObservableValueType>(a: A, b: B) -> AnyObservableValue<Bool>
where A.Value == B.Value, A.Value: Comparable {
return a.combined(b, by: >=)
}
public func min<A: ObservableValueType, B: ObservableValueType, Value: Comparable>(_ a: A, _ b: B) -> AnyObservableValue<Value>
where A.Value == Value, B.Value == Value {
return a.combined(b, by: min)
}
public func max<A: ObservableValueType, B: ObservableValueType, Value: Comparable>(_ a: A, _ b: B) -> AnyObservableValue<Value>
where A.Value == Value, B.Value == Value {
return a.combined(b, by: max)
}
//MARK: Operations with observables of boolean values
public prefix func ! <O: ObservableValueType>(v: O) -> AnyObservableValue<Bool> where O.Value == Bool {
return v.map { !$0 }
}
public func && <A: ObservableValueType, B: ObservableValueType>(a: A, b: B) -> AnyObservableValue<Bool>
where A.Value == Bool, B.Value == Bool {
return a.combined(b, by: { a, b in a && b })
}
public func || <A: ObservableValueType, B: ObservableValueType>(a: A, b: B) -> AnyObservableValue<Bool>
where A.Value == Bool, B.Value == Bool {
return a.combined(b, by: { a, b in a || b })
}
//MARK: Operations with observables of integer arithmetic values
public prefix func - <O: ObservableValueType>(v: O) -> AnyObservableValue<O.Value> where O.Value: SignedNumeric {
return v.map { -$0 }
}
public func + <A: ObservableValueType, B: ObservableValueType, Value: Numeric>(a: A, b: B) -> AnyObservableValue<Value>
where A.Value == Value, B.Value == Value {
return a.combined(b, by: +)
}
public func - <A: ObservableValueType, B: ObservableValueType, Value: Numeric>(a: A, b: B) -> AnyObservableValue<Value>
where A.Value == Value, B.Value == Value {
return a.combined(b, by: -)
}
public func * <A: ObservableValueType, B: ObservableValueType, Value: Numeric>(a: A, b: B) -> AnyObservableValue<Value>
where A.Value == Value, B.Value == Value {
return a.combined(b, by: *)
}
public func / <A: ObservableValueType, B: ObservableValueType, Value: BinaryInteger>(a: A, b: B) -> AnyObservableValue<Value>
where A.Value == Value, B.Value == Value {
return a.combined(b, by: /)
}
public func % <A: ObservableValueType, B: ObservableValueType, Value: BinaryInteger>(a: A, b: B) -> AnyObservableValue<Value>
where A.Value == Value, B.Value == Value {
return a.combined(b, by: %)
}
//MARK: Operations with floating point values
extension ObservableValueType where Value: FloatingPoint {
public func squareRoot() -> AnyObservableValue<Value> {
return self.map { $0.squareRoot() }
}
}
public func + <A: ObservableValueType, B: ObservableValueType, Value: FloatingPoint>(a: A, b: B) -> AnyObservableValue<Value>
where A.Value == Value, B.Value == Value {
return a.combined(b, by: +)
}
public func - <A: ObservableValueType, B: ObservableValueType, Value: FloatingPoint>(a: A, b: B) -> AnyObservableValue<Value>
where A.Value == Value, B.Value == Value {
return a.combined(b, by: -)
}
public func * <A: ObservableValueType, B: ObservableValueType, Value: FloatingPoint>(a: A, b: B) -> AnyObservableValue<Value>
where A.Value == Value, B.Value == Value {
return a.combined(b, by: *)
}
public func / <A: ObservableValueType, B: ObservableValueType, Value: FloatingPoint>(a: A, b: B) -> AnyObservableValue<Value>
where A.Value == Value, B.Value == Value {
return a.combined(b, by: /)
}
| mit | 9bea143ee430f097c77dbaa2219cae21 | 38.958801 | 313 | 0.65545 | 3.687867 | false | false | false | false |
moonknightskye/Luna | Luna/WebViewManager.swift | 1 | 4681 | //
// WebViewManager.swift
// Luna
//
// Created by Mart Civil on 2017/03/01.
// Copyright © 2017年 salesforce.com. All rights reserved.
//
import Foundation
import WebKit
import AVFoundation
public enum Status:Int {
case INIT = 200
case LOAD = 201
case LOADING = 202
case LOADED = 203
}
class WebViewManager {
static var SYSTEM_WEBVIEW = 0
static var LIST:[WebViewManager] = [WebViewManager]();
//static var counter = 0;
private var webview_id:Int!
private var htmlFile:HtmlFile!
private var webview:WKWebView!
private var sourceWebViewID:Int!
private var value:Any!
private var type:FilePathType!
private var status:Status!
public init( source_webview_id:Int?=0, htmlFile:HtmlFile ) {
self.setStatus(status: Status.INIT)
self.webview_id = htmlFile.getID()
self.setHTMLFile(htmlFile: htmlFile)
self.setType(type: htmlFile.getPathType()!)
self.setWebview(webview: WKWebView(webview_id: self.webview_id))
self.setSourceWebViewID(sourceWebViewID: source_webview_id!)
WebViewManager.LIST.append(self)
Shared.shared.ViewController.view.addSubview( self.getWebview() )
}
func load( onSuccess:(()->())?=nil, onFail:((String)->())?=nil ) {
switch ( self.getType() ) {
case FilePathType.BUNDLE_TYPE:
self.getWebview().load( bundlefilePath: self.getHTMLFile().getFilePath()!, onSuccess:onSuccess )
break;
case FilePathType.DOCUMENT_TYPE:
self.getWebview().load( docfilePath: self.getHTMLFile().getFilePath()!, onSuccess:onSuccess )
break;
case FilePathType.URL_TYPE:
self.getWebview().load( url: self.getHTMLFile().getFilePath()!, onSuccess:onSuccess )
break;
default:
if onFail != nil {
onFail!(FileError.INVALID_PARAMETERS.localizedDescription)
return
}
}
}
public func setHTMLFile( htmlFile: HtmlFile ) {
self.htmlFile = htmlFile
}
public func getHTMLFile() -> HtmlFile {
return self.htmlFile
}
public class func getManager( webview_id:Int?=nil, webview:WKWebView?=nil ) -> WebViewManager? {
for (_, manager) in WebViewManager.LIST.enumerated() {
if webview_id != nil && manager.getID() == webview_id {
return manager
} else if webview != nil && manager.getWebview() == webview {
return manager
}
}
return nil
}
public class func removeManager( webview_id:Int?=nil, webview:WKWebView?=nil ) {
for ( index, manager) in WebViewManager.LIST.enumerated() {
if webview_id != nil && manager.getID() == webview_id {
WebViewManager.LIST.remove(at: index)
} else if webview != nil && manager.getWebview() == webview {
WebViewManager.LIST.remove(at: index)
}
}
}
func remove() {
WebViewManager.removeManager(webview_id: self.getID() )
}
func getID() -> Int {
return self.webview_id
}
private func setWebview( webview:WKWebView ) {
self.webview = webview
}
func getWebview() -> WKWebView {
return self.webview
}
private func setStatus( status:Status ) {
self.status = status
}
func getStatus() -> Status {
return self.status
}
private func setSourceWebViewID( sourceWebViewID: Int ) {
self.sourceWebViewID = sourceWebViewID
}
func getSourceWebViewID() -> Int {
return self.sourceWebViewID
}
private func setValue( value:Any ) {
self.value = value
}
func getValue() -> Any {
return self.value
}
private func setType( type:FilePathType ) {
self.type = type
}
func getType() -> FilePathType {
return self.type
}
func onLoad() {
CommandProcessor.processWebViewOnload(wkmanager: self)
}
func onLoaded( isSuccess:Bool?=true, errorMessage: String?=nil ) {
CommandProcessor.processWebViewOnLoaded(wkmanager: self, isSuccess: isSuccess!, errorMessage: errorMessage)
}
func onLoading( progress: Double ) {
CommandProcessor.processWebViewOnLoading(wkmanager: self, progress: progress)
}
func close( onSuccess: (()->())?=nil) {
self.getWebview().removeFromSuperview( onSuccess: {
self.remove()
onSuccess?()
})
}
}
| gpl-3.0 | 41818cc5859323b2523fde183f596f69 | 25.731429 | 115 | 0.590209 | 4.429924 | false | false | false | false |
hooman/swift | test/refactoring/ConvertAsync/convert_function.swift | 1 | 32630 | // REQUIRES: concurrency
// RUN: %empty-directory(%t)
enum CustomError : Error {
case Bad
}
func run(block: () -> Bool) -> Bool { return false }
func makeOptionalError() -> Error? { return nil }
func makeOptionalString() -> String? { return nil }
func simple(_ completion: @escaping (String) -> Void) { }
func simple() async -> String { }
func simple2(arg: String, _ completion: @escaping (String) -> Void) { }
func simple2(arg: String) async -> String { }
func simpleErr(arg: String, _ completion: @escaping (String?, Error?) -> Void) { }
func simpleErr(arg: String) async throws -> String { }
func simpleRes(arg: String, _ completion: @escaping (Result<String, Error>) -> Void) { }
func simpleRes(arg: String) async throws -> String { }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ALREADY-ASYNC %s
func alreadyAsync() async {
simple {
print($0)
}
}
// ALREADY-ASYNC: func alreadyAsync() async {
// ALREADY-ASYNC-NEXT: let val0 = await simple()
// ALREADY-ASYNC-NEXT: print(val0)
// ALREADY-ASYNC-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NESTED %s
func nested() {
simple {
simple2(arg: $0) { str2 in
print(str2)
}
}
}
// NESTED: func nested() async {
// NESTED-NEXT: let val0 = await simple()
// NESTED-NEXT: let str2 = await simple2(arg: val0)
// NESTED-NEXT: print(str2)
// NESTED-NEXT: }
// Can't check for compilation since throws isn't added
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NO-THROWS %s
func noThrowsAdded() {
simpleErr(arg: "") { _, _ in }
}
// NO-THROWS: func noThrowsAdded() async {
// NO-THROWS-NEXT: let _ = try await simpleErr(arg: "")
// NO-THROWS-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):9 | %FileCheck -check-prefix=ATTRIBUTES %s
@available(*, deprecated, message: "Deprecated")
private func functionWithAttributes() {
simple { str in
print(str)
}
}
// ATTRIBUTES: convert_function.swift [[# @LINE-6]]:1 -> [[# @LINE-1]]:2
// ATTRIBUTES-NEXT: @available(*, deprecated, message: "Deprecated")
// ATTRIBUTES-NEXT: private func functionWithAttributes() async {
// ATTRIBUTES-NEXT: let str = await simple()
// ATTRIBUTES-NEXT: print(str)
// ATTRIBUTES-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MANY-NESTED %s
func manyNested() throws {
simple { str1 in
print("simple")
simple2(arg: str1) { str2 in
print("simple2")
simpleErr(arg: str2) { str3, err in
print("simpleErr")
guard let str3 = str3, err == nil else {
return
}
simpleRes(arg: str3) { res in
print("simpleRes")
if case .success(let str4) = res {
print("\(str1) \(str2) \(str3) \(str4)")
print("after")
}
}
}
}
}
}
// MANY-NESTED: func manyNested() async throws {
// MANY-NESTED-NEXT: let str1 = await simple()
// MANY-NESTED-NEXT: print("simple")
// MANY-NESTED-NEXT: let str2 = await simple2(arg: str1)
// MANY-NESTED-NEXT: print("simple2")
// MANY-NESTED-NEXT: let str3 = try await simpleErr(arg: str2)
// MANY-NESTED-NEXT: print("simpleErr")
// MANY-NESTED-NEXT: let str4 = try await simpleRes(arg: str3)
// MANY-NESTED-NEXT: print("simpleRes")
// MANY-NESTED-NEXT: print("\(str1) \(str2) \(str3) \(str4)")
// MANY-NESTED-NEXT: print("after")
// MANY-NESTED-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLE %s
func asyncParams(arg: String, _ completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: arg) { str, err in
print("simpleErr")
guard let str = str, err == nil else {
completion(nil, err!)
return
}
completion(str, nil)
print("after")
}
}
// ASYNC-SIMPLE: func {{[a-zA-Z_]+}}(arg: String) async throws -> String {
// ASYNC-SIMPLE-NEXT: let str = try await simpleErr(arg: arg)
// ASYNC-SIMPLE-NEXT: print("simpleErr")
// ASYNC-SIMPLE-NEXT: {{^}}return str{{$}}
// ASYNC-SIMPLE-NEXT: print("after")
// ASYNC-SIMPLE-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-SIMPLE %s
func asyncResErrPassed(arg: String, _ completion: @escaping (Result<String, Error>) -> Void) {
simpleErr(arg: arg) { str, err in
print("simpleErr")
guard let str = str, err == nil else {
completion(.failure(err!))
return
}
completion(.success(str))
print("after")
}
}
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ASYNC-ERR %s
func asyncResNewErr(arg: String, _ completion: @escaping (Result<String, Error>) -> Void) {
simpleErr(arg: arg) { str, err in
print("simpleErr")
guard let str = str, err == nil else {
completion(.failure(CustomError.Bad))
return
}
completion(.success(str))
print("after")
}
}
// ASYNC-ERR: func asyncResNewErr(arg: String) async throws -> String {
// ASYNC-ERR-NEXT: do {
// ASYNC-ERR-NEXT: let str = try await simpleErr(arg: arg)
// ASYNC-ERR-NEXT: print("simpleErr")
// ASYNC-ERR-NEXT: {{^}}return str{{$}}
// ASYNC-ERR-NEXT: print("after")
// ASYNC-ERR-NEXT: } catch let err {
// ASYNC-ERR-NEXT: throw CustomError.Bad
// ASYNC-ERR-NEXT: }
// ASYNC-ERR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-NON-ASYNC-IN-ASYNC %s
func callNonAsyncInAsync(_ completion: @escaping (String) -> Void) {
simple { str in
let success = run {
completion(str)
return true
}
if !success {
completion("bad")
}
}
}
// CALL-NON-ASYNC-IN-ASYNC: func callNonAsyncInAsync() async -> String {
// CALL-NON-ASYNC-IN-ASYNC-NEXT: let str = await simple()
// CALL-NON-ASYNC-IN-ASYNC-NEXT: return await withCheckedContinuation { continuation in
// CALL-NON-ASYNC-IN-ASYNC-NEXT: let success = run {
// CALL-NON-ASYNC-IN-ASYNC-NEXT: continuation.resume(returning: str)
// CALL-NON-ASYNC-IN-ASYNC-NEXT: {{^}} return true{{$}}
// CALL-NON-ASYNC-IN-ASYNC-NEXT: }
// CALL-NON-ASYNC-IN-ASYNC-NEXT: if !success {
// CALL-NON-ASYNC-IN-ASYNC-NEXT: continuation.resume(returning: "bad")
// CALL-NON-ASYNC-IN-ASYNC-NEXT: }
// CALL-NON-ASYNC-IN-ASYNC-NEXT: }
// CALL-NON-ASYNC-IN-ASYNC-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=CALL-NON-ASYNC-IN-ASYNC-COMMENT %s
func callNonAsyncInAsyncComment(_ completion: @escaping (String) -> Void) {
// a
simple { str in // b
// c
let success = run {
// d
completion(str)
// e
return true
// f
}
// g
if !success {
// h
completion("bad")
// i
}
// j
}
// k
}
// CALL-NON-ASYNC-IN-ASYNC-COMMENT: func callNonAsyncInAsyncComment() async -> String {
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // a
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: let str = await simple()
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // b
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // c
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: return await withCheckedContinuation { continuation in
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: let success = run {
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // d
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: continuation.resume(returning: str)
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // e
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: {{^}} return true{{$}}
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // f
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: }
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // g
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: if !success {
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // h
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: continuation.resume(returning: "bad")
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // i
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: }
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // j
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: {{ }}
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: // k
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: }
// CALL-NON-ASYNC-IN-ASYNC-COMMENT-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-AND-ERROR-HANDLER %s
func voidAndErrorCompletion(completion: @escaping (Void?, Error?) -> Void) {
if .random() {
completion((), nil) // Make sure we drop the ()
} else {
completion(nil, CustomError.Bad)
}
}
// VOID-AND-ERROR-HANDLER: func voidAndErrorCompletion() async throws {
// VOID-AND-ERROR-HANDLER-NEXT: if .random() {
// VOID-AND-ERROR-HANDLER-NEXT: return // Make sure we drop the ()
// VOID-AND-ERROR-HANDLER-NEXT: } else {
// VOID-AND-ERROR-HANDLER-NEXT: throw CustomError.Bad
// VOID-AND-ERROR-HANDLER-NEXT: }
// VOID-AND-ERROR-HANDLER-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix TOO-MUCH-VOID-AND-ERROR-HANDLER %s
func tooMuchVoidAndErrorCompletion(completion: @escaping (Void?, Void?, Error?) -> Void) {
if .random() {
completion((), (), nil) // Make sure we drop the ()s
} else {
completion(nil, nil, CustomError.Bad)
}
}
// TOO-MUCH-VOID-AND-ERROR-HANDLER: func tooMuchVoidAndErrorCompletion() async throws {
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: if .random() {
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: return // Make sure we drop the ()s
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: } else {
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: throw CustomError.Bad
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: }
// TOO-MUCH-VOID-AND-ERROR-HANDLER-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-RESULT-HANDLER %s
func voidResultCompletion(completion: @escaping (Result<Void, Error>) -> Void) {
if .random() {
completion(.success(())) // Make sure we drop the .success(())
} else {
completion(.failure(CustomError.Bad))
}
}
// VOID-RESULT-HANDLER: func voidResultCompletion() async throws {
// VOID-RESULT-HANDLER-NEXT: if .random() {
// VOID-RESULT-HANDLER-NEXT: return // Make sure we drop the .success(())
// VOID-RESULT-HANDLER-NEXT: } else {
// VOID-RESULT-HANDLER-NEXT: throw CustomError.Bad
// VOID-RESULT-HANDLER-NEXT: }
// VOID-RESULT-HANDLER-NEXT: }
// rdar://77789360 Make sure we don't print a double return statement.
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING %s
func testReturnHandling(_ completion: @escaping (String?, Error?) -> Void) {
return completion("", nil)
}
// RETURN-HANDLING: func testReturnHandling() async throws -> String {
// RETURN-HANDLING-NEXT: {{^}} return ""{{$}}
// RETURN-HANDLING-NEXT: }
// rdar://77789360 Make sure we don't print a double return statement and don't
// completely drop completion(a).
// Note we cannot use refactor-check-compiles here, as the placeholders mean we
// don't form valid AST.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING2 %s
func testReturnHandling2(completion: @escaping (String) -> ()) {
simpleErr(arg: "") { x, err in
guard let _ = x else {
let a = ""
return completion(a)
}
let b = ""
return completion(b)
}
}
// RETURN-HANDLING2: func testReturnHandling2() async -> String {
// RETURN-HANDLING2-NEXT: do {
// RETURN-HANDLING2-NEXT: let x = try await simpleErr(arg: "")
// RETURN-HANDLING2-NEXT: let b = ""
// RETURN-HANDLING2-NEXT: {{^}}<#return#> b{{$}}
// RETURN-HANDLING2-NEXT: } catch let err {
// RETURN-HANDLING2-NEXT: let a = ""
// RETURN-HANDLING2-NEXT: {{^}}<#return#> a{{$}}
// RETURN-HANDLING2-NEXT: }
// RETURN-HANDLING2-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING3 %s
func testReturnHandling3(_ completion: @escaping (String?, Error?) -> Void) {
return (completion("", nil))
}
// RETURN-HANDLING3: func testReturnHandling3() async throws -> String {
// RETURN-HANDLING3-NEXT: {{^}} return ""{{$}}
// RETURN-HANDLING3-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RETURN-HANDLING4 %s
func testReturnHandling4(_ completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "xxx") { str, err in
if str != nil {
completion(str, err)
return
}
print("some error stuff")
completion(str, err)
}
}
// RETURN-HANDLING4: func testReturnHandling4() async throws -> String {
// RETURN-HANDLING4-NEXT: do {
// RETURN-HANDLING4-NEXT: let str = try await simpleErr(arg: "xxx")
// RETURN-HANDLING4-NEXT: return str
// RETURN-HANDLING4-NEXT: } catch let err {
// RETURN-HANDLING4-NEXT: print("some error stuff")
// RETURN-HANDLING4-NEXT: throw err
// RETURN-HANDLING4-NEXT: }
// RETURN-HANDLING4-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=RDAR78693050 %s
func rdar78693050(_ completion: @escaping () -> Void) {
simple { str in
print(str)
}
if .random() {
return completion()
}
completion()
}
// RDAR78693050: func rdar78693050() async {
// RDAR78693050-NEXT: let str = await simple()
// RDAR78693050-NEXT: print(str)
// RDAR78693050-NEXT: if .random() {
// RDAR78693050-NEXT: return
// RDAR78693050-NEXT: }
// RDAR78693050-NEXT: return
// RDAR78693050-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DISCARDABLE-RESULT %s
func withDefaultedCompletion(arg: String, completion: @escaping (String) -> Void = {_ in}) {
completion(arg)
}
// DISCARDABLE-RESULT: @discardableResult
// DISCARDABLE-RESULT-NEXT: func withDefaultedCompletion(arg: String) async -> String {
// DISCARDABLE-RESULT-NEXT: return arg
// DISCARDABLE-RESULT-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DEFAULT-ARG %s
func withDefaultArg(x: String = "") {
}
// DEFAULT-ARG: convert_function.swift [[# @LINE-2]]:1 -> [[# @LINE-1]]:2
// DEFAULT-ARG-NOT: @discardableResult
// DEFAULT-ARG-NEXT: {{^}}func withDefaultArg(x: String = "") async
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=IMPLICIT-RETURN %s
func withImplicitReturn(completionHandler: @escaping (String) -> Void) {
simple {
completionHandler($0)
}
}
// IMPLICIT-RETURN: func withImplicitReturn() async -> String {
// IMPLICIT-RETURN-NEXT: let val0 = await simple()
// IMPLICIT-RETURN-NEXT: return val0
// IMPLICIT-RETURN-NEXT: }
// This code doesn't compile after refactoring because we can't return `nil` from the async function.
// But there's not much else we can do here.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-NIL-ERROR %s
func nilResultAndNilError(completion: @escaping (String?, Error?) -> Void) {
completion(nil, nil)
}
// NIL-RESULT-AND-NIL-ERROR: func nilResultAndNilError() async throws -> String {
// NIL-RESULT-AND-NIL-ERROR-NEXT: return nil
// NIL-RESULT-AND-NIL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR %s
func nilResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(nil, err)
}
}
// NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR: func nilResultAndOptionalRelayedError() async throws -> String {
// NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR-EMPTY:
// NIL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: }
// This code doesn't compile after refactoring because we can't throw an optional error returned from makeOptionalError().
// But it's not clear what the intended result should be either.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s
func nilResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) {
completion(nil, makeOptionalError())
}
// NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func nilResultAndOptionalComplexError() async throws -> String {
// NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw makeOptionalError()
// NIL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NIL-RESULT-AND-NON-OPTIONAL-ERROR %s
func nilResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) {
completion(nil, CustomError.Bad)
}
// NIL-RESULT-AND-NON-OPTIONAL-ERROR: func nilResultAndNonOptionalError() async throws -> String {
// NIL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad
// NIL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: }
// In this case, we are previously ignoring the error returned from simpleErr but are rethrowing it in the refactored case.
// That's probably fine although it changes semantics.
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR %s
func optionalRelayedResultAndNilError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(res, nil)
}
}
// OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR: func optionalRelayedResultAndNilError() async throws -> String {
// OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: return res
// OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR %s
func optionalRelayedResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(res, err)
}
}
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR: func optionalRelayedResultAndOptionalRelayedError() async throws -> String {
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: return res
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s
func optionalRelayedResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(res, makeOptionalError())
}
}
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func optionalRelayedResultAndOptionalComplexError() async throws -> String {
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() {
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else {
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return res
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR %s
func optionalRelayedResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(res, CustomError.Bad)
}
}
// OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR: func optionalRelayedResultAndNonOptionalError() async throws -> String {
// OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad
// OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR %s
func nonOptionalRelayedResultAndNilError(completion: @escaping (String?, Error?) -> Void) {
simple { res in
completion(res, nil)
}
}
// NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR: func nonOptionalRelayedResultAndNilError() async throws -> String {
// NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: let res = await simple()
// NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: return res
// NON-OPTIONAL-RELAYED-RESULT-AND-NIL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s
func nonOptionalRelayedResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) {
simple { res in
completion(res, makeOptionalError())
}
}
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func nonOptionalRelayedResultAndOptionalComplexError() async throws -> String {
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: let res = await simple()
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() {
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else {
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return res
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// NON-OPTIONAL-RELAYED-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR %s
func nonOptionalRelayedResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) {
simple { res in
completion(res, CustomError.Bad)
}
}
// NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR: func nonOptionalRelayedResultAndNonOptionalError() async throws -> String {
// NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: let res = await simple()
// NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad
// NON-OPTIONAL-RELAYED-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: }
// The refactored code doesn't compile because we can't return an optional String from the async function.
// But it's not clear what the intended result should be either, because `error` is always `nil`.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR %s
func optionalComplexResultAndNilError(completion: @escaping (String?, Error?) -> Void) {
completion(makeOptionalString(), nil)
}
// OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR: func optionalComplexResultAndNilError() async throws -> String {
// OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR-NEXT: return makeOptionalString()
// OPTIONAL-COMPLEX-RESULT-AND-NIL-ERROR-NEXT: }
// The refactored code doesn't compile because we can't return an optional
// String from the async function.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR %s
func optionalComplexResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(makeOptionalString(), err)
}
}
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR: func optionalComplexResultAndOptionalRelayedError() async throws -> String {
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: return makeOptionalString()
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: }
// The refactored code doesn't compile because we can't return an optional
// String or throw an optional Error from the async function.
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s
func optionalComplexResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) {
completion(makeOptionalString(), makeOptionalError())
}
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func optionalComplexResultAndOptionalComplexError() async throws -> String {
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() {
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else {
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return makeOptionalString()
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// OPTIONAL-COMPLEX-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR %s
func optionalComplexResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) {
completion(makeOptionalString(), CustomError.Bad)
}
// OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR: func optionalComplexResultAndNonOptionalError() async throws -> String {
// OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad
// OPTIONAL-COMPLEX-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-NIL-ERROR %s
func nonOptionalResultAndNilError(completion: @escaping (String?, Error?) -> Void) {
completion("abc", nil)
}
// NON-OPTIONAL-RESULT-AND-NIL-ERROR: func nonOptionalResultAndNilError() async throws -> String {
// NON-OPTIONAL-RESULT-AND-NIL-ERROR-NEXT: return "abc"
// NON-OPTIONAL-RESULT-AND-NIL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR %s
func nonOptionalResultAndOptionalRelayedError(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion("abc", err)
}
}
// NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR: func nonOptionalResultAndOptionalRelayedError() async throws -> String {
// NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: let res = try await simpleErr(arg: "test")
// NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: return "abc"
// NON-OPTIONAL-RESULT-AND-OPTIONAL-RELAYED-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR %s
func nonOptionalResultAndOptionalComplexError(completion: @escaping (String?, Error?) -> Void) {
completion("abc", makeOptionalError())
}
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR: func nonOptionalResultAndOptionalComplexError() async throws -> String {
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: if let error = makeOptionalError() {
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: throw error
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: } else {
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: return "abc"
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// NON-OPTIONAL-RESULT-AND-OPTIONAL-COMPLEX-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR %s
func nonOptionalResultAndNonOptionalError(completion: @escaping (String?, Error?) -> Void) {
completion("abc", CustomError.Bad)
}
// NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR: func nonOptionalResultAndNonOptionalError() async throws -> String {
// NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: throw CustomError.Bad
// NON-OPTIONAL-RESULT-AND-NON-OPTIONAL-ERROR-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=WRAP-COMPLETION-CALL-IN-PARENS %s
func wrapCompletionCallInParenthesis(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
(completion(res, err))
}
}
// WRAP-COMPLETION-CALL-IN-PARENS: func wrapCompletionCallInParenthesis() async throws -> String {
// WRAP-COMPLETION-CALL-IN-PARENS-NEXT: let res = try await simpleErr(arg: "test")
// WRAP-COMPLETION-CALL-IN-PARENS-NEXT: return res
// WRAP-COMPLETION-CALL-IN-PARENS-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=WRAP-RESULT-IN-PARENS %s
func wrapResultInParenthesis(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion((res).self, err)
}
}
// WRAP-RESULT-IN-PARENS: func wrapResultInParenthesis() async throws -> String {
// WRAP-RESULT-IN-PARENS-NEXT: let res = try await simpleErr(arg: "test")
// WRAP-RESULT-IN-PARENS-NEXT: return res
// WRAP-RESULT-IN-PARENS-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=TWO-COMPLETION-HANDLER-CALLS %s
func twoCompletionHandlerCalls(completion: @escaping (String?, Error?) -> Void) {
simpleErr(arg: "test") { (res, err) in
completion(res, err)
completion(res, err)
}
}
// TWO-COMPLETION-HANDLER-CALLS: func twoCompletionHandlerCalls() async throws -> String {
// TWO-COMPLETION-HANDLER-CALLS-NEXT: let res = try await simpleErr(arg: "test")
// TWO-COMPLETION-HANDLER-CALLS-NEXT: return res
// TWO-COMPLETION-HANDLER-CALLS-NEXT: return res
// TWO-COMPLETION-HANDLER-CALLS-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NESTED-IGNORED %s
func nestedIgnored() throws {
simple { _ in
print("done")
simple { _ in
print("done")
}
}
}
// NESTED-IGNORED: func nestedIgnored() async throws {
// NESTED-IGNORED-NEXT: let _ = await simple()
// NESTED-IGNORED-NEXT: print("done")
// NESTED-IGNORED-NEXT: let _ = await simple()
// NESTED-IGNORED-NEXT: print("done")
// NESTED-IGNORED-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=IGNORED-ERR %s
func nestedIgnoredErr() throws {
simpleErr(arg: "") { str, _ in
if str == nil {
print("error")
}
simpleErr(arg: "") { str, _ in
if str == nil {
print("error")
}
}
}
}
// IGNORED-ERR: func nestedIgnoredErr() async throws {
// IGNORED-ERR-NEXT: do {
// IGNORED-ERR-NEXT: let str = try await simpleErr(arg: "")
// IGNORED-ERR-NEXT: do {
// IGNORED-ERR-NEXT: let str1 = try await simpleErr(arg: "")
// IGNORED-ERR-NEXT: } catch {
// IGNORED-ERR-NEXT: print("error")
// IGNORED-ERR-NEXT: }
// IGNORED-ERR-NEXT: } catch {
// IGNORED-ERR-NEXT: print("error")
// IGNORED-ERR-NEXT: }
// IGNORED-ERR-NEXT: }
| apache-2.0 | b6a1501f29859a075f904eb46ae43a27 | 46.985294 | 183 | 0.695035 | 3.199647 | false | false | false | false |
macacajs/XCTestWD | XCTestWD/XCTestWDUnitTest/ControllerTests/XCTestWDUrlControllerTests.swift | 1 | 1396 | //
// XCTestWDUrlController.swift
// XCTestWDUnitTest
//
// Created by SamuelZhaoY on 2/4/18.
// Copyright © 2018 XCTestWD. All rights reserved.
//
import XCTest
import Nimble
@testable import XCTestWD
import Swifter
class XCTestWDUrlControllerTests: XCTestWDUnitTestBase {
func testUrlController() {
let request = Swifter.HttpRequest.init()
let response = XCTestWDUrlController.url(request: request)
response.shouldBeSuccessful()
}
func testGetUrlController() {
let request = Swifter.HttpRequest.init()
let response = XCTestWDUrlController.getUrl(request: request)
response.shouldBeSuccessful()
}
func testForwardUrlController() {
let request = Swifter.HttpRequest.init()
let response = XCTestWDUrlController.forward(request: request)
response.shouldBeSuccessful()
}
func testRefreshUrlController() {
let request = Swifter.HttpRequest.init()
let response = XCTestWDUrlController.refresh(request: request)
response.shouldBeSuccessful()
}
func testBack() {
let request = Swifter.HttpRequest.init()
let response = XCTestWDUrlController.back(request: request)
let contentJSON = XCTestWDUnitTestBase.getResponseData(response)
expect(contentJSON["status"].int).to(equal(WDStatus.ElementIsNotSelectable.rawValue))
}
}
| mit | 8f575dd38784e466944a6452b244e8c6 | 29.326087 | 93 | 0.701075 | 4.65 | false | true | false | false |
vector-im/vector-ios | Riot/Modules/KeyVerification/Common/Verify/Scanning/KeyVerificationVerifyByScanningViewModel.swift | 1 | 10637 | // File created from ScreenTemplate
// $ createScreen.sh Verify KeyVerificationVerifyByScanning
/*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
enum KeyVerificationVerifyByScanningViewModelError: Error {
case unknown
}
final class KeyVerificationVerifyByScanningViewModel: KeyVerificationVerifyByScanningViewModelType {
// MARK: - Properties
// MARK: Private
private let session: MXSession
private let verificationKind: KeyVerificationKind
private let keyVerificationRequest: MXKeyVerificationRequest
private let qrCodeDataCoder: MXQRCodeDataCoder
private let keyVerificationManager: MXKeyVerificationManager
private var qrCodeTransaction: MXQRCodeTransaction?
private var scannedQRCodeData: MXQRCodeData?
// MARK: Public
weak var viewDelegate: KeyVerificationVerifyByScanningViewModelViewDelegate?
weak var coordinatorDelegate: KeyVerificationVerifyByScanningViewModelCoordinatorDelegate?
// MARK: - Setup
init(session: MXSession, verificationKind: KeyVerificationKind, keyVerificationRequest: MXKeyVerificationRequest) {
self.session = session
self.verificationKind = verificationKind
self.keyVerificationManager = self.session.crypto.keyVerificationManager
self.keyVerificationRequest = keyVerificationRequest
self.qrCodeDataCoder = MXQRCodeDataCoder()
}
deinit {
self.removePendingQRCodeTransaction()
}
// MARK: - Public
func process(viewAction: KeyVerificationVerifyByScanningViewAction) {
switch viewAction {
case .loadData:
self.loadData()
case .scannedCode(payloadData: let payloadData):
self.scannedQRCode(payloadData: payloadData)
case .cannotScan:
self.startSASVerification()
case .cancel:
self.cancel()
case .acknowledgeMyUserScannedOtherCode:
self.acknowledgeScanOtherCode()
}
}
// MARK: - Private
private func loadData() {
let qrCodePlayloadData: Data?
let canShowScanAction: Bool
self.qrCodeTransaction = self.keyVerificationManager.qrCodeTransaction(withTransactionId: self.keyVerificationRequest.requestId)
if let supportedVerificationMethods = self.keyVerificationRequest.myMethods {
if let qrCodeData = self.qrCodeTransaction?.qrCodeData {
qrCodePlayloadData = self.qrCodeDataCoder.encode(qrCodeData)
} else {
qrCodePlayloadData = nil
}
canShowScanAction = self.canShowScanAction(from: supportedVerificationMethods)
} else {
qrCodePlayloadData = nil
canShowScanAction = false
}
let viewData = KeyVerificationVerifyByScanningViewData(verificationKind: self.verificationKind,
qrCodeData: qrCodePlayloadData,
showScanAction: canShowScanAction)
self.update(viewState: .loaded(viewData: viewData))
self.registerTransactionDidStateChangeNotification()
}
private func canShowScanAction(from verificationMethods: [String]) -> Bool {
return verificationMethods.contains(MXKeyVerificationMethodQRCodeScan)
}
private func cancel() {
self.cancelQRCodeTransaction()
self.keyVerificationRequest.cancel(with: MXTransactionCancelCode.user(), success: nil, failure: nil)
self.unregisterTransactionDidStateChangeNotification()
self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModelDidCancel(self)
}
private func cancelQRCodeTransaction() {
guard let transaction = self.qrCodeTransaction else {
return
}
transaction.cancel(with: MXTransactionCancelCode.user())
self.removePendingQRCodeTransaction()
}
private func update(viewState: KeyVerificationVerifyByScanningViewState) {
self.viewDelegate?.keyVerificationVerifyByScanningViewModel(self, didUpdateViewState: viewState)
}
// MARK: QR code
private func scannedQRCode(payloadData: Data) {
self.scannedQRCodeData = self.qrCodeDataCoder.decode(payloadData)
let isQRCodeValid = self.scannedQRCodeData != nil
self.update(viewState: .scannedCodeValidated(isValid: isQRCodeValid))
}
private func acknowledgeScanOtherCode() {
guard let scannedQRCodeData = self.scannedQRCodeData else {
return
}
guard let qrCodeTransaction = self.qrCodeTransaction else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModel(self, didScanOtherQRCodeData: scannedQRCodeData, withTransaction: qrCodeTransaction)
}
private func removePendingQRCodeTransaction() {
guard let qrCodeTransaction = self.qrCodeTransaction else {
return
}
self.keyVerificationManager.removeQRCodeTransaction(withTransactionId: qrCodeTransaction.transactionId)
}
// MARK: SAS
private func startSASVerification() {
self.update(viewState: .loading)
self.session.crypto.keyVerificationManager.beginKeyVerification(from: self.keyVerificationRequest, method: MXKeyVerificationMethodSAS, success: { [weak self] (keyVerificationTransaction) in
guard let self = self else {
return
}
// Remove pending QR code transaction, as we are going to use SAS verification
self.removePendingQRCodeTransaction()
if keyVerificationTransaction is MXOutgoingSASTransaction == false {
MXLog.debug("[KeyVerificationVerifyByScanningViewModel] SAS transaction should be outgoing")
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .error(KeyVerificationVerifyByScanningViewModelError.unknown))
}
}, failure: { [weak self] (error) in
guard let self = self else {
return
}
self.update(viewState: .error(error))
}
)
}
// MARK: - MXKeyVerificationTransactionDidChange
private func registerTransactionDidStateChangeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(transactionDidStateChange(notification:)), name: .MXKeyVerificationTransactionDidChange, object: nil)
}
private func unregisterTransactionDidStateChangeNotification() {
NotificationCenter.default.removeObserver(self, name: .MXKeyVerificationTransactionDidChange, object: nil)
}
@objc private func transactionDidStateChange(notification: Notification) {
guard let transaction = notification.object as? MXKeyVerificationTransaction else {
return
}
guard self.keyVerificationRequest.requestId == transaction.transactionId else {
MXLog.debug("[KeyVerificationVerifyByScanningViewModel] transactionDidStateChange: Not for our transaction (\(self.keyVerificationRequest.requestId)): \(transaction.transactionId)")
return
}
if let sasTransaction = transaction as? MXSASTransaction {
self.sasTransactionDidStateChange(sasTransaction)
} else if let qrCodeTransaction = transaction as? MXQRCodeTransaction {
self.qrCodeTransactionDidStateChange(qrCodeTransaction)
}
}
private func sasTransactionDidStateChange(_ transaction: MXSASTransaction) {
switch transaction.state {
case MXSASTransactionStateShowSAS:
self.unregisterTransactionDidStateChangeNotification()
self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModel(self, didStartSASVerificationWithTransaction: transaction)
case MXSASTransactionStateCancelled:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelled(cancelCode: reason, verificationKind: verificationKind))
case MXSASTransactionStateCancelledByMe:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelledByMe(reason))
default:
break
}
}
private func qrCodeTransactionDidStateChange(_ transaction: MXQRCodeTransaction) {
switch transaction.state {
case .verified:
// Should not happen
self.unregisterTransactionDidStateChangeNotification()
self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModelDidCancel(self)
case .qrScannedByOther:
self.unregisterTransactionDidStateChangeNotification()
self.coordinatorDelegate?.keyVerificationVerifyByScanningViewModel(self, qrCodeDidScannedByOtherWithTransaction: transaction)
case .cancelled:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelled(cancelCode: reason, verificationKind: verificationKind))
case .cancelledByMe:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelledByMe(reason))
default:
break
}
}
}
| apache-2.0 | 6c70ce26702e282bae19808690e6f0cd | 39.139623 | 197 | 0.674814 | 6.677338 | false | false | false | false |
zixun/GodEye | GodEye/Classes/Main/Controller/TabController/ConsoleController/ConsoleController.swift | 1 | 1622 | //
// ConsoleViewController.swift
// Pods
//
// Created by zixun on 16/12/27.
//
//
import Foundation
class ConsoleController: UIViewController {
init() {
super.init(nibName: nil, bundle: nil)
self.openEyes()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.niceBlack()
self.view.addSubview(self.tableView)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.tableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
}
lazy var tableView: UITableView = { [unowned self] in
let new = UITableView(frame: CGRect.zero, style: .grouped)
new.delegate = self
new.dataSource = self
new.backgroundColor = UIColor.clear
return new
}()
private(set) lazy var dataSource: [[RecordType]] = {
var new = [[RecordType]]()
var section1 = [RecordType]()
section1.append(RecordType.log)
section1.append(RecordType.crash)
section1.append(RecordType.network)
section1.append(RecordType.anr)
section1.append(RecordType.leak)
new.append(section1)
var section2 = [RecordType]()
section2.append(RecordType.command)
new.append(section2)
return new
}()
weak var printViewController: ConsolePrintViewController?
}
| mit | bc766112d7662929eb9b67af3ecf79d8 | 25.590164 | 121 | 0.612824 | 4.419619 | false | false | false | false |
alejandrogarin/ADGCoreDataKit | Tests/ModelTests.swift | 1 | 10196 | //
// ModelTests.swift
// ADGCoreDataKit
//
// Created by Alejandro Diego Garin
// The MIT License (MIT)
//
// Copyright (c) 2015 Alejandro Garin @alejandrogarin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import XCTest
import CoreData
import ADGCoreDataKit
class ModelTests: BaseTestCase {
override func setUp() {
super.setUp()
}
func testInsertPlaylist() {
tryTest {
let playlist: Playlist = try self.insertPlaylist("play1")
if let name = playlist.name, let order = playlist.order {
XCTAssertEqual(name, "play1")
XCTAssertEqual(order, 0)
try self.playlistDAO.delete(managedObject: playlist)
XCTAssert(true)
} else {
XCTFail("Couldn't insert playlist correctly");
}
}
}
func testInsert_WithNull() {
tryTest {
let playlist: Playlist = try self.insertPlaylist(nil)
let name = playlist.name, order = playlist.order
XCTAssertNil(name)
XCTAssertEqual(order, 0)
try self.playlistDAO.delete(managedObject: playlist)
XCTAssert(true)
}
}
func testUpdatePlaylist() {
tryTest {
let playlist: Playlist = try self.insertPlaylist("play1")
playlist.name = "updated"
try self.playlistDAO.commit()
let array: [Playlist] = try self.playlistDAO.find()
XCTAssertEqual(array.count, 1)
let updatedPlaylist:Playlist! = array.first
XCTAssertEqual(updatedPlaylist.name!, "updated")
}
}
func testUpdatePlaylist_WithNullInProperty() {
tryTest {
let playlist: Playlist = try self.insertPlaylist("play1")
playlist.name = nil
try self.playlistDAO.commit()
let array: [Playlist] = try self.playlistDAO.find()
XCTAssertEqual(array.count, 1)
let updatedPlaylist:Playlist! = array.first
XCTAssertNil(updatedPlaylist.name)
}
}
func testInsertAudio() {
tryTest {
let audio: Audio = try self.insertAudio("audio1", playlist: self.insertPlaylist("p1"))
if let title = audio.title, let audioPlaylist = audio.playlist {
XCTAssertEqual(title, "audio1")
XCTAssertNotNil(audioPlaylist)
} else {
XCTFail("Couldn't insert audio correctly");
}
}
}
func testInsertAudioWithoutPlaylist() {
tryTest {
let audio: Audio = try self.insertAudio("audio1", playlist: nil)
if let title = audio.title {
XCTAssertEqual(title, "audio1")
XCTAssertNil(audio.playlist)
} else {
XCTFail("Couldn't insert audio correctly");
}
}
}
func testFetch_UsingStringObjectId() {
tryTest {
let playlist: Playlist = try self.insertPlaylist("play1")
let objectId = self.stringObjectId(fromMO: playlist)
let retrieved: Playlist = try self.playlistDAO.fetch(byId: objectId)
if let name = retrieved.name {
XCTAssertEqual(name, "play1")
} else {
XCTFail("Playlist object is invalid");
}
}
}
func testFetch_UsingManagedObjectId() {
tryTest {
let playlist: Playlist = try self.insertPlaylist("play1")
let retrived: Playlist = try self.playlistDAO.fetch(byManagedObjectId: playlist.objectID)
if let name = retrived.name {
XCTAssertEqual(name, "play1")
} else {
XCTFail("Playlist object is invalid");
}
}
}
func testFind() {
tryTest {
for i in 0..<100 {
let _ = try self.insertPlaylist("play \(i)")
}
let result:[Playlist] = try self.playlistDAO.find()
XCTAssertEqual(result.count, 100)
}
}
func testCount() {
tryTest {
for i in 0..<100 {
let _ = try self.insertPlaylist("play \(i)")
}
XCTAssertEqual(try self.playlistDAO.count(), 100)
}
}
func testCount_WithPredicate() {
tryTest {
for i in 0..<100 {
let _ = try self.insertPlaylist("play \(i)")
}
let predicate = NSPredicate(format: "name == %@", "play 1")
XCTAssertEqual(try self.playlistDAO.count(withPredicate: predicate), 1)
}
}
func testDelete_UsingManagedObject() {
tryTest {
let playlist = try self.insertPlaylist("playlist")
XCTAssertEqual(try self.playlistDAO.find().count, 1)
try self.playlistDAO.delete(managedObject: playlist)
XCTAssertEqual(try self.playlistDAO.find().count, 0)
}
}
func testDelete_UsingStringObjectId() {
tryTest {
let playlist = try self.insertPlaylist("playlist")
XCTAssertEqual(try self.playlistDAO.find().count, 1)
let objectId = self.stringObjectId(fromMO: playlist)
try self.playlistDAO.delete(byId: objectId)
XCTAssertEqual(try self.playlistDAO.find().count, 0)
}
}
func testOperationWithManualCommit() {
tryTest {
self.playlistDAO.autocommit = false
let _ = self.playlistDAO.create()
self.playlistDAO.rollback()
XCTAssertEqual(try self.playlistDAO.count(), 0)
}
}
func testFind_Transformed() {
tryTest {
struct PlaylistDAO {
var name: String
}
let _ = try self.insertPlaylist("playlist1")
let _ = try self.insertPlaylist("playlist2")
let result = try self.playlistDAO.findTransformed(transformationHandler: { (entity: Playlist) -> PlaylistDAO in
return PlaylistDAO(name: entity.name!)
})
XCTAssertEqual(result[0].name, "playlist1")
XCTAssertEqual(result[1].name, "playlist2")
}
}
func testFindAllPlaylists() {
tryTest {
for i in 0 ..< 100 {
let _ = try self.insertPlaylist("play \(i)", order: i)
}
let array: [AnyObject] = try self.coreDataContext.find(entityName: "Playlist")
XCTAssertEqual(array.count, 100)
}
}
func testFindPlaylistWithPredicate() {
tryTest {
for i in 0 ..< 100 {
let _ = try self.insertPlaylist("play \(i)", order: i)
}
let predicate = NSPredicate(format: "name CONTAINS %@", "play 2")
let array: [AnyObject] = try self.coreDataContext.find(entityName: "Playlist", predicate: predicate)
XCTAssertEqual(array.count, 11)
}
}
func testFindPlaylistWithPaggingAndOrder() {
tryTest {
for i in 0 ..< 100 {
let _ = try self.insertPlaylist("play \(i)", order: i)
}
let descriptor = [NSSortDescriptor(key: "order", ascending: true)]
let arrayPage0: [AnyObject] = try self.coreDataContext.find(entityName: "Playlist", predicate: nil, sortDescriptors: descriptor, page: 0, pageSize: 10)
let arrayPage1: [AnyObject] = try self.coreDataContext.find(entityName: "Playlist", predicate: nil, sortDescriptors: descriptor, page: 1, pageSize: 10)
let arrayPage9: [AnyObject] = try self.coreDataContext.find(entityName: "Playlist", predicate: nil, sortDescriptors: descriptor, page: 9, pageSize: 10)
let arrayPage10: [AnyObject] = try self.coreDataContext.find(entityName: "Playlist", predicate: nil, sortDescriptors: descriptor, page: 10, pageSize: 10)
XCTAssertEqual(arrayPage0.count, 10)
XCTAssertEqual(arrayPage1.count, 10)
XCTAssertEqual(arrayPage9.count, 10)
XCTAssertEqual(arrayPage10.count, 0)
var object1: NSManagedObject = arrayPage0.first! as! NSManagedObject
var object10: NSManagedObject = arrayPage0.last! as! NSManagedObject
XCTAssertEqual((object1.value(forKey: "name") as? String)!, "play 0")
XCTAssertEqual((object10.value(forKey: "name") as? String)!, "play 9")
object1 = arrayPage1.first! as! NSManagedObject
object10 = arrayPage1.last! as! NSManagedObject
XCTAssertEqual((object1.value(forKey: "name") as? String)!, "play 10")
XCTAssertEqual((object10.value(forKey: "name") as? String)!, "play 19")
object1 = arrayPage9.first! as! NSManagedObject
object10 = arrayPage9.last! as! NSManagedObject
XCTAssertEqual((object1.value(forKey: "name") as? String)!, "play 90")
XCTAssertEqual((object10.value(forKey: "name") as? String)!, "play 99")
}
}
}
| mit | 0f6d9cd64b3fda99efb22b658fc46973 | 37.475472 | 165 | 0.586701 | 4.687816 | false | true | false | false |
apple/swift-corelibs-foundation | Darwin/Foundation-swiftoverlay/UUID.swift | 1 | 6180 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import Darwin.uuid
@_implementationOnly import _CoreFoundationOverlayShims
/// Represents UUID strings, which can be used to uniquely identify types, interfaces, and other items.
@available(macOS 10.8, iOS 6.0, *)
public struct UUID : ReferenceConvertible, Hashable, Equatable, CustomStringConvertible {
public typealias ReferenceType = NSUUID
public private(set) var uuid: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
/* Create a new UUID with RFC 4122 version 4 random bytes */
public init() {
withUnsafeMutablePointer(to: &uuid) {
$0.withMemoryRebound(to: UInt8.self, capacity: 16) {
uuid_generate_random($0)
}
}
}
private init(reference: __shared NSUUID) {
var bytes: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
withUnsafeMutablePointer(to: &bytes) {
$0.withMemoryRebound(to: UInt8.self, capacity: 16) {
reference.getBytes($0)
}
}
uuid = bytes
}
/// Create a UUID from a string such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F".
///
/// Returns nil for invalid strings.
public init?(uuidString string: __shared String) {
let res = withUnsafeMutablePointer(to: &uuid) {
$0.withMemoryRebound(to: UInt8.self, capacity: 16) {
return uuid_parse(string, $0)
}
}
if res != 0 {
return nil
}
}
/// Create a UUID from a `uuid_t`.
public init(uuid: uuid_t) {
self.uuid = uuid
}
/// Returns a string created from the UUID, such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
public var uuidString: String {
var bytes: uuid_string_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
return withUnsafePointer(to: uuid) {
$0.withMemoryRebound(to: UInt8.self, capacity: 16) { val in
withUnsafeMutablePointer(to: &bytes) {
$0.withMemoryRebound(to: Int8.self, capacity: 37) { str in
uuid_unparse(val, str)
return String(cString: UnsafePointer(str), encoding: .utf8)!
}
}
}
}
}
public func hash(into hasher: inout Hasher) {
withUnsafeBytes(of: uuid) { buffer in
hasher.combine(bytes: buffer)
}
}
public var description: String {
return uuidString
}
public var debugDescription: String {
return description
}
// MARK: - Bridging Support
private var reference: NSUUID {
return withUnsafePointer(to: uuid) {
$0.withMemoryRebound(to: UInt8.self, capacity: 16) {
return NSUUID(uuidBytes: $0)
}
}
}
public static func ==(lhs: UUID, rhs: UUID) -> Bool {
return withUnsafeBytes(of: rhs.uuid) { (rhsPtr) -> Bool in
return withUnsafeBytes(of: lhs.uuid) { (lhsPtr) -> Bool in
let lhsFirstChunk = lhsPtr.load(fromByteOffset: 0, as: UInt64.self)
let lhsSecondChunk = lhsPtr.load(fromByteOffset: MemoryLayout<UInt64>.size, as: UInt64.self)
let rhsFirstChunk = rhsPtr.load(fromByteOffset: 0, as: UInt64.self)
let rhsSecondChunk = rhsPtr.load(fromByteOffset: MemoryLayout<UInt64>.size, as: UInt64.self)
return ((lhsFirstChunk ^ rhsFirstChunk) | (lhsSecondChunk ^ rhsSecondChunk)) == 0
}
}
}
}
extension UUID : CustomReflectable {
public var customMirror: Mirror {
let c : [(label: String?, value: Any)] = []
let m = Mirror(self, children:c, displayStyle: Mirror.DisplayStyle.struct)
return m
}
}
extension UUID : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSUUID {
return reference
}
public static func _forceBridgeFromObjectiveC(_ x: NSUUID, result: inout UUID?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSUUID, result: inout UUID?) -> Bool {
result = UUID(reference: input)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSUUID?) -> UUID {
var result: UUID?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension NSUUID : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as UUID)
}
}
extension UUID : Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let uuidString = try container.decode(String.self)
guard let uuid = UUID(uuidString: uuidString) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Attempted to decode UUID from invalid UUID string."))
}
self = uuid
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.uuidString)
}
}
| apache-2.0 | d4a654b87e764fe97edf55594920ff03 | 34.930233 | 146 | 0.583172 | 4.342937 | false | false | false | false |
soapyigu/LeetCode_Swift | DP/WiggleSubsequence.swift | 1 | 668 | /**
* Question Link: https://leetcode.com/problems/wiggle-subsequence/
* Primary idea: Classic Dynamic Programming, two variables/arries to track up or down status
* Time Complexity: O(n), Space Complexity: O(1)
*/
class WiggleSubsequence {
func wiggleMaxLength(_ nums: [Int]) -> Int {
guard nums.count >= 2 else {
return nums.count
}
var up = 1, down = 1
for i in 1..<nums.count {
if nums[i] > nums[i - 1] {
up = down + 1
} else if nums[i] < nums[i - 1] {
down = up + 1
}
}
return max(up, down)
}
} | mit | 6387479e28122991abb2597063648535 | 25.76 | 93 | 0.497006 | 3.861272 | false | false | false | false |
soapyigu/LeetCode_Swift | Array/ExamRoom.swift | 1 | 1143 | /**
* Question Link: https://leetcode.com/problems/exam-room/
* Primary idea: Calculate and compare middle point between two taken seats.
*
* Time Complexity: O(n) for seat(), O(1) for leave(at:), Space Complexity: O(n)
*
*/
class ExamRoom {
var seats: [Int]
init(_ n: Int) {
seats = Array(repeating: 0, count: n)
}
func seat() -> Int {
var maxDistance = 0, maxIndex = 0, lastOne = -1
for (i, seat) in seats.enumerated() {
if seat == 1 {
if lastOne == -1 {
if maxDistance < i {
maxDistance = i
maxIndex = 0
}
} else {
if maxDistance < (i - lastOne) / 2 {
maxDistance = (i - lastOne) / 2
maxIndex = lastOne + (i - lastOne) / 2
}
}
}
lastOne = i
}
if lastOne != -1 {
if maxDistance < (seats.count - 1 - lastOne) / 2 {
maxIndex = seats.count - 1
}
}
seats[maxIndex] = 1
return maxIndex
}
func leave(_ seat: Int) {
seats[seat] = 0
}
} | mit | 304fb0028808b6833bb0ee8b373b1f03 | 21.431373 | 80 | 0.461942 | 3.442771 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet | SwiftGL-Demo/Source/Common/SwiftyJSON.swift | 1 | 35404 | // SwiftyJSON.swift
//
// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "as!IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Error
///Error domain
public let ErrorDomain: String! = "SwiftyJSONErrorDomain"
///Error code
public let ErrorUnsupportedType: Int! = 999
public let ErrorIndexOutOfBounds: Int! = 900
public let ErrorWrongType: Int! = 901
public let ErrorNotExist: Int! = 500
// MARK: - JSON Type
/**
JSON's type definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Type :Int{
case Number
case String
case Bool
case Array
case Dictionary
case Null
case Unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
- parameter error: error The NSErrorPointer used to return the error. `nil` by default.
- returns: The created JSON
*/
public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) {
do {
let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt)
self.init(object)
} catch let error1 as NSError {
error.memory = error1
self.init(NSNull())
}
}
/**
Creates a JSON using the object.
- parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
public init(_ object: AnyObject) {
self.object = object
}
/// Private object
private var _object: AnyObject = NSNull()
/// Private type
private var _type: Type = .Null
/// prviate error
private var _error: NSError?
/// Object in JSON
public var object: AnyObject {
get {
return _object
}
set {
_object = newValue
switch newValue {
case let number as NSNumber:
if number.isBool {
_type = .Bool
} else {
_type = .Number
}
case let string as NSString:
_type = .String
case let null as NSNull:
_type = .Null
case let array as [AnyObject]:
_type = .Array
case let dictionary as [String : AnyObject]:
_type = .Dictionary
default:
_type = .Unknown
_object = NSNull()
_error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
/// json type
public var type: Type { get { return _type } }
/// Error in JSON
public var error: NSError? { get { return self._error } }
/// The static null json
public static var nullJSON: JSON { get { return JSON(NSNull()) } }
}
// MARK: - SequenceType
extension JSON: SequenceType{
/// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`.
public var isEmpty: Bool {
get {
switch self.type {
case .Array:
return (self.object as! [AnyObject]).isEmpty
case .Dictionary:
return (self.object as![String : AnyObject]).isEmpty
default:
return false
}
}
}
/// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`.
public var count: Int {
get {
switch self.type {
case .Array:
return self.arrayValue.count
case .Dictionary:
return self.dictionaryValue.count
default:
return 0
}
}
}
/**
If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary, otherwise return a generator over empty.
- returns: Return a *generator* over the elements of this *sequence*.
*/
public func generate() -> AnyGenerator<(String, JSON)> {
switch self.type {
case .Array:
let array_ = object as![AnyObject]
var generate_ = array_.generate()
var index_: Int = 0
return anyGenerator {
if let element_: AnyObject = generate_.next() {
return ("\(index_++)", JSON(element_))
} else {
return nil
}
}
case .Dictionary:
let dictionary_ = object as! [String : AnyObject]
var generate_ = dictionary_.generate()
return anyGenerator {
if let (key_, value_): (String, AnyObject) = generate_.next() {
return (key_, JSON(value_))
} else {
return nil
}
}
default:
return anyGenerator {
return nil
}
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public protocol SubscriptType {}
extension Int: SubscriptType {}
extension String: SubscriptType {}
extension JSON {
/// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error.
private subscript(index index: Int) -> JSON {
get {
if self.type != .Array {
var errorResult_ = JSON.nullJSON
errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
return errorResult_
}
let array_ = self.object as! [AnyObject]
if index >= 0 && index < array_.count {
return JSON(array_[index])
}
var errorResult_ = JSON.nullJSON
errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
return errorResult_
}
set {
if self.type == .Array {
var array_ = self.object as![AnyObject]
if array_.count > index {
array_[index] = newValue.object
self.object = array_
}
}
}
}
/// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error.
private subscript(key key: String) -> JSON {
get {
var returnJSON = JSON.nullJSON
if self.type == .Dictionary {
if let object_: AnyObject = self.object[key] {
returnJSON = JSON(object_)
} else {
returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
}
} else {
returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
}
return returnJSON
}
set {
if self.type == .Dictionary {
var dictionary_ = self.object as![String : AnyObject]
dictionary_[key] = newValue.object
self.object = dictionary_
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
private subscript(sub sub: SubscriptType) -> JSON {
get {
if sub is String {
return self[key:sub as!String]
} else {
return self[index:sub as!Int]
}
}
set {
if sub is String {
self[key:sub as! String] = newValue
} else {
self[index:sub as! Int] = newValue
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [SubscriptType]) -> JSON {
get {
if path.count == 0 {
return JSON.nullJSON
}
var next = self
for sub in path {
next = next[sub:sub]
}
return next
}
set {
switch path.count {
case 0: return
case 1: self[sub:path[0]] = newValue
default:
var last = newValue
var newPath = path
newPath.removeLast()
for sub in Array(path.reverse()) {
var previousLast = self[newPath]
previousLast[sub:sub] = last
last = previousLast
if newPath.count <= 1 {
break
}
newPath.removeLast()
}
self[sub:newPath[0]] = last
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: SubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
extension JSON: IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
extension JSON: BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
extension JSON: FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
extension JSON: DictionaryLiteralConvertible {
public init(dictionaryLiteral elements: (String, AnyObject)...) {
var dictionary_ = [String : AnyObject]()
for (key_, value) in elements {
dictionary_[key_] = value
}
self.init(dictionary_)
}
}
extension JSON: ArrayLiteralConvertible {
public init(arrayLiteral elements: AnyObject...) {
self.init(elements)
}
}
extension JSON: NilLiteralConvertible {
public init(nilLiteral: ()) {
self.init(NSNull())
}
}
// MARK: - Raw
extension JSON: RawRepresentable {
public init?(rawValue: AnyObject) {
if JSON(rawValue).type == .Unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: AnyObject {
return self.object
}
public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData {
return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt)
}
public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? {
switch self.type {
case .Array, .Dictionary:
do {
let data = try self.rawData(options: opt)
return NSString(data: data, encoding: encoding) asString!
} catch _ {
return nil
}
case .String:
return (self.object as! String)
case .Number:
return (self.object as! NSNumber).stringValue
case .Bool:
return (self.object as! Bool).description
case .Null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
if let string = self.rawString(options:.PrettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
get {
if self.type == .Array {
return (self.object as! [AnyObject]).map{ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
get {
return self.array ?? []
}
}
//Optional [AnyObject]
public var arrayObject: [AnyObject]? {
get {
switch self.type {
case .Array:
return self.object as? [AnyObject]
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSMutableArray(array: newValue!, copyItems: true)
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] {
var result = [Key: NewValue](minimumCapacity:source.count)
for (key,value) in source {
result[key] = transform(value)
}
return result
}
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
get {
if self.type == .Dictionary {
return _map(self.object as! [String : AnyObject]){ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
get {
return self.dictionary ?? [:]
}
}
//Optional [String : AnyObject]
public var dictionaryObject: [String : AnyObject]? {
get {
switch self.type {
case .Dictionary:
return self.object as? [String : AnyObject]
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true)
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON: BooleanType {
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .Bool:
return self.object.boolValue
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSNumber(bool: newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .Bool, .Number, .String:
return self.object.boolValue
default:
return false
}
}
set {
self.object = NSNumber(bool: newValue)
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .String:
return self.object as? String
default:
return nil
}
}
set {
if newValue != nil {
self.object = NSString(string:newValue!)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
public var stringValue: String {
get {
switch self.type {
case .String:
return self.object as! String
case .Number:
return self.object.stringValue
case .Bool:
return (self.object as! Bool).description
default:
return ""
}
}
set {
self.object = NSString(string:newValue)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .Number, .Bool:
return self.object as? NSNumber
default:
return nil
}
}
set {
self.object = newValue?.copy() ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .String:
let scanner = NSScanner(string: self.object as! String)
if scanner.scanDouble(nil){
if (scanner.atEnd) {
return NSNumber(double:(self.object as!NSString).doubleValue)
}
}
return NSNumber(double: 0.0)
case .Number, .Bool:
return self.object as! NSNumber
default:
return NSNumber(double: 0.0)
}
}
set {
self.object = newValue.copy()
}
}
}
//MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .Null:
return NSNull()
default:
return nil
}
}
set {
self.object = NSNull()
}
}
}
//MARK: - URL
extension JSON {
//Optional URL
public var URL: NSURL? {
get {
switch self.type {
case .String:
if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
return NSURL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString ?? NSNull()
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if newValue != nil {
self.object = NSNumber(double: newValue!)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(double: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if newValue != nil {
self.object = NSNumber(float: newValue!)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(float: newValue)
}
}
public var int: Int? {
get {
return self.number?.longValue
}
set {
if newValue != nil {
self.object = NSNumber(integer: newValue!)
} else {
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.integerValue
}
set {
self.object = NSNumber(integer: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.unsignedLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.unsignedLongValue
}
set {
self.object = NSNumber(unsignedLong: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.charValue
}
set {
if newValue != nil {
self.object = NSNumber(char: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.charValue
}
set {
self.object = NSNumber(char: newValue)
}
}
public var uInt8: UInt8? {
get {
return self.number?.unsignedCharValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedChar: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.unsignedCharValue
}
set {
self.object = NSNumber(unsignedChar: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.shortValue
}
set {
if newValue != nil {
self.object = NSNumber(short: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.shortValue
}
set {
self.object = NSNumber(short: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.unsignedShortValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedShort: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.unsignedShortValue
}
set {
self.object = NSNumber(unsignedShort: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.intValue
}
set {
if newValue != nil {
self.object = NSNumber(int: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(int: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.unsignedIntValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedInt: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.unsignedIntValue
}
set {
self.object = NSNumber(unsignedInt: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.longLongValue
}
set {
if newValue != nil {
self.object = NSNumber(longLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.longLongValue
}
set {
self.object = NSNumber(longLong: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.unsignedLongLongValue
}
set {
if newValue != nil {
self.object = NSNumber(unsignedLongLong: newValue!)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.unsignedLongLongValue
}
set {
self.object = NSNumber(unsignedLongLong: newValue)
}
}
}
//MARK: - Comparable
extension JSON: Comparable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as!NSNumber) == (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as!String) == (rhs.object as! String)
case (.Bool, .Bool):
return (lhs.object as!Bool) == (rhs.object as! Bool)
case (.Array, .Array):
return (lhs.object as!NSArray) == (rhs.object as! NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as!NSDictionary) == (rhs.object as! NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func <=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as! NSNumber) <= (rhs.object as! NSNumber)
case (.String, .String):
return (lhs.object as! String) <= (rhs.object as! String)
case (.Bool, .Bool):
return (lhs.object as! Bool) == (rhs.object as! Bool)
case (.Array, .Array):
return (lhs.object as!NSArray) == (rhs.object as! NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func >=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as!NSNumber) >= (rhs.object as!NSNumber)
case (.String, .String):
return (lhs.object as!String) >= (rhs.object as!String)
case (.Bool, .Bool):
return (lhs.object as!Bool) == (rhs.object as!Bool)
case (.Array, .Array):
return (lhs.object as!NSArray) == (rhs.object as!NSArray)
case (.Dictionary, .Dictionary):
return (lhs.object as!NSDictionary) == (rhs.object as!NSDictionary)
case (.Null, .Null):
return true
default:
return false
}
}
public func >(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as!NSNumber) > (rhs.object as!NSNumber)
case (.String, .String):
return (lhs.object as!String) > (rhs.object as!String)
default:
return false
}
}
public func <(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return (lhs.object as!NSNumber) < (rhs.object as!NSNumber)
case (.String, .String):
return (lhs.object as!String) < (rhs.object as!String)
default:
return false
}
}
private let trueNumber = NSNumber(bool: true)
private let falseNumber = NSNumber(bool: false)
private let trueObjCType = String.fromCString(trueNumber.objCType)
private let falseObjCType = String.fromCString(falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber: Comparable {
var isBool:Bool {
get {
let objCType = String.fromCString(self.objCType)
if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedSame
}
}
public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
public func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
}
}
public func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
}
}
public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedDescending
}
}
public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedAscending
}
}
//MARK:- Unavailable
@available(*, unavailable, renamed="JSON")
public typealias JSONValue = JSON
extension JSON {
@available(*, unavailable, message="use 'init(_ object:AnyObject)' instead")
public init(object: AnyObject) {
self = JSON(object)
}
@available(*, unavailable, renamed="dictionaryObject")
public var dictionaryObjects: [String : AnyObject]? {
get { return self.dictionaryObject }
}
@available(*, unavailable, renamed="arrayObject")
public var arrayObjects: [AnyObject]? {
get { return self.arrayObject }
}
@available(*, unavailable, renamed="int8")
public var char: Int8? {
get {
return self.number?.charValue
}
}
@available(*, unavailable, renamed="int8Value")
public var charValue: Int8 {
get {
return self.numberValue.charValue
}
}
@available(*, unavailable, renamed="uInt8")
public var unsignedChar: UInt8? {
get{
return self.number?.unsignedCharValue
}
}
@available(*, unavailable, renamed="uInt8Value")
public var unsignedCharValue: UInt8 {
get{
return self.numberValue.unsignedCharValue
}
}
@available(*, unavailable, renamed="int16")
public var short: Int16? {
get{
return self.number?.shortValue
}
}
@available(*, unavailable, renamed="int16Value")
public var shortValue: Int16 {
get{
return self.numberValue.shortValue
}
}
@available(*, unavailable, renamed="uInt16")
public var unsignedShort: UInt16? {
get{
return self.number?.unsignedShortValue
}
}
@available(*, unavailable, renamed="uInt16Value")
public var unsignedShortValue: UInt16 {
get{
return self.numberValue.unsignedShortValue
}
}
@available(*, unavailable, renamed="int")
public var long: Int? {
get{
return self.number?.longValue
}
}
@available(*, unavailable, renamed="intValue")
public var longValue: Int {
get{
return self.numberValue.longValue
}
}
@available(*, unavailable, renamed="uInt")
public var unsignedLong: UInt? {
get{
return self.number?.unsignedLongValue
}
}
@available(*, unavailable, renamed="uIntValue")
public var unsignedLongValue: UInt {
get{
return self.numberValue.unsignedLongValue
}
}
@available(*, unavailable, renamed="int64")
public var longLong: Int64? {
get{
return self.number?.longLongValue
}
}
@available(*, unavailable, renamed="int64Value")
public var longLongValue: Int64 {
get{
return self.numberValue.longLongValue
}
}
@available(*, unavailable, renamed="uInt64")
public var unsignedLongLong: UInt64? {
get{
return self.number?.unsignedLongLongValue
}
}
@available(*, unavailable, renamed="uInt64Value")
public var unsignedLongLongValue: UInt64 {
get{
return self.numberValue.unsignedLongLongValue
}
}
@available(*, unavailable, renamed="int")
public var integer: Int? {
get {
return self.number?.integerValue
}
}
@available(*, unavailable, renamed="intValue")
public var integerValue: Int {
get {
return self.numberValue.integerValue
}
}
@available(*, unavailable, renamed="uInt")
public var unsignedInteger: Int? {
get {
return self.number?.unsignedIntegerValue
}
}
@available(*, unavailable, renamed="uIntValue")
public var unsignedIntegerValue: Int {
get {
return self.numberValue.unsignedIntegerValue
}
}
}
| mit | 0bedab7d089ea8a010d80dd271d402ab | 25.460389 | 264 | 0.527483 | 4.723682 | false | false | false | false |
karstengresch/layout_studies | countidon/countidon/SoundsViewController.swift | 1 | 3129 | //
// SoundsViewController.swift
// countidon
//
// Created by Karsten Gresch on 10.10.16.
// Copyright © 2016 Closure One. All rights reserved.
//
import UIKit
class SoundsViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| unlicense | 10312f2ab2e3c1186357bf0af7bee8d2 | 31.926316 | 136 | 0.670396 | 5.310696 | false | false | false | false |
banxi1988/BXModel | Pod/Classes/BXMutipleSectionGenericDataSource.swift | 4 | 3032 | //
// SimpleMutipleSectionGenericTableViewAdapter.swift
// Pods
//
// Created by Haizhen Lee on 15/11/30.
//
//
import Foundation
open class BXMutipleSectionGenericDataSource<Key:Hashable,T:BXModelAware>:NSObject,UITableViewDataSource,UICollectionViewDataSource{
open var reuseIdentifier = "cell"
var dict:Dictionary<Key,[T]> = [:]
public typealias DidSelectedItemBlock = ( (T,_ atIndexPath:IndexPath) -> Void )
var sectionKeys:[Key] = []
var shouldShowSectionHeaderTitle = true
public init(dict:Dictionary<Key,[T]>){
self.dict = dict
sectionKeys = Array(dict.keys)
}
open func itemAtIndexPath(_ indexPath:IndexPath) -> T{
let sectionKey = sectionKeys[(indexPath as NSIndexPath).section]
return dict[sectionKey]![(indexPath as NSIndexPath).row]
}
open func rowsOfSection(_ section:Int) -> Int {
let sectionKey = sectionKeys[section]
return dict[sectionKey]!.count
}
//
//
// MARK: UITableViewDataSource
open func numberOfSections(in tableView: UITableView) -> Int {
return sectionKeys.count
}
//
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rowsOfSection(section)
}
open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if shouldShowSectionHeaderTitle{
return "\(self.sectionKeys[section])"
}else{
return nil
}
}
//
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.reuseIdentifier, for: indexPath)
configureTableViewCell(cell, atIndexPath: indexPath)
return cell
}
//
// // MARK: UICollectionViewDataSource
//
public final func numberOfSections(in collectionView: UICollectionView) -> Int {
return sectionKeys.count
}
//
public final func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return rowsOfSection(section)
}
//
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseIdentifier, for: indexPath)
configureCollectionViewCell(cell, atIndexPath: indexPath)
return cell
}
// MARK : Helper
open func configureCollectionViewCell(_ cell:UICollectionViewCell,atIndexPath indexPath:IndexPath){
}
//
open func configureTableViewCell(_ cell:UITableViewCell,atIndexPath indexPath:IndexPath){
}
//
// // MARK: BXDataSourceContainer
open func updateDict(_ dict:Dictionary<Key,[T]>){
self.dict = dict
self.sectionKeys = Array(dict.keys)
}
//
//
// public func appendItems(items:[T]){
// self.items.appendContentsOf(items)
// }
//
// public var numberOfItems:Int{
// return self.items.count
// }
}
| mit | 960ff1e9ce9b614a0047f4554cbcdf19 | 29.626263 | 132 | 0.723945 | 4.586989 | false | false | false | false |
PGSSoft/AutoMate | AutoMate/Launch Option/Launch Environment/LaunchEnvironments.swift | 1 | 2485 | //
// LaunchEnvironments.swift
// AutoMate
//
// Created by Joanna Bednarz on 20/01/2017.
// Copyright © 2017 PGS Software. All rights reserved.
//
import Foundation
// MARK: - Launch Environments
/// Most basic and generic structure to pass `(key: value)` pairs through `TestLauncher`.
///
/// **Example:**
///
/// ```swift
/// let launchEnvironmentDictionary: LaunchEnvironments = ["CORPORATION_KEY": "PGS", "PROJECT_KEY": "AutoMate"]
public struct LaunchEnvironments: LaunchEnvironmentProtocol, ExpressibleByDictionaryLiteral {
// MARK: Typealiases
public typealias Key = String
public typealias Value = String
// MARK: Properties
/// Data passed as value for environment variable
public let data: [String: String]
/// Unique value to use when comparing with other launch options.
public var uniqueIdentifier: String {
return "\(data.reduce(0) { $0 ^ $1.0.hashValue })"
}
/// Launch environment variables provided by this option.
public var launchEnvironments: [String: String]? {
return data
}
// MARK: Initialization
/// Initialize structure with dictionary of keys and values.
///
/// - Parameter elements: Dictionary of keys and values.
public init(dictionaryLiteral elements: (Key, Value)...) {
data = Dictionary(elements: elements)
}
}
// MARK: - Launch Environment
/// Simple implementation of `LaunchEnvironment` that wraps single `(key: value)` pair for `TestLauncher`.
///
/// **Example:**
///
/// ```swift
/// let launchEnvironmentOption = LaunchEnvironment(key: "MADE_WITH_LOVE_BY", value: "PGS")
public struct LaunchEnvironment: LaunchEnvironmentProtocol {
// MARK: Typealiases
public typealias Value = String
// MARK: Properties
/// Launch environment key.
public let key: String
/// Launch environment value.
public let value: String
/// Launch environment variables provided by this option.
public var launchEnvironments: [String: String]? {
return [key: value]
}
/// Unique value to use when comparing with other launch options.
public var uniqueIdentifier: String {
return key
}
// MARK: - Initialization
/// Initialize structure with `key` and `value`.
///
/// - Parameters:
/// - key: Launch environment key.
/// - value: Launch environment value.
public init(key: String, value: String) {
self.key = key
self.value = value
}
}
| mit | 5fd51d757ad70602ea35e76b7898484a | 28.223529 | 111 | 0.662238 | 4.380952 | false | false | false | false |
AuspiciousApps/matchingFlags | Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel.swift | 6 | 16203 | //
// LTMorphingLabel.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2016 Lex Tang, http://lexrus.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files
// (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import UIKit
import QuartzCore
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
enum LTMorphingPhases: Int {
case start, appear, disappear, draw, progress, skipFrames
}
typealias LTMorphingStartClosure =
(Void) -> Void
typealias LTMorphingEffectClosure =
(Character, _ index: Int, _ progress: Float) -> LTCharacterLimbo
typealias LTMorphingDrawingClosure =
(LTCharacterLimbo) -> Bool
typealias LTMorphingManipulateProgressClosure =
(_ index: Int, _ progress: Float, _ isNewChar: Bool) -> Float
typealias LTMorphingSkipFramesClosure =
(Void) -> Int
@objc public protocol LTMorphingLabelDelegate {
@objc optional func morphingDidStart(_ label: LTMorphingLabel)
@objc optional func morphingDidComplete(_ label: LTMorphingLabel)
@objc optional func morphingOnProgress(_ label: LTMorphingLabel, progress: Float)
}
// MARK: - LTMorphingLabel
@IBDesignable open class LTMorphingLabel: UILabel {
@IBInspectable open var morphingProgress: Float = 0.0
@IBInspectable open var morphingDuration: Float = 0.6
@IBInspectable open var morphingCharacterDelay: Float = 0.026
@IBInspectable open var morphingEnabled: Bool = true
@IBOutlet open weak var delegate: LTMorphingLabelDelegate?
open var morphingEffect: LTMorphingEffect = .scale
var startClosures = [String: LTMorphingStartClosure]()
var effectClosures = [String: LTMorphingEffectClosure]()
var drawingClosures = [String: LTMorphingDrawingClosure]()
var progressClosures = [String: LTMorphingManipulateProgressClosure]()
var skipFramesClosures = [String: LTMorphingSkipFramesClosure]()
var diffResults: LTStringDiffResult?
var previousText = ""
var currentFrame = 0
var totalFrames = 0
var totalDelayFrames = 0
var totalWidth: Float = 0.0
var previousRects = [CGRect]()
var newRects = [CGRect]()
var charHeight: CGFloat = 0.0
var skipFramesCount: Int = 0
#if TARGET_INTERFACE_BUILDER
let presentingInIB = true
#else
let presentingInIB = false
#endif
override open var font: UIFont! {
get {
return super.font
}
set {
super.font = newValue
setNeedsLayout()
}
}
override open var text: String! {
get {
return super.text
}
set {
guard text != newValue else { return }
previousText = text ?? ""
diffResults = previousText.diffWith(newValue)
super.text = newValue ?? ""
morphingProgress = 0.0
currentFrame = 0
totalFrames = 0
setNeedsLayout()
if !morphingEnabled {
return
}
if presentingInIB {
morphingDuration = 0.01
morphingProgress = 0.5
} else if previousText != text {
displayLink.isPaused = false
let closureKey = "\(morphingEffect.description)\(LTMorphingPhases.start)"
if let closure = startClosures[closureKey] {
return closure()
}
delegate?.morphingDidStart?(self)
}
}
}
open override func setNeedsLayout() {
super.setNeedsLayout()
previousRects = rectsOfEachCharacter(previousText, withFont: font)
newRects = rectsOfEachCharacter(text ?? "", withFont: font)
}
override open var bounds: CGRect {
get {
return super.bounds
}
set {
super.bounds = newValue
setNeedsLayout()
}
}
override open var frame: CGRect {
get {
return super.frame
}
set {
super.frame = newValue
setNeedsLayout()
}
}
fileprivate lazy var displayLink: CADisplayLink = {
let displayLink = CADisplayLink(
target: self,
selector: #selector(LTMorphingLabel.displayFrameTick))
displayLink.add(
to: RunLoop.current,
forMode: RunLoopMode.commonModes)
return displayLink
}()
lazy var emitterView: LTEmitterView = {
let emitterView = LTEmitterView(frame: self.bounds)
self.addSubview(emitterView)
return emitterView
}()
}
// MARK: - Animation extension
extension LTMorphingLabel {
func displayFrameTick() {
if displayLink.duration > 0.0 && totalFrames == 0 {
let frameRate = Float(displayLink.duration) / Float(displayLink.frameInterval)
totalFrames = Int(ceil(morphingDuration / frameRate))
let totalDelay = Float((text!).characters.count) * morphingCharacterDelay
totalDelayFrames = Int(ceil(totalDelay / frameRate))
}
currentFrame += 1
if previousText != text && currentFrame < totalFrames + totalDelayFrames + 5 {
morphingProgress += 1.0 / Float(totalFrames)
let closureKey = "\(morphingEffect.description)\(LTMorphingPhases.skipFrames)"
if let closure = skipFramesClosures[closureKey] {
skipFramesCount += 1
if skipFramesCount > closure() {
skipFramesCount = 0
setNeedsDisplay()
}
} else {
setNeedsDisplay()
}
if let onProgress = delegate?.morphingOnProgress {
onProgress(self, morphingProgress)
}
} else {
displayLink.isPaused = true
delegate?.morphingDidComplete?(self)
}
}
// Could be enhanced by kerning text:
// http://stackoverflow.com/questions/21443625/core-text-calculate-letter-frame-in-ios
func rectsOfEachCharacter(_ textToDraw: String, withFont font: UIFont) -> [CGRect] {
var charRects = [CGRect]()
var leftOffset: CGFloat = 0.0
charHeight = "Leg".size(attributes: [NSFontAttributeName: font]).height
let topOffset = (bounds.size.height - charHeight) / 2.0
for char in textToDraw.characters {
let charSize = String(char).size(attributes: [NSFontAttributeName: font])
charRects.append(
CGRect(
origin: CGPoint(
x: leftOffset,
y: topOffset
),
size: charSize
)
)
leftOffset += charSize.width
}
totalWidth = Float(leftOffset)
var stringLeftOffSet: CGFloat = 0.0
switch textAlignment {
case .center:
stringLeftOffSet = CGFloat((Float(bounds.size.width) - totalWidth) / 2.0)
case .right:
stringLeftOffSet = CGFloat(Float(bounds.size.width) - totalWidth)
default:
()
}
var offsetedCharRects = [CGRect]()
for r in charRects {
offsetedCharRects.append(r.offsetBy(dx: stringLeftOffSet, dy: 0.0))
}
return offsetedCharRects
}
func limboOfOriginalCharacter(
_ char: Character,
index: Int,
progress: Float) -> LTCharacterLimbo {
var currentRect = previousRects[index]
let oriX = Float(currentRect.origin.x)
var newX = Float(currentRect.origin.x)
let diffResult = diffResults!.0[index]
var currentFontSize: CGFloat = font.pointSize
var currentAlpha: CGFloat = 1.0
switch diffResult {
// Move the character that exists in the new text to current position
case .same:
newX = Float(newRects[index].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
case .move(let offset):
newX = Float(newRects[index + offset].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
case .moveAndAdd(let offset):
newX = Float(newRects[index + offset].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
default:
// Otherwise, remove it
// Override morphing effect with closure in extenstions
if let closure = effectClosures[
"\(morphingEffect.description)\(LTMorphingPhases.disappear)"
] {
return closure(char, index, progress)
} else {
// And scale it by default
let fontEase = CGFloat(
LTEasing.easeOutQuint(
progress, 0, Float(font.pointSize)
)
)
// For emojis
currentFontSize = max(0.0001, font.pointSize - fontEase)
currentAlpha = CGFloat(1.0 - progress)
currentRect = previousRects[index].offsetBy(
dx: 0,
dy: CGFloat(font.pointSize - currentFontSize)
)
}
}
return LTCharacterLimbo(
char: char,
rect: currentRect,
alpha: currentAlpha,
size: currentFontSize,
drawingProgress: 0.0
)
}
func limboOfNewCharacter(
_ char: Character,
index: Int,
progress: Float) -> LTCharacterLimbo {
let currentRect = newRects[index]
var currentFontSize = CGFloat(
LTEasing.easeOutQuint(progress, 0, Float(font.pointSize))
)
if let closure = effectClosures[
"\(morphingEffect.description)\(LTMorphingPhases.appear)"
] {
return closure(char, index, progress)
} else {
currentFontSize = CGFloat(
LTEasing.easeOutQuint(progress, 0.0, Float(font.pointSize))
)
// For emojis
currentFontSize = max(0.0001, currentFontSize)
let yOffset = CGFloat(font.pointSize - currentFontSize)
return LTCharacterLimbo(
char: char,
rect: currentRect.offsetBy(dx: 0, dy: yOffset),
alpha: CGFloat(morphingProgress),
size: currentFontSize,
drawingProgress: 0.0
)
}
}
func limboOfCharacters() -> [LTCharacterLimbo] {
var limbo = [LTCharacterLimbo]()
// Iterate original characters
for (i, character) in previousText.characters.enumerated() {
var progress: Float = 0.0
if let closure = progressClosures[
"\(morphingEffect.description)\(LTMorphingPhases.progress)"
] {
progress = closure(i, morphingProgress, false)
} else {
progress = min(1.0, max(0.0, morphingProgress + morphingCharacterDelay * Float(i)))
}
let limboOfCharacter = limboOfOriginalCharacter(character, index: i, progress: progress)
limbo.append(limboOfCharacter)
}
// Add new characters
for (i, character) in (text!).characters.enumerated() {
if i >= diffResults?.0.count {
break
}
var progress: Float = 0.0
if let closure = progressClosures[
"\(morphingEffect.description)\(LTMorphingPhases.progress)"
] {
progress = closure(i, morphingProgress, true)
} else {
progress = min(1.0, max(0.0, morphingProgress - morphingCharacterDelay * Float(i)))
}
// Don't draw character that already exists
if diffResults?.skipDrawingResults[i] == true {
continue
}
if let diffResult = diffResults?.0[i] {
switch diffResult {
case .moveAndAdd, .replace, .add, .delete:
let limboOfCharacter = limboOfNewCharacter(
character,
index: i,
progress: progress
)
limbo.append(limboOfCharacter)
default:
()
}
}
}
return limbo
}
}
// MARK: - Drawing extension
extension LTMorphingLabel {
override open func didMoveToSuperview() {
if let s = text {
text = s
}
// Load all morphing effects
for effectName: String in LTMorphingEffect.allValues {
let effectFunc = Selector("\(effectName)Load")
if responds(to: effectFunc) {
perform(effectFunc)
}
}
}
override open func drawText(in rect: CGRect) {
if !morphingEnabled || limboOfCharacters().count == 0 {
super.drawText(in: rect)
return
}
for charLimbo in limboOfCharacters() {
let charRect = charLimbo.rect
let willAvoidDefaultDrawing: Bool = {
if let closure = drawingClosures[
"\(morphingEffect.description)\(LTMorphingPhases.draw)"
] {
return closure($0)
}
return false
}(charLimbo)
if !willAvoidDefaultDrawing {
let s = String(charLimbo.char)
s.draw(in: charRect, withAttributes: [
NSFontAttributeName:
UIFont.init(name: font.fontName, size: charLimbo.size)!,
NSForegroundColorAttributeName:
textColor.withAlphaComponent(charLimbo.alpha)
])
}
}
}
}
| mit | 6b0e2aeca7105e0f889edf3f1fdf3f3e | 32.25462 | 100 | 0.542513 | 5.214102 | false | false | false | false |
danghoa/GGModules | GGModules/Controllers/GGNetwork/GGCore/GGWSIncredible.swift | 1 | 1759 | //
// GGWSIncredible.swift
// GGModuleLogin
//
// Created by Đăng Hoà on 1/12/17.
// Copyright © 2017 Green Global. All rights reserved.
//
import UIKit
import SwiftHTTP
import SwiftyJSON
class GGWSIncredible: NSObject {
typealias successReturn = (_ value: Any?, _ error: GGWSError?)-> Void
class func requestGETwithPath(path: String, completed: @escaping successReturn) {
let urlString = path
do {
let request = try HTTP.GET(urlString)
request.start({ (response) in
let j = JSON(data: response.data)
let dicData = j.dictionaryObject
if dicData == nil || response.statusCode == nil {
completed(nil, nil)
} else {
GGWSParse.parseDataAPIHaveDataReturn(statusCode: response.statusCode!, dic: dicData as AnyObject, complete: { (object, error) in
completed(object, error)
})
}
})
} catch let error {
print(error)
completed(nil, nil)
}
}
class func requestPOSTwithPath(path: String, params: [String: Any], completed: @escaping successReturn) {
let urlString = path
do {
let request = try HTTP.POST(urlString, parameters: params)
request.start({ (response) in
let j = JSON(data: response.data)
let dicData = j.dictionaryObject
if dicData == nil || response.statusCode == nil {
completed(nil, nil)
} else {
GGWSParse.parseDataAPIHaveDataReturn(statusCode: response.statusCode!, dic: dicData as AnyObject, complete: { (object, error) in
completed(object, error)
})
}
})
} catch let error {
print(error)
completed(nil, nil)
}
}
}
| mit | e8a7ed5aa37f3d031a98fe99b897a1fd | 25.590909 | 138 | 0.598291 | 4.198565 | false | false | false | false |
giovannipozzobon/PNChart-Swift | PNChartWatch Extension/Carthage/Checkouts/SwiftyJSON/Tests/RawTests.swift | 2 | 3308 | // RawTests.swift
//
// Copyright (c) 2014 Pinglin Tang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import SwiftyJSON
class RawTests: XCTestCase {
func testRawData() {
let json: JSON = ["somekey" : "some string value"]
let expectedRawData = "{\"somekey\":\"some string value\"}".data(using: String.Encoding.utf8)
do {
let data: Data = try json.rawData()
XCTAssertEqual(expectedRawData, data)
} catch _ {
XCTFail()
}
}
func testInvalidJSONForRawData() {
let json: JSON = "...<nonsense>xyz</nonsense>"
do {
_ = try json.rawData()
} catch let error as NSError {
XCTAssertEqual(error.code, ErrorInvalidJSON)
}
}
func testArray() {
let json:JSON = [1, "2", 3.12, NSNull(), true, ["name": "Jack"]]
let data: Data?
do {
data = try json.rawData()
} catch _ {
data = nil
}
let string = json.rawString()
XCTAssertTrue (data != nil)
XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0)
print(string!)
}
func testDictionary() {
let json:JSON = ["number":111111.23456789, "name":"Jack", "list":[1,2,3,4], "bool":false, "null":NSNull()]
let data: Data?
do {
data = try json.rawData()
} catch _ {
data = nil
}
let string = json.rawString()
XCTAssertTrue (data != nil)
XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0)
print(string!)
}
func testString() {
let json:JSON = "I'm a json"
print(json.rawString())
XCTAssertTrue(json.rawString() == "I'm a json")
}
func testNumber() {
let json:JSON = 123456789.123
print(json.rawString())
XCTAssertTrue(json.rawString() == "123456789.123")
}
func testBool() {
let json:JSON = true
print(json.rawString())
XCTAssertTrue(json.rawString() == "true")
}
func testNull() {
let json:JSON = nil
print(json.rawString())
XCTAssertTrue(json.rawString() == "null")
}
}
| mit | 3bc46edf4ebfc311dbead90c9a4bf8ba | 32.414141 | 114 | 0.60399 | 4.301691 | false | true | false | false |
codercd/DPlayer | DPlayer/LocalFolderViewController.swift | 1 | 5439 | //
// LocalFloderViewController.swift
// DPlayer
//
// Created by LiChendi on 16/4/6.
// Copyright © 2016年 LiChendi. All rights reserved.
//
import UIKit
class LocalFolderViewController: UITableViewController {
let path: NSString
var subFolders = Array<String>()
var files = Array<String>()
init(path: String) {
self.path = path
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView .registerClass(UITableViewCell.self, forCellReuseIdentifier: "LocalFloderViewController")
guard let fileArray = try? NSFileManager.defaultManager().contentsOfDirectoryAtPath(path as String) else {
subFolders = Array<String>()
files = Array<String>()
return
}
var isDirectory = ObjCBool(true)
for fileName in fileArray {
if fileName.hasPrefix(".") {
continue
}
let fullFileName = path.stringByAppendingPathComponent(fileName)
NSFileManager.defaultManager().fileExistsAtPath(fullFileName, isDirectory: &isDirectory)
if (isDirectory) {
subFolders.append(fileName)
} else {
files.append(fileName)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
switch section {
case 0:
return subFolders.count
case 1:
return files.count
default:
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("LocalFloderViewController", forIndexPath: indexPath)
switch indexPath.section {
case 0:
cell.textLabel?.text = subFolders[indexPath.row]
case 1:
cell.textLabel?.text = files[indexPath.row]
default:
cell.textLabel?.text = ""
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.section {
case 0:
let folderPath = path.stringByAppendingPathComponent(subFolders[indexPath.row])
let localFolderViewController = LocalFolderViewController(path:folderPath)
self.navigationController?.pushViewController(localFolderViewController, animated: true)
// self .presentViewController(localFolderViewController, animated: true, completion: nil)
case 1:
let filePath = path.stringByAppendingPathComponent(files[indexPath.row])
let moviePlayerController = DPlayerMoviePlayerViewController(url: NSURL(fileURLWithPath: filePath))
// self.navigationController?.pushViewController(playerCon, animated: true)
self.presentViewController(moviePlayerController, animated: true, completion: nil)
default:
return
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 06b896edb31e3d745e31f438d0863c39 | 34.763158 | 157 | 0.652502 | 5.546939 | false | false | false | false |
jardamach/playground | Playground/AppDelegate.swift | 1 | 6099 | //
// AppDelegate.swift
// Playground
//
// Created by Jaroslav Mach on 11/10/15.
// Copyright © 2015 Jaroslav Mach. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.mach.Playground" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Playground", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 9930cbbde7ba6a46d629bbff8d67cde9 | 53.936937 | 291 | 0.719744 | 5.914646 | false | false | false | false |
zvonler/PasswordElephant | PasswordElephant/Support/NSViewController-extension.swift | 1 | 540 | //
// NSViewController-extension.swift
// PasswordElephant
//
// Created by Zach Vonler on 11/4/17.
// Copyright © 2017 Relnova Software. All rights reserved.
//
import Cocoa
extension NSViewController {
func dialogOKCancel(question: String, text: String = "") -> NSAlert {
let alert = NSAlert()
alert.messageText = question
alert.informativeText = text
alert.alertStyle = .warning
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
return alert
}
}
| gpl-3.0 | abfc019863c3d12cef054b3fb9c1a043 | 24.666667 | 73 | 0.653061 | 4.178295 | false | false | false | false |
dtrauger/Charts | Source/Charts/Formatters/DefaultValueFormatter.swift | 1 | 2569 | //
// DefaultValueFormatter.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
@objc(ChartDefaultValueFormatter)
open class DefaultValueFormatter: NSObject, IValueFormatter
{
public typealias Block = (
_ value: Double,
_ entry: ChartDataEntry,
_ dataSetIndex: Int,
_ viewPortHandler: ViewPortHandler?) -> String
@objc open var block: Block?
@objc open var hasAutoDecimals: Bool = false
fileprivate var _formatter: NumberFormatter?
@objc open var formatter: NumberFormatter?
{
get { return _formatter }
set
{
hasAutoDecimals = false
_formatter = newValue
}
}
fileprivate var _decimals: Int?
open var decimals: Int?
{
get { return _decimals }
set
{
_decimals = newValue
if let digits = newValue
{
self.formatter?.minimumFractionDigits = digits
self.formatter?.maximumFractionDigits = digits
self.formatter?.usesGroupingSeparator = true
}
}
}
public override init()
{
super.init()
self.formatter = NumberFormatter()
hasAutoDecimals = true
}
@objc public init(formatter: NumberFormatter)
{
super.init()
self.formatter = formatter
}
@objc public init(decimals: Int)
{
super.init()
self.formatter = NumberFormatter()
self.formatter?.usesGroupingSeparator = true
self.decimals = decimals
hasAutoDecimals = true
}
@objc public init(block: @escaping Block)
{
super.init()
self.block = block
}
public static func with(block: @escaping Block) -> DefaultValueFormatter?
{
return DefaultValueFormatter(block: block)
}
@objc open func stringForValue(_ value: Double,
entry: ChartDataEntry,
dataSetIndex: Int,
viewPortHandler: ViewPortHandler?) -> String
{
if block != nil
{
return block!(value, entry, dataSetIndex, viewPortHandler)
}
else
{
return formatter?.string(from: NSNumber(floatLiteral: value)) ?? ""
}
}
}
| apache-2.0 | 06d10be342d657e6b2a1189bc820e342 | 23.009346 | 79 | 0.550798 | 5.329876 | false | false | false | false |
asadari/GHImageMetaDataHelper | Example/GHImageMetaDataHelper/ViewController.swift | 1 | 3763 | //
// ViewController.swift
// GHImageMetaDataHelper
//
// Created by Gwanho on 09/20/2016.
// Copyright (c) 2016 Gwanho. All rights reserved.
//
import UIKit
import ImageIO
import MobileCoreServices
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var objects = [AnyObject]()
@IBOutlet var tableView : UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.objects = ["GoGoGoGo심심해서 만들어봤음" as AnyObject]
self.tableView.reloadData()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return objects.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
let title = self.objects[indexPath.row]
if let title = title as? String{
cell.textLabel?.text = title
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
let viewController = DetailViewController.detailViewControllerFromStoryboard()
self.navigationController?.pushViewController(viewController, animated: true)
} else if indexPath.row == 1 {
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 523550a2a61fc4a54f475a11d4bec1db | 35.359223 | 158 | 0.676101 | 5.380747 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Settings/HomepageSettings/WallpaperSettings/v1/WallpaperBaseViewController.swift | 2 | 2550 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import UIKit
class WallpaperBaseViewController: UIViewController {
// Updates the layout when the horizontal or vertical size class changes
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass
|| previousTraitCollection?.verticalSizeClass != traitCollection.verticalSizeClass {
updateOnRotation()
}
}
// Updates the layout on rotation
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
updateOnRotation()
}
/// On iPhone, we call updateOnRotation when the trait collection has changed, to ensure calculation
/// is done with the new trait. On iPad, trait collection doesn't change from portrait to landscape (and vice-versa)
/// since it's `.regular` on both. We updateOnRotation from viewWillTransition in that case.
func updateOnRotation() {
}
func showError(_ error: Error, retryHandler: @escaping (UIAlertAction) -> Void) {
let alert: UIAlertController
switch error {
case WallpaperManagerError.downloadFailed(_):
alert = UIAlertController(title: .CouldntDownloadWallpaperErrorTitle,
message: .CouldntDownloadWallpaperErrorBody,
preferredStyle: .alert)
default:
alert = UIAlertController(title: .CouldntChangeWallpaperErrorTitle,
message: .CouldntChangeWallpaperErrorBody,
preferredStyle: .alert)
}
let retryAction = UIAlertAction(title: .WallpaperErrorTryAgain,
style: .default,
handler: retryHandler)
let dismissAction = UIAlertAction(title: .WallpaperErrorDismiss,
style: .cancel,
handler: nil)
alert.addAction(retryAction)
alert.addAction(dismissAction)
present(alert, animated: true, completion: nil)
}
}
| mpl-2.0 | 129abe26b2263a3fee663742136ec8c8 | 45.363636 | 120 | 0.637647 | 5.971897 | false | false | false | false |
SimonFairbairn/Stormcloud | example/iOS example/DetailViewController.swift | 1 | 7549 | //
// DetailViewController.swift
// iCloud Extravaganza
//
// Created by Simon Fairbairn on 20/10/2015.
// Copyright © 2015 Voyage Travel Apps. All rights reserved.
//
import UIKit
import Stormcloud
class DetailViewController: UIViewController {
let byteFormatter = ByteCountFormatter()
var metadataItem : StormcloudMetadata?
var itemURL : URL?
var document : JSONDocument?
var backupManager : Stormcloud?
var stack : CoreDataStack?
@IBOutlet var detailLabel : UILabel!
@IBOutlet var iCloudStatus : UILabel!
@IBOutlet var iCloudProgress : UILabel!
@IBOutlet var activityIndicator : UIActivityIndicatorView!
@IBOutlet var imageView: UIImageView!
@IBOutlet var progressView : UIProgressView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
guard let hasMetadata = metadataItem else {
return
}
self.imageView.isHidden = true
self.detailLabel.isHidden = true
metadataItem?.delegate = self
updateLabel(with: hasMetadata)
backupManager?.delegate = self
backupManager?.coreDataDelegate = self
self.title = ( hasMetadata.iniCloud ) ? "☁️" : "💾"
switch hasMetadata {
case is JSONMetadata:
getObjectCount()
case is JPEGMetadata:
showImage()
default:
break
}
}
func updateLabel( with metadata : StormcloudMetadata ) {
var textItems : [String] = []
var progress = ""
if metadata.isUploading && metadata.percentUploaded < 100 {
self.progressView.progress = (Float(metadata.percentUploaded) / 100.0)
progress = String(format: "%.2f", Float(metadata.percentUploaded)).appending("%")
textItems.append("Uploading")
}
if metadata.iniCloud {
self.progressView.progress = 1.0
textItems.append("☁️")
}
if metadata.isDownloading && metadata.percentDownloaded < 100 {
self.progressView.progress = (Float(metadata.percentDownloaded) / 100.0)
progress = String(format: "%.2f", Float(metadata.percentDownloaded)).appending("%")
textItems.append("Downloading")
}
if metadata.isDownloaded {
self.progressView.progress = 1.0
textItems.append("💾")
}
self.iCloudStatus.text = textItems.joined(separator: " & ")
self.iCloudProgress.text = progress
}
func updateLabel( with text : String ) {
self.iCloudStatus.text = text
}
func showImage() {
guard let manager = backupManager, let jpegMetadata = metadataItem as? JPEGMetadata else {
return
}
self.activityIndicator.startAnimating()
manager.restoreBackup(from: jpegMetadata) { (error, image) in
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
self.activityIndicator.isHidden = true
if let hasError = error {
switch hasError {
case .couldntOpenDocument:
self.updateLabel(with: "Error with document. Possible internet.")
default:
self.updateLabel(with: "\(hasError.localizedDescription)")
}
} else {
self.updateLabel(with: jpegMetadata)
if let image = image as? UIImage {
self.imageView.image = image
self.imageView.isHidden = false
}
}
}
}
}
@IBAction func shareItem(_ sender: UIBarButtonItem ) {
guard let item = metadataItem, let url = backupManager?.urlForItem(item ) else {
return
}
let vc = UIActivityViewController(activityItems: [url], applicationActivities: nil)
vc.popoverPresentationController?.permittedArrowDirections = [.up, .down]
vc.popoverPresentationController?.barButtonItem = sender
present(vc, animated: true, completion: nil)
}
func getObjectCount() {
guard let manager = backupManager, let jsonMetadata = metadataItem as? JSONMetadata else {
return
}
self.detailLabel.isHidden = false
self.detailLabel.text = "Fetching object count..."
self.activityIndicator.startAnimating()
self.document = JSONDocument(fileURL: manager.urlForItem(jsonMetadata)! )
guard let doc = self.document else {
updateLabel(with: "Error with document")
return
}
doc.open(completionHandler: { (success) -> Void in
DispatchQueue.main.async {
DispatchQueue.main.async {
self.updateLabel(with: jsonMetadata)
}
self.activityIndicator.stopAnimating()
if let dict = doc.objectsToBackup as? [String : AnyObject] {
let fs : String
if let icloudData = jsonMetadata.iCloudMetadata, let size = icloudData.value(forAttribute: NSMetadataItemFSSizeKey) as? Int64 {
fs = self.byteFormatter.string(fromByteCount: size)
} else {
fs = ""
}
self.detailLabel.text = "Objects backed up: \(dict.count). \(fs)"
}
}
})
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.document?.close(completionHandler: nil)
}
@IBAction func restoreObject(_ sender : UIButton) {
if let context = self.stack?.managedObjectContext, let doc = self.document {
self.activityIndicator.startAnimating()
self.view.isUserInteractionEnabled = false
self.backupManager?.restoreCoreDataBackup(from: doc, to: context , completion: { (error) -> () in
self.activityIndicator.stopAnimating()
self.view.isUserInteractionEnabled = true
let message : String
if let hasError = error {
message = "With Errors"
self.updateLabel(with: hasError.localizedDescription)
} else {
message = "Successfully"
self.iCloudProgress.text = ""
self.updateLabel(with: "Successfully Restored")
}
self.presentAlert(with: message)
})
}
}
func presentAlert(with message : String ) {
let avc = UIAlertController(title: "Completed!", message: message, preferredStyle: .alert)
avc.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(avc, animated: true, completion: nil)
}
}
extension DetailViewController : StormcloudDelegate, StormcloudCoreDataDelegate {
func stormcloudFileListDidLoad(_ stormcloud: Stormcloud) {
}
func metadataDidUpdate(_ metadata: StormcloudMetadata, for type: StormcloudDocumentType) {
if metadata == self.metadataItem {
updateLabel(with: metadata)
}
}
func metadataListDidAddItemsAt(_ addedItems: IndexSet?, andDeletedItemsAt deletedItems: IndexSet?, for type: StormcloudDocumentType) {
}
func metadataListDidChange(_ manager: Stormcloud) {
}
func metadataListDidAddItemsAtIndexes(_ addedItems: IndexSet?, andDeletedItemsAtIndexes deletedItems: IndexSet?) {
}
func stormcloud(_ stormcloud: Stormcloud, coreDataHit error: StormcloudError, for status: StormcloudCoreDataStatus) {
updateLabel(with: "ERROR RESTORING")
}
func stormcloud(_ stormcloud: Stormcloud, didUpdate objectsUpdated: Int, of total: Int, for status: StormcloudCoreDataStatus) {
self.progressView.progress = (Float(objectsUpdated) / Float(total))
self.iCloudProgress.text = String(format: "%.2f", (Float(objectsUpdated) / Float(total) ) * 100).appending("%")
switch status {
case .deletingOldObjects:
updateLabel(with: "Deleting Old Objects")
case .insertingNewObjects:
updateLabel(with: "Inserting New Objects")
case .establishingRelationships:
updateLabel(with: "Establishing Relationships")
}
}
}
extension DetailViewController : StormcloudMetadataDelegate {
func iCloudMetadataDidUpdate(_ metadata: StormcloudMetadata) {
updateLabel(with: metadata)
}
}
| mit | 8b2bd40af019ccf776c8f7c0c6e81e2c | 29.75102 | 135 | 0.69485 | 4.11694 | false | false | false | false |
Masteryyz/CSYMicroBlockSina | CSYMicroBlockSina/CSYMicroBlockSina/Classes/Tools/Extension/UIButton+Extension.swift | 1 | 955 | //
// UIButton+Extension.swift
// CSYMicroBlockSina
//
// Created by 姚彦兆 on 15/11/12.
// Copyright © 2015年 姚彦兆. All rights reserved.
//
import UIKit
extension UIButton {
convenience init(title buttonTitle : String , titleColor : UIColor? , image : String = "" , backImage : String? , fontSize : CGFloat = 14){
self.init()
setTitle(buttonTitle, forState: .Normal)
if backImage != nil{
setBackgroundImage(UIImage(named: backImage!), forState: .Normal)
setBackgroundImage(UIImage(named: "\(backImage)_highlighted"), forState: .Highlighted)
}
titleLabel?.font = UIFont.systemFontOfSize(fontSize)
setImage(UIImage(named: image), forState: .Normal)
if titleColor != nil{
setTitleColor(titleColor, forState: .Normal)
}
}
} | mit | 40578809913c1168be80f3928e49db02 | 22.525 | 143 | 0.56383 | 5.081081 | false | false | false | false |
typelift/SwiftCheck | Sources/SwiftCheck/Random.swift | 1 | 13451 | //
// Random.swift
// SwiftCheck
//
// Created by Robert Widmann on 8/3/14.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
/// Provides a standard interface to an underlying Random Value Generator of any
/// type. It is analogous to `GeneratorType`, but rather than consume a
/// sequence it uses sources of randomness to generate values indefinitely.
public protocol RandomGeneneratorType {
/// Returns an `Int` that is uniformly distributed in the range returned by
/// `genRange` (including both end points), and a new random value generator.
var next : (Int, Self) { get }
/// Yields the range of values returned by the generator.
///
/// This property must return integers in ascending order.
@available(*, deprecated, message: "genRange serves no purpose and will be removed in a future release")
var genRange : (Int, Int) { get }
/// Splits the current random value generator into two distinct random value
/// generators.
var split : (Self, Self) { get }
}
/// `StdGen` represents a pseudo-random number generator. The library makes it
/// possible to generate repeatable results, by starting with a specified
/// initial random number generator, or to get different results on each run by
/// using the system-initialised generator or by supplying a seed from some
/// other source.
public struct StdGen : RandomGeneneratorType {
let seed1 : Int
let seed2 : Int
/// Creates a `StdGen` initialized at the given seeds that is suitable for
/// replaying of tests.
public init(_ replaySeed1 : Int, _ replaySeed2 : Int) {
self.seed1 = replaySeed1
self.seed2 = replaySeed2
}
/// Convenience to create a `StdGen` from a given integer.
public init(_ o : Int) {
func mkStdGen32(_ sMaybeNegative : Int) -> StdGen {
let s = sMaybeNegative & Int.max
let (q, s1) = (s / 2147483562, s % 2147483562)
let s2 = q % 2147483398
return StdGen((s1 + 1), (s2 + 1))
}
self = mkStdGen32(o)
}
/// Returns an `Int` generated uniformly within the bounds of the generator
/// and a new distinct random number generator.
public var next : (Int, StdGen) {
// P. L'Ecuyer, "Efficient and Portable Combined Random Number
///Generators". Communications of the ACM, 31 (1988), 742-749 and 774.
// https://www.iro.umontreal.ca/~lecuyer/myftp/papers/cacm88.pdf
let s1 = self.seed1
let s2 = self.seed2
let k = s1 / 53668
let s1_ = 40014 * (s1 - k * 53668) - k * 12211
let s1__ = s1_ < 0 ? s1_ + 2147483563 : s1_
let k_ = s2 / 52774
let s2_ = 40692 * (s2 - k_ * 52774) - k_ * 3791
let s2__ = s2_ < 0 ? s2_ + 2147483399 : s2_
let z = s1__ - s2__
let z_ = z < 1 ? z + 2147483562 : z
return (z_, StdGen(s1__, s2__))
}
/// Splits the random number generator and returns two distinct random
/// number generators.
public var split : (StdGen, StdGen) {
let s1 = self.seed1
let s2 = self.seed2
let std = self.next.1
return (StdGen(s1 == 2147483562 ? 1 : s1 + 1, std.seed2), StdGen(std.seed1, s2 == 1 ? 2147483398 : s2 - 1))
}
public var genRange : (Int, Int) {
return (Int.min, Int.max)
}
}
extension StdGen : Equatable, CustomStringConvertible {
/// Equality over random number generators.
///
/// Two `StdGen`s are equal iff their seeds match.
public static func == (l : StdGen, r : StdGen) -> Bool {
return l.seed1 == r.seed1 && l.seed2 == r.seed2
}
public var description : String {
return "\(self.seed1) \(self.seed2)"
}
}
private var theStdGen : StdGen = mkStdRNG(0)
/// A library-provided standard random number generator.
public func newStdGen() -> StdGen {
let (left, right) = theStdGen.split
theStdGen = left
return right
}
/// Types that can generate random versions of themselves.
public protocol RandomType {
/// Takes a range as a tuple of values `(lo, hi)` and a random number
/// generator `G`, and returns a random value uniformly distributed in the
/// closed interval `[lo,hi]`, together with a new generator.
///
/// - Note: It is unspecified what happens if `lo > hi`.
///
/// - Remark: For continuous types there is no requirement that the values
/// `lo` and `hi` are ever produced, but they may be, depending on the
/// implementation and the interval.
static func randomInRange<G : RandomGeneneratorType>(_ range : (Self, Self), gen : G) -> (Self, G)
}
/// Generates a random value from a LatticeType random type.
public func randomBound<A : LatticeType & RandomType, G : RandomGeneneratorType>(_ gen : G) -> (A, G) {
return A.randomInRange((A.min, A.max), gen: gen)
}
extension Bool : RandomType {
/// Returns a random `Bool`ean value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (Bool, Bool), gen: G) -> (Bool, G) {
let (x, gg) = Int.randomInRange((range.0 ? 1 : 0, range.1 ? 1 : 0), gen: gen)
return (x == 1, gg)
}
}
extension Character : RandomType {
/// Returns a random `Character` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (Character, Character), gen : G) -> (Character, G) {
let (min, max) = range
let minc = String(min).unicodeScalars.first!
let maxc = String(max).unicodeScalars.first!
let (val, gg) = UnicodeScalar.randomInRange((minc, maxc), gen: gen)
return (Character(val), gg)
}
}
extension UnicodeScalar : RandomType {
/// Returns a random `UnicodeScalar` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (UnicodeScalar, UnicodeScalar), gen : G) -> (UnicodeScalar, G) {
let (val, gg) = UInt32.randomInRange((range.0.value, range.1.value), gen: gen)
return (UnicodeScalar(val)!, gg)
}
}
extension Int : RandomType {
/// Returns a random `Int` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (Int, Int), gen : G) -> (Int, G) {
let (minl, maxl) = range
let (bb, gg) = Int64.randomInRange((Int64(minl), Int64(maxl)), gen: gen)
return (Int(truncatingIfNeeded: bb), gg)
}
}
extension Int8 : RandomType {
/// Returns a random `Int8` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (Int8, Int8), gen : G) -> (Int8, G) {
let (minl, maxl) = range
let (bb, gg) = Int64.randomInRange((Int64(minl), Int64(maxl)), gen: gen)
return (Int8(truncatingIfNeeded: bb), gg)
}
}
extension Int16 : RandomType {
/// Returns a random `Int16` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (Int16, Int16), gen : G) -> (Int16, G) {
let (minl, maxl) = range
let (bb, gg) = Int64.randomInRange((Int64(minl), Int64(maxl)), gen: gen)
return (Int16(truncatingIfNeeded: bb), gg)
}
}
extension Int32 : RandomType {
/// Returns a random `Int32` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (Int32, Int32), gen : G) -> (Int32, G) {
let (minl, maxl) = range
let (bb, gg) = Int64.randomInRange((Int64(minl), Int64(maxl)), gen: gen)
return (Int32(truncatingIfNeeded: bb), gg)
}
}
extension Int64 : RandomType {
/// Returns a random `Int64` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (Int64, Int64), gen : G) -> (Int64, G) {
let (l, h) = range
if l > h {
return Int64.randomInRange((h, l), gen: gen)
} else {
let (genlo, genhi) : (Int64, Int64) = (1, 2147483562)
let b = Double(genhi - genlo + 1)
let q : Double = 1000
let k = Double(h) - Double(l) + 1
let magtgt = k * q
func entropize(_ mag : Double, _ v : Double, _ g : G) -> (Double, G) {
if mag >= magtgt {
return (v, g)
} else {
let (x, g_) = g.next
let v_ = (v * b + (Double(x) - Double(genlo)))
return entropize(mag * b, v_, g_)
}
}
let (v, rng_) = entropize(1, 0, gen)
let ret = Double(l) + v.truncatingRemainder(dividingBy: k)
// HACK: There exist the following 512 integers that cannot be
// safely converted by `Builtin.fptosi_FPIEEE64_Int64`. Instead we
// calculate their distance from `max` and perform the calculation
// in integer-land by hand.
if Double(Int64.max - 512) <= ret && ret <= Double(Int64.max) {
let deviation = Int64(Double(Int64.max) - ret)
return (Int64.max - deviation, rng_)
}
return (Int64(ret), rng_)
}
}
}
extension UInt : RandomType {
/// Returns a random `UInt` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (UInt, UInt), gen : G) -> (UInt, G) {
let (minl, maxl) = range
let (bb, gg) = UInt64.randomInRange((UInt64(minl), UInt64(maxl)), gen: gen)
return (UInt(truncatingIfNeeded: bb), gg)
}
}
extension UInt8 : RandomType {
/// Returns a random `UInt8` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (UInt8, UInt8), gen : G) -> (UInt8, G) {
let (minl, maxl) = range
let (bb, gg) = UInt64.randomInRange((UInt64(minl), UInt64(maxl)), gen: gen)
return (UInt8(truncatingIfNeeded: bb), gg)
}
}
extension UInt16 : RandomType {
/// Returns a random `UInt16` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (UInt16, UInt16), gen : G) -> (UInt16, G) {
let (minl, maxl) = range
let (bb, gg) = UInt64.randomInRange((UInt64(minl), UInt64(maxl)), gen: gen)
return (UInt16(truncatingIfNeeded: bb), gg)
}
}
extension UInt32 : RandomType {
/// Returns a random `UInt32` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (UInt32, UInt32), gen : G) -> (UInt32, G) {
let (minl, maxl) = range
let (bb, gg) = UInt64.randomInRange((UInt64(minl), UInt64(maxl)), gen: gen)
return (UInt32(truncatingIfNeeded: bb), gg)
}
}
extension UInt64 : RandomType {
/// Returns a random `UInt64` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (UInt64, UInt64), gen : G) -> (UInt64, G) {
let (l, h) = range
if l > h {
return UInt64.randomInRange((h, l), gen: gen)
} else {
let (genlo, genhi) : (Int64, Int64) = (1, 2147483562)
let b = Double(genhi - genlo + 1)
let q : Double = 1000
let k = Double(h) - Double(l) + 1
let magtgt = k * q
func entropize(_ mag : Double, _ v : Double, _ g : G) -> (Double, G) {
if mag >= magtgt {
return (v, g)
} else {
let (x, g_) = g.next
let v_ = (v * b + (Double(x) - Double(genlo)))
return entropize(mag * b, v_, g_)
}
}
let (v, rng_) = entropize(1, 0, gen)
return (UInt64(Double(l) + (v.truncatingRemainder(dividingBy: k))), rng_)
}
}
}
extension Float : RandomType {
/// Produces a random `Float` value in the range `[Float.min, Float.max]`.
public static func random<G : RandomGeneneratorType>(_ rng : G) -> (Float, G) {
let (x, rng_) : (Int32, G) = randomBound(rng)
let twoto24: Int32 = 1 << 24
let mask24 = twoto24 - 1
return (Float(mask24 & (x)) / Float(twoto24), rng_)
}
/// Returns a random `Float` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (Float, Float), gen : G) -> (Float, G) {
let (l, h) = range
if l > h {
return Float.randomInRange((h , l), gen: gen)
} else {
let (coef, g_) = Float.random(gen)
return (2.0 * (0.5 * l + coef * (0.5 * h - 0.5 * l)), g_)
}
}
}
extension Double : RandomType {
/// Produces a random `Float` value in the range `[Double.min, Double.max]`.
public static func random<G : RandomGeneneratorType>(_ rng : G) -> (Double, G) {
let (x, rng_) : (Int64, G) = randomBound(rng)
let twoto53: Int64 = 1 << 53
let mask53 = twoto53 - 1
return (Double(mask53 & (x)) / Double(twoto53), rng_)
}
/// Returns a random `Double` value using the given range and generator.
public static func randomInRange<G : RandomGeneneratorType>(_ range : (Double, Double), gen : G) -> (Double, G) {
let (l, h) = range
if l > h {
return Double.randomInRange((h , l), gen: gen)
} else {
let (coef, g_) = Double.random(gen)
return (2.0 * (0.5 * l + coef * (0.5 * h - 0.5 * l)), g_)
}
}
}
// MARK: - Implementation Details
private enum ClockTimeResult {
case success
case failure(Int)
}
private func mkStdRNG(_ o : Int) -> StdGen {
func mkStdGen32(_ sMaybeNegative : Int) -> StdGen {
let s = sMaybeNegative & Int.max
let (q, s1) = (s / 2147483562, s % 2147483562)
let s2 = q % 2147483398
return StdGen(s1 + 1, s2 + 1)
}
let ct = Int(clock())
var tt = timespec()
switch clock_gettime(0, &tt) {
case .success:
break
case let .failure(error):
fatalError("call to `clock_gettime` failed. error: \(error)")
}
let (sec, psec) = (tt.tv_sec, tt.tv_nsec)
let (ll, _) = Int(sec).multipliedReportingOverflow(by: 12345)
return mkStdGen32(ll.addingReportingOverflow(psec.addingReportingOverflow(ct.addingReportingOverflow(o).0).0).0)
}
private func clock_gettime(_ : Int, _ t : UnsafeMutablePointer<timespec>) -> ClockTimeResult {
var now : timeval = timeval()
let rv = gettimeofday(&now, nil)
if rv != 0 {
return .failure(Int(rv))
}
t.pointee.tv_sec = now.tv_sec
t.pointee.tv_nsec = Int(now.tv_usec) * 1000
return .success
}
#if os(Linux)
import Glibc
#else
import Darwin
#endif
| mit | d909dbd47d333dca4a347563a81a6e5e | 33.757106 | 135 | 0.656159 | 3.007826 | false | false | false | false |
rymcol/Server-Side-Swift-Benchmarks-Summer-2017 | KituraPress/Sources/CommonHandler.swift | 1 | 1267 | let header = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>KituraPress</title><link rel=\"stylesheet\" href=\"/inc/bootstrap.min.css\"><link rel=\"stylesheet\" type=\"text/css\" href=\"/inc/slick.css\"/><link rel=\"stylesheet\" type=\"text/css\" href=\"/inc/slick-theme.css\"/><link rel=\"stylesheet\" href=\"/style.css\"></head><body><header><div class=\"container\"><div class=\"row\"><div class=\"col-sm-6\"><a href=\"/\"><img src=\"/img/[email protected]\" class=\"logo img-responsive\" id=\"header-logo\" /></a></div><div class=\"col-sm-6 text-right\"><nav><ul><li><a href=\"/\">Home</a></li><li><a href=\"/blog\">Blog</a></li></ul></nav></div></div></div></header>"
let footer = "<footer><script src=\"/inc/bootstrap.min.js\"></script><script type=\"text/javascript\" src=\"/inc/jquery-1.11.0.min.js\"></script><script type=\"text/javascript\" src=\"/inc/jquery-migrate-1.2.1.min.js\"></script><script type=\"text/javascript\" src=\"/inc/slick.min.js\"></script><script src=\"/inc/dynamics.min.js\"></script><script src=\"/inc/animations.js\"></script></footer></body></html>"
struct CommonHandler {
func getHeader() -> String {
return header
}
func getFooter() -> String {
return footer
}
}
| apache-2.0 | de876903c73a5e9eb5ba5914af7dc344 | 83.466667 | 690 | 0.617995 | 3.424324 | false | false | false | false |
fortmarek/Supl | Supl/Extensions.swift | 1 | 7224 | //
// Extensions.swift
// Supl
//
// Created by Marek Fořt on 16.11.15.
// Copyright © 2015 Marek Fořt. All rights reserved.
//
import Foundation
import UIKit
extension UIFont {
enum FontWeight {
case light, medium, semibold, regular
}
fileprivate func getOldFont(_ size: CGFloat, weight: FontWeight) -> UIFont {
switch weight {
case .light:
guard let font = UIFont(name: "HelveticaNeue-Thin", size: size) else {return UIFont()}
return font
case .medium:
guard let font = UIFont(name: "HelveticaNeue-Light", size: size) else {return UIFont()}
return font
default:
guard let font = UIFont(name: "HelveticaNeue", size: size) else {return UIFont()}
return font
}
}
@available(iOS 8.2, *)
fileprivate func getNewFont (_ size: CGFloat, weight: FontWeight) -> UIFont {
switch weight {
case .light:
return UIFont.systemFont(ofSize: size, weight: UIFontWeightLight)
case .semibold:
return UIFont.systemFont(ofSize: size, weight: UIFontWeightSemibold)
case .regular:
return UIFont.systemFont(ofSize: size)
default:
return UIFont.systemFont(ofSize: size, weight: UIFontWeightMedium)
}
}
func getFont(_ size: CGFloat, weight: FontWeight) -> UIFont {
if #available (iOS 8.2, *) {
return getNewFont(size, weight: weight)
}
else {
return getOldFont(size, weight: weight)
}
}
}
extension UIView {
func setConstraints(_ item: AnyObject, attribute: NSLayoutAttribute, constant: CGFloat) {
let horizontalConstraint = NSLayoutConstraint(item: item, attribute: attribute, relatedBy: .equal, toItem: self, attribute: attribute, multiplier: 1, constant: constant)
self.addConstraint(horizontalConstraint)
let verticalConstraint = NSLayoutConstraint(item: item, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)
self.addConstraint(verticalConstraint)
let widthConstraint = NSLayoutConstraint(item: item, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: item.frame.width)
self.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: item, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: item.frame.height)
self.addConstraint(heightConstraint)
}
}
extension Array {
func ref (_ i:Int) -> Element? {
return 0 <= i && i < count ? self[i] : nil
}
}
extension String {
var removeExcessiveSpaces: String {
let components = self.components(separatedBy: CharacterSet.whitespaces)
let filtered = components.filter({!$0.isEmpty})
return filtered.joined(separator: " ")
}
func replaceString (_ stringArray: [String]) -> String {
var result = self
for i in 0 ..< stringArray.count {
let stringToReplace = stringArray[i]
result = result.replacingOccurrences(of: stringToReplace, with: "")
}
return result
}
func compareDate () -> (date: Date?, isNotBeforeToday: Bool) {
let comparedDate = self.stringToDate()
let today = Date().addingTimeInterval(-60*60*24*1)
let compare = today.compare(comparedDate)
if compare == .orderedDescending {
return (Date(), false)
}
//Pokud je supl z minulosti, není potřeba ho dávat do feedu
else {
return (comparedDate, true)
}
}
func contains(_ find: String) -> Bool{
return self.range(of: find) != nil
}
func getDate() -> String {
let dateCharacters = Array(self.characters)
var stringDate = ""
for character in dateCharacters {
if "\(character)" == "(" {
break
}
else if Int("\(character)") != nil || "\(character)" == "." {
stringDate.append(character)
}
}
return stringDate
}
func stringToDate() -> Date {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
let date = formatter.date(from: self)
guard let finalDate = date else {return Date()}
return finalDate
}
}
extension Date {
func isBeforeToday() -> Bool {
let today = Date().addingTimeInterval(-60*60*24*1)
let compare = today.compare(self)
if compare == .orderedDescending {
return false
}
else {
return true
}
}
func daysFrom(_ date:Date) -> Int {
let myCalendar = Calendar(identifier: Calendar.Identifier.gregorian)
let myComponents = (myCalendar as NSCalendar).components(.day, from: date, to: self, options: [])
return myComponents.day!
}
func getDateForm() -> String {
let today = Date().addingTimeInterval(-60*60*24*1)
let result = self.daysFrom(today)
//var week = ""
//TODO: Sudý a lichý týden
/*
if let weekOpt = weekArray.ref(section) {
week = weekOpt
return ("Dnes", week) ...
}
*/
if result == 0 {
return "Dnes"
}
else if result == 1 {
return "Zítra"
}
//If the result > 5, it means that the change is more than a week away - and so there are not any duplicates of Monday etc., we must show the whole date
else if result > 5 {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d.M.yyyy"
let dateString = dateFormatter.string(from: self)
let weekDay = self.getWeekDay()
return "\(weekDay) \(dateString)"
}
//Showing just the day eg. Monday, Tuesday...
else {
let weekDay = self.getWeekDay()
return weekDay
}
}
func getWeekDay() -> String {
let myCalendar = Calendar(identifier: Calendar.Identifier.gregorian)
let myComponents = (myCalendar as NSCalendar).components(.weekday, from: self)
guard let weekDay = myComponents.weekday else {return ""}
switch weekDay {
case 1:
return "Neděle"
case 2:
return "Pondělí"
case 3:
return "Úterý"
case 4:
return "Středa"
case 5:
return "Čtvrtek"
case 6:
return "Pátek"
case 7:
return "Sobota"
default:
return ""
}
}
func dateToString() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
let date = formatter.string(from: self)
return date
}
}
| mit | dd5f3d7c9cd4d442591be224ac5c74e6 | 29.66383 | 185 | 0.561338 | 4.658048 | false | false | false | false |
EZ-NET/ESNotification | ESNotification/NotificationManager.swift | 1 | 10278 | //
// NotificationManager.swift
// ESOcean
//
// Created by Tomohiro Kumagai on H27/04/23.
//
//
import Foundation
import Swim
import ESThread
// MARK: - Manager
/// Current notification manager.
let _notificationManager = NotificationManager()
public func == (lhs:HandlerID, rhs:HandlerID) -> Bool {
return lhs.value == rhs.value
}
/// Manage native notifications.
public class NotificationManager {
public static var dammingNotifications:Bool {
get {
return _notificationManager.dammingNotifications
}
set {
_notificationManager.dammingNotifications = newValue
}
}
public var dammingNotifications:Bool = false {
didSet {
if self.dammingNotifications {
NSLog("Damming notifications.")
}
else {
NSLog("Release notification dam.")
self.invokeDammedNotifications()
}
}
}
private var _notificationDam = [NotificationBox]()
/// Native notifications that the manager managed.
private var _notificationObservingHandlers = Array<_NotificationObservingHandler>()
/// Notification observer for Raw notifications.
private var _rawNotificationObserver:_NotificationObserver!
/// Current Raw Notification Center.
private var _notificationCenter:NSNotificationCenter {
return NSNotificationCenter.defaultCenter()
}
init() {
self._rawNotificationObserver = _NotificationObserver(self)
self._notificationCenter.addObserver(self._rawNotificationObserver, selector: #selector(_NotificationObserver.received(_:)), name: nil, object: nil)
}
deinit {
self._notificationCenter.removeObserver(self._rawNotificationObserver)
}
/// Observe an named notification. When the named notification was post, the `handler` called in main thread.
/// The argument `notification` is used to help type inference.
@warn_unused_result(message="Need to keep while using and release after use.")
public func observe(notificationName:String, handler:(NamedNotification)->Void) -> HandlerID {
return self.observe(notificationName, handler: handler, handlerManager: nil)
}
@warn_unused_result(message="Need to keep while using and release after use.")
internal func observe(notificationName:String, handler:(NamedNotification)->Void, handlerManager:NotificationHandlers?) -> HandlerID {
let _handler = { (notification: NotificationProtocol) -> Void in
let notification = notification as! NamedNotification
if notification.name == notificationName {
handler(notification)
}
}
return invokeOnProcessingQueueSynchronously {
let handler = _NotificationObservingHandler(NamedNotification.self, targetName: notificationName, handler: _handler, handlerManager: handlerManager)
self._notificationObservingHandlers.append(handler)
try! handlerManager?._addHandlerID(handler.handlerID)
return handler.handlerID
}
}
/// Observe an Native notification. When the native notification was post, the `handler` called in main thread.
/// The argument `notification` is used to help type inference.
@warn_unused_result(message="Need to keep while using and release after use.")
public func observe<T:NotificationProtocol>(notification:T.Type, handler:(T)->Void) -> HandlerID {
return self.observe(handler, handlerManager: nil)
}
/// Observe an Native notification. When the native notification was post, the `handler` called in main thread.
@warn_unused_result(message="Need to keep while using and release after use.")
public func observe<T:NotificationProtocol>(handler:(T)->Void) -> HandlerID {
return self.observe(handler, handlerManager: nil)
}
@warn_unused_result(message="Need to keep while using and release after use.")
public func observe<T:NotificationProtocol>(handler:(T)->Void, handlerManager: NotificationHandlers?) -> HandlerID {
let _getNotification:(NotificationProtocol)->T = {
if T.self is AnyNotification.Type {
return AnyNotification($0) as! T
}
else {
return $0 as! T
}
}
let _handler:(NotificationProtocol) -> Void = {
handler(_getNotification($0))
}
return invokeOnProcessingQueueSynchronously {
let handler = _NotificationObservingHandler(T.self, targetName: nil, handler: _handler, handlerManager: handlerManager)
self._notificationObservingHandlers.append(handler)
try! handlerManager?._addHandlerID(handler.handlerID)
return handler.handlerID
}
}
/// Release all observing handler for the `target`.
public static func releaseObservingHandler(handlerIDs:HandlerID...) {
_notificationManager.releaseObservingHandlers(Set(handlerIDs))
}
/// Release all observing handler for the `target`.
public static func releaseObservingHandlers(handlerIDs:Set<HandlerID>) {
_notificationManager.releaseObservingHandlers(Set(handlerIDs))
}
/// Release all observing handler for the `target`.
public func releaseObservingHandlers(handlerIDs:Set<HandlerID>) {
// Invoke `release` synchronously.
invokeOnProcessingQueueSynchronously {
self._releaseObservingHandlers(handlerIDs)
}
}
/// Release all observing handler for the `target`.
func _releaseObservingHandlers(targetHandlerIDs: Set<HandlerID>) {
let indexOfObservingHandlersByTargetHandlerID: (HandlerID) -> Int? = { targetHandlerID in
self._notificationObservingHandlers.indexOf { observingHandler in targetHandlerID.containsInHandler(observingHandler) }
}
let targetHandlerIndexes: () -> [Int] = {
targetHandlerIDs.flatMap(indexOfObservingHandlersByTargetHandlerID)
}
for index in targetHandlerIndexes().sort(>) {
self._notificationObservingHandlers.removeAtIndex(index)
}
}
}
extension NotificationManager {
/// The method is called when the observer received an notification.
func received(notification:NotificationProtocol) {
guard !NotificationManager.dammingNotifications else {
self.dammNotification(notification)
return
}
invokeOnProcessingQueueSyncIfNeeded {
self._received(notification)
}
}
/// The method is called when the observer received an notification.
func received(rawNotification:NSNotification) {
guard !NotificationManager.dammingNotifications else {
self.dammNotification(rawNotification)
return
}
invokeOnProcessingQueueSyncIfNeeded {
self._received(rawNotification)
}
}
private func _received(notification:NotificationProtocol) {
self._notificationObservingHandlers.forEach {
$0.invoke(notification)
}
}
private func _received(rawNotification:NSNotification) {
let targetNotificationNames = self._notificationObservingHandlers.flatMap { $0.targetName }
guard targetNotificationNames.contains(rawNotification.name) else {
// drop the notification which will not be handled.
return
}
self._received(NamedNotification(rawNotification: rawNotification))
}
private func _received(dammedNotification:NotificationBox) {
switch dammedNotification {
case .NativeNotification(let notification):
self._received(notification)
case .RawNotification(let notification):
self._received(notification)
}
}
func dammNotification(notification:NotificationProtocol) {
invokeOnProcessingQueue {
self._dammNotification(notification)
}
}
func dammNotification(rawNotification:NSNotification) {
invokeOnProcessingQueue {
self._dammNotification(rawNotification)
}
}
func _dammNotification(notification:NotificationProtocol) {
self._notificationDam.append(notification)
}
func _dammNotification(rawNotification:NSNotification) {
self._notificationDam.append(rawNotification)
}
func invokeDammedNotifications() {
invokeOnProcessingQueue {
self._notificationDam.forEach(self._received)
self._notificationDam.removeAll()
}
}
}
extension _NotificationObservingHandler : Equatable {
}
func == (lhs: _NotificationObservingHandler, rhs: _NotificationObservingHandler) -> Bool {
return lhs.handlerID == rhs.handlerID
}
// MARK: - Internal Container
/// Check if the `value` Type means same notification as `patternType`.
func ~= (pattern:NotificationProtocol.Type, value:NotificationProtocol.Type) -> Bool {
let id1 = ObjectIdentifier(pattern)
let id2 = ObjectIdentifier(value)
return id1 == id2
}
/// Notification Handler Wrapper.
final class _NotificationObservingHandler {
typealias NotificationHandler = (NotificationProtocol) -> Void
private static var _lastHandlerID = Int.min
private(set) var handlerID:HandlerID
private(set) var target:NotificationProtocol.Type
private(set) var targetName:String?
private(set) var handler:NotificationHandler
init(_ target:NotificationProtocol.Type, targetName:String?, handler:NotificationHandler, handlerManager: NotificationHandlers?) {
self.handlerID = _NotificationObservingHandler._getNextHandlerID(handlerManager)
self.target = target
self.targetName = targetName
self.handler = handler
}
private static func _getNextHandlerID(handlerManager: NotificationHandlers?) -> HandlerID {
defer {
_lastHandlerID = _lastHandlerID.successor()
}
return HandlerID(_lastHandlerID, handlerManager: handlerManager)
}
/// Invoke notification handler. If the `notification` type is not same type as self.target, do nothing.
func invoke(notification:NotificationProtocol) {
switch self.target {
case notification.dynamicType, AnyNotification.self:
self._invokeHandlerOnMainThread(notification)
default:
break
}
}
/// Invoke notification handler on main thread asynchronously.
func _invokeHandlerOnMainThread(notification:NotificationProtocol) {
invokeAsyncOnMainQueue {
self.handler(notification)
}
}
}
// MARK: - Internal Observer
/// Observe raw notifications.
final class _NotificationObserver : NSObject {
private unowned var _manager:NotificationManager
init(_ manager:NotificationManager) {
self._manager = manager
super.init()
}
/// The method is called when the observer received an notification.
func received(rawNotification:NSNotification) {
if let notification = rawNotification.toESNativeNotification() {
self._manager.received(notification)
}
else {
self._manager.received(rawNotification)
}
}
}
| mit | 27b458618ec13b7d44d402ecf6efb430 | 24.695 | 151 | 0.747519 | 4.189971 | false | false | false | false |
zyuanming/YMStretchableHeaderTabViewController | Sources/SegmentedControl.swift | 1 | 14342 |
import UIKit
open class SegmentedControl: UIControl {
struct SegmentedItem: ExpressibleByStringLiteral {
fileprivate enum ItemType {
case image(normal: UIImage?, selected: UIImage?)
case title(String)
}
fileprivate var type: ItemType
init(value: String) {
type = .title(value)
}
init(stringLiteral value: String) {
type = .title(value)
}
init(unicodeScalarLiteral value: String) {
type = .title(value)
}
init(extendedGraphemeClusterLiteral value: String) {
type = .title(value)
}
init(normal: UIImage?, selected: UIImage?) {
type = .image(normal: normal, selected: selected)
}
}
var scrollViewContentSizeBottomMargin: CGFloat = 50
var selectionIndicatorHeight: CGFloat = 2.5
var animationDuration: TimeInterval = 0.2
var segmentNormalColor: UIColor = UIColor.black.withAlphaComponent(0.6)
var segmentDisabledColor: UIColor = UIColor.black.withAlphaComponent(0.6)
var isItemScrollEnabled = true
var kJumpFlag: Bool = false
var items: [SegmentedItem] = [] {
willSet { removeAllSegments() }
didSet { insertAllSegments() }
}
var normalFont = UIFont.systemFont(ofSize: 16)
var selectedFont = UIFont.systemFont(ofSize: 17)
var numberOfSegments: Int {
return items.count
}
var selectedSegmentIndex: Int {
get { return _selectedSegmentIndex }
set {
setSelected(true, forSegmentAtIndex: newValue)
}
}
var isTopSeparatorHidden: Bool {
get { return separatorTopLine.isHidden }
set { separatorTopLine.isHidden = newValue }
}
fileprivate var _selectedSegmentIndex = 0
fileprivate var segmentsButtons: [UIButton] = []
fileprivate(set) var segmentsContainerView: UIScrollView?
fileprivate var indicatorView = UIView()
fileprivate var separatorTopLine = UIView()
fileprivate var separatorLine = UIView()
//MARK: lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
convenience init(items: [SegmentedItem]) {
self.init()
self.items = items
insertAllSegments()
}
fileprivate func commonInit() {
separatorTopLine.isHidden = true
separatorTopLine.backgroundColor = UIColor.black.withAlphaComponent(0.1)
separatorLine.backgroundColor = UIColor.black.withAlphaComponent(0.1)
}
//MARK:
override open func layoutSubviews() {
super.layoutSubviews()
if segmentsButtons.count == 0 {
selectedSegmentIndex = -1;
} else if selectedSegmentIndex < 0 {
selectedSegmentIndex = 0
}
layoutButtons()
layoutIndicator()
layoutSeparator()
}
override open func willMove(toWindow newWindow: UIWindow?) {
super.willMove(toWindow: newWindow)
setColors()
}
override open func willMove(toSuperview newSuperview: UIView?) {
super.willMove(toSuperview: newSuperview)
setColors()
}
open func setSelected(_ selected: Bool, forSegmentAtIndex index: Int) {
guard 0 <= index, index < segmentsButtons.count else { return }
layoutSelectedOffset(at: index)
if selectedSegmentIndex == index {
return
}
let previousButton = buttonAtIndex(selectedSegmentIndex)
let currentButton = buttonAtIndex(index)
let isPreviousButtonShowAnimation = isButtonTitlePresentation(at: selectedSegmentIndex)
let isCurrentButtonShowAnimation = isButtonTitlePresentation(at: index)
previousButton?.isUserInteractionEnabled = true
previousButton?.isSelected = false
currentButton?.isSelected = true
currentButton?.isUserInteractionEnabled = false
_selectedSegmentIndex = index
var scale: CGFloat = 1
if let selectHeight = previousButton?.titleLabel?.bounds.height, let normalHeight = currentButton?.titleLabel?.bounds.height, let t = previousButton?.transform {
if normalHeight > 0 && selectHeight > 0 && t.a + t.c > 0 {
//缩放大小 = 选中的字体高度 * 仿射变换的缩放系数 / 未选中的字体高度
scale = selectHeight * sqrt(t.a * t.a + t.c * t.c) / normalHeight
}
}
UIView.animate(withDuration: animationDuration,
delay: 0,
options: .beginFromCurrentState,
animations: {
self.layoutIndicator()
if isPreviousButtonShowAnimation {
previousButton?.transform = CGAffineTransform(scaleX: 1 / scale, y: 1 / scale)
}
if isCurrentButtonShowAnimation {
currentButton?.transform = CGAffineTransform(scaleX: scale, y: scale)
}
},
completion: { _ in
previousButton?.transform = CGAffineTransform.identity
currentButton?.transform = CGAffineTransform.identity
previousButton?.titleLabel?.font = (previousButton?.isSelected ?? true) ? self.selectedFont : self.normalFont
currentButton?.titleLabel?.font = (currentButton?.isSelected ?? true) ? self.selectedFont : self.normalFont
})
}
//MARK: Private Methods
fileprivate func setColors() {
indicatorView.backgroundColor = tintColor
}
fileprivate func layoutIndicator() {
if let button = selectedButton() {
let rect = CGRect(x: button.frame.minX, y: bounds.height - selectionIndicatorHeight, width: button.frame.width, height: selectionIndicatorHeight)
indicatorView.frame = rect
}
}
fileprivate func layoutSeparator() {
separatorTopLine.frame = CGRect(x: 0, y: 0, width: bounds.width, height: 0.5)
separatorLine.frame = CGRect(x: 0, y: bounds.height - 0.5, width: bounds.width, height: 0.5)
}
fileprivate func layoutButtons() {
segmentsContainerView?.frame = bounds
var originX: CGFloat = 4
var margin: CGFloat = 11
let buttonMargin: CGFloat = 10
var allWidth: CGFloat = 0
for index in 0..<segmentsButtons.count {
if let button = buttonAtIndex(index) {
button.sizeToFit()
let rect = CGRect(x: margin + originX, y: 0, width: button.frame.width + buttonMargin, height: bounds.height - selectionIndicatorHeight)
button.frame = rect
button.isSelected = (index == selectedSegmentIndex)
originX = originX + margin + rect.width + margin
if index == segmentsButtons.count - 1 {
allWidth = button.frame.maxX + margin
}
}
}
if allWidth <= frame.width - scrollViewContentSizeBottomMargin {
segmentsContainerView?.contentSize = CGSize(width: frame.width, height: floor(bounds.height))
let buttonContentAllWidth = allWidth - margin * CGFloat(segmentsButtons.count * 2)
margin = (frame.width - (buttonContentAllWidth)) / CGFloat(segmentsButtons.count * 2)
originX = 0
for index in 0..<segmentsButtons.count {
if let button = buttonAtIndex(index) {
let rect = CGRect(x: margin + originX, y: 0, width: button.frame.width, height: button.frame.height)
button.frame = rect
button.isSelected = (index == selectedSegmentIndex)
originX = originX + margin + rect.width + margin
}
}
} else {
segmentsContainerView?.contentSize = CGSize(width: allWidth + scrollViewContentSizeBottomMargin,
height: floor(bounds.height))
}
}
fileprivate func layoutSelectedOffset(at index: Int) {
guard let segmentsContainerView = segmentsContainerView,
let button = buttonAtIndex(index),
isItemScrollEnabled else { return }
var targetX = max(0, button.frame.midX - self.frame.width / 2.0)
targetX = min(segmentsContainerView.contentSize.width - self.frame.width, targetX)
targetX = max(0, targetX)
let point = CGPoint(x: targetX, y: 0)
segmentsContainerView.setContentOffset(point, animated: true)
}
fileprivate func insertAllSegments() {
for index in 0..<items.count {
addButtonForSegment(index)
}
configureSegments()
setNeedsLayout()
if segmentsButtons.count == 0 {
selectedSegmentIndex = -1;
} else if selectedSegmentIndex < 0 {
selectedSegmentIndex = 0
}
if self.bounds.width > 0 {
layoutButtons()
layoutIndicator()
layoutSeparator()
}
}
fileprivate func removeAllSegments() {
segmentsButtons.forEach { $0.removeFromSuperview() }
segmentsButtons.removeAll(keepingCapacity: true)
}
fileprivate func addButtonForSegment(_ segment: Int) {
let button = UIButton(type:.custom)
button.addTarget(self, action: #selector(willSelected(_:)), for: .touchDown)
button.addTarget(self, action: #selector(didSelected(_:)), for: .touchUpInside)
button.backgroundColor = nil
button.isOpaque = true
button.clipsToBounds = true
button.adjustsImageWhenDisabled = false
button.adjustsImageWhenHighlighted = false
button.isExclusiveTouch = true
button.tag = segment
if segmentsContainerView == nil {
segmentsContainerView = UIScrollView(frame: bounds)
segmentsContainerView?.showsVerticalScrollIndicator = false
segmentsContainerView?.showsHorizontalScrollIndicator = false
segmentsContainerView?.backgroundColor = UIColor.clear
segmentsContainerView?.isScrollEnabled = isItemScrollEnabled
addSubview(segmentsContainerView!)
self.sendSubview(toBack: segmentsContainerView!)
addSubview(separatorTopLine)
addSubview(separatorLine)
segmentsContainerView?.addSubview(indicatorView)
}
segmentsButtons.append(button)
segmentsContainerView?.addSubview(button)
}
fileprivate func buttonAtIndex(_ index: Int) -> UIButton? {
if 0 <= index && index < segmentsButtons.count {
return segmentsButtons[index]
}
return nil
}
fileprivate func selectedButton() -> UIButton? {
return buttonAtIndex(selectedSegmentIndex)
}
fileprivate func titleForSegmentAtIndex(_ index: Int) -> String? {
guard 0 <= index && index < items.count else { return nil }
if case .title(let title) = items[index].type {
return title
}
return nil
}
fileprivate func isButtonTitlePresentation(at position: Int) -> Bool {
guard 0 <= position && position < items.count else { return false }
if case .title = items[position].type {
return true
}
return false
}
fileprivate func setButtonImages(at position: Int) {
guard 0 <= position && position < items.count else { return }
if case .image(let image) = items[position].type {
let button = buttonAtIndex(position)
button?.setImage(image.normal, for: UIControlState())
button?.setImage(image.selected, for: .highlighted)
button?.setImage(image.selected, for: .selected)
}
}
fileprivate func configureSegments() {
for button in segmentsButtons {
configureButtonForSegment(button.tag)
}
}
fileprivate func configureButtonForSegment(_ segment: Int) {
assert(segment >= 0, "segment index must greater than 0")
assert(segment < numberOfSegments, "segment button must exist")
setFont(segment == selectedSegmentIndex ? selectedFont : normalFont, forSegmentAtIndex: segment)
if let title = titleForSegmentAtIndex(segment) {
setTitle(title, forSegmentAtIndex: segment)
setTitleColor(titleColorForButtonState(UIControlState()), forState: UIControlState())
setTitleColor(titleColorForButtonState(.highlighted), forState: .highlighted)
setTitleColor(titleColorForButtonState(.selected), forState: .selected)
} else {
setButtonImages(at: segment)
}
}
fileprivate func setFont(_ font: UIFont, forSegmentAtIndex index: Int) {
let button = buttonAtIndex(index)
button?.titleLabel?.font = font
}
fileprivate func setTitle(_ title: String, forSegmentAtIndex index: Int) {
let button = buttonAtIndex(index)
button?.setTitle(title, for: UIControlState())
button?.setTitle(title, for: .highlighted)
button?.setTitle(title, for: .selected)
button?.setTitle(title, for: .disabled)
}
fileprivate func setTitleColor(_ color: UIColor, forState state: UIControlState) {
for button in segmentsButtons {
button.setTitleColor(color, for: state)
}
}
fileprivate func titleColorForButtonState(_ state: UIControlState) -> UIColor {
switch state {
case UIControlState(): return segmentNormalColor
case UIControlState.disabled: return segmentDisabledColor
default: return tintColor
}
}
//MARK: Segment Actions
@objc fileprivate func willSelected(_ sender: UIButton) {
}
@objc fileprivate func didSelected(_ sender: UIButton) {
if selectedSegmentIndex != sender.tag {
selectedSegmentIndex = sender.tag
sendActions(for: .valueChanged)
}
}
}
| mit | 2205b95c9e32d1a3573600b5d7a9557b | 33.090692 | 169 | 0.613204 | 5.325876 | false | false | false | false |
vulgur/Sources | CodeReader/View/InsetsLabel.swift | 1 | 1455 | //
// InsetsLabel.swift
// CodeReader
//
// Created by vulgur on 2016/10/20.
// Copyright © 2016年 MAD. All rights reserved.
//
import UIKit
@IBDesignable class InsetsLabel: UILabel {
@IBInspectable var topInsets: CGFloat = 0.0
@IBInspectable var bottomInsets: CGFloat = 0.0
@IBInspectable var leftInsets: CGFloat = 5.0
@IBInspectable var rightInsets: CGFloat = 5.0
var insets: UIEdgeInsets {
get {
return UIEdgeInsetsMake(topInsets, leftInsets, bottomInsets, rightInsets)
}
set {
topInsets = newValue.top
bottomInsets = newValue.bottom
leftInsets = newValue.left
rightInsets = newValue.right
}
}
override func drawText(in rect: CGRect) {
let insects = UIEdgeInsets.init(top:topInsets, left: leftInsets, bottom: bottomInsets, right: rightInsets)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insects))
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var newSize = super.sizeThatFits(size)
newSize.width += leftInsets + rightInsets
newSize.height += topInsets + bottomInsets
return newSize
}
override var intrinsicContentSize : CGSize {
var contentSize = super.intrinsicContentSize
contentSize.width += leftInsets + rightInsets
contentSize.height += topInsets + bottomInsets
return contentSize
}
}
| mit | f23bd5307af7204b149d35e549f6a3d7 | 29.893617 | 114 | 0.647383 | 4.624204 | false | false | false | false |
jkolb/midnightbacon | MidnightBacon/Modules/Comments/CommentCell.swift | 1 | 4164 | //
// CommentCell.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import DrapierLayout
class CommentCell : UITableViewCell {
let authorLabel = UILabel()
let bodyLabel = UILabel()
let indentionView = UIView()
let separatorView = UIView()
var insets = UIEdgeInsetsZero
var separatorHeight: CGFloat = 0.0
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
bodyLabel.numberOfLines = 0
bodyLabel.lineBreakMode = .ByWordWrapping
bodyLabel.opaque = true
contentView.addSubview(bodyLabel)
contentView.addSubview(authorLabel)
// contentView.addSubview(indentionView)
contentView.addSubview(separatorView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
struct CellLayout {
let authorFrame: CGRect
let bodyFrame: CGRect
let indentionFrame: CGRect
let separatorFrame: CGRect
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = generateLayout(contentView.bounds)
authorLabel.frame = layout.authorFrame
bodyLabel.frame = layout.bodyFrame
indentionView.frame = layout.indentionFrame
separatorView.frame = layout.separatorFrame
}
override func sizeThatFits(size: CGSize) -> CGSize {
let layout = generateLayout(size.rect())
let maxBottom = layout.bodyFrame.bottom
return CGSize(width: size.width, height: maxBottom + insets.bottom)
}
func generateLayout(bounds: CGRect) -> CellLayout {
let indent = CGFloat(indentationLevel) * CGFloat(4.0)
let authorFrame = authorLabel.layout(
Leading(equalTo: bounds.leading(insets), constant: indent),
Trailing(equalTo: bounds.trailing(insets)),
Capline(equalTo: bounds.top(insets))
)
let bodyFrame = bodyLabel.layout(
Leading(equalTo: bounds.leading(insets), constant: indent),
Trailing(equalTo: bounds.trailing(insets)),
Capline(equalTo: authorFrame.baseline(font: authorLabel.font), constant: CGFloat(8.0))
)
let indentionFrame = indentionView.layout(
Leading(equalTo: bounds.leading(insets), constant: indent - CGFloat(8.0)),
Top(equalTo: bounds.top),
Width(equalTo: separatorHeight),
Height(equalTo: bounds.height)
)
let separatorFrame = separatorView.layout(
Leading(equalTo: bounds.leading(insets), constant: indent),
Trailing(equalTo: bounds.trailing),
Bottom(equalTo: bodyFrame.bottom + insets.bottom),
Height(equalTo: separatorHeight)
)
return CellLayout(
authorFrame: authorFrame,
bodyFrame: bodyFrame,
indentionFrame: indentionFrame,
separatorFrame: separatorFrame
)
}
}
| mit | 85f2f44e8739c8fa6b103f6d1d21ecd5 | 37.915888 | 98 | 0.673391 | 4.893067 | false | false | false | false |
andreaantonioni/AAPhotoCircleCrop | AAPhotoCircleCrop/Classes/AACircleCropCutterView.swift | 1 | 2147 | //
// AACircleCropCutterView.swift
//
// Created by Keke Arif on 21/02/2016.
// Modified by Andrea Antonioni on 14/01/2017
// Copyright © 2017 Andrea Antonioni. All rights reserved.
//
import UIKit
class AACircleCropCutterView: UIView {
/// Diameter of the circle
var circleDiameter: CGFloat = 240 {
didSet {
setNeedsDisplay()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.isOpaque = false
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.isOpaque = false
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7).setFill()
UIRectFill(rect)
// Draw the circle
let circle = UIBezierPath(ovalIn: CGRect(x: rect.size.width/2 - circleDiameter/2,
y: rect.size.height/2 - circleDiameter/2,
width: circleDiameter,
height: circleDiameter))
context?.setBlendMode(.clear)
UIColor.clear.setFill()
circle.fill()
// Draw a rectangle around the circle, just to see the effective cutted image
// let square = UIBezierPath(rect: CGRect(x: rect.size.width/2 - circleDiameter/2, y: rect.size.height/2 - circleDiameter/2, width: circleDiameter, height: circleDiameter))
// UIColor.lightGray.setStroke()
// square.lineWidth = 1.0
// context?.setBlendMode(.normal)
// square.stroke()
}
// Allow touches through the circle crop cutter view
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
for subview in subviews as [UIView] {
if !subview.isHidden && subview.alpha > 0 && subview.isUserInteractionEnabled && subview.point(inside: convert(point, to: subview), with: event) {
return true
}
}
return false
}
}
| mit | c4f2bd94b813fd67d61a3b5d47160207 | 32.015385 | 179 | 0.569432 | 4.556263 | false | false | false | false |
malcommac/SwiftDate | Playgrounds/SwiftDate.playground/Pages/Date Manipulation.xcplaygroundpage/Contents.swift | 2 | 8577 | import Foundation
import SwiftDate
/*:
## 3.0 - Add & Subtract Time Units from Date
SwiftDate allows to use numbers to work with time components in dates. By extending the `Int` type it defines a list of time units:
- `nanoseconds`
- `seconds`
- `minutes`
- `days`
- `weeks`
- `months`
- `quarters`
- `years`
You can use a value followed by one of these unit specifications to add or remove the component from a date.
So, for example, you can produce a date which can be a mix of intuitive math operations:
*/
let date1 = DateInRegion() + 1.years
let date2 = DateInRegion() - 2.minutes
let date3 = date2 + 3.hours - 5.minutes + 1.weeks
/*:
> IMPORTANT NOTE: These values are converted automatically to `DateComponents` evaluated in the same context of the target `Date` or `DateInRegion`'s `calendar`.
Another way to add time components to a date is to use the `dateByAdding()` function:
*/
let date4 = DateInRegion().dateByAdding(5, .month)
/*:
## 3.1 - Get DateTime Components Components
With SwiftDate you have several convenience properties to inspect each datetime unit of a date, both for `Date` and `DateInRegion`.
These properties are strictly correlated to the date's calendar (and some also with locale): if you are manipulating a `DateInRegion` remember these properties return values in the context of the associated `region` attributes (Locale, TimeZone and Calendar).
> **IMPORTANT NOTE**: If you are working with plain `Date` properties uses as reference the currently set `SwiftDate.defaultRegion` which, unless you modify it, is set to Gregorian/UTC/Device's Language.
*/
let regionNY = Region(calendar: Calendars.gregorian, zone: Zones.americaNewYork, locale: Locales.english)
let date5 = DateInRegion(components: {
$0.year = 2015
$0.month = 6
$0.day = 1
$0.hour = 23
}, region: regionNY)!
print("Origin date in NY: \(date5.hour):\(date5.minute) of \(date5.day)/\(date5.month)")
print("Month is \(date5.monthName(.default).uppercased())")
print("Month in italian is \(date5.convertTo(locale: Locales.italian).monthName(.default).uppercased())")
// We can convert it to UTC and get the same properties which are now updated!
let date5InUTC = date5.convertTo(region: Region.UTC)
print("Converted date in UTC: \(date5InUTC.hour):\(date5InUTC.minute) of \(date5InUTC.day)/\(date5InUTC.month)")
/*:
## 3.2 - Get Interval Between Dates
You can get the interval between two dates and express it in form of time units easily with SwiftDate.
*/
let format = "yyyy-MM-dd HH:mm:ss"
let date6 = DateInRegion("2017-07-22 00:00:00", format: format, region: regionNY)!
let date7 = DateInRegion("2017-07-23 12:00:00", format: format, region: regionNY)!
let hours = date6.getInterval(toDate: date7, component: .hour) // 36 hours
let days = date6.getInterval(toDate: date7, component: .day) // 1 day
/*:
## 3.3 - Convert Date's Region (Locale/TimeZone/Calendar)
`DateInRegion` can be converted easily to anothe region just using `.convertTo(region:)` or `.convertTo(calendar: timezone:locale:)` functions.
- `convertTo(region:)` convert the receiver date to another region. Region may include a different time zone for example, or a locale.
- `convertTo(calendar:timezone:locale:)` allows to convert the receiver date instance to a specific calendar/timezone/locale. All parameters are optional and only non-nil parameters alter the final region. For a nil param the current receiver's region attribute is kept.
Examples:
*/
// Create a date in NY: "2001-09-11 12:00:05"
let date8 = DateInRegion(components: {
$0.year = 2001
$0.month = 9
$0.day = 11
$0.hour = 12
$0.minute = 0
$0.second = 5
}, region: regionNY)!
// Convert to GMT timezone (and locale)
let date8inGMT = date8.convertTo(region: Region.UTC) // date is now: "2001-09-11 16:00:05"
print(date8inGMT.toISO())
/*:
## 3.4 - Rounding Date
`.dateRoundedAt()` function allows to round a given date time to the passed style: off, up or down.
*/
let regionRome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
// Round down 10mins
let date9 = DateInRegion("2017-07-22 00:03:50", format: format, region: regionRome)!
let r10min = date9.dateRoundedAt(.to10Mins)
/*:
## 3.5 - Trouncating Date
Sometimes you may need to truncate a date by zeroing all values below certain time unit. `.dateTruncated(from:) and .dateTruncated(to:)` functions can be used for this scope.
#### Truncating From
It creates a new instance by truncating the components starting from given components down the granurality.
`func dateTruncated(from component: Calendar.Component) -> DateInRegion?`
#### Truncated At
It creates a new instance by truncating all passed components.
`func dateTruncated(at components: [Calendar.Component]) -> DateInRegion?`
*/
let date10 = "2017-07-22 15:03:50".toDate("yyyy-MM-dd HH:mm:ss", region: regionRome)!
let truncatedTime = date10.dateTruncated(from: .hour)
let truncatedCmps = date10.dateTruncated(at: [.month, .day, .minute])
/*:
## 3.6 - Set Time in Date
Sometimes you may need to alter time in a specified date. SwiftDate allows you to perform this using `.dateBySet(hour:min:secs:options:)` function.
*/
let date11 = DateInRegion("2010-01-01 00:00:00", format: "yyyy-MM-dd HH:mm:ss", region: regionRome)!
let alteredDate = date11.dateBySet(hour: 20, min: 13, secs: 15)
/*:
## 3.7 - Set DateTime Components
SwiftDate allows you to return new date representing the date calculated by setting a specific components of a given date to given values, while trying to keep lower components the same (altering more components at the same time may result in different-than-expected results, this because lower components maybe need to be recalculated).
*/
let date12 = date11.dateBySet([.month: 1, .day: 1, .hour: 9, .minute: 26, .second: 0])
/*:
## 3.8 - Generate Related Dates (`nextYear, nextWeeekday, startOfMonth, startOfWeek, prevMonth`...)
Sometimes you may need to generate a related date from a specified instance; maybe the next sunday, the first day of the next week or the start datetime of a date.
SwiftDate includes 20+ different "interesting" dates you can obtain by calling `.dateAt()` function from any `Date` or `DateInRegion` instance.
*/
// Return today's datetime at 00:00:00
let date13 = DateInRegion().dateAt(.startOfDay)
// Return today's datetime at 23:59:59
let date14 = DateInRegion().dateAt(.endOfDay)
// Return the date at the start of this week
let date15 = DateInRegion().dateAt(.startOfWeek)
// Return current time tomorrow
let date16 = DateInRegion().dateAt(.tomorrow)
// Return the next sunday from specified date
let date17 = date16.dateAt(.nextWeekday(.sunday))
// and so on...
/*:
## 3.9 - Date at start/end of time component
Two functions called `.dateAtStartOf()` and `.dateAtEndOf()` allows you to get the related date from a `Date`/`DateInRegion` instance moved at the start or end of the specified component.
*/
// Return today's date at 23:59:59
let date18 = DateInRegion().dateAtEndOf(.day)
// Return the first day's date of the month described in date1
let date19 = DateInRegion().dateAtStartOf(.month)
// Return the first day of the current week at 00:00
let date20 = DateInRegion().dateAtStartOf([.week, .day])
/*:
## 3.10 - Enumerate Dates
Dates enumeration function allows you to generate a list of dates in a closed date intervals incrementing date components by a fixed or variable interval at each new date.
- **VARIABLE INCREMENT** `static func enumerateDates(from startDate: DateInRegion, to endDate: DateInRegion, increment: ((DateInRegion) -> (DateComponents))) -> [DateInRegion]`
- **FIXED INCREMENT** `static func enumerateDates(from startDate: DateInRegion, to endDate: DateInRegion, increment: DateComponents) -> [DateInRegion]`
*/
let toDate = DateInRegion()
let fromDate = toDate - 30.days
let dates = DateInRegion.enumerateDates(from: fromDate, to: toDate, increment: DateComponents.create {
$0.hour = 1
$0.minute = 30
})
/*:
## 3.11 - Random Dates
SwiftDate exposes a set of functions to generate a random date or array of random dates in a bounds.
There are several functions to perform this operation:
*/
let randomDates = DateInRegion.randomDates(count: 40,
between: fromDate,
and: toDate)
let randomDate = DateInRegion.randomDate(withinDaysBeforeToday: 7, region: regionRome)
/*:
## 3.12 - Sort Dates
Two conveniences function allows you to sort an array of dates by newest or oldest. Naming is pretty simple:
*/
let orderedByNewest = DateInRegion.sortedByNewest(list: randomDates)
let oldestDate = DateInRegion.oldestIn(list: randomDates)
| mit | 25bdc48df918e40a9ecc734971e7f2b1 | 44.86631 | 338 | 0.744549 | 3.755254 | false | false | false | false |
Draveness/NightNight | Example/NightNight/ViewController.swift | 1 | 3294 | //
// ViewController.swift
// NightNight
//
// Created by Draveness on 06/18/2016.
// Copyright (c) 2016 Draveness. All rights reserved.
//
import UIKit
import NightNight
class ViewController: UIViewController {
let label = UILabel()
let button = UIButton(type: .custom)
override func viewDidLoad() {
super.viewDidLoad()
view.mixedBackgroundColor = MixedColor(normal: 0xfafafa, night: 0x222222)
// setupLabel()
button.setTitle("NightNight", for: UIControl.State())
button.setMixedTitleColor(MixedColor(normal: 0x000000, night: 0xffffff), forState: UIControl.State())
button.addTarget(self, action: #selector(changeTheme), for: .touchUpInside)
button.frame = view.frame
view.addSubview(button)
navigationItem.title = "NightNight"
navigationController?.navigationBar.mixedTitleTextAttributes = [NNForegroundColorAttributeName: MixedColor(normal: 0x000000, night: 0xfafafa)]
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Normal",
style: .done,
target: self,
action: #selector(changeToNormal))
let nightModeButtonItem = UIBarButtonItem(image: nil, style: .done, target: self, action: #selector(changeToNight))
nightModeButtonItem.mixedImage = MixedImage(normal: UIImage(named: "lightModeButton")!, night: UIImage(named: "nightModeButton")!)
navigationItem.setRightBarButton(nightModeButtonItem, animated: true)
navigationController?.navigationBar.mixedBarTintColor = MixedColor(normal: 0xffffff, night: 0x222222)
navigationController?.navigationBar.mixedTintColor = MixedColor(normal: 0x0000ff, night: 0xfafafa)
// Change bar style will change status bar style cuz current view controller is a child of navigation controller, preferredStatusBarStyle will never be called http://stackoverflow.com/questions/19022210/preferredstatusbarstyle-isnt-called .
navigationController?.navigationBar.mixedBarStyle = MixedBarStyle(normal: .default, night: .black)
}
func setupLabel() {
label.frame = view.frame
// label.text = "NightNight"
let attributedString = NSMutableAttributedString(string: "NightNight")
attributedString.setMixedAttributes(
[NNForegroundColorAttributeName: MixedColor(normal: 0x000000, night: 0xfafafa)],
range: NSRange(location: 0, length: 9)
)
label.attributedText = attributedString
label.textAlignment = .center
// label.mixedTextColor = MixedColor(normal: 0x000000, night: 0xfafafa)
view.addSubview(label)
}
@objc func changeToNormal() {
NightNight.theme = .normal
}
@objc func changeToNight() {
NightNight.theme = .night
}
@objc func changeTheme() {
if NightNight.theme == .night {
NightNight.theme = .normal
} else {
NightNight.theme = .night
}
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return MixedStatusBarStyle(normal: .default, night: .lightContent).unfold()
}
}
| mit | 0fc00ef85b679bffc15cdf82cb81fc5e | 38.214286 | 248 | 0.655738 | 4.872781 | false | false | false | false |
joeytat/Gorge | Gorge/ViewController.swift | 1 | 3689 | //
// ViewController.swift
// Gorge
//
// Created by Joey on 05/02/2017.
// Copyright © 2017 Joey. All rights reserved.
//
import UIKit
import RxSwift
class ViewController: UIViewController {
#if TRACE_RESOURCES
#if !RX_NO_MODULE
private let startResourceCount = RxSwift.Resources.total
#else
private let startResourceCount = Resources.total
#endif
#endif
var disposeBag = DisposeBag()
override func viewDidLoad() {
#if TRACE_RESOURCES
print("Number of start resources = \(Resources.total)")
#endif
}
deinit {
#if TRACE_RESOURCES
print("View controller disposed with \(Resources.total) resources")
/*
!!! This cleanup logic is adapted for example app use case. !!!
It is being used to detect memory leaks during pre release tests.
!!! In case you want to have some resource leak detection logic, the simplest
method is just printing out `RxSwift.Resources.total` periodically to output. !!!
/* add somewhere in
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
*/
_ = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.subscribe(onNext: { _ in
print("Resource count \(RxSwift.Resources.total)")
})
Most efficient way to test for memory leaks is:
* navigate to your screen and use it
* navigate back
* observe initial resource count
* navigate second time to your screen and use it
* navigate back
* observe final resource count
In case there is a difference in resource count between initial and final resource counts, there might be a memory
leak somewhere.
The reason why 2 navigations are suggested is because first navigation forces loading of lazy resources.
*/
let numberOfResourcesThatShouldRemain = startResourceCount
let mainQueue = DispatchQueue.main
/*
This first `dispatch_async` is here to compensate for CoreAnimation delay after
changing view controller hierarchy. This time is usually ~100ms on simulator and less on device.
If somebody knows more about why this delay happens, you can make a PR with explanation here.
*/
let when = DispatchTime.now() + DispatchTimeInterval.milliseconds(OSApplication.isInUITest ? 1000 : 10)
mainQueue.asyncAfter (deadline: when) {
/*
Some small additional period to clean things up. In case there were async operations fired,
they can't be cleaned up momentarily.
*/
// If this fails for you while testing, and you've been clicking fast, it's ok, just click slower,
// this is a debug build with resource tracing turned on.
//
// If this crashes when you've been clicking slowly, then it would be interesting to find out why.
// ¯\_(ツ)_/¯
assert(Resources.total <= numberOfResourcesThatShouldRemain, "Resources weren't cleaned properly, \(Resources.total) remained, \(numberOfResourcesThatShouldRemain) expected")
}
#endif
}
}
| mit | ce513a686ba102f71e52565559509734 | 39.933333 | 190 | 0.587134 | 5.693972 | false | false | false | false |
kristinathai/watchOS3Counter | Counter/ViewController.swift | 1 | 2336 | //
// ViewController.swift
// Counter
//
// Created by Thai, Kristina on 9/18/16.
//
//
import UIKit
import WatchConnectivity
class ViewController: UIViewController {
@IBOutlet var tableView: UITableView!
var counterData = [Int]()
private let session: WCSession? = WCSession.isSupported() ? WCSession.default : nil
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureWCSession()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
configureWCSession()
}
private func configureWCSession() {
session?.delegate = self;
session?.activate()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.title = "Count List"
self.tableView.dataSource = self
}
}
extension ViewController: WCSessionDelegate {
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
//Dispatch to main thread to update the UI instantaneously (otherwise, takes a little while)
DispatchQueue.main.async {
if let counterValue = message["counterValue"] as? Int {
self.counterData.append(counterValue)
self.tableView.reloadData()
}
}
}
//Handlers in case the watch and phone watch connectivity session becomes disconnected
func sessionDidDeactivate(_ session: WCSession) {}
func sessionDidBecomeInactive(_ session: WCSession) {}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return counterData.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "CounterCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
let counterValueString = String(counterData[indexPath.row])
cell?.textLabel?.text = counterValueString
return cell!
}
}
| mit | aaf4d79f3b41670aceaeea3b0013bea1 | 28.948718 | 125 | 0.666952 | 5.191111 | false | false | false | false |
dreamsxin/swift | test/IRGen/abitypes.swift | 1 | 35483 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/abi %s -emit-ir | FileCheck -check-prefix=%target-cpu-%target-os %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import gadget
import Foundation
@objc protocol P1 {}
@objc protocol P2 {}
@objc protocol Work {
func doStuff(_ x: Int64)
}
// armv7s-ios: [[ARMV7S_MYRECT:%.*]] = type { float, float, float, float }
// arm64-ios: [[ARM64_MYRECT:%.*]] = type { float, float, float, float }
// arm64-tvos: [[ARM64_MYRECT:%.*]] = type { float, float, float, float }
// armv7k-watchos: [[ARMV7K_MYRECT:%.*]] = type { float, float, float, float }
class Foo {
// x86_64-macosx: define hidden void @_TFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: define hidden { <2 x float>, <2 x float> } @_TToFC8abitypes3Foo3bar{{.*}}(i8*, i8*) unnamed_addr {{.*}} {
// x86_64-ios: define hidden void @_TFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// x86_64-ios: define hidden { <2 x float>, <2 x float> } @_TToFC8abitypes3Foo3bar{{.*}}(i8*, i8*) unnamed_addr {{.*}} {
// i386-ios: define hidden void @_TFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// i386-ios: define hidden void @_TToFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
// armv7-ios: define hidden void @_TFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// armv7-ios: define hidden void @_TToFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
// armv7s-ios: define hidden void @_TFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// armv7s-ios: define hidden void @_TToFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
// arm64-ios: define hidden void @_TFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// arm64-ios: define hidden [[ARM64_MYRECT]] @_TToFC8abitypes3Foo3bar{{.*}}(i8*, i8*) unnamed_addr {{.*}} {
// x86_64-tvos: define hidden void @_TFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// x86_64-tvos: define hidden { <2 x float>, <2 x float> } @_TToFC8abitypes3Foo3bar{{.*}}(i8*, i8*) unnamed_addr {{.*}} {
// arm64-tvos: define hidden void @_TFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// arm64-tvos: define hidden [[ARM64_MYRECT]] @_TToFC8abitypes3Foo3bar{{.*}}(i8*, i8*) unnamed_addr {{.*}} {
// i386-watchos: define hidden void @_TFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// i386-watchos: define hidden void @_TToFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
// armv7k-watchos: define hidden void @_TFC8abitypes3Foo3bar{{.*}}(%VSC6MyRect* noalias nocapture sret, %C8abitypes3Foo*) {{.*}} {
// armv7k-watchos: define hidden [[ARMV7K_MYRECT]] @_TToFC8abitypes3Foo3bar{{.*}}(i8*, i8*) unnamed_addr {{.*}} {
dynamic func bar() -> MyRect {
return MyRect(x: 1, y: 2, width: 3, height: 4)
}
// x86_64-macosx: define hidden double @_TFC8abitypes3Foo14getXFromNSRect{{.*}}(%VSC6CGRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: define hidden double @_TToFC8abitypes3Foo14getXFromNSRect{{.*}}(i8*, i8*, %VSC6CGRect* byval align 8) unnamed_addr {{.*}} {
// armv7-ios: define hidden double @_TFC8abitypes3Foo14getXFromNSRect{{.*}}(%VSC6CGRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// armv7-ios: define hidden double @_TToFC8abitypes3Foo14getXFromNSRect{{.*}}(i8*, i8*, [4 x i32]) unnamed_addr {{.*}} {
// armv7s-ios: define hidden double @_TFC8abitypes3Foo14getXFromNSRect{{.*}}(%VSC6CGRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// armv7s-ios: define hidden double @_TToFC8abitypes3Foo14getXFromNSRect{{.*}}(i8*, i8*, [4 x i32]) unnamed_addr {{.*}} {
// armv7k-watchos: define hidden double @_TFC8abitypes3Foo14getXFromNSRect{{.*}}(%VSC6CGRect* noalias nocapture dereferenceable(16), %C8abitypes3Foo*) {{.*}} {
// armv7k-watchos: define hidden double @_TToFC8abitypes3Foo14getXFromNSRect{{.*}}(i8*, i8*, [4 x float]) unnamed_addr {{.*}} {
dynamic func getXFromNSRect(_ r: NSRect) -> Double {
return Double(r.origin.x)
}
// x86_64-macosx: define hidden float @_TFC8abitypes3Foo12getXFromRect{{.*}}(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: define hidden float @_TToFC8abitypes3Foo12getXFromRect{{.*}}(i8*, i8*, <2 x float>, <2 x float>) unnamed_addr {{.*}} {
// armv7-ios: define hidden float @_TFC8abitypes3Foo12getXFromRect{{.*}}(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// armv7-ios: define hidden float @_TToFC8abitypes3Foo12getXFromRect{{.*}}(i8*, i8*, [4 x i32]) unnamed_addr {{.*}} {
// armv7s-ios: define hidden float @_TFC8abitypes3Foo12getXFromRect{{.*}}(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// armv7s-ios: define hidden float @_TToFC8abitypes3Foo12getXFromRect{{.*}}(i8*, i8*, [4 x i32]) unnamed_addr {{.*}} {
// armv7k-watchos: define hidden float @_TFC8abitypes3Foo12getXFromRect{{.*}}(%VSC6MyRect* noalias nocapture dereferenceable(16), %C8abitypes3Foo*) {{.*}} {
// armv7k-watchos: define hidden float @_TToFC8abitypes3Foo12getXFromRect{{.*}}(i8*, i8*, [4 x float]) unnamed_addr {{.*}} {
dynamic func getXFromRect(_ r: MyRect) -> Float {
return r.x
}
// Call from Swift entrypoint with exploded Rect to @objc entrypoint
// with unexploded ABI-coerced type.
// x86_64-macosx: define hidden float @_TFC8abitypes3Foo17getXFromRectSwift{{.*}}(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), [[SELF:%.*]]*) {{.*}} {
// x86_64-macosx: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// x86_64-macosx: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 8
// x86_64-macosx: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to { <2 x float>, <2 x float> }*
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 0
// x86_64-macosx: [[FIRST_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]]
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 1
// x86_64-macosx: [[SECOND_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]]
// x86_64-macosx: [[SELFCAST:%.*]] = bitcast [[SELF]]* %1 to i8*
// x86_64-macosx: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, <2 x float>, <2 x float>)*)(i8* [[SELFCAST]], i8* [[SEL]], <2 x float> [[FIRST_HALF]], <2 x float> [[SECOND_HALF]])
// armv7-ios: define hidden float @_TFC8abitypes3Foo17getXFromRectSwift{{.*}}(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), [[SELF:%.*]]*) {{.*}} {
// armv7-ios: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7-ios: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4
// armv7-ios: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x i32]*
// armv7-ios: [[LOADED:%.*]] = load [4 x i32], [4 x i32]* [[CAST]]
// armv7-ios: [[SELFCAST:%.*]] = bitcast [[SELF]]* %1 to i8*
// armv7-ios: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x i32])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x i32] [[LOADED]])
// armv7s-ios: define hidden float @_TFC8abitypes3Foo17getXFromRectSwift{{.*}}(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), [[SELF:%.*]]*) {{.*}} {
// armv7s-ios: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7s-ios: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4
// armv7s-ios: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x i32]*
// armv7s-ios: [[LOADED:%.*]] = load [4 x i32], [4 x i32]* [[CAST]]
// armv7s-ios: [[SELFCAST:%.*]] = bitcast [[SELF]]* %1 to i8*
// armv7s-ios: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x i32])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x i32] [[LOADED]])
// armv7k-watchos: define hidden float @_TFC8abitypes3Foo17getXFromRectSwift{{.*}}(%VSC6MyRect* noalias nocapture dereferenceable(16), [[SELF:%.*]]*) {{.*}} {
// armv7k-watchos: [[COERCED:%.*]] = alloca [[MYRECT:%.*MyRect.*]], align 4
// armv7k-watchos: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(getXFromRect:)", align 4
// armv7k-watchos: [[CAST:%.*]] = bitcast [[MYRECT]]* [[COERCED]] to [4 x float]*
// armv7k-watchos: [[LOADED:%.*]] = load [4 x float], [4 x float]* [[CAST]]
// armv7k-watchos: [[SELFCAST:%.*]] = bitcast [[SELF]]* %1 to i8*
// armv7k-watchos: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, [4 x float])*)(i8* [[SELFCAST]], i8* [[SEL]], [4 x float] [[LOADED]])
func getXFromRectSwift(_ r: MyRect) -> Float {
return getXFromRect(r)
}
// Ensure that MyRect is passed as an indirect-byval on x86_64 because we run out of registers for direct arguments
// x86_64-macosx: define hidden float @_TToFC8abitypes3Foo25getXFromRectIndirectByVal{{.*}}(i8*, i8*, float, float, float, float, float, float, float, %VSC6MyRect* byval align 4) unnamed_addr {{.*}} {
dynamic func getXFromRectIndirectByVal(_: Float, second _: Float,
third _: Float, fourth _: Float,
fifth _: Float, sixth _: Float,
seventh _: Float, withRect r: MyRect)
-> Float {
return r.x
}
// Make sure the caller-side from Swift also uses indirect-byval for the argument
// x86_64-macosx: define hidden float @_TFC8abitypes3Foo25getXFromRectIndirectSwift{{.*}}(%VSC6MyRect* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
func getXFromRectIndirectSwift(_ r: MyRect) -> Float {
let f : Float = 1.0
// x86_64-macosx: [[TEMP:%.*]] = alloca [[TEMPTYPE:%.*]], align 4
// x86_64-macosx: [[RESULT:%.*]] = call float bitcast (void ()* @objc_msgSend to float (i8*, i8*, float, float, float, float, float, float, float, [[TEMPTYPE]]*)*)(i8* %{{.*}}, i8* %{{.*}}, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, [[TEMPTYPE]]* byval align 4 [[TEMP]])
// x86_64-macosx: ret float [[RESULT]]
return getXFromRectIndirectByVal(f, second: f, third: f, fourth: f, fifth: f, sixth: f, seventh: f, withRect: r);
}
// x86_64 returns an HA of four floats directly in two <2 x float>
// x86_64-macosx: define hidden float @_TFC8abitypes3Foo4barc{{.*}}(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: load i8*, i8** @"\01L_selector(newRect)", align 8
// x86_64-macosx: [[RESULT:%.*]] = call { <2 x float>, <2 x float> } bitcast (void ()* @objc_msgSend
// x86_64-macosx: store { <2 x float>, <2 x float> } [[RESULT]]
// x86_64-macosx: [[CAST:%.*]] = bitcast { <2 x float>, <2 x float> }*
// x86_64-macosx: load { float, float, float, float }, { float, float, float, float }* [[CAST]]
// x86_64-macosx: ret float
//
// armv7 returns an HA of four floats indirectly
// armv7-ios: define hidden float @_TFC8abitypes3Foo4barc{{.*}}(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// armv7-ios: [[RESULT:%.*]] = alloca [[RECTTYPE:%.*MyRect.*]], align 4
// armv7-ios: load i8*, i8** @"\01L_selector(newRect)", align 4
// armv7-ios: call void bitcast (void ()* @objc_msgSend_stret to void ([[RECTTYPE]]*, [[RECEIVER:.*]]*, i8*)*)([[RECTTYPE]]* noalias nocapture sret %call.aggresult
// armv7-ios: [[GEP1:%.*]] = getelementptr inbounds [[RECTTYPE]], [[RECTTYPE]]* [[RESULT]], i32 0, i32 1
// armv7-ios: [[GEP2:%.*]] = getelementptr inbounds {{.*}}, {{.*}}* [[GEP1]], i32 0, i32 0
// armv7-ios: [[RETVAL:%.*]] = load float, float* [[GEP2]], align 4
// armv7-ios: ret float [[RETVAL]]
//
// armv7s returns an HA of four floats indirectly
// armv7s-ios: define hidden float @_TFC8abitypes3Foo4barc{{.*}}(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// armv7s-ios: [[RESULT:%.*]] = alloca [[RECTTYPE:%.*MyRect.*]], align 4
// armv7s-ios: load i8*, i8** @"\01L_selector(newRect)", align 4
// armv7s-ios: call void bitcast (void ()* @objc_msgSend_stret to void ([[RECTTYPE]]*, [[RECEIVER:.*]]*, i8*)*)([[RECTTYPE]]* noalias nocapture sret %call.aggresult
// armv7s-ios: [[GEP1:%.*]] = getelementptr inbounds [[RECTTYPE]], [[RECTTYPE]]* [[RESULT]], i32 0, i32 1
// armv7s-ios: [[GEP2:%.*]] = getelementptr inbounds {{.*}}, {{.*}}* [[GEP1]], i32 0, i32 0
// armv7s-ios: [[RETVAL:%.*]] = load float, float* [[GEP2]], align 4
// armv7s-ios: ret float [[RETVAL]]
//
// armv7k returns an HA of four floats directly
// armv7k-watchos: define hidden float @_TFC8abitypes3Foo4barc{{.*}}(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// armv7k-watchos: load i8*, i8** @"\01L_selector(newRect)", align 4
// armv7k-watchos: [[RESULT:%.*]] = call [[ARMV7K_MYRECT]] bitcast (void ()* @objc_msgSend
// armv7k-watchos: store [[ARMV7K_MYRECT]] [[RESULT]]
// armv7k-watchos: [[CAST:%.*]] = bitcast [[ARMV7K_MYRECT]]*
// armv7k-watchos: load { float, float, float, float }, { float, float, float, float }* [[CAST]]
// armv7k-watchos: ret float
func barc(_ p: StructReturns) -> Float {
return p.newRect().y
}
// x86_64-macosx: define hidden { double, double, double } @_TFC8abitypes3Foo3baz{{.*}}(%C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: define hidden void @_TToFC8abitypes3Foo3baz{{.*}}(%VSC4Trio* noalias nocapture sret, i8*, i8*) unnamed_addr {{.*}} {
dynamic func baz() -> Trio {
return Trio(i: 1.0, j: 2.0, k: 3.0)
}
// x86_64-macosx: define hidden double @_TFC8abitypes3Foo4bazc{{.*}}(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: load i8*, i8** @"\01L_selector(newTrio)", align 8
// x86_64-macosx: [[CAST:%[0-9]+]] = bitcast {{%.*}}* %0
// x86_64-macosx: call void bitcast (void ()* @objc_msgSend_stret to void (%VSC4Trio*, [[OPAQUE:.*]]*, i8*)*)
func bazc(_ p: StructReturns) -> Double {
return p.newTrio().j
}
// x86_64-macosx: define hidden { i32, i32 } @_TFC8abitypes3Foo7getpair{{.*}}(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: [[RESULT:%.*]] = call i64 bitcast (void ()* @objc_msgSend to i64 ([[OPAQUE:.*]]*, i8*)*)
// x86_64-macosx: store i64 [[RESULT]]
// x86_64-macosx: [[CAST:%.*]] = bitcast i64* {{%.*}} to { i32, i32 }*
// x86_64-macosx: load { i32, i32 }, { i32, i32 }* [[CAST]]
// x86_64-macosx: ret { i32, i32 }
func getpair(_ p: StructReturns) -> IntPair {
return p.newPair()
}
// x86_64-macosx: define hidden i64 @_TToFC8abitypes3Foo8takepair{{.*}}(i8*, i8*, i64) unnamed_addr {{.*}} {
dynamic func takepair(_ p: IntPair) -> IntPair {
return p
}
// x86_64-macosx: define hidden { i32, i32 } @_TFC8abitypes3Foo9getnested{{.*}}(%CSo13StructReturns*, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: call i64 bitcast (void ()* @objc_msgSend to i64 ([[OPAQUE:.*]]*, i8*)*)
// x86_64-macosx-NEXT: bitcast
// x86_64-macosx-NEXT: llvm.lifetime.start
// x86_64-macosx-NEXT: store i64
// x86_64-macosx-NEXT: bitcast i64* {{[^ ]*}} to { i32, i32 }*
// x86_64-macosx-NEXT: load { i32, i32 }, { i32, i32 }*
// x86_64-macosx-NEXT: bitcast
// x86_64-macosx-NEXT: llvm.lifetime.end
// x86_64-macosx: ret { i32, i32 }
func getnested(_ p: StructReturns) -> NestedInts {
return p.newNestedInts()
}
// x86_64-macosx: define hidden i8* @_TToFC8abitypes3Foo9copyClass{{.*}}(i8*, i8*, i8*) unnamed_addr {{.*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call [[TYPE:%.*]]* @_TFC8abitypes3Foo9copyClass
// x86_64-macosx: [[T0:%.*]] = phi [[TYPE]]* [ [[VALUE]],
// x86_64-macosx: [[T1:%.*]] = bitcast [[TYPE]]* [[T0]] to [[OBJC:%objc_class]]*
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[OBJC]]* [[T1]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
dynamic func copyClass(_ a: AnyClass) -> AnyClass {
return a
}
// x86_64-macosx: define hidden i8* @_TToFC8abitypes3Foo9copyProto{{.*}}(i8*, i8*, i8*) unnamed_addr {{.*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call [[TYPE:%.*]] @_TFC8abitypes3Foo9copyProt
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[TYPE]] [[VALUE]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
dynamic func copyProto(_ a: AnyObject) -> AnyObject {
return a
}
// x86_64-macosx: define hidden i8* @_TToFC8abitypes3Foo13copyProtoComp{{.*}}(i8*, i8*, i8*) unnamed_addr {{.*}} {
// x86_64-macosx: [[VALUE:%[0-9]+]] = call [[TYPE:%.*]] @_TFC8abitypes3Foo13copyProtoComp
// x86_64-macosx: [[RESULT:%[0-9]+]] = bitcast [[TYPE]] [[VALUE]] to i8*
// x86_64-macosx: ret i8* [[RESULT]]
dynamic func copyProtoComp(_ a: protocol<P1, P2>) -> protocol<P1, P2> {
return a
}
// x86_64-macosx: define hidden i1 @_TFC8abitypes3Foo6negate{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: define hidden signext i8 @_TToFC8abitypes3Foo6negate{{.*}}(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
// x86_64-macosx: [[R1:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBool
// x86_64-macosx: [[R2:%[0-9]+]] = call i1 @_TFC8abitypes3Foo6negate
// x86_64-macosx: [[R3:%[0-9]+]] = call i8 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 [[R2]]
// x86_64-macosx: ret i8 [[R3]]
//
// x86_64-ios-fixme: define hidden i1 @_TFC8abitypes3Foo6negate{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-ios-fixme: define internal zeroext i1 @_TToFC8abitypes3Foo6negate{{.*}}
// x86_64-ios-fixme: [[R1:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBoolFT1xVS_8ObjCBool_Sb(i1 %2)
// x86_64-ios-fixme: [[R2:%[0-9]+]] = call i1 @_TFC8abitypes3Foo6negate{{.*}}(i1 [[R1]]
// x86_64-ios-fixme: [[R3:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertBoolToObjCBoolFT1xSb_VS_8ObjCBool(i1 [[R2]])
// x86_64-ios-fixme: ret i1 [[R3]]
//
// armv7-ios-fixme: define hidden i1 @_TFC8abitypes3Foo6negate{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// armv7-ios-fixme: define internal signext i8 @_TToFC8abitypes3Foo6negate{{.*}}(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
// armv7-ios-fixme: [[R1:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBoolFT1xVS_8ObjCBool_Sb
// armv7-ios-fixme: [[R2:%[0-9]+]] = call i1 @_TFC8abitypes3Foo6negate{{.*}}(i1 [[R1]]
// armv7-ios-fixme: [[R3:%[0-9]+]] = call i8 @_TF10ObjectiveC22_convertBoolToObjCBoolFT1xSb_VS_8ObjCBool(i1 [[R2]]
// armv7-ios-fixme: ret i8 [[R3]]
//
// armv7s-ios-fixme: define hidden i1 @_TFC8abitypes3Foo6negate{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// armv7s-ios-fixme: define internal signext i8 @_TToFC8abitypes3Foo6negate{{.*}}(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
// armv7s-ios-fixme: [[R1:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBoolFT1xVS_8ObjCBool_Sb
// armv7s-ios-fixme: [[R2:%[0-9]+]] = call i1 @_TFC8abitypes3Foo6negate{{.*}}(i1 [[R1]]
// armv7s-ios-fixme: [[R3:%[0-9]+]] = call i8 @_TF10ObjectiveC22_convertBoolToObjCBoolFT1xSb_VS_8ObjCBool(i1 [[R2]]
// armv7s-ios-fixme: ret i8 [[R3]]
//
// arm64-ios-fixme: define hidden i1 @_TFC8abitypes3Foo6negate{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// arm64-ios-fixme: define internal zeroext i1 @_TToFC8abitypes3Foo6negate
// arm64-ios-fixme: [[R2:%[0-9]+]] = call i1 @_TFC8abitypes3Foo6negate
// arm64-ios-fixme: ret i1 [[R2]]
//
// i386-ios-fixme: define hidden i1 @_TFC8abitypes3Foo6negate{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// i386-ios-fixme: define internal signext i8 @_TToFC8abitypes3Foo6negate{{.*}}(i8*, i8*, i8 signext) unnamed_addr {{.*}} {
// i386-ios-fixme: [[R1:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBool
// i386-ios-fixme: [[R2:%[0-9]+]] = call i1 @_TFC8abitypes3Foo6negate{{.*}}(i1 [[R1]]
// i386-ios-fixme: [[R3:%[0-9]+]] = call i8 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 [[R2]]
// i386-ios-fixme: ret i8 [[R3]]
//
// x86_64-tvos-fixme: define hidden i1 @_TFC8abitypes3Foo6negate{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-tvos-fixme: define internal zeroext i1 @_TToFC8abitypes3Foo6negate{{.*}}
// x86_64-tvos-fixme: [[R1:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBoolFT1xVS_8ObjCBool_Sb(i1 %2)
// x86_64-tvos-fixme: [[R2:%[0-9]+]] = call i1 @_TFC8abitypes3Foo6negate{{.*}}(i1 [[R1]]
// x86_64-tvos-fixme: [[R3:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertBoolToObjCBoolFT1xSb_VS_8ObjCBool(i1 [[R2]])
// x86_64-tvos-fixme: ret i1 [[R3]]
//
// arm64-tvos-fixme: define hidden i1 @_TFC8abitypes3Foo6negate{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// arm64-tvos-fixme: define internal zeroext i1 @_TToFC8abitypes3Foo6negate
// arm64-tvos-fixme: [[R2:%[0-9]+]] = call i1 @_TFC8abitypes3Foo6negate
// arm64-tvos-fixme: ret i1 [[R2]]
// i386-watchos: define hidden i1 @_TFC8abitypes3Foo6negate{{.*}}(i1, %C8abitypes3Foo*)
// i386-watchos: define hidden zeroext i1 @_TToFC8abitypes3Foo6negate{{.*}}
// i386-watchos: [[R1:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBoolFVS_8ObjCBoolSb(i1 %2)
// i386-watchos: [[R2:%[0-9]+]] = call i1 @_TFC8abitypes3Foo6negate{{.*}}(i1 [[R1]]
// i386-watchos: [[R3:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertBoolToObjCBoolFSbVS_8ObjCBool(i1 [[R2]])
// i386-watchos: ret i1 [[R3]]
dynamic func negate(_ b: Bool) -> Bool {
return !b
}
// x86_64-macosx: define hidden i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 %0)
// x86_64-macosx: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// x86_64-macosx: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// x86_64-macosx: [[TOBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBool{{.*}}(i8 [[NEG]])
// x86_64-macosx: ret i1 [[TOBOOL]]
//
// x86_64-macosx: define hidden signext i8 @_TToFC8abitypes3Foo7negate2{{.*}}(i8*, i8*, i8 signext)
// x86_64-macosx: [[TOBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBool
// x86_64-macosx: [[NEG:%[0-9]+]] = call i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1 [[TOBOOL]]
// x86_64-macosx: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 [[NEG]])
// x86_64-macosx: ret i8 [[TOOBJCBOOL]]
//
// x86_64-ios: define hidden i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// x86_64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// x86_64-ios: ret i1 [[NEG]]
//
// x86_64-ios: define hidden zeroext i1 @_TToFC8abitypes3Foo7negate2{{.*}}(i8*, i8*, i1 zeroext)
// x86_64-ios: [[NEG:%[0-9]+]] = call i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1
// x86_64-ios: [[TOOBJCBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 [[NEG]])
// x86_64-ios: ret i1 [[TOOBJCBOOL]]
//
// armv7-ios: define hidden i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// armv7-ios: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 %0)
// armv7-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// armv7-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// armv7-ios: [[TOBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBool{{.*}}(i8 [[NEG]])
// armv7-ios: ret i1 [[TOBOOL]]
//
// armv7-ios: define hidden signext i8 @_TToFC8abitypes3Foo7negate2{{.*}}(i8*, i8*, i8 signext)
// armv7-ios: [[TOBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBool
// armv7-ios: [[NEG:%[0-9]+]] = call i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1 [[TOBOOL]]
// armv7-ios: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 [[NEG]])
// armv7-ios: ret i8 [[TOOBJCBOOL]]
//
// armv7s-ios: define hidden i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// armv7s-ios: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 %0)
// armv7s-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// armv7s-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// armv7s-ios: [[TOBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBool{{.*}}(i8 [[NEG]])
// armv7s-ios: ret i1 [[TOBOOL]]
//
// armv7s-ios: define hidden signext i8 @_TToFC8abitypes3Foo7negate2{{.*}}(i8*, i8*, i8 signext)
// armv7s-ios: [[TOBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBool
// armv7s-ios: [[NEG:%[0-9]+]] = call i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1 [[TOBOOL]]
// armv7s-ios: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 [[NEG]])
// armv7s-ios: ret i8 [[TOOBJCBOOL]]
//
// arm64-ios: define hidden i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// arm64-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// arm64-ios: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// arm64-ios: ret i1 [[NEG]]
//
// arm64-ios: define hidden zeroext i1 @_TToFC8abitypes3Foo7negate2{{.*}}(i8*, i8*, i1 zeroext)
// arm64-ios: [[NEG:%[0-9]+]] = call i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1
// arm64-ios: [[TOOBJCBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 [[NEG]])
// arm64-ios: ret i1 [[TOOBJCBOOL]]
//
// i386-ios: define hidden i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// i386-ios: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 %0)
// i386-ios: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// i386-ios: [[NEG:%[0-9]+]] = call signext i8 bitcast (void ()* @objc_msgSend to i8 ([[RECEIVER:.*]]*, i8*, i8)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i8 signext [[TOOBJCBOOL]])
// i386-ios: [[TOBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBool{{.*}}(i8 [[NEG]])
// i386-ios: ret i1 [[TOBOOL]]
//
// i386-ios: define hidden signext i8 @_TToFC8abitypes3Foo7negate2{{.*}}(i8*, i8*, i8 signext)
// i386-ios: [[TOBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertObjCBoolToBool
// i386-ios: [[NEG:%[0-9]+]] = call i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1 [[TOBOOL]]
// i386-ios: [[TOOBJCBOOL:%[0-9]+]] = call i8 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 [[NEG]])
// i386-ios: ret i8 [[TOOBJCBOOL]]
//
// x86_64-tvos: define hidden i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// x86_64-tvos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// x86_64-tvos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// x86_64-tvos: ret i1 [[NEG]]
//
// x86_64-tvos: define hidden zeroext i1 @_TToFC8abitypes3Foo7negate2{{.*}}(i8*, i8*, i1 zeroext)
// x86_64-tvos: [[NEG:%[0-9]+]] = call i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1
// x86_64-tvos: [[TOOBJCBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 [[NEG]])
// x86_64-tvos: ret i1 [[TOOBJCBOOL]]
//
// arm64-tvos: define hidden i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// arm64-tvos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 8
// arm64-tvos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// arm64-tvos: ret i1 [[NEG]]
//
// arm64-tvos: define hidden zeroext i1 @_TToFC8abitypes3Foo7negate2{{.*}}(i8*, i8*, i1 zeroext)
// arm64-tvos: [[NEG:%[0-9]+]] = call i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1
// arm64-tvos: [[TOOBJCBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 [[NEG]])
// arm64-tvos: ret i1 [[TOOBJCBOOL]]
// i386-watchos: define hidden i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// i386-watchos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// i386-watchos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// i386-watchos: ret i1 [[NEG]]
//
// i386-watchos: define hidden zeroext i1 @_TToFC8abitypes3Foo7negate2{{.*}}(i8*, i8*, i1 zeroext)
// i386-watchos: [[NEG:%[0-9]+]] = call i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1
// i386-watchos: [[TOOBJCBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 [[NEG]])
// i386-watchos: ret i1 [[TOOBJCBOOL]]
//
// armv7k-watchos: define hidden i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1, %C8abitypes3Foo*) {{.*}} {
// armv7k-watchos: [[SEL:%[0-9]+]] = load i8*, i8** @"\01L_selector(negate:)", align 4
// armv7k-watchos: [[NEG:%[0-9]+]] = call zeroext i1 bitcast (void ()* @objc_msgSend to i1 ([[RECEIVER:.*]]*, i8*, i1)*)([[RECEIVER]]* {{%[0-9]+}}, i8* [[SEL]], i1 zeroext %0)
// armv7k-watchos: ret i1 [[NEG]]
//
// armv7k-watchos: define hidden zeroext i1 @_TToFC8abitypes3Foo7negate2{{.*}}(i8*, i8*, i1 zeroext)
// armv7k-watchos: [[NEG:%[0-9]+]] = call i1 @_TFC8abitypes3Foo7negate2{{.*}}(i1
// armv7k-watchos: [[TOOBJCBOOL:%[0-9]+]] = call i1 @_TF10ObjectiveC22_convertBoolToObjCBool{{.*}}(i1 [[NEG]])
// armv7k-watchos: ret i1 [[TOOBJCBOOL]]
//
dynamic func negate2(_ b: Bool) -> Bool {
var g = Gadget()
return g.negate(b)
}
// x86_64-macosx: define hidden i32* @_TToFC8abitypes3Foo24copyUnsafeMutablePointer{{.*}}(i8*, i8*, i32*) unnamed_addr {{.*}} {
dynamic func copyUnsafeMutablePointer(_ p: UnsafeMutablePointer<Int32>) -> UnsafeMutablePointer<Int32> {
return p
}
// x86_64-macosx: define hidden i64 @_TToFC8abitypes3Foo17returnNSEnumValue{{.*}}(i8*, i8*) unnamed_addr {{.*}} {
dynamic func returnNSEnumValue() -> NSByteCountFormatterCountStyle {
return .file
}
// x86_64-macosx: define hidden zeroext i16 @_TToFC8abitypes3Foo20returnOtherEnumValue{{.*}}(i8*, i8*, i16 zeroext) unnamed_addr {{.*}} {
dynamic func returnOtherEnumValue(_ choice: ChooseTo) -> ChooseTo {
switch choice {
case .takeIt: return .leaveIt
case .leaveIt: return .takeIt
}
}
// x86_64-macosx: define hidden i32 @_TFC8abitypes3Foo10getRawEnum{{.*}}(%C8abitypes3Foo*) {{.*}} {
// x86_64-macosx: define hidden i32 @_TToFC8abitypes3Foo10getRawEnum{{.*}}(i8*, i8*) unnamed_addr {{.*}} {
dynamic func getRawEnum() -> RawEnum {
return Intergalactic
}
var work : Work
init (work: Work) {
self.work = work
}
// x86_64-macosx: define hidden void @_TToFC8abitypes3Foo13testArchetypef{{.*}}(i8*, i8*, i8*) unnamed_addr {{.*}} {
dynamic func testArchetype(_ work: Work) {
work.doStuff(1)
// x86_64-macosx: [[OBJCPTR:%.*]] = bitcast i8* %2 to %objc_object*
// x86_64-macosx: call void @_TFC8abitypes3Foo13testArchetype{{.*}}(%objc_object* [[OBJCPTR]], %C8abitypes3Foo* %{{.*}})
}
dynamic func foo(_ x: @convention(block) (Int) -> Int) -> Int {
// FIXME: calling blocks is currently unimplemented
// return x(5)
return 1
}
// x86_64-macosx: define hidden void @_TFC8abitypes3Foo20testGenericTypeParam{{.*}}(%objc_object*, %swift.type* %T, %C8abitypes3Foo*) {{.*}} {
func testGenericTypeParam<T: Pasta>(_ x: T) {
// x86_64-macosx: [[CAST:%.*]] = bitcast %objc_object* %0 to i8*
// x86_64-macosx: call void bitcast (void ()* @objc_msgSend to void (i8*, i8*)*)(i8* [[CAST]], i8* %{{.*}})
x.alDente()
}
// arm64-ios: define hidden void @_TFC8abitypes3Foo14callJustReturn{{.*}}(%VSC9BigStruct* noalias nocapture sret, %CSo13StructReturns*, %VSC9BigStruct* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// arm64-ios: define hidden void @_TToFC8abitypes3Foo14callJustReturn{{.*}}(%VSC9BigStruct* noalias nocapture sret, i8*, i8*, [[OPAQUE:.*]]*, %VSC9BigStruct*) unnamed_addr {{.*}} {
//
// arm64-tvos: define hidden void @_TFC8abitypes3Foo14callJustReturn{{.*}}(%VSC9BigStruct* noalias nocapture sret, %CSo13StructReturns*, %VSC9BigStruct* noalias nocapture dereferenceable({{.*}}), %C8abitypes3Foo*) {{.*}} {
// arm64-tvos: define hidden void @_TToFC8abitypes3Foo14callJustReturn{{.*}}(%VSC9BigStruct* noalias nocapture sret, i8*, i8*, [[OPAQUE:.*]]*, %VSC9BigStruct*) unnamed_addr {{.*}} {
dynamic func callJustReturn(_ r: StructReturns, with v: BigStruct) -> BigStruct {
return r.justReturn(v)
}
// Test that the makeOne() that we generate somewhere below doesn't
// use arm_aapcscc for armv7.
func callInline() -> Float {
return makeOne(3,5).second
}
}
// armv7-ios: define internal void @makeOne(%struct.One* noalias sret %agg.result, float %f, float %s)
// armv7s-ios: define internal void @makeOne(%struct.One* noalias sret %agg.result, float %f, float %s)
// armv7k-watchos: define internal %struct.One @makeOne(float %f, float %s)
// rdar://17631440 - Expand direct arguments that are coerced to aggregates.
// x86_64-macosx: define{{( protected)?}} float @_TF8abitypes13testInlineAggFVSC6MyRectSf(%VSC6MyRect* noalias nocapture dereferenceable({{.*}})) {{.*}} {
// x86_64-macosx: [[COERCED:%.*]] = alloca %VSC6MyRect, align 4
// x86_64-macosx: store float %
// x86_64-macosx: store float %
// x86_64-macosx: store float %
// x86_64-macosx: store float %
// x86_64-macosx: [[CAST:%.*]] = bitcast %VSC6MyRect* [[COERCED]] to { <2 x float>, <2 x float> }*
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 0
// x86_64-macosx: [[FIRST_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]], align 4
// x86_64-macosx: [[T0:%.*]] = getelementptr inbounds { <2 x float>, <2 x float> }, { <2 x float>, <2 x float> }* [[CAST]], i32 0, i32 1
// x86_64-macosx: [[SECOND_HALF:%.*]] = load <2 x float>, <2 x float>* [[T0]], align 4
// x86_64-macosx: [[RESULT:%.*]] = call float @MyRect_Area(<2 x float> [[FIRST_HALF]], <2 x float> [[SECOND_HALF]])
// x86_64-macosx: ret float [[RESULT]]
public func testInlineAgg(_ rect: MyRect) -> Float {
return MyRect_Area(rect)
}
| apache-2.0 | 7a1f40b2cad83d3e891d8c03449924bc | 69.683267 | 371 | 0.612547 | 2.979011 | false | false | false | false |
kaushaldeo/Olympics | Olympics/ViewControllers/KDCountriesViewController.swift | 1 | 12113 | //
// KDCountriesViewController.swift
// Olympics
//
// Created by Kaushal Deo on 6/10/16.
// Copyright © 2016 Scorpion Inc. All rights reserved.
//
import UIKit
import CoreData
import Firebase
class KDCountriesViewController: UITableViewController, NSFetchedResultsControllerDelegate, UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
lazy var searchController: UISearchController = {
var searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.delegate = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.sizeToFit()
searchController.searchBar.tintColor = UIColor.whiteColor()
searchController.searchBar.delegate = self // so we can monitor text changes + others
/*
Search is now just presenting a view controller. As such, normal view controller
presentation semantics apply. Namely that presentation will walk up the view controller
hierarchy until it finds the root view controller or one that defines a presentation context.
*/
return searchController
}()
var leftBarItem : UIBarButtonItem? = nil
var rigthBarItem : UIBarButtonItem? = nil
//MARK: - Private Methods
func cancelTapped(sender: AnyObject) {
self.performSegueWithIdentifier("replace", sender: nil)
}
//MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.tableView.estimatedRowHeight = 44.0
self.tableView.rowHeight = UITableViewAutomaticDimension
self.navigationController?.navigationBar.barTintColor = UIColor(red: 0, green: 103, blue: 173)
self.searchController.searchBar.barTintColor = UIColor(red: 0, green: 103, blue: 173)
let setting = NSUserDefaults.standardUserDefaults()
if let _ = setting.valueForKey("kCountry") {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(KDCountriesViewController.cancelTapped(_:)))
}
self.tableView.reloadSections(NSIndexSet(indexesInRange: NSMakeRange(0, self.tableView.numberOfSections)), withRowAnimation: .None)
self.navigationItem.titleView = self.searchController.searchBar
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style: .Plain, target: nil, action: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.fetchedResultsController.update()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! KDCountryViewCell
// Configure the cell...
let country = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Country
cell.nameLabel.text = country.name
cell.aliasLabel.text = country.alias
if let text = country.alias?.lowercaseString {
cell.iconView.image = UIImage(named: "Images/\(text).png")
}
return cell
}
override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return self.fetchedResultsController.sectionIndexTitles
}
override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return self.fetchedResultsController.sectionForSectionIndexTitle(title, atIndex: index)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let country = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Country
let setting = NSUserDefaults.standardUserDefaults()
let url = country.objectID.URIRepresentation().absoluteString
setting.setValue(url, forKey: "kCountry");
if let string = country.alias {
FIRMessaging.messaging().subscribeToTopic(string)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: - Fetched results controller
lazy var fetchedResultsController: NSFetchedResultsController = {
let context = NSManagedObjectContext.mainContext()
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Country", inManagedObjectContext: context)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true), NSSortDescriptor(key: "alias", ascending: true)]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
var fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext:context, sectionNameKeyPath: "name", cacheName: nil)
fetchedResultsController.delegate = self
fetchedResultsController.update()
return fetchedResultsController
}()
/*
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Move:
tableView.moveRowAtIndexPath(indexPath!, toIndexPath: newIndexPath!)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
*/
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
// MARK: UISearchBarDelegate
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
// MARK: UISearchResultsUpdating
func updateSearchResultsForSearchController(searchController: UISearchController) {
// Strip out all the leading and trailing spaces.
let whitespaceCharacterSet = NSCharacterSet.whitespaceCharacterSet()
let strippedString = searchController.searchBar.text!.stringByTrimmingCharactersInSet(whitespaceCharacterSet)
if strippedString.characters.count > 0 {
let predicate = NSPredicate(format: "name contains[cd] %@ OR alias contains[cd] %@", strippedString,strippedString)
self.fetchedResultsController.fetchRequest.predicate = predicate
}
else {
self.fetchedResultsController.fetchRequest.predicate = nil
}
self.fetchedResultsController.update()
self.tableView.reloadData()
}
func willPresentSearchController(searchController: UISearchController) {
self.leftBarItem = self.navigationItem.leftBarButtonItem
self.rigthBarItem = self.navigationItem.rightBarButtonItem
self.navigationItem.setLeftBarButtonItem(nil, animated: true)
self.navigationItem.setRightBarButtonItem(nil, animated: true)
}
// @available(iOS 8.0, *)
// optional public func didPresentSearchController(searchController: UISearchController)
// @available(iOS 8.0, *)
func willDismissSearchController(searchController: UISearchController) {
self.navigationItem.setLeftBarButtonItem(self.leftBarItem, animated: true)
self.navigationItem.setRightBarButtonItem(self.rigthBarItem, animated: true)
}
}
| apache-2.0 | 247a1a2ad00fbe3e82832cc4a7d95dbf | 40.910035 | 359 | 0.700297 | 5.981235 | false | false | false | false |
johannkerr/flipt-web | Sources/App/Models/Book.swift | 1 | 3612 | //
// Book.swift
// Flipt-web
//
// Created by Johann Kerr on 11/21/16.
//
//
//
// Book.swift
// flatiron-teacher-assistant
//
// Created by Johann Kerr on 11/15/16.
//
//
import Vapor
import Foundation
import Fluent
import Foundation
final class Book: Model{
var id: Node?
var bookId: String?
var exists: Bool = false
var title:String
var isbn:String
var imgUrl:String
var mainuser_id: Node?
var publisher: String
var author: String
var description: String
var publishYear: String
var lat:Double
var long:Double
var userImg: String = ""
var status: String = ""
init(title:String, isbn:String,imgUrl:String, lat:Double,long:Double, mainuser_id:Node?, publisher:String, author:String, description:String, publishYear:String){
self.bookId = UUID().uuidString
self.title = title
self.isbn = isbn
self.imgUrl = imgUrl
self.publisher = publisher
self.author = author
self.description = description
self.publishYear = publishYear
self.lat = lat
self.long = long
self.mainuser_id = mainuser_id
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
title = try node.extract("title")
isbn = try node.extract("isbn")
imgUrl = try node.extract("imgurl")
mainuser_id = try node.extract("mainuser_id")
lat = try node.extract("lat")
long = try node.extract("long")
publisher = try node.extract("publisher")
author = try node.extract("author")
description = try node.extract("description")
publishYear = try node.extract("publishyear")
userImg = try node.extract("userimg")
bookId = try node.extract("bookid")
//status = try node.extract("status")
}
func makeNode(context: Context) throws -> Node {
print("getting called")
return try Node(node: [
"id":id,
"bookId":bookId,
"title": title,
"isbn": isbn,
"imgUrl": imgUrl,
"mainuser_id": mainuser_id,
"lat":lat,
"long":long,
"publisher":publisher,
"author":author,
"description": description,
"publishYear":publishYear,
"userimg": userImg//,
//"status": status
])
}
static func prepare(_ database: Database) throws {
try database.create("books"){ books in
books.id()
books.string("bookId")
books.string("title")
books.string("isbn")
books.string("imgUrl")
books.double("lat")
books.double("long")
books.parent(MainUser.self, optional: false)
books.string("publisher")
books.string("author")
books.string("description")
books.string("publishYear")
books.string("userimg", length: 255, optional: true)
books.string("status", length: 255, optional: true)
}
}
static func revert(_ database: Database) throws{
try database.delete("books")
}
}
extension Book {
func owner() throws -> MainUser?{
return try parent(mainuser_id, nil, MainUser.self).get()
}
func findOwner() throws -> MainUser? {
if let owner = try MainUser.query().filter("id", self.mainuser_id!).first() {
return owner
}
return nil
}
}
| mit | 3cc9e72a6164d93dc46c426ca0afdeba | 23.405405 | 166 | 0.554817 | 4.2 | false | false | false | false |
SereivoanYong/Charts | Source/Charts/Renderers/BubbleRenderer.swift | 1 | 8848 | //
// BubbleRenderer.swift
// Charts
//
// Bubble chart implementation:
// Copyright 2015 Pierre-Marc Airoldi
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import UIKit
open class BubbleRenderer: BarLineScatterCandleBubbleRenderer {
open unowned let dataProvider: BubbleChartDataProvider
public init(dataProvider: BubbleChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler) {
self.dataProvider = dataProvider
super.init(animator: animator, viewPortHandler: viewPortHandler)
}
open override func drawData(context: CGContext) {
guard let bubbleData = dataProvider.bubbleData
else { return }
for set in bubbleData.dataSets as! [IBubbleChartDataSet]
{
if set.isVisible
{
drawDataSet(context: context, dataSet: set)
}
}
}
fileprivate func getShapeSize(entrySize: CGFloat, maxSize: CGFloat, reference: CGFloat, normalizeSize: Bool) -> CGFloat {
let factor = normalizeSize ? (maxSize == 0.0 ? 1.0 : sqrt(entrySize / maxSize)) : entrySize
return reference * factor
}
fileprivate var _pointBuffer = CGPoint()
fileprivate var _sizeBuffer = [CGPoint](repeating: CGPoint(), count: 2)
open func drawDataSet(context: CGContext, dataSet: IBubbleChartDataSet) {
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let valueToPixelMatrix = trans.valueToPixelMatrix
_sizeBuffer[0].x = 0.0
_sizeBuffer[0].y = 0.0
_sizeBuffer[1].x = 1.0
_sizeBuffer[1].y = 0.0
trans.pointValuesToPixel(&_sizeBuffer)
context.saveGState()
let normalizeSize = dataSet.isNormalizeSizeEnabled
// calcualte the full width of 1 step on the x-axis
let maxBubbleWidth: CGFloat = abs(_sizeBuffer[1].x - _sizeBuffer[0].x)
let maxBubbleHeight: CGFloat = abs(viewPortHandler.contentBottom - viewPortHandler.contentTop)
let referenceSize: CGFloat = min(maxBubbleHeight, maxBubbleWidth)
for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
guard let entry = dataSet.entries[j] as? BubbleEntry else { continue }
_pointBuffer.x = entry.x
_pointBuffer.y = entry.y * phaseY
_pointBuffer = _pointBuffer.applying(valueToPixelMatrix)
let shapeSize = getShapeSize(entrySize: entry.size, maxSize: dataSet.maxSize, reference: referenceSize, normalizeSize: normalizeSize)
let shapeHalf = shapeSize / 2.0
if !viewPortHandler.isInBoundsTop(_pointBuffer.y + shapeHalf)
|| !viewPortHandler.isInBoundsBottom(_pointBuffer.y - shapeHalf)
{
continue
}
if !viewPortHandler.isInBoundsLeft(_pointBuffer.x + shapeHalf)
{
continue
}
if !viewPortHandler.isInBoundsRight(_pointBuffer.x - shapeHalf)
{
break
}
let color = dataSet.color(atIndex: Int(entry.x))
let rect = CGRect(
x: _pointBuffer.x - shapeHalf,
y: _pointBuffer.y - shapeHalf,
width: shapeSize,
height: shapeSize
)
context.setFillColor(color.cgColor)
context.fillEllipse(in: rect)
}
context.restoreGState()
}
open override func drawValues(context: CGContext)
{
guard let bubbleData = dataProvider.bubbleData
else { return }
// if values are drawn
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
guard let dataSets = bubbleData.dataSets as? [IBubbleChartDataSet] else { return }
let phaseX = max(0.0, min(1.0, animator.phaseX))
let phaseY = animator.phaseY
var pt = CGPoint()
for i in 0..<dataSets.count
{
let dataSet = dataSets[i]
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let alpha = phaseX == 1 ? phaseY : phaseX
guard let formatter = dataSet.valueFormatter else { continue }
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let iconsOffset = dataSet.iconsOffset
for j in stride(from: _xBounds.min, through: _xBounds.range + _xBounds.min, by: 1)
{
guard let e = dataSet.entries[j] as? BubbleEntry else { break }
let valueTextColor = dataSet.valueTextColorAt(j).withAlphaComponent(alpha)
pt.x = e.x
pt.y = e.y * phaseY
pt = pt.applying(valueToPixelMatrix)
if !viewPortHandler.isInBoundsRight(pt.x) {
break
}
if !viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y) {
continue
}
let text = formatter.stringForValue(e.size, entry: e, dataSetIndex: i, viewPortHandler: viewPortHandler)
// Larger font for larger bubbles?
let valueFont = dataSet.valueFont
let lineHeight = valueFont.lineHeight
if dataSet.isDrawValuesEnabled
{
ChartUtils.drawText(
context: context,
text: text,
point: CGPoint(
x: pt.x,
y: pt.y - (0.5 * lineHeight)),
align: .center,
attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor])
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
ChartUtils.drawImage(context: context,
image: icon,
x: pt.x + iconsOffset.x,
y: pt.y + iconsOffset.y,
size: icon.size)
}
}
}
}
}
open override func drawExtras(context: CGContext)
{
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard let bubbleData = dataProvider.bubbleData
else { return }
context.saveGState()
let phaseY = animator.phaseY
for high in indices {
guard let dataSet = bubbleData.getDataSetByIndex(high.dataSetIndex) as? IBubbleChartDataSet, dataSet.isHighlightEnabled
else { continue }
guard let entry = dataSet.entryForXValue(high.x, closestToY: high.y) as? BubbleEntry else { continue }
if !isInBoundsX(entry: entry, dataSet: dataSet) { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
_sizeBuffer[0].x = 0.0
_sizeBuffer[0].y = 0.0
_sizeBuffer[1].x = 1.0
_sizeBuffer[1].y = 0.0
trans.pointValuesToPixel(&_sizeBuffer)
let normalizeSize = dataSet.isNormalizeSizeEnabled
// calcualte the full width of 1 step on the x-axis
let maxBubbleWidth: CGFloat = abs(_sizeBuffer[1].x - _sizeBuffer[0].x)
let maxBubbleHeight: CGFloat = abs(viewPortHandler.contentBottom - viewPortHandler.contentTop)
let referenceSize: CGFloat = min(maxBubbleHeight, maxBubbleWidth)
_pointBuffer.x = entry.x
_pointBuffer.y = entry.y * phaseY
trans.pointValueToPixel(&_pointBuffer)
let shapeSize = getShapeSize(entrySize: entry.size, maxSize: dataSet.maxSize, reference: referenceSize, normalizeSize: normalizeSize)
let shapeHalf = shapeSize / 2.0
if !viewPortHandler.isInBoundsTop(_pointBuffer.y + shapeHalf) || !viewPortHandler.isInBoundsBottom(_pointBuffer.y - shapeHalf) {
continue
}
if !viewPortHandler.isInBoundsLeft(_pointBuffer.x + shapeHalf) {
continue
}
if !viewPortHandler.isInBoundsRight(_pointBuffer.x - shapeHalf) {
break
}
let originalColor = dataSet.color(atIndex: Int(entry.x))
var h: CGFloat = 0.0
var s: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
originalColor.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
let color = UIColor(hue: h, saturation: s, brightness: b * 0.5, alpha: a)
let rect = CGRect(x: _pointBuffer.x - shapeHalf, y: _pointBuffer.y - shapeHalf, width: shapeSize, height: shapeSize)
context.setLineWidth(dataSet.highlightCircleWidth)
context.setStrokeColor(color.cgColor)
context.strokeEllipse(in: rect)
high.drawPosition = _pointBuffer
}
context.restoreGState()
}
}
| apache-2.0 | 120c447d4b477e96fa608c488bc1b54e | 31.057971 | 139 | 0.617315 | 4.706383 | false | false | false | false |
khizkhiz/swift | validation-test/compiler_crashers_fixed/00206-swift-type-subst.swift | 1 | 2096 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
typealias h
}
protocol a {
class func c()
}
class b: a {
c T) {
}
f(true as Boolean)
func f() {
({})
}
import Foundation
class Foo<T>: 1)
func c<d {
enum c {
func e
var _ = e
}
}
struct c<d : Sequence> {
var b: d
}
func a<d>() -> [c<d>] -> Bool {
return !(a)
}
protocol a {
class func c()
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
b
protocol c : b { func b
func some<S: Sequence, T where Optional<T> == S.Iterator.Element>(xs : S) -> T? {
for (mx : if let x = mx {
d: f{ ceanTy b {
clasi() {
}
}
func a(b: Int = 0) {
}
let c = a
c()
proto func b(B X<Y> : A {
funrn z({
(p: Any, q:Any) -> Any in
return p
})
}
b(a(1, a(2, 3)))
protocol A {
typealias E
}
struct B<T : As a {
typealias b = b
}
func a<T>() {f {
class func i()
}
class d: f{ class func i {}
func f() {
({})
}
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
protocol a : a {
}
import Foundation
class Foo<T>: NSObject {
var foo: T
= 1
var f1: Int -> Int = return $0
}
let succeeds: Intr _ = i() {
}
}
func c<d {
enum c {
func e
var _ = e
}
}
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
func f<T : Boolean>(b: T) {
}
f(true as Boolean)
func i(c: () -> ()) {
}
c1, f1)
func prefix(with: String) -> <T>(() -> T) -> String {
return { h):g())" }
}
.a()
}
b
func b<c-> c { class d:b class b
protocol a : a {
}
protocol a {
typealias d
typealias e = d
typealeanType>(b: T) {
}
f(true as Boolean)
func a<T>() {
enum b {
case c
}
}
func prefix(with: String) -> <T>(() -> T)> Int {
return []
}
protocol A
| apache-2.0 | 424c91070565001f5747bd20d57561b5 | 14.759398 | 87 | 0.512405 | 2.673469 | false | false | false | false |
wenfzhao/SimpleRouter | Source/Router.swift | 1 | 5922 | //
// Router.swift
//
// Created by Wen Zhao on 2/19/16.
//
import Foundation
public typealias RouteHandlerClosure = (RouteRequest) -> RouteRequest
public class Router {
public static let sharedInstance = Router()
private let routeKey = "_routeIdentifierKey"
private var routeMaps = NSMutableDictionary()
private var namedRoutes = [String: Route]()
private init() {
}
public func map(routePattern: String, name: String? = nil, handler: RouteHandlerClosure) -> Route {
let route = Route(pattern: routePattern, handler: handler, name: name)
addRoute(route)
return route
}
public func findRoute(url: String) -> Route? {
let encodedUrl = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
var route: Route?
var maps = routeMaps
let urlPathComponents = getPathComponents(encodedUrl)
for i in 0 ..< urlPathComponents.count {
let pathComponent = urlPathComponents[i]
for (key, value) in maps {
if maps[pathComponent] != nil { //no exact match
// reach the end
if i == (urlPathComponents.count - 1) {
let routeMap = maps[pathComponent] as! NSMutableDictionary
route = routeMap[routeKey] as? Route
return route
}
maps = maps[pathComponent] as! NSMutableDictionary
break
} else if key.hasPrefix(":") { //param match
// reach the end
if i == (urlPathComponents.count - 1) {
route = value[routeKey] as? Route
return route
}
maps = maps[String(key)] as! NSMutableDictionary
break
}
}
}
return route
}
func findRouteByName(name: String) -> Route? {
return namedRoutes[name]
}
public func getRouteUrl(routeName: String, parameters: [String: String]?) -> String? {
var url: String?
var urlParts = [String]()
if let route = findRouteByName(routeName) {
if (parameters != nil) {
let routePathComponents = getPathComponents(route.pattern)
for pathComponent in routePathComponents {
if pathComponent.hasPrefix(":"),
let value = parameters![pathComponent.substringFromIndex(pathComponent.startIndex.advancedBy(1))] {
urlParts.append(value)
} else {
urlParts.append(pathComponent)
}
}
}
let urlString = urlParts.joinWithSeparator("/")
if urlString != "" {
url = urlString.hasPrefix("//") ? urlString.substringFromIndex(urlString.startIndex.advancedBy(1)) : urlString
}
}
return url
}
public func routeURL(url: String, data: AnyObject? = nil) {
let encodedUrl = url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
if let route = findRoute(encodedUrl) {
let params = getParamForRoute(encodedUrl, route: route)
let request = RouteRequest(url: encodedUrl, parameters: params, data: data)
let pipeline = Pipeline()
pipeline.sendThroughPipline(request, middlewares: route.middlewares, handler: route.handler)
}
}
private func addRoute(route: Route) {
namedRoutes[route.name] = route
var routePathComponents = getPathComponents(route.pattern)
var map: NSMutableDictionary = routeMaps
for i in 0 ..< routePathComponents.count {
let pathComponent = routePathComponents[i]
// new path
if map[pathComponent] == nil {
map[pathComponent] = NSMutableDictionary()
}
map = map[pathComponent] as! NSMutableDictionary
if i == (routePathComponents.count - 1) {
map[routeKey] = route
return
}
}
}
private func getParamForRoute(url: String, route: Route) -> [String: String] {
var parameters = [String: String]()
// get parameters from route
let routePathComponents = getPathComponents(route.pattern)
let urlPathComponents = getPathComponents(url)
for i in 0 ..< routePathComponents.count {
let pathComponent = routePathComponents[i]
if pathComponent.hasPrefix(":") {
let name = pathComponent.substringFromIndex(pathComponent.startIndex.advancedBy(1))
parameters[name] = urlPathComponents[i]
}
}
// get parameters from url query string
if let url = NSURL(string: url) where (url.query != nil) {
let queryParts = url.query!.componentsSeparatedByString("&")
for queryPart in queryParts {
if let range = queryPart.rangeOfString("=") {
let name = queryPart.substringToIndex(range.startIndex)
let value = queryPart.substringFromIndex(range.endIndex).stringByRemovingPercentEncoding
parameters[name] = value?.stringByRemovingPercentEncoding
}
}
}
return parameters
}
private func getPathComponents(path: String) -> [String] {
var pathComponents = [String]()
if let url = NSURL(string: path) where (url.pathComponents != nil) {
pathComponents += url.pathComponents!
}
return pathComponents
}
}
| mit | 37b38445d361640bd76352edfe065c8b | 37.206452 | 126 | 0.563154 | 5.478261 | false | false | false | false |
XiaoChenYung/GitSwift | GitSwift/View/BaseViewController.swift | 1 | 3790 | //
// ViewController.swift
// GitSwift
//
// Created by tm on 2017/7/31.
// Copyright © 2017年 tm. All rights reserved.
//
import UIKit
import RAMAnimatedTabBarController
import RxSwift
class BaseViewController: UIViewController, UIGestureRecognizerDelegate {
let disposeBag = DisposeBag()
public var snapshot: UIView?
public var interactivePopTransition: UIPercentDrivenInteractiveTransition?
var viewModel: ViewModel?
init(viewModel: ViewModel) {
super.init(nibName: nil, bundle: nil)
self.viewModel = viewModel
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if self.navigationController != nil && self.navigationController?.viewControllers.count == 1 {
let tabbarVC = self.tabBarController as! RAMAnimatedTabBarController
tabbarVC.animationTabBarHidden(false)
}
}
override func viewWillDisappear(_ animated: Bool) {
if isMovingFromParentViewController {
snapshot = navigationController?.view.snapshotView(afterScreenUpdates: false)
}
}
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
automaticallyAdjustsScrollViewInsets = false
extendedLayoutIncludesOpaqueBars = true
if navigationController != nil && self != navigationController?.viewControllers.first {
let popRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePopRecognizer(recognizer:)))
view.addGestureRecognizer(popRecognizer)
popRecognizer.delegate = self
}
bindViewModel()
// Do any additional setup after loading the view.
}
func bindViewModel() {
viewModel?.title.asObservable()
.subscribe(onNext: { [unowned self] (title) in
self.navigationItem.title = title
}).addDisposableTo(disposeBag)
}
func handlePopRecognizer(recognizer: UIPanGestureRecognizer) {
var progress = recognizer.translation(in: view).x / view.frame.width
progress = min(1.0, max(0.0, progress))
if recognizer.state == UIGestureRecognizerState.began {
interactivePopTransition = UIPercentDrivenInteractiveTransition()
navigationController?.popViewController(animated: true)
} else if recognizer.state == UIGestureRecognizerState.changed {
interactivePopTransition?.update(progress)
} else if recognizer.state == UIGestureRecognizerState.ended || recognizer.state == UIGestureRecognizerState.cancelled {
if progress > 0.2 {
interactivePopTransition?.finish()
} else {
interactivePopTransition?.cancel()
}
interactivePopTransition = nil
}
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
let panGes = gestureRecognizer as! UIPanGestureRecognizer
return panGes.velocity(in: view).x > 0
}
// private func gestureRecognizerShouldBegin(_ gestureRecognizer: UIPanGestureRecognizer) -> Bool {
// print("llll")
// return gestureRecognizer.velocity(in: view).x > 0
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 8a64be90ec8cad17207c1f173a369d1f | 33.117117 | 128 | 0.663322 | 5.817204 | false | false | false | false |
Sharelink/Bahamut | Bahamut/UserProfileViewController.swift | 1 | 15929 | //
// UserProfileViewController.swift
// Bahamut
//
// Created by AlexChow on 15/8/15.
// Copyright © 2015年 GStudio. All rights reserved.
//
import UIKit
//MARK: UserService
extension UserService
{
func showUserProfileViewController(currentNavigationController:UINavigationController,userId:String)
{
if let userProfile = self.getUser(userId)
{
showUserProfileViewController(currentNavigationController, userProfile: userProfile)
}
}
func showUserProfileViewController(currentNavigationController:UINavigationController,userProfile:Sharelinker)
{
let controller = UserProfileViewController.instanceFromStoryBoard()
controller.userProfileModel = userProfile
currentNavigationController.pushViewController(controller , animated: true)
}
}
//MARK: extension SharelinkThemeService
extension SharelinkThemeService
{
func showConfirmAddThemeAlert(currentViewController:UIViewController,theme:SharelinkTheme)
{
let alert = UIAlertController(title: "FOCUS".localizedString() , message: String(format: "CONFIRM_FOCUS_THEME".localizedString(), theme.getShowName()), preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "YES".localizedString(), style: .Default){ _ in
self.addThisThemeToMyFocus(currentViewController,theme: theme)
})
alert.addAction(UIAlertAction(title: "UMMM".localizedString(), style: .Cancel){ _ in
})
currentViewController.presentViewController(alert, animated: true, completion: nil)
}
func addThisThemeToMyFocus(currentViewController:UIViewController,theme:SharelinkTheme,callback:((Bool)->Void)! = nil)
{
if self.isThemeExists(theme.data)
{
let alert = UIAlertController(title: nil, message: "SAME_THEME_EXISTS".localizedString(), preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "I_SEE".localizedString(), style: .Cancel, handler: nil))
currentViewController.presentViewController(alert, animated: true, completion: nil)
return
}
let newTag = SharelinkTheme()
newTag.tagName = theme.tagName
newTag.tagColor = theme.tagColor
newTag.isFocus = "true"
newTag.type = theme.type
newTag.showToLinkers = "true"
newTag.data = theme.data
self.addSharelinkTheme(newTag) { (suc) -> Void in
let alerttitle = suc ? "FOCUS_THEME_SUCCESS".localizedString() : "FOCUS_THEME_ERROR".localizedString()
let alert = UIAlertController(title:alerttitle , message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "I_SEE".localizedString(), style: .Cancel){ _ in
})
currentViewController.presentViewController(alert, animated: true, completion: nil)
if let handler = callback
{
handler(suc)
}
}
}
}
//MARK:UserProfileViewController
class UserProfileViewController: UIViewController,UIEditTextPropertyViewControllerDelegate,UIResourceExplorerDelegate,ThemeCollectionViewControllerDelegate,ProgressTaskDelegate,QupaiSDKDelegate
{
//MARK: properties
private var profileVideoView:BahamutFilmView!{
didSet{
profileVideoViewContainer.addSubview(profileVideoView)
profileVideoViewContainer.sendSubviewToBack(profileVideoView)
}
}
@IBOutlet weak var editProfileVideoButton: UIButton!
@IBOutlet weak var profileVideoViewContainer: UIView!
@IBOutlet weak var avatarImageView: UIImageView!{
didSet{
avatarImageView.layer.cornerRadius = 3
avatarImageView.userInteractionEnabled = true
}
}
@IBOutlet weak var userMottoView: UILabel!{
didSet{
userMottoView.userInteractionEnabled = true
}
}
@IBOutlet weak var userNickNameLabelView: UILabel!{
didSet{
userNickNameLabelView.userInteractionEnabled = true
}
}
var fileService:FileService!
var userProfileModel:Sharelinker!
var isMyProfile:Bool{
return userProfileModel.userId == ServiceContainer.getService(UserService).myUserId
}
//MARK: init
override func viewDidLoad() {
super.viewDidLoad()
fileService = ServiceContainer.getService(FileService)
initProfileVideoView()
initThemes()
}
private func initThemes()
{
self.themes = ServiceContainer.getService(SharelinkThemeService).getUserTheme(userProfileModel.userId){ result in
self.themes = result
}
}
func bindTapActions()
{
avatarImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(UserProfileViewController.avatarTapped(_:))))
}
func avatarTapped(_:UITapGestureRecognizer)
{
UUImageAvatarBrowser.showImage(avatarImageView)
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
bindTapActions()
update()
updateEditVideoButton()
MobClick.beginLogPageView("SharelinkerProfile")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillAppear(animated)
MobClick.endLogPageView("SharelinkerProfile")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
private func initProfileVideoView()
{
if profileVideoView == nil
{
let frame = profileVideoViewContainer.bounds
profileVideoView = BahamutFilmView(frame: frame)
profileVideoView.backgroundColor = UIColor.whiteColor()
profileVideoView.playerController.fillMode = AVLayerVideoGravityResizeAspectFill
profileVideoView.autoPlay = true
profileVideoView.autoLoad = true
profileVideoView.canSwitchToFullScreen = true
profileVideoView.isMute = false
}
}
//MARK: focus tags
var focusThemeController:ThemeCollectionViewController!{
didSet{
self.addChildViewController(focusThemeController)
focusThemeController.delegate = self
}
}
func themeCellDidClick(sender: ThemeCollectionViewController, cell: ThemeCollectionCell, indexPath: NSIndexPath) {
if isMyProfile
{
return
}
if sender == focusThemeController
{
ServiceContainer.getService(SharelinkThemeService).showConfirmAddThemeAlert(self,theme: sender.themes[indexPath.row])
}
}
//TODO: add RefreshThemes functions
private var refreshThemesButton:UIButton!
private var refreshingIndicator:UIActivityIndicatorView!
private func initRefreshThemes()
{
refreshingIndicator = UIActivityIndicatorView()
refreshingIndicator.center = focusThemeViewContainer.center
refreshThemesButton = UIButton(type: .InfoDark)
refreshThemesButton.center = focusThemeViewContainer.center
}
@IBOutlet weak var focusThemeViewContainer: UIView!{
didSet{
focusThemeViewContainer.layer.cornerRadius = 7
focusThemeController = ThemeCollectionViewController.instanceFromStoryBoard()
focusThemeViewContainer.addSubview(focusThemeController.view)
}
}
//MARK: personal video
private var taskFileMap = [String:FileAccessInfo]()
func saveProfileVideo()
{
let fService = ServiceContainer.getService(FileService)
fService.sendFileToAliOSS(profileVideoView.filePath, type: FileType.Video) { (taskId, fileKey) -> Void in
ProgressTaskWatcher.sharedInstance.addTaskObserver(taskId, delegate: self)
if let fk = fileKey
{
self.taskFileMap[taskId] = fk
}
}
}
func taskCompleted(taskIdentifier: String, result: AnyObject!) {
let uService = ServiceContainer.getService(UserService)
if let fileKey = taskFileMap.removeValueForKey(taskIdentifier)
{
uService.setMyProfileVideo(fileKey.fileId, setProfileCallback: { (isSuc, msg) -> Void in
if isSuc
{
self.userProfileModel.personalVideoId = fileKey.accessKey
self.userProfileModel.saveModel()
self.updatePersonalFilm()
self.playToast("SET_PROFILE_VIDEO_SUC".localizedString())
}
})
}
}
func taskFailed(taskIdentifier: String, result: AnyObject!) {
self.playToast("SET_PROFILE_VIDEO_FAILED".localizedString())
taskFileMap.removeValueForKey(taskIdentifier)
}
@IBAction func editProfileVideo()
{
showEditProfileVideoActionSheet()
}
private func showEditProfileVideoActionSheet()
{
let alert = UIAlertController(title:"CHANGE_PROFILE_VIDEO".localizedString() , message: nil, preferredStyle: .ActionSheet)
alert.addAction(UIAlertAction(title:"REC_NEW_VIDEO".localizedString() , style: .Destructive) { _ in
self.recordVideo()
})
alert.addAction(UIAlertAction(title:"SELECT_VIDEO".localizedString(), style: .Destructive) { _ in
self.seleteVideo()
})
alert.addAction(UIAlertAction(title:"USE_DEFAULT_VIDEO".localizedString(), style: .Destructive) { _ in
self.useDefaultVideo()
})
alert.addAction(UIAlertAction(title:"CANCEL".localizedString(), style: .Cancel){ _ in})
presentViewController(alert, animated: true, completion: nil)
}
private func useDefaultVideo()
{
ServiceContainer.getService(UserService).setMyProfileVideo("")
self.profileVideoView.filePath = FilmAssetsConstants.SharelinkFilm
}
private func recordVideo()
{
if let qpController = QuPaiRecordCamera().getQuPaiController(self)
{
self.presentViewController(qpController, animated: true, completion: nil)
}else{
self.playToast("Camera Not Ready")
}
}
#if APP_VERSION
func qupaiSDK(sdk: QupaiSDKDelegate!, compeleteVideoPath videoPath: String!, thumbnailPath: String!) {
self.dismissViewControllerAnimated(false, completion: nil)
if videoPath == nil
{
return
}
let fileService = ServiceContainer.getService(FileService)
let newFilePath = fileService.createLocalStoreFileName(FileType.Video)
if PersistentFileHelper.moveFile(videoPath, destinationPath: newFilePath)
{
profileVideoView.fileFetcher = fileService.getFileFetcherOfFilePath(FileType.Video)
profileVideoView.filePath = newFilePath
self.playToast( "VIDEO_SAVED".localizedString())
saveProfileVideo()
}else
{
self.playToast( "SAVE_VIDEO_FAILED".localizedString())
}
}
#endif
private func seleteVideo()
{
let files = ServiceContainer.getService(FileService).getFileModelsOfFileLocalStore(FileType.Video)
ServiceContainer.getService(FileService).showFileCollectionControllerView(self.navigationController!, files: files,selectionMode:.Single, delegate: self)
}
//MARK: delegate for video resource item
func resourceExplorerItemsSelected(itemModels: [UIResrouceItemModel],sender: UIResourceExplorerController!) {
if itemModels.count > 0
{
let fileModel = itemModels.first as! UIFileCollectionCellModel
profileVideoView.fileFetcher = fileService.getFileFetcherOfFilePath(FileType.Video)
profileVideoView.filePath = fileModel.filePath
saveProfileVideo()
}
}
func resourceExplorerOpenItem(itemModel: UIResrouceItemModel, sender: UIResourceExplorerController!) {
let fileModel = itemModel as! UIFileCollectionCellModel
BahamutFilmView.showPlayer(sender, uri: fileModel.filePath, fileFetcer: FilePathFileFetcher.shareInstance)
}
//MARK: update
func updateEditVideoButton()
{
if isMyProfile && UserSetting.isAppstoreReviewing == false
{
editProfileVideoButton.hidden = false
}else
{
editProfileVideoButton.hidden = true
}
}
func update()
{
updateName()
userMottoView.text = userProfileModel.motto
updateAvatar()
updatePersonalFilm()
updateNoteButton()
}
private func updateNoteButton()
{
if userProfileModel.userId == ServiceContainer.getService(UserService).myUserId
{
self.navigationItem.rightBarButtonItems?.removeAll()
}
}
func updateName()
{
self.navigationItem.title = userProfileModel.getNoteName()
userNickNameLabelView.text = userProfileModel.nickName
}
func updatePersonalFilm()
{
if profileVideoView == nil
{
return
}
profileVideoView.fileFetcher = fileService.getFileFetcherOfFileId(FileType.Video)
if String.isNullOrWhiteSpace(userProfileModel.personalVideoId)
{
profileVideoView.fileFetcher = fileService.getFileFetcherOfFilePath(.Video)
profileVideoView.filePath = FilmAssetsConstants.SharelinkFilm
}else
{
profileVideoView.filePath = userProfileModel.personalVideoId
}
}
func updateAvatar()
{
fileService.setAvatar(avatarImageView, iconFileId: userProfileModel.avatarId)
}
//MARK: user theme
var themes:[SharelinkTheme]!{
didSet{
self.focusThemeController.themes = self.themes
}
}
@IBAction func editNoteName()
{
let propertySet = UIEditTextPropertySet()
propertySet.propertyIdentifier = "note"
propertySet.propertyValue = userProfileModel.noteName
propertySet.propertyLabel = "NOTE_NAME".localizedString()
UIEditTextPropertyViewController.showEditPropertyViewController(self.navigationController!,propertySet:propertySet, controllerTitle: "NOTE_NAME".localizedString(), delegate: self)
}
func editPropertySave(propertyId: String!, newValue: String!)
{
let userService = ServiceContainer.getService(UserService)
if propertyId == "note"
{
let hud = self.showActivityHudWithMessage("",message:"UPDATING".localizedString())
if SharelinkerCenterNoteName == newValue
{
let alert = UIAlertController(title: "INVALID_VALUE".localizedString(), message: "USE_ANOTHER_VALUE".localizedString(), preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "I_SEE".localizedString(), style: UIAlertActionStyle.Cancel ,handler:nil))
self.presentViewController(alert, animated: true, completion: nil)
return
}
userService.setLinkerNoteName(userProfileModel.userId, newNoteName: newValue){ isSuc,msg in
hud.hideAsync(true)
if isSuc
{
self.userProfileModel.noteName = newValue
self.userProfileModel.saveModel()
self.updateName()
}
}
}
}
static func instanceFromStoryBoard() -> UserProfileViewController
{
return instanceFromStoryBoard("UserAccount", identifier: "userProfileViewController",bundle: Sharelink.mainBundle()) as! UserProfileViewController
}
}
| mit | d5b37a71a1693897973834526347ab1f | 35.113379 | 205 | 0.657855 | 5.184245 | false | false | false | false |
jordane-quincy/M2_DevMobileIos | JSONProject/Demo/ResultatViewController.swift | 1 | 9978 | //
// ResultatViewController.swift
// Demo
//
// Created by morgan basset on 24/04/2017.
// Copyright © 2017 UVHC. All rights reserved.
//
import UIKit
import RealmSwift
import Darwin
import Foundation
class ResultatViewController: UITableViewController, UIDocumentMenuDelegate, UIDocumentPickerDelegate, UINavigationControllerDelegate {
var realmServices = RealmServices()
var services: Array<BusinessService> = Array<BusinessService>()
var exportServices = ExportServices()
var fileServices = FileServices()
var path : URL? = nil
var isImportingFile = false
var customNavigationController: UINavigationController? = nil
public func setupNavigationController(navigationController: UINavigationController){
self.customNavigationController = navigationController
}
@available(iOS 8.0, *)
public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt urlDocument: URL) {
//print("The Url is : \(urlDocument)")
//let contentDocument = try String(contentsOf: urlDocument)
//print("The document content : \(contentDocument)")
if (isImportingFile) {
isImportingFile = false
URLSession.shared.dataTask(with:urlDocument) { (data, response, error) in
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
//if let dictionary = json as? [String: Any] {
// for (key, value) in dictionary {
// // access all key / value pairs in dictionary
//
// //print("key : \(key) , value : \(value)")
// }
//}
do {
let jsonModel = try JsonModel(jsonContent: json as! [String: Any])
print("jsonModel : \(jsonModel)")
} catch let serializationError {
//in case of unsuccessful deserialization
print(serializationError)
}
}.resume()
}
}
@available(iOS 8.0, *)
public func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print("we cancelled document picker")
isImportingFile = false
// We have to delete the file from the local repo if it exists
// path is different of nil if we are creating a file
// If we cancel the document picker during the selection of a file
// We have to do nothing and so path will be equal to nil
if (path != nil) {
do {
_ = try String(contentsOf: path!, encoding: String.Encoding.utf8)
do {
try FileManager.default.removeItem(at: path!)
path = nil;
} catch {
print("error deleting file at path : " + (path?.absoluteString)!)
}
}
catch {
path = nil
}
}
dismiss(animated: true, completion: nil)
}
func documentMenuWasCancelled(_ documentMenu: UIDocumentMenuViewController) {
print("we cancelled document menu")
isImportingFile = false
// We have to delete the file from the local repo if it exists
// path is different of nil if we are creating a file
// If we cancel the document picker during the selection of a file
// We have to do nothing and so path will be equal to nil
if (path != nil) {
do {
_ = try String(contentsOf: path!, encoding: String.Encoding.utf8)
do {
try FileManager.default.removeItem(at: path!)
path = nil;
} catch {
print("error deleting file at path : " + (path?.absoluteString)!)
}
}
catch {
path = nil
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
// setup swipe
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeRight.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeLeft)
}
// swipe function
func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
// GO TO THE LEFT Pannel
DispatchQueue.main.async() {
self.tabBarController?.selectedIndex = 0
}
case UISwipeGestureRecognizerDirection.left:
// GO TO THE RIGHT Pannel
DispatchQueue.main.async() {
self.tabBarController?.selectedIndex = 2
}
default:
break
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func refreshServicesArray(){
self.services = self.realmServices.getBusinessServicesArray()
}
override func viewDidAppear(_ animated: Bool) {
self.refreshServicesArray()
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return services.count
}
override func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
let export = UITableViewRowAction(style: .normal, title: "Exporter") { action, index in
print("export button tapped")
let businessTitle = self.services[editActionsForRowAt.row].title
let alert = UIAlertController(title: "Exporter", message: "Selectionner un type de fichier", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "JSON", style: UIAlertActionStyle.default, handler: { action in
let fileString = self.exportServices.getSubscribersJSON(_businessServiceTitle: businessTitle)
_ = self.fileServices.createJSONFileFromString(JSONStringified: fileString, businessServiceTitle: businessTitle, viewController: self)
self.fileServices.createAndMoveFileiCloud(file: "file", fileStringified: fileString, viewController: self)
}))
alert.addAction(UIAlertAction(title: "CSV", style: UIAlertActionStyle.default, handler: { action in
let fileString = self.exportServices.getSubscribersCSV(_businessServiceTitle: businessTitle)
_ = self.fileServices.createCSVFileFromString(CSVStringified: fileString, businessServiceTitle: businessTitle, viewController: self)
self.fileServices.createAndMoveFileiCloud(file: "file", fileStringified: fileString, viewController: self)
}))
self.present(alert, animated: true, completion: nil)
alert.addAction(UIAlertAction(title: "Annuler", style: UIAlertActionStyle.cancel, handler: { (UIAlertAction) in
print("Export cancel")
}))
}
export.backgroundColor = .blue
let delete = UITableViewRowAction(style: .normal, title: "Supprimer") { action, index in
print("delete button tapped")
print(self.services[editActionsForRowAt.row])
// Delete BusinessService from DataBase
self.realmServices.deleteBusinessService(_title: self.services[editActionsForRowAt.row].title)
// Refresh 'services' variable
self.refreshServicesArray()
// Delete Row in TableView
tableView.deleteRows(at: [editActionsForRowAt], with: .automatic)
}
delete.backgroundColor = .red
return [delete, export]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("CustomCell", owner: self, options: nil)?.first as! CustomCell
let row = indexPath.row
cell.textLabel?.text = services[row].title
cell.detailTextLabel?.text = String(services[row].subscribers.count)
return cell
}
// method after tap on cell
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// go to person tableview
let resultatPersonTableView = ResultatPersonTableView(nibName: "ResultatPersonTableView", bundle: nil)
resultatPersonTableView.setupNavigationController(navigationController: self.customNavigationController!)
// setup affiliates
resultatPersonTableView.setupAffiliates(affiliates: Array(self.services[indexPath.row].subscribers))
self.customNavigationController?.pushViewController(resultatPersonTableView, animated: true)
self.customNavigationController?.setNavigationBarHidden(false, animated: true)
}
}
| mit | d1e1bf6af364294bb99e517fbe03d2c1 | 39.889344 | 150 | 0.610604 | 5.573743 | false | false | false | false |
avnerbarr/AVBForm | Classes/AVBFormViewController.swift | 1 | 1514 | //
// AVBFormViewController.swift
// AVBForm
//
// Created by Avner on 5/6/15.
// Copyright (c) 2015 Avner. All rights reserved.
//
import UIKit
class AVBFormViewController: UIViewController, AVBFormDelegate {
let tableView = AVBFormTableView()
var dataSource : AVBFormController?
var form : AVBForm?
override func loadView() {
self.view = tableView
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
convenience init(form : AVBForm) {
self.init(nibName: nil, bundle: nil)
form.tableView = self.tableView
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.form = makeTestForm(self.tableView)
}
override func viewDidLoad() {
super.viewDidLoad()
self.form?.formDelegate = self
}
func presentChildForm(form : AVBForm) {
var vc = AVBFormViewController(form: form)
self.navigationController?.showViewController(vc, sender: self)
}
@IBAction func validateForm(sender: UIBarButtonItem) {
if self.form?.isValid() == true {
println("Valid")
} else {
println("Invalid")
}
self.form?.mode = Mode.Validate
}
func validateForm() -> Bool? {
return self.form?.isValid()
}
}
| mit | 60c32fa4b9ae4164ee40da563f8867eb | 25.103448 | 84 | 0.624174 | 4.301136 | false | false | false | false |
openhab/openhab.ios | OpenHABCore/Tests/OpenHABCoreTests/OpenHABCoreGeneralTests.swift | 1 | 1095 | // Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import Foundation
@testable import OpenHABCore
import XCTest
final class OpenHABCoreGeneralTests: XCTestCase {
func testEndPoints() {
let urlc = Endpoint.icon(
rootUrl: "http://192.169.2.1",
version: 2,
icon: "switch",
state: "OFF",
iconType: .svg
).url
XCTAssertEqual(urlc, URL(string: "http://192.169.2.1/icon/switch?state=OFF&format=SVG"), "Check endpoint creation")
}
func testLabelVale() {
let widget = OpenHABWidget()
widget.label = "llldl [llsl]"
XCTAssertEqual(widget.labelValue, "llsl")
widget.label = "llllsl[kkks] llls"
XCTAssertEqual(widget.labelValue, "kkks")
}
}
| epl-1.0 | a4c50073694d87e219ae2f50ea19c7e3 | 28.594595 | 123 | 0.646575 | 3.869258 | false | true | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.HeartBeat.swift | 1 | 2021 | import Foundation
public extension AnyCharacteristic {
static func heartBeat(
_ value: UInt32 = 0,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Heart Beat",
format: CharacteristicFormat? = .uint32,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.heartBeat(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func heartBeat(
_ value: UInt32 = 0,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Heart Beat",
format: CharacteristicFormat? = .uint32,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<UInt32> {
GenericCharacteristic<UInt32>(
type: .heartBeat,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | b2f8fd6deef1cfdbba2eed92c8bcdbc6 | 32.131148 | 67 | 0.572984 | 5.318421 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/SellingPlanAllocationPriceAdjustment.swift | 1 | 7944 | //
// SellingPlanAllocationPriceAdjustment.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// The resulting prices for variants when they're purchased with a specific
/// selling plan.
open class SellingPlanAllocationPriceAdjustmentQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = SellingPlanAllocationPriceAdjustment
/// The price of the variant when it's purchased without a selling plan for the
/// same number of deliveries. For example, if a customer purchases 6
/// deliveries of $10.00 granola separately, then the price is 6 x $10.00 =
/// $60.00.
@discardableResult
open func compareAtPrice(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> SellingPlanAllocationPriceAdjustmentQuery {
let subquery = MoneyV2Query()
subfields(subquery)
addField(field: "compareAtPrice", aliasSuffix: alias, subfields: subquery)
return self
}
/// The effective price for a single delivery. For example, for a prepaid
/// subscription plan that includes 6 deliveries at the price of $48.00, the
/// per delivery price is $8.00.
@discardableResult
open func perDeliveryPrice(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> SellingPlanAllocationPriceAdjustmentQuery {
let subquery = MoneyV2Query()
subfields(subquery)
addField(field: "perDeliveryPrice", aliasSuffix: alias, subfields: subquery)
return self
}
/// The price of the variant when it's purchased with a selling plan For
/// example, for a prepaid subscription plan that includes 6 deliveries of
/// $10.00 granola, where the customer gets 20% off, the price is 6 x $10.00 x
/// 0.80 = $48.00.
@discardableResult
open func price(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> SellingPlanAllocationPriceAdjustmentQuery {
let subquery = MoneyV2Query()
subfields(subquery)
addField(field: "price", aliasSuffix: alias, subfields: subquery)
return self
}
/// The resulting price per unit for the variant associated with the selling
/// plan. If the variant isn't sold by quantity or measurement, then this field
/// returns `null`.
@discardableResult
open func unitPrice(alias: String? = nil, _ subfields: (MoneyV2Query) -> Void) -> SellingPlanAllocationPriceAdjustmentQuery {
let subquery = MoneyV2Query()
subfields(subquery)
addField(field: "unitPrice", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// The resulting prices for variants when they're purchased with a specific
/// selling plan.
open class SellingPlanAllocationPriceAdjustment: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = SellingPlanAllocationPriceAdjustmentQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "compareAtPrice":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: SellingPlanAllocationPriceAdjustment.self, field: fieldName, value: fieldValue)
}
return try MoneyV2(fields: value)
case "perDeliveryPrice":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: SellingPlanAllocationPriceAdjustment.self, field: fieldName, value: fieldValue)
}
return try MoneyV2(fields: value)
case "price":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: SellingPlanAllocationPriceAdjustment.self, field: fieldName, value: fieldValue)
}
return try MoneyV2(fields: value)
case "unitPrice":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: SellingPlanAllocationPriceAdjustment.self, field: fieldName, value: fieldValue)
}
return try MoneyV2(fields: value)
default:
throw SchemaViolationError(type: SellingPlanAllocationPriceAdjustment.self, field: fieldName, value: fieldValue)
}
}
/// The price of the variant when it's purchased without a selling plan for the
/// same number of deliveries. For example, if a customer purchases 6
/// deliveries of $10.00 granola separately, then the price is 6 x $10.00 =
/// $60.00.
open var compareAtPrice: Storefront.MoneyV2 {
return internalGetCompareAtPrice()
}
func internalGetCompareAtPrice(alias: String? = nil) -> Storefront.MoneyV2 {
return field(field: "compareAtPrice", aliasSuffix: alias) as! Storefront.MoneyV2
}
/// The effective price for a single delivery. For example, for a prepaid
/// subscription plan that includes 6 deliveries at the price of $48.00, the
/// per delivery price is $8.00.
open var perDeliveryPrice: Storefront.MoneyV2 {
return internalGetPerDeliveryPrice()
}
func internalGetPerDeliveryPrice(alias: String? = nil) -> Storefront.MoneyV2 {
return field(field: "perDeliveryPrice", aliasSuffix: alias) as! Storefront.MoneyV2
}
/// The price of the variant when it's purchased with a selling plan For
/// example, for a prepaid subscription plan that includes 6 deliveries of
/// $10.00 granola, where the customer gets 20% off, the price is 6 x $10.00 x
/// 0.80 = $48.00.
open var price: Storefront.MoneyV2 {
return internalGetPrice()
}
func internalGetPrice(alias: String? = nil) -> Storefront.MoneyV2 {
return field(field: "price", aliasSuffix: alias) as! Storefront.MoneyV2
}
/// The resulting price per unit for the variant associated with the selling
/// plan. If the variant isn't sold by quantity or measurement, then this field
/// returns `null`.
open var unitPrice: Storefront.MoneyV2? {
return internalGetUnitPrice()
}
func internalGetUnitPrice(alias: String? = nil) -> Storefront.MoneyV2? {
return field(field: "unitPrice", aliasSuffix: alias) as! Storefront.MoneyV2?
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "compareAtPrice":
response.append(internalGetCompareAtPrice())
response.append(contentsOf: internalGetCompareAtPrice().childResponseObjectMap())
case "perDeliveryPrice":
response.append(internalGetPerDeliveryPrice())
response.append(contentsOf: internalGetPerDeliveryPrice().childResponseObjectMap())
case "price":
response.append(internalGetPrice())
response.append(contentsOf: internalGetPrice().childResponseObjectMap())
case "unitPrice":
if let value = internalGetUnitPrice() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
default:
break
}
}
return response
}
}
}
| mit | d1b8a98bda9cce34b1de82530a3e615c | 38.919598 | 134 | 0.727971 | 3.96012 | false | false | false | false |
debugsquad/Hyperborea | Hyperborea/Controller/CSettings.swift | 1 | 3195 | import UIKit
class CSettings:CController
{
let model:MSettings
private weak var viewSettings:VSettings!
private var firstTime:Bool
private let urlMap:[String:String]?
private let kResourceName:String = "ResourceUrl"
private let kResourceExtension:String = "plist"
private let kReviewKey:String = "review"
private let kShareKey:String = "share"
override init()
{
model = MSettings()
firstTime = true
guard
let resourceUrl:URL = Bundle.main.url(
forResource:kResourceName,
withExtension:kResourceExtension),
let urlDictionary:NSDictionary = NSDictionary(
contentsOf:resourceUrl),
let urlMap:[String:String] = urlDictionary as? [String:String]
else
{
self.urlMap = nil
super.init()
return
}
self.urlMap = urlMap
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
deinit
{
viewSettings.viewBackground.timer?.invalidate()
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidAppear(animated)
parentController.statusBarAppareance(statusBarStyle:UIStatusBarStyle.lightContent)
if firstTime
{
firstTime = false
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.viewSettings.viewBackground.startTimer()
}
}
}
override func viewWillDisappear(_ animated:Bool)
{
super.viewWillDisappear(animated)
parentController.statusBarAppareance(statusBarStyle:UIStatusBarStyle.default)
}
override func loadView()
{
let viewSettings:VSettings = VSettings(controller:self)
self.viewSettings = viewSettings
view = viewSettings
}
//MARK: public
func back()
{
parentController.pop(horizontal:CParent.TransitionHorizontal.fromRight)
}
func review()
{
guard
let urlString:String = urlMap?[kReviewKey],
let url:URL = URL(string:urlString)
else
{
return
}
UIApplication.shared.openURL(url)
}
func share()
{
guard
let urlString:String = urlMap?[kShareKey],
let url:URL = URL(string:urlString)
else
{
return
}
let activity:UIActivityViewController = UIActivityViewController(
activityItems:[url],
applicationActivities:nil)
if let popover:UIPopoverPresentationController = activity.popoverPresentationController
{
popover.sourceView = viewSettings
popover.sourceRect = CGRect.zero
popover.permittedArrowDirections = UIPopoverArrowDirection.up
}
present(activity, animated:true)
}
}
| mit | ee3d7543e0b088ebff408e19539ac4a4 | 23.960938 | 95 | 0.557121 | 5.605263 | false | false | false | false |
kickstarter/ios-oss | Library/Extensions/Double+Currency.swift | 1 | 826 | import Foundation
extension Double {
public func addingCurrency(_ otherDouble: Double) -> Double {
let amountDecimal = Decimal(self)
let otherDecimal = Decimal(otherDouble)
let sum = NSDecimalNumber(decimal: amountDecimal + otherDecimal)
return sum.doubleValue
}
public func multiplyingCurrency(_ otherDouble: Double) -> Double {
let amountDecimal = Decimal(self)
let otherDecimal = Decimal(otherDouble)
let multiplied = NSDecimalNumber(decimal: amountDecimal * otherDecimal)
return multiplied.doubleValue
}
public func subtractingCurrency(_ otherDouble: Double) -> Double {
let amountDecimal = Decimal(self)
let otherDecimal = Decimal(otherDouble)
let subtraction = NSDecimalNumber(decimal: amountDecimal - otherDecimal)
return subtraction.doubleValue
}
}
| apache-2.0 | f8fe2cb62d8b83c765cbbc6ea0d099c0 | 26.533333 | 76 | 0.739709 | 4.802326 | false | false | false | false |
simeonpp/home-hunt | ios-client/HomeHunt/ViewControllers/Appointments/SubmitReviewViewController.swift | 1 | 4355 | import UIKit
import CoreLocation
class SubmitReviewViewController: UIViewController, CLLocationManagerDelegate, ReviewDataDelegate {
var locationManager: CLLocationManager!
var reviewData: ReviewData?
var appointmentId: Int?
var addId: Int?
var agentId: Int?
let sliderStep: Float = 1
var compassDirectionNumber: Int = 0
var geoLat: Double = 0
var geoLong: Double = 0
@IBOutlet weak var vTextFieldAddComment: UITextView!
@IBOutlet weak var vSliderAddRating: UISlider!
@IBOutlet weak var vTextFieldAgentComment: UITextView!
@IBOutlet weak var vSliderAgentRating: UISlider!
@IBOutlet weak var vTextAddRatingSlider: UILabel!
@IBOutlet weak var vTextAgentRatingSlider: UILabel!
@IBOutlet weak var vTextCompassNumber: UILabel!
@IBOutlet weak var vTextCompassDirection: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Option 1
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
// Close keyboard
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SubmitReviewViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
geoLat = location.coordinate.latitude
geoLong = location.coordinate.longitude
}
func dismissKeyboard() {
view.endEditing(true)
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
let directionNumber = Int(newHeading.magneticHeading)
self.vTextCompassNumber.text = directionNumber.description
self.vTextCompassDirection.text = DirectionHelper.getDirectionString(directionNumber)
compassDirectionNumber = directionNumber
}
@IBAction func addRatingChanged(_ sender: UISlider) {
let roundedValue = round(sender.value / sliderStep) * sliderStep
sender.value = roundedValue
self.vTextAddRatingSlider.text = String("\(Int(roundedValue))/5")
}
@IBAction func agentRatingChanged(_ sender: UISlider) {
let roundedValue = round(sender.value / sliderStep) * sliderStep
sender.value = roundedValue
self.vTextAgentRatingSlider.text = String("\(Int(roundedValue))/5")
}
@IBAction func submit(_ sender: UIButton) {
let addRating = Int(vSliderAddRating.value)
let agentRating = Int(vSliderAgentRating.value)
let review = Review(withAddId: self.addId!,
andAgentId: self.agentId!,
andAddRating: addRating,
andAgentRating: agentRating,
andAddNote: self.vTextFieldAddComment.text,
andAgentNote: self.vTextFieldAgentComment.text,
andCompass: self.compassDirectionNumber,
andLatitude: self.geoLat,
andLongitude: self.geoLong)
self.showLoading()
self.reviewData?.post(appointmentId: self.appointmentId!, review: review, cookie: self.cookie)
}
func didPost(error: ApiError?) {
let weakSelf = self
DispatchQueue.main.async {
weakSelf.hideLoading()
if (error == nil) {
weakSelf.showInformDialog(withTitle: "Review saved", andMessage: "Your review was successfully saved", andHandler: { action in
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let homeVC = storyBoard.instantiateViewController(withIdentifier: "home")
self.navigationController!.pushViewController(homeVC, animated: true)
})
} else {
weakSelf.handleApiRequestError(error: error!)
}
}
}
}
| mit | e860efaa0c8e5794848c1eccb200cc43 | 39.324074 | 142 | 0.650517 | 5.246988 | false | false | false | false |
PatMurrayDEV/WWDC17 | PatMurrayWWDC17.playground/Sources/extensions.swift | 1 | 3744 | import UIKit
internal struct RotationOptions: OptionSet {
let rawValue: Int
static let flipOnVerticalAxis = RotationOptions(rawValue: 1)
static let flipOnHorizontalAxis = RotationOptions(rawValue: 2)
}
public extension UIImage {
// This outputs the image as an array of pixels
public func pixelData() -> [[UInt8]]? {
// Resize and rotate the image
let resizedImage = self.resizeImage(newHeight: 50)
let rotatedImage = resizedImage.rotated(by: Measurement(value: 90, unit: .degrees), options: RotationOptions.flipOnHorizontalAxis)!
// Get the size of the image to be used in calculatations below
let size = rotatedImage.size
let width = size.width
let height = size.height
// Generate pixel array
let dataSize = width * height * 4
var pixelData = [UInt8](repeating: 0, count: Int(dataSize))
let colorSpace = CGColorSpaceCreateDeviceGray()
let context = CGContext(data: &pixelData,
width: Int(width),
height: Int(height),
bitsPerComponent: 8,
bytesPerRow: 4 * Int(width),
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)
guard let cgImage = rotatedImage.cgImage else { return nil }
context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: width, height: height))
// Clean pixels to just keep black pixels
let cleanedPixels = stride(from: 1, to: pixelData.count, by: 2).map {
pixelData[$0]
}
// Separate pixels into rows (Array of arrays)
let chunkSize = 2 * Int(width) // this was 4
let chunks = stride(from: 0, to: cleanedPixels.count, by: chunkSize).map {
Array(cleanedPixels[$0..<min($0 + chunkSize, cleanedPixels.count)])
}
return chunks
}
func resizeImage(newHeight: CGFloat) -> UIImage {
let scale = newHeight / self.size.height
let newWidth = self.size.width * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
internal func rotated(by rotationAngle: Measurement<UnitAngle>, options: RotationOptions = []) -> UIImage? {
guard let cgImage = self.cgImage else { return nil }
let rotationInRadians = CGFloat(rotationAngle.converted(to: .radians).value)
let transform = CGAffineTransform(rotationAngle: rotationInRadians)
var rect = CGRect(origin: .zero, size: self.size).applying(transform)
rect.origin = .zero
let renderer = UIGraphicsImageRenderer(size: rect.size)
return renderer.image { renderContext in
renderContext.cgContext.translateBy(x: rect.midX, y: rect.midY)
renderContext.cgContext.rotate(by: rotationInRadians)
let x = options.contains(.flipOnVerticalAxis) ? -1.0 : 1.0
let y = options.contains(.flipOnHorizontalAxis) ? 1.0 : -1.0
renderContext.cgContext.scaleBy(x: CGFloat(x), y: CGFloat(y))
let drawRect = CGRect(origin: CGPoint(x: -self.size.width/2, y: -self.size.height/2), size: self.size)
renderContext.cgContext.draw(cgImage, in: drawRect)
}
}
}
| mit | fc3238779a13ca82449031709b3434ae | 35.705882 | 139 | 0.591346 | 4.932806 | false | false | false | false |
Eric217/-OnSale | 打折啦/打折啦/UpLoadView.swift | 1 | 10561 | //
// UpLoadViewController.swift
// Application
//
// Created by Eric on 7/15/17.
// Copyright © 2017 Eric. All rights reserved.
//
import Foundation
import UIKit
class UpLoadViewController: HWPublishBaseController {
var scrollView: UIScrollView!
var headBar: ELMeNavigationBar!
var footBar: ELFooterBaseView!
var txf: UITextField!
var txv: BRPlaceholderTextView!
var scrollPhoto: UIScrollView!
var location: UITableViewCell!
var kind: RightLabelCell!
var time: RightLabelCell!
var business: RoundButton!
var weChat: RoundButton!
var qqZone: RoundButton!
var question: RoundButton!
var currPickerHeight: CGFloat!
//var delta: CGFloat = 0
var pic: [UIImage]!
let placehold = " 在这里添加店铺楼层、门牌号等详细打折信息"
let chooseLoca = "选择地点"
let choosType = "选择种类"
//大小11. arr[11]即视为arr[10]
let timeArr = ["不足六小时", "今天", "两天", "三天", "五天", "七天", "十天", "十五天", "一个月", "两个月", "更长"]
var dateArr: [String]!
var type = -1
var l1 = "", l2 = "", l3 = "", locaStr = ""
var lon = 0.0, lat = 0.0
var deadLine: String!
func d(_ quarters: Int) -> String {
return "\(Date(timeIntervalSinceNow: TimeInterval(60*60*6*quarters)))"
}
override func viewDidLoad() {
super.viewDidLoad()
let is6P = IPHONE6P
let bigger6 = is6P || IPHONE6
title = "发布"
dateArr = [d(1),d(4),d(8),d(12),d(20),d(28),d(40),d(60),d(120),d(240),d(300)]
deadLine = dateArr[3]
print(dateArr)
view.backgroundColor = UIColor.groupTableViewBackground
//MARK: - 头部视图
headBar = ELMeNavigationBar()
view.addSubview(headBar)
headBar.setupTitle("发布")
headBar.setBackColor(Config.themeColor)
headBar.setLeftRightTitle(left: "取消", right: "发布秘籍")
headBar.setButton.addTarget(self, action: #selector(cancel), for: .touchUpInside)
headBar.codeButton.addTarget(self, action: #selector(showtip), for: .touchUpInside)
//MARK: - footer view
let footHeit: CGFloat = bigger6 ? 54 : 44
footBar = ELFooterBaseView(frame: myRect(0, ScreenHeight-footHeit, ScreenWidth, footHeit))
view.addSubview(footBar)
footBar.setupOneTab(title: "确定发布", corner: 5, font: UIFont.boldSystemFont(ofSize: 18))
footBar.button1.addTarget(self, action: #selector(fabu), for: .touchUpInside)
scrollView = UIScrollView(frame: myRect(0, 64, ScreenWidth, ScreenHeight - 64 - 44))
let contentH = scrollView.frame.height + (is6P ? 1 : (IPHONE6 ? 10 : 32))
updateContentSize(value: contentH)
view.addSubview(scrollView)
scrollView.delegate = self
scrollView.showsVerticalScrollIndicator = false
scrollView.backgroundColor = UIColor.groupTableViewBackground
showInView = scrollView
let txfHeight: CGFloat = is6P ? 55 : 48
initPickerView()
updatePickerViewFrameY(txfHeight)
currPickerHeight = pickerCollectionView.frame.height
txf = UITextField(frame: myRect(0, 0, ScreenWidth, txfHeight))
txf.backgroundColor = .white
scrollView.addSubview(txf)
txf.font = UIFont.systemFont(ofSize: 17)
txf.placeholder = "标题 一个合适的标题可以吸引更多人哦"
txf.clearButtonMode = .whileEditing
txf.delegate = self
txf.returnKeyType = .done
txf.addBottomLine(height: 0.5)
txf.leftView = UIView(frame: myRect(0, 0, 12, txfHeight))
txf.leftViewMode = .always
location = UITableViewCell()
location.backgroundColor = .white
location.textLabel?.text = chooseLoca
location.textLabel?.textColor = .gray
scrollView.addSubview(location)
location.accessoryType = .disclosureIndicator
let cellHeight: CGFloat = is6P ? 49 : (bigger6 ? 46 : 42)
location.snp.makeConstraints{ make in
make.width.centerX.equalTo(pickerCollectionView)
make.height.equalTo(cellHeight)
make.top.equalTo(pickerCollectionView.snp.bottom)
}
location.addTapGest(target: self, action: #selector(didTap(_ :)))
let groupColor = UIColor.groupTableViewBackground.withAlphaComponent(0.99)
txv = BRPlaceholderTextView()
txv.placeholder = placehold
txv.font = UIFont.systemFont(ofSize: 16)
txv.setPlaceholderFont(UIFont.systemFont(ofSize: 16))
txv.returnKeyType = .next
txv.delegate = self
txv.maxTextLength = 200
txv.textContainerInset = .init(top: 6, left: 12, bottom: 2, right: 16)
scrollView.addSubview(txv)
let txvHeight: CGFloat = bigger6 ? 138 : 95
txv.snp.makeConstraints{ make in
make.width.centerX.equalTo(txf)
make.top.equalTo(location.snp.bottom).offset(12)
make.height.equalTo(txvHeight)
}
let separator = UIView(frame: myRect(12, 0, ScreenWidth-12, 1))
separator.backgroundColor = groupColor
location.addSubview(separator)
time = RightLabelCell()
time.backgroundColor = UIColor.white
time.setLeftText("持续时间")
time.setRightText("三天")
scrollView.addSubview(time)
time.snp.makeConstraints{ make in
make.width.centerX.equalTo(location)
make.height.equalTo(cellHeight)
make.top.equalTo(txv.snp.bottom).offset(12)
}
time.addTapGest(target: self, action: #selector(didTap(_ :)))
kind = RightLabelCell()
kind.setLeftText(choosType, color: .gray)
kind.rightLabel.text = ""
kind.backgroundColor = .white
scrollView.addSubview(kind)
kind.snp.makeConstraints{ make in
make.width.height.centerX.equalTo(time)
make.top.equalTo(time.snp.bottom)
}
kind.addTapGest(target: self, action: #selector(didTap(_ :)))
let separator2 = UIView(frame: myRect(12, 0, ScreenWidth-12, 1))
separator2.backgroundColor = UIColor.lightGray.withAlphaComponent(0.3)
kind.addSubview(separator2)
var _left: CGFloat = 23
var _h: CGFloat = 28
var _w: CGFloat = 90
var _plus: CGFloat = 0
if is6P {
_left += 10; _h += 4; _w += 20; _plus = 18
txv.font = UIFont.systemFont(ofSize: 18)
txf.font = UIFont.systemFont(ofSize: 18)
}else if !bigger6 { _left -= 3 }
business = RoundButton()
scrollView.addSubview(business)
business.snp.makeConstraints{ make in
make.left.equalTo(_left)
make.width.equalTo(_w)
make.height.equalTo(_h)
make.top.equalTo(kind.snp.bottom).offset(_left)
}
business.fillDefault("我是商家", font: UIFont.systemFont(ofSize: 16, weight: UIFontWeightMedium))
business.tag = 200
business.layer.cornerRadius = 6
business.addTarget(self, action: #selector(didClick(_ :)), for: .touchUpInside)
question = RoundButton()
scrollView.addSubview(question)
question.snp.makeConstraints{ m in
m.left.equalTo(business.snp.right).offset(10)
m.width.height.equalTo(_h - 3)
m.centerY.equalTo(business)
}
question.tag = 201
question.fillBasic(corner: 13, txt: "?", tint: Config.systemBlue, borderW: 1, size: 14)
question.addTarget(self, action: #selector(didClick(_ :)), for: .touchUpInside)
/*
qqZone = RoundButton()
qqZone.tag = 202
scrollView.addSubview(qqZone)
qqZone.snp.makeConstraints{ m in
m.left.equalTo(ScreenWidth-40-_plus-_left)
m.centerY.equalTo(business)
m.width.height.equalTo(53 + _plus)
}
qqZone.fillImage(corner: 8, borderColor: UIColor.clear, img: "qqzone")
qqZone.addTarget(self, action: #selector(didClick(_ :)), for: .touchUpInside)
weChat = RoundButton()
weChat.tag = 203
scrollView.addSubview(weChat)
weChat.snp.makeConstraints{ m in
m.right.equalTo(qqZone.snp.left).offset(-15)
m.width.height.centerY.equalTo(qqZone)
}
weChat.fillImage(corner: 8, borderColor: UIColor.clear, img: "wechat")
weChat.addTarget(self, action: #selector(didClick(_ :)), for: .touchUpInside)
*/
navBarShadowImageHidden = true
navBarBackgroundAlpha = 0
navBarTintColor = UIColor.white
fd_prefersNavigationBarHidden = true
}
}
/*
view.backgroundColor = UIColor.white
statusBarStyle = .lightContent
var tempFrame = view.bounds
tempFrame.origin.y = 15
let maskPath = UIBezierPath(roundedRect: tempFrame, byRoundingCorners:
[UIRectCorner.topRight, UIRectCorner.topLeft], cornerRadii: CGSize(width: 30, height: 30))
let maskLayer = CAShapeLayer()
maskLayer.frame = tempFrame
maskLayer.path = maskPath.cgPath
view.layer.mask = maskLayer
//view.frame.origin.y = 40
let label = UILabel(frame: myRect(100, 200, 100, 200))
label.backgroundColor = UIColor.red
view.addSubview(label)
UIView.animate(withDuration: 0.5, animations: {
//self.view.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
})
//
// let view2 = UIScrollView(frame: CGRect(x: 0, y: 30, width: view.bounds.width, height: view.bounds.height))
// view2.backgroundColor = UIColor.white
// let maskPath = UIBezierPath(roundedRect: view2.bounds, byRoundingCorners:
// [UIRectCorner.topRight, UIRectCorner.topLeft], cornerRadii: CGSize(width: 5, height: 5))
// let maskLayer = CAShapeLayer()
// maskLayer.frame = view2.bounds
// maskLayer.path = maskPath.cgPath
// view2.layer.mask = maskLayer
// view.addSubview(view2)
// view2.isUserInteractionEnabled = true
// let gesture = UITapGestureRecognizer(target: self, action: #selector(onTap))
// view2.addGestureRecognizer(gesture)
*/
| apache-2.0 | 4b936a54133b38530036a72484033fb9 | 34.438356 | 116 | 0.611422 | 4.082051 | false | false | false | false |
cpageler93/RAML-Swift | Sources/Property.swift | 1 | 4351 | //
// Property.swift
// RAML
//
// Created by Christoph Pageler on 24.06.17.
//
import Foundation
import Yaml
public class Property: HasAnnotations {
public var name: String
public var required: Bool?
public var type: DataType?
public var restrictions: PropertyRestrictions?
public var `enum`: StringEnum?
public var annotations: [Annotation]?
public init(name: String) {
self.name = name
}
internal init() {
self.name = ""
}
}
// MARK: Property Parsing
internal extension RAML {
internal func parseProperties(yaml: Yaml?, propertiesKey: String = "properties") throws -> [Property]? {
guard let yaml = yaml else { return nil }
switch yaml {
case .dictionary(let yamlDict):
for (key, value) in yamlDict {
if let keyString = key.string, keyString == propertiesKey {
if let valueDict = value.dictionary {
return try parseProperties(dict: valueDict)
} else {
return []
}
}
}
return nil
default: return nil
}
}
internal func parseProperties(dict: [Yaml: Yaml]) throws -> [Property] {
var properties: [Property] = []
for (key, value) in dict {
guard let keyString = key.string else {
throw RAMLError.ramlParsingError(.invalidDataType(for: "Property Key",
mustBeKindOf: "String"))
}
let property = try parseProperty(name: keyString, yaml: value)
properties.append(property)
}
return properties
}
private func parseProperty(name: String, yaml: Yaml) throws -> Property {
let property = Property(name: name)
property.required = yaml["required"].bool
property.type = try DataType.dataTypeEnumFrom(yaml: yaml, dictKey: "type")
if let type = property.type {
property.restrictions = try parseRestrictions(forType: type, yaml: yaml)
}
property.enum = try parseStringEnum(ParseInput(yaml["enum"]))
property.annotations = try parseAnnotations(ParseInput(yaml))
return property
}
}
public protocol HasProperties {
var properties: [Property]? { get set }
}
public extension HasProperties {
public func propertyWith(name: String) -> Property? {
for property in properties ?? [] {
if property.name == name {
return property
}
}
return nil
}
public func hasPropertyWith(name: String) -> Bool {
return propertyWith(name: name) != nil
}
}
// MARK: Default Values
public extension Property {
public func typeOrDefault() -> DataType? {
if let type = type { return type }
return DataType.scalar(type: .string)
}
public func restrictionsOrDefault() -> PropertyRestrictions? {
if let restrictions = restrictions { return restrictions.applyDefaults() }
guard let type = typeOrDefault() else {
return nil
}
let newRestrictions = RAML.propertyRestrictionsFor(type: type)
return newRestrictions?.applyDefaults()
}
public func nameOrDefault() -> String {
if name.hasSuffix("?") {
return String(name.dropLast())
}
return name
}
public func requiredOrDefault() -> Bool {
if let required = required { return required }
return !name.hasSuffix("?")
}
public convenience init(initWithDefaultsBasedOn property: Property) {
self.init()
self.name = property.nameOrDefault()
self.required = property.requiredOrDefault()
self.type = property.typeOrDefault()
self.restrictions = property.restrictionsOrDefault()
self.enum = property.enum
self.annotations = property.annotations?.map { $0.applyDefaults() }
}
public func applyDefaults() -> Property {
return Property(initWithDefaultsBasedOn: self)
}
}
| mit | 3b0ca1c10709caa0f649bca64732e046 | 27.253247 | 108 | 0.562399 | 4.938706 | false | false | false | false |
u10int/AmazonS3RequestManager | Example/Tests/AmazonS3RequestSerializerTests.swift | 1 | 8943 | //
// AmazonS3RequestSerializerTests.swift
// AmazonS3RequestManager
//
// Created by Anthony Miller on 10/14/15.
// Copyright © 2015 Anthony Miller. All rights reserved.
//
import XCTest
import Nimble
@testable import AmazonS3RequestManager
class AmazonS3RequestSerializerTests: XCTestCase {
var sut: AmazonS3RequestSerializer!
let accessKey = "key"
let secret = "secret"
let bucket = "bucket"
let region = Region.USWest1
override func setUp() {
super.setUp()
sut = AmazonS3RequestSerializer(accessKey: accessKey, secret: secret, region: region, bucket: bucket)
}
/*
* MARK: - Initialization - Tests
*/
func test__inits__withConfiguredRequestSerializer() {
expect(self.sut.accessKey).to(equal(self.accessKey))
expect(self.sut.secret).to(equal(self.secret))
expect(self.sut.bucket).to(equal(self.bucket))
expect(self.sut.region.hostName).to(equal(self.region.hostName))
}
/*
* MARK: Amazon URL Request Serialization - Tests
*/
func test__amazonURLRequest__setsURLWithEndpointURL() {
// given
let path = "TestPath"
let expectedURL = URL(string: "https://\(region.endpoint)/\(bucket)/\(path)")!
// when
let request = sut.amazonURLRequest(method: .get, path: path)
// then
XCTAssertEqual(request.url!, expectedURL)
}
func test__amazonURLRequest__givenCustomRegion_setsURLWithEndpointURL() {
// given
let path = "TestPath"
let expectedEndpoint = "test.endpoint.com"
let region = Region.custom(hostName: "", endpoint: expectedEndpoint)
sut.region = region
let expectedURL = URL(string: "https://\(expectedEndpoint)/\(bucket)/\(path)")!
// when
let request = sut.amazonURLRequest(method: .get, path: path)
// then
XCTAssertEqual(request.url!, expectedURL)
}
func test__amazonURLRequest__givenNoBucket__setsURLWithEndpointURL() {
// given
sut.bucket = nil
let path = "TestPath"
let expectedURL = URL(string: "https://\(region.endpoint)/\(path)")!
// when
let request = sut.amazonURLRequest(method: .get, path: path)
// then
XCTAssertEqual(request.url!, expectedURL)
}
func test__amazonURLRequest__givenNoPath() {
// given
sut.bucket = "test"
let expectedURL = URL(string: "https://\(region.endpoint)/test")!
// when
let request = sut.amazonURLRequest(method: .get)
// then
XCTAssertEqual(request.url!, expectedURL)
}
func test__amazonURLRequest__givenUseSSL_false_setsURLWithEndpointURL_usingHTTP() {
// given
sut.useSSL = false
let path = "TestPath"
let expectedURL = URL(string: "http://\(region.endpoint)/\(bucket)/\(path)")!
// when
let request = sut.amazonURLRequest(method: .get, path: path)
// then
XCTAssertEqual(request.url!, expectedURL)
}
func test__amazonURLRequest__setsHTTPMethod() {
// given
let expected = "GET"
// when
let request = sut.amazonURLRequest(method: .get, path: "test")
// then
XCTAssertEqual(request.httpMethod!, expected)
}
func test__amazonURLRequest__setsCachePolicy() {
// given
let expected = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
// when
let request = sut.amazonURLRequest(method: .get, path: "test")
// then
XCTAssertEqual(request.cachePolicy, expected)
}
func test__amazonURLRequest__givenNoPathExtension_setsHTTPHeader_ContentType() {
// given
let request = sut.amazonURLRequest(method: .get, path: "test")
// when
let headers = request.allHTTPHeaderFields!
let typeHeader: String? = headers["Content-Type"]
// then
XCTAssertNotNil(typeHeader, "Should have 'Content-Type' header field")
XCTAssertEqual(typeHeader!, "application/octet-stream")
}
func test__amazonURLRequest__givenJPGPathExtension_setsHTTPHeader_ContentType() {
// given
let request = sut.amazonURLRequest(method: .get, path: "test.jpg")
// when
let headers = request.allHTTPHeaderFields!
let typeHeader: String? = headers["Content-Type"]
// then
XCTAssertNotNil(typeHeader, "Should have 'Content-Type' header field")
expect(typeHeader).to(equal("image/jpeg"))
}
func test__amazonURLRequest__givenTXTPathExtension_setsHTTPHeader_ContentType() {
// given
let request = sut.amazonURLRequest(method: .get, path: "test.txt")
// when
let headers = request.allHTTPHeaderFields!
let typeHeader: String? = headers["Content-Type"]
// then
XCTAssertNotNil(typeHeader, "Should have 'Content-Type' header field")
XCTAssertEqual(typeHeader!, "text/plain")
}
func test__amazonURLRequest__givenMarkDownPathExtension_setsHTTPHeader_ContentType() {
// given
let request = sut.amazonURLRequest(method: .get, path: "test.md")
// when
let headers = request.allHTTPHeaderFields!
let typeHeader: String? = headers["Content-Type"]
// then
XCTAssertNotNil(typeHeader, "Should have 'Content-Type' header field")
#if os(iOS) || os(watchOS) || os(tvOS)
expect(typeHeader).to(equal("application/octet-stream"))
#elseif os(OSX)
expect(typeHeader).to(equal("text/markdown"))
#endif
}
func test__amazonURLRequest__setsHTTPHeader_Date() {
// given
let request = sut.amazonURLRequest(method: .get, path: "test")
// when
let headers = request.allHTTPHeaderFields!
let dateHeader: String? = headers["Date"]
// then
XCTAssertNotNil(dateHeader, "Should have 'Date' header field")
XCTAssertTrue(dateHeader!.hasSuffix("GMT"))
}
func test__amazonURLRequest__setsHTTPHeader_Authorization() {
// given
let request = sut.amazonURLRequest(method: .get, path: "test")
// when
let headers = request.allHTTPHeaderFields!
let authHeader: String? = headers["Authorization"]
// then
XCTAssertNotNil(authHeader, "Should have 'Authorization' header field")
XCTAssertTrue(authHeader!.hasPrefix("AWS \(accessKey):"), "Authorization header should begin with 'AWS [accessKey]'.")
}
func test__amazonURLRequest__givenACL__setsHTTPHeader_ACL() {
// given
let acl = PredefinedACL.publicReadWrite
let request = sut.amazonURLRequest(method: .get, path: "test", acl: acl)
// when
let headers = request.allHTTPHeaderFields!
let aclHeader: String? = headers["x-amz-acl"]
// then
XCTAssertNotNil(aclHeader, "Should have ACL header field")
}
func test__amazonURLRequest__givenMetaData__setsHTTPHeader_amz_meta() {
// given
let metaData = ["demo" : "foo"]
let request = sut.amazonURLRequest(method: .head, path: "test", acl: nil, metaData: metaData)
// when
let headers = request.allHTTPHeaderFields!
let metaDataHeader: String? = headers["x-amz-meta-demo"]
// then
XCTAssertEqual(metaDataHeader, "foo", "Meta data header field is not set correctly.")
}
func test__amazonURLRequest__givenCustomParameters_setsURLWithEndpointURL() {
// given
let path = "TestPath"
let expectedEndpoint = "test.endpoint.com"
let region = Region.custom(hostName: "", endpoint: expectedEndpoint)
sut.region = region
let expectedURL = URL(string: "https://\(expectedEndpoint)/\(bucket)/\(path)?custom-param=custom%20value%21%2F")!
// when
let request = sut.amazonURLRequest(method: .get, path: path, customParameters: ["custom-param" : "custom value!/"])
// then
XCTAssertEqual(request.url!, expectedURL)
}
func test__amazonURLRequest__givenCustomParameters_setsURLWithEndpointURL_ContinuationToken() {
// given
let path = "TestPath"
let expectedEndpoint = "test.endpoint.com"
let region = Region.custom(hostName: "", endpoint: expectedEndpoint)
sut.region = region
let expectedURL = URL(string: "https://\(expectedEndpoint)/\(bucket)/\(path)?continuation-token=1%2FkCRyYIP%2BApo2oop%2FGa8%2FnVMR6hC7pDH%2FlL6JJrSZ3blAYaZkzJY%2FRVMcJ")!
// when
let request = sut.amazonURLRequest(method: .get, path: path, customParameters: ["continuation-token" : "1/kCRyYIP+Apo2oop/Ga8/nVMR6hC7pDH/lL6JJrSZ3blAYaZkzJY/RVMcJ"])
// then
XCTAssertEqual(request.url!, expectedURL)
}
func test_amazonURLRequest__givenCustomHeaders() {
// given
let headers = ["header-demo" : "foo", "header-test" : "bar"]
let request = sut.amazonURLRequest(method: .head, path: "test", customHeaders: headers)
// when
let httpHeaders = request.allHTTPHeaderFields!
let header1: String? = httpHeaders["header-demo"]
let header2: String? = httpHeaders["header-test"]
// then
XCTAssertEqual(header1, "foo", "Meta data header field is not set correctly.")
XCTAssertEqual(header2, "bar", "Meta data header field is not set correctly.")
}
}
| mit | 7c0a8b6d4b4d5e378c7e63e74af6059c | 29.941176 | 174 | 0.669202 | 4.18633 | false | true | false | false |
docileninja/Calvin-and-Hobbes-Viewer | Viewer/Calvin and Hobbes/Supporting Files/StringFormatter.swift | 1 | 930 | //
// StringFormatter.swift
// Calvin and Hobbes
//
// Created by Adam Van Prooyen on 10/3/16.
// Copyright © 2016 Adam Van Prooyen. All rights reserved.
//
import Foundation
import UIKit
func attributeString(_ string: String) -> NSAttributedString {
let attributedString = NSMutableAttributedString()
let boldAttrs = [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 15)]
var isBold = false
for c in string.characters {
if (c == "_") {
isBold = !isBold
}
else {
if (isBold) {
let boldString = NSMutableAttributedString(string: String(c), attributes: boldAttrs)
attributedString.append(boldString)
}
else {
let normalString = NSMutableAttributedString(string: String(c))
attributedString.append(normalString)
}
}
}
return attributedString
}
| mit | bbbcb32810beda8e87b44a643fa63e0b | 28.03125 | 100 | 0.609257 | 4.78866 | false | false | false | false |
ripitrust/Fitapp | iOSClient/SIOSwift2/SwiftIO/SocketPacket.swift | 1 | 7240 | //
// SocketPacket.swift
// Socket.IO-Swift
//
// Created by Erik Little on 1/18/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
enum SocketPacketType: Int {
case CONNECT = 0
case DISCONNECT = 1
case EVENT = 2
case ACK = 3
case ERROR = 4
case BINARY_EVENT = 5
case BINARY_ACK = 6
init(str:String) {
if let int = str.toInt() {
self = SocketPacketType(rawValue: int)!
} else {
self = SocketPacketType(rawValue: 4)!
}
}
}
class SocketPacket {
var binary = ContiguousArray<NSData>()
var currentPlace = 0
var data:[AnyObject]?
var id:Int?
var justAck = false
var nsp = ""
var placeholders:Int?
var type:SocketPacketType?
init(type:SocketPacketType?, data:[AnyObject]? = nil, nsp:String = "",
placeholders:Int? = nil, id:Int? = nil) {
self.type = type
self.data = data
self.nsp = nsp
self.placeholders = placeholders
self.id = id
}
func getEvent() -> String {
return data?.removeAtIndex(0) as! String
}
func addData(data:NSData) -> Bool {
func checkDoEvent() -> Bool {
if self.placeholders == self.currentPlace {
return true
} else {
return false
}
}
if checkDoEvent() {
return true
}
self.binary.append(data)
self.currentPlace++
if checkDoEvent() {
self.currentPlace = 0
return true
} else {
return false
}
}
func createMessageForEvent(event:String) -> String {
var message:String
var jsonSendError:NSError?
if self.binary.count == 0 {
self.type = SocketPacketType.EVENT
if self.nsp == "/" {
if self.id == nil {
message = "2[\"\(event)\""
} else {
message = "2\(self.id!)[\"\(event)\""
}
} else {
if self.id == nil {
message = "2/\(self.nsp),[\"\(event)\""
} else {
message = "2/\(self.nsp),\(self.id!)[\"\(event)\""
}
}
} else {
self.type = SocketPacketType.BINARY_EVENT
if self.nsp == "/" {
if self.id == nil {
message = "5\(self.binary.count)-[\"\(event)\""
} else {
message = "5\(self.binary.count)-\(self.id!)[\"\(event)\""
}
} else {
if self.id == nil {
message = "5\(self.binary.count)-/\(self.nsp),[\"\(event)\""
} else {
message = "5\(self.binary.count)-/\(self.nsp),\(self.id!)[\"\(event)\""
}
}
}
return self.completeMessage(message)
}
func createAck() -> String {
var msg:String
if self.binary.count == 0 {
if nsp == "/" {
msg = "3\(self.id!)["
} else {
msg = "3/\(self.nsp),\(self.id!)["
}
} else {
if nsp == "/" {
msg = "6\(self.binary.count)-\(self.id!)["
} else {
msg = "6\(self.binary.count)-/\(self.nsp),\(self.id!)["
}
}
return self.completeMessage(msg, ack: true)
}
func completeMessage(var message:String, ack:Bool = false) -> String {
var err:NSError?
if self.data == nil || self.data!.count == 0 {
return message + "]"
} else if !ack {
message += ","
}
for arg in self.data! {
if arg is NSDictionary || arg is [AnyObject] {
let jsonSend = NSJSONSerialization.dataWithJSONObject(arg,
options: NSJSONWritingOptions(0), error: &err)
let jsonString = NSString(data: jsonSend!, encoding: NSUTF8StringEncoding)
message += jsonString! as String
message += ","
continue
}
if arg is String {
message += "\"\(arg)\""
message += ","
continue
}
message += "\(arg)"
message += ","
}
if message != "" {
message.removeAtIndex(message.endIndex.predecessor())
}
return message + "]"
}
func fillInPlaceholders() {
var newArr = NSMutableArray(array: self.data!)
for i in 0..<self.data!.count {
if let str = self.data?[i] as? String {
if let num = str["~~(\\d)"].groups() {
newArr[i] = self.binary[num[1].toInt()!]
} else {
newArr[i] = str
}
} else if self.data?[i] is NSDictionary || self.data?[i] is NSArray {
newArr[i] = self._fillInPlaceholders(self.data![i])
}
}
self.data = newArr as [AnyObject]
}
private func _fillInPlaceholders(data:AnyObject) -> AnyObject {
if let str = data as? String {
if let num = str["~~(\\d)"].groups() {
return self.binary[num[1].toInt()!]
} else {
return str
}
} else if let dict = data as? NSDictionary {
var newDict = NSMutableDictionary(dictionary: dict)
for (key, value) in dict {
newDict[key as! NSCopying] = _fillInPlaceholders(value)
}
return newDict
} else if let arr = data as? NSArray {
var newArr = NSMutableArray(array: arr)
for i in 0..<arr.count {
newArr[i] = _fillInPlaceholders(arr[i])
}
return newArr
} else {
return data
}
}
}
| mit | b1947c079885f867920f0db31efc85eb | 29.808511 | 95 | 0.48453 | 4.632118 | false | false | false | false |
matthewpurcell/firefox-ios | Client/Frontend/Widgets/ThumbnailCell.swift | 1 | 11667 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
struct ThumbnailCellUX {
/// Ratio of width:height of the thumbnail image.
static let ImageAspectRatio: Float = 1.0
static let BorderColor = UIColor.blackColor().colorWithAlphaComponent(0.1)
static let BorderWidth: CGFloat = 1
static let LabelColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.blackColor() : UIColor(rgb: 0x353535)
static let LabelBackgroundColor = UIColor(white: 1.0, alpha: 0.5)
static let LabelAlignment: NSTextAlignment = .Center
static let InsetSize: CGFloat = 20
static let InsetSizeCompact: CGFloat = 6
static func insetsForCollectionViewSize(size: CGSize, traitCollection: UITraitCollection) -> UIEdgeInsets {
let largeInsets = UIEdgeInsets(
top: ThumbnailCellUX.InsetSize,
left: ThumbnailCellUX.InsetSize,
bottom: ThumbnailCellUX.InsetSize,
right: ThumbnailCellUX.InsetSize
)
let smallInsets = UIEdgeInsets(
top: ThumbnailCellUX.InsetSizeCompact,
left: ThumbnailCellUX.InsetSizeCompact,
bottom: ThumbnailCellUX.InsetSizeCompact,
right: ThumbnailCellUX.InsetSizeCompact
)
if traitCollection.horizontalSizeClass == .Compact {
return smallInsets
} else {
return largeInsets
}
}
static let ImagePaddingWide: CGFloat = 20
static let ImagePaddingCompact: CGFloat = 10
static func imageInsetsForCollectionViewSize(size: CGSize, traitCollection: UITraitCollection) -> UIEdgeInsets {
let largeInsets = UIEdgeInsets(
top: ThumbnailCellUX.ImagePaddingWide,
left: ThumbnailCellUX.ImagePaddingWide,
bottom: ThumbnailCellUX.ImagePaddingWide,
right: ThumbnailCellUX.ImagePaddingWide
)
let smallInsets = UIEdgeInsets(
top: ThumbnailCellUX.ImagePaddingCompact,
left: ThumbnailCellUX.ImagePaddingCompact,
bottom: ThumbnailCellUX.ImagePaddingCompact,
right: ThumbnailCellUX.ImagePaddingCompact
)
if traitCollection.horizontalSizeClass == .Compact {
return smallInsets
} else {
return largeInsets
}
}
static let LabelInsets = UIEdgeInsetsMake(10, 3, 10, 3)
static let PlaceholderImage = UIImage(named: "defaultTopSiteIcon")
static let CornerRadius: CGFloat = 3
// Make the remove button look 20x20 in size but have the clickable area be 44x44
static let RemoveButtonSize: CGFloat = 44
static let RemoveButtonInsets = UIEdgeInsets(top: 11, left: 11, bottom: 11, right: 11)
static let RemoveButtonAnimationDuration: NSTimeInterval = 0.4
static let RemoveButtonAnimationDamping: CGFloat = 0.6
static let NearestNeighbordScalingThreshold: CGFloat = 24
}
@objc protocol ThumbnailCellDelegate {
func didRemoveThumbnail(thumbnailCell: ThumbnailCell)
func didLongPressThumbnail(thumbnailCell: ThumbnailCell)
}
class ThumbnailCell: UICollectionViewCell {
weak var delegate: ThumbnailCellDelegate?
var imageInsets: UIEdgeInsets = UIEdgeInsetsZero
var cellInsets: UIEdgeInsets = UIEdgeInsetsZero
var imagePadding: CGFloat = 0 {
didSet {
imageView.snp_remakeConstraints { make in
let insets = UIEdgeInsets(top: imagePadding, left: imagePadding, bottom: imagePadding, right: imagePadding)
make.top.equalTo(self.imageWrapper).inset(insets.top)
make.left.equalTo(self.imageWrapper).inset(insets.left)
make.right.equalTo(self.imageWrapper).inset(insets.right)
make.bottom.equalTo(textWrapper.snp_top).offset(-imagePadding)
}
imageView.setNeedsUpdateConstraints()
}
}
var image: UIImage? = nil {
didSet {
if let image = image {
imageView.image = image
imageView.contentMode = UIViewContentMode.ScaleAspectFit
// Force nearest neighbor scaling for small favicons
if image.size.width < ThumbnailCellUX.NearestNeighbordScalingThreshold {
imageView.layer.shouldRasterize = true
imageView.layer.rasterizationScale = 2
imageView.layer.minificationFilter = kCAFilterNearest
imageView.layer.magnificationFilter = kCAFilterNearest
}
} else {
imageView.image = ThumbnailCellUX.PlaceholderImage
imageView.contentMode = UIViewContentMode.Center
}
}
}
lazy var longPressGesture: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: "SELdidLongPress")
}()
lazy var textWrapper: UIView = {
let wrapper = UIView()
wrapper.backgroundColor = ThumbnailCellUX.LabelBackgroundColor
return wrapper
}()
lazy var textLabel: UILabel = {
let textLabel = UILabel()
textLabel.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Vertical)
textLabel.font = DynamicFontHelper.defaultHelper.DefaultSmallFont
textLabel.textColor = ThumbnailCellUX.LabelColor
textLabel.textAlignment = ThumbnailCellUX.LabelAlignment
return textLabel
}()
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = UIViewContentMode.ScaleAspectFit
imageView.clipsToBounds = true
imageView.layer.cornerRadius = ThumbnailCellUX.CornerRadius
return imageView
}()
lazy var imageWrapper: UIView = {
let imageWrapper = UIView()
imageWrapper.layer.borderColor = ThumbnailCellUX.BorderColor.CGColor
imageWrapper.layer.borderWidth = ThumbnailCellUX.BorderWidth
imageWrapper.layer.cornerRadius = ThumbnailCellUX.CornerRadius
imageWrapper.clipsToBounds = true
return imageWrapper
}()
lazy var removeButton: UIButton = {
let removeButton = UIButton()
removeButton.exclusiveTouch = true
removeButton.setImage(UIImage(named: "TileCloseButton"), forState: UIControlState.Normal)
removeButton.addTarget(self, action: "SELdidRemove", forControlEvents: UIControlEvents.TouchUpInside)
removeButton.accessibilityLabel = NSLocalizedString("Remove page", comment: "Button shown in editing mode to remove this site from the top sites panel.")
removeButton.hidden = true
removeButton.imageEdgeInsets = ThumbnailCellUX.RemoveButtonInsets
return removeButton
}()
lazy var backgroundImage: UIImageView = {
let backgroundImage = UIImageView()
backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill
return backgroundImage
}()
override init(frame: CGRect) {
super.init(frame: frame)
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.mainScreen().scale
isAccessibilityElement = true
addGestureRecognizer(longPressGesture)
contentView.addSubview(imageWrapper)
imageWrapper.addSubview(backgroundImage)
backgroundImage.snp_remakeConstraints { make in
make.top.bottom.left.right.equalTo(self.imageWrapper)
}
imageWrapper.addSubview(imageView)
imageWrapper.addSubview(textWrapper)
textWrapper.addSubview(textLabel)
contentView.addSubview(removeButton)
textWrapper.snp_makeConstraints { make in
make.bottom.equalTo(self.imageWrapper.snp_bottom) // .offset(ThumbnailCellUX.BorderWidth)
make.left.right.equalTo(self.imageWrapper) // .offset(ThumbnailCellUX.BorderWidth)
}
textLabel.snp_remakeConstraints { make in
make.edges.equalTo(self.textWrapper).inset(ThumbnailCellUX.LabelInsets) // TODO swift-2.0 I changes insets to inset - how can that be right?
}
// Prevents the textLabel from getting squished in relation to other view priorities.
textLabel.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Vertical)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
// TODO: We can avoid creating this button at all if we're not in editing mode.
var frame = removeButton.frame
let insets = cellInsets
frame.size = CGSize(width: ThumbnailCellUX.RemoveButtonSize, height: ThumbnailCellUX.RemoveButtonSize)
frame.center = CGPoint(x: insets.left, y: insets.top)
removeButton.frame = frame
}
override func prepareForReuse() {
super.prepareForReuse()
backgroundImage.image = nil
removeButton.hidden = true
imageWrapper.backgroundColor = UIColor.clearColor()
textLabel.font = DynamicFontHelper.defaultHelper.DefaultSmallFont
}
func SELdidRemove() {
delegate?.didRemoveThumbnail(self)
}
func SELdidLongPress() {
delegate?.didLongPressThumbnail(self)
}
func toggleRemoveButton(show: Bool) {
// Only toggle if we change state
if removeButton.hidden != show {
return
}
if show {
removeButton.hidden = false
}
let scaleTransform = CGAffineTransformMakeScale(0.01, 0.01)
removeButton.transform = show ? scaleTransform : CGAffineTransformIdentity
UIView.animateWithDuration(ThumbnailCellUX.RemoveButtonAnimationDuration,
delay: 0,
usingSpringWithDamping: ThumbnailCellUX.RemoveButtonAnimationDamping,
initialSpringVelocity: 0,
options: [UIViewAnimationOptions.AllowUserInteraction, UIViewAnimationOptions.CurveEaseInOut],
animations: {
self.removeButton.transform = show ? CGAffineTransformIdentity : scaleTransform
}, completion: { _ in
if !show {
self.removeButton.hidden = true
}
})
}
/**
Updates the insets and padding of the cell based on the size of the container collection view
- parameter size: Size of the container collection view
*/
func updateLayoutForCollectionViewSize(size: CGSize, traitCollection: UITraitCollection) {
let cellInsets = ThumbnailCellUX.insetsForCollectionViewSize(size,
traitCollection: traitCollection)
let imageInsets = ThumbnailCellUX.imageInsetsForCollectionViewSize(size,
traitCollection: traitCollection)
if cellInsets != self.cellInsets {
self.cellInsets = cellInsets
imageWrapper.snp_remakeConstraints { make in
make.edges.equalTo(self.contentView).inset(cellInsets)
}
}
if imageInsets != self.imageInsets {
imageView.snp_remakeConstraints { make in
make.top.equalTo(self.imageWrapper).inset(imageInsets.top)
make.left.right.equalTo(self.imageWrapper).inset(imageInsets.left)
make.right.equalTo(self.imageWrapper).inset(imageInsets.right)
make.bottom.equalTo(textWrapper.snp_top).offset(-imageInsets.top)
}
}
}
}
| mpl-2.0 | ce2f4497895944d9680aad49579b246a | 38.683673 | 161 | 0.669667 | 5.682903 | false | false | false | false |
Blackjacx/SwiftTrace | Sources/Light.swift | 1 | 790 | //
// Light.swift
// SwiftTrace
//
// Created by Stefan Herold on 13/08/16.
//
//
public struct Light: JSONSerializable {
public var color: Color
public var center: Point3
/**
* Returns a light from a json object
*/
public init(json: [String: AnyObject]) throws {
guard
let color = json["color"] as? [String: AnyObject],
let center = json["center"] as? [String: AnyObject] else {
throw JSONError.decodingError(type(of: self), json)
}
self.color = try Color(json: color)
self.center = try Point3(json: center)
}
/**
* Returns a light from its components
*/
public init(center: Point3, color: Color) {
self.color = color
self.center = center
}
}
| mit | 0b952c557c9bb161e11af458538150f2 | 22.939394 | 70 | 0.572152 | 3.95 | false | false | false | false |
jantimar/Weather-forecast | Weather forecast/ForecastViewController.swift | 1 | 7414 | //
// ForecastViewController.swift
// Weather forecast
//
// Created by Jan Timar on 7.5.2015.
// Copyright (c) 2015 Jan Timar. All rights reserved.
//
import UIKit
class ForecastViewController: UITableViewController {
// MARK: Properties
private lazy var openWeatherAPIManager: OpenWeatheAPIManager = { // lazy initialization
let lazilyOpenWeatherAPIManager = OpenWeatheAPIManager()
return lazilyOpenWeatherAPIManager
}()
private var defaults = NSUserDefaults.standardUserDefaults()
private var forecasts = OpenWeatheAPIManager.Forecasts() {
didSet {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView?.reloadData()
self.navigationItem.title = self.forecasts.city
})
}
}
private var tempratureConverter = TempratureConverter()
// MARK: Life cycle methods
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
forecasts.forecast = nil
tableView.reloadData()
let useSpecificPositionForWeather = defaults.boolForKey(Constants.UsingSpecificPositionKey)
if useSpecificPositionForWeather
{ // load weather forecast from saved coordinate
let latitude = defaults.doubleForKey(Constants.LatitudeKey)
let longitude = defaults.doubleForKey(Constants.LongitudeKey)
openWeatherAPIManager.asynchronlyGetForecast(6, longitude: longitude, latitude: latitude, loadedForecasts: { (forecasts) -> () in
self.forecasts = forecasts
})
} else {
var (latitude,longitude) = WeatherLocationManager.sharedInstance.userPosition()
if latitude != nil && longitude != nil {
openWeatherAPIManager.asynchronlyGetForecast(6, longitude: longitude!, latitude: latitude!, loadedForecasts: { (forecasts) -> () in
self.forecasts = forecasts
})
}
else {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "locationUpdated:", name: Constants.UserCoordinateKey, object: nil)
}
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: Constants.UserCoordinateKey, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
var swipeRight = UISwipeGestureRecognizer(target: self, action: "swipeGesture:")
swipeRight.direction = .Right
self.tableView?.addGestureRecognizer(swipeRight)
var swipeLeft = UISwipeGestureRecognizer(target: self, action: "swipeGesture:")
swipeLeft.direction = .Left
self.tableView?.addGestureRecognizer(swipeLeft)
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return forecasts.forecast != nil ? forecasts.forecast!.count : 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Constants.TempretureCelldentifire, forIndexPath: indexPath) as! UITableViewCell
if let temperatureCell = cell as? TempretureTableViewCell {
let dayForecast = forecasts.forecast![indexPath.row]
if dayForecast.error != nil {
temperatureCell.tempratureLabel.setTextWithAnimation("")
temperatureCell.titleLabel.text = dayNameFromToday(indexPath.row)
temperatureCell.weatherDescriptionLabel.setTextWithAnimation(dayForecast.error!.description)
} else {
// set temprature in format
if let tempratureTypeRawValue = defaults.stringForKey(Constants.TempratureUnitKey) {
temperatureCell.tempratureLabel.setTextWithAnimation(String(format:"%@°", dayForecast.tempratue.tempratureInFormatFromKelvin(SettignsTableViewController.TempratureType(rawValue: tempratureTypeRawValue)!)))
} else {
temperatureCell.tempratureLabel.setTextWithAnimation(String(format:"%@°", dayForecast.tempratue.tempratureInFormatFromKelvin(.Celsius)))
}
// set image when description contain key word
temperatureCell.weatherImageView.setImageWithAnimation(UIImage.weatherImage(dayForecast.description))
temperatureCell.weatherDescriptionLabel.setTextWithAnimation(dayForecast.description.firstCharacterUpperCase())
// dont animate is still same
temperatureCell.titleLabel.text = dayNameFromToday(indexPath.row)
}
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 92.0
}
// MAKR: Help methods
func locationUpdated(notification: NSNotification) {
var (latitude,longitude) = WeatherLocationManager.sharedInstance.userPosition()
if latitude != nil && longitude != nil {
openWeatherAPIManager.asynchronlyGetForecast(6, longitude: longitude!, latitude: latitude!, loadedForecasts: { (forecasts) -> () in
self.forecasts = forecasts
})
} else {
var alertController = UIAlertController (title: "Error", message: "User position is denied", preferredStyle: .Alert)
var settingsAction = UIAlertAction(title: "Open Settings", style: .Default) { (_) -> Void in
let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
if let url = settingsUrl {
UIApplication.sharedApplication().openURL(url)
}
}
var cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
alertController.addAction(settingsAction)
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil);
}
}
private func dayNameFromToday(daysFromToday: Int) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE"
let today = NSDate()
return dateFormatter.stringFromDate(today.dateByAddingTimeInterval(NSTimeInterval(60*60*24*daysFromToday)))
}
// MARK: Gestures
@IBAction func swipeGesture(sender: UISwipeGestureRecognizer) {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
if let tabBarController = appDelegate.window?.rootViewController as? UITabBarController {
switch sender.direction {
case UISwipeGestureRecognizerDirection.Left: tabBarController.selectedIndex = 2
case UISwipeGestureRecognizerDirection.Right: tabBarController.selectedIndex = 0
default: break
}
}
}
}
}
| mit | 0830bcace76d7f6a61bfba71496902d9 | 41.597701 | 225 | 0.639234 | 5.859289 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Online/Views/OnlinePrefreshControl.swift | 1 | 1559 | //
// OnlinePrefreshControl.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/16/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
import RxSwift
import RxCocoa
import NSObject_Rx
class OnlineRefreshControl: UIRefreshControl {
private var indicatorView: NVActivityIndicatorView!
override init() {
super.init()
configure()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configure() {
tintColor = .clear
backgroundColor = .clear
let refreshContents = Bundle.main.loadNibNamed("OnlineRefreshControl", owner: self, options: nil)!
let containerView = refreshContents[0] as! UIView
indicatorView = containerView.subviews.first as! NVActivityIndicatorView
containerView.frame = bounds
self.addSubview(containerView)
self.rx.controlEvent(.valueChanged)
.map { [weak self] _ in self?.isRefreshing ?? false }
.subscribe(onNext: { [weak self] refreshing in
if refreshing { self?.beginRefreshing() }
else { self?.endRefreshing() }
})
.addDisposableTo(rx_disposeBag)
}
override func beginRefreshing() {
super.beginRefreshing()
indicatorView.startAnimating()
}
override func endRefreshing() {
super.endRefreshing()
indicatorView.stopAnimating()
}
}
| mit | 8885c01e6c2e6ba581978838480d01c5 | 26.263158 | 106 | 0.625483 | 5.25 | false | false | false | false |
amandafer/ecommerce | ecommerce/Model/User.swift | 1 | 1326 | //
// User.swift
// ecommerce
//
// Created by Amanda Fernandes on 17/04/2017.
// Copyright © 2017 Amanda Fernandes. All rights reserved.
//
import Foundation
class User {
private var _userID: String!
private var _name: String!
private var _email: String!
private var _profilePicture: String!
private var _provider: String!
var userID: String {
return _userID
}
var name: String {
return _name
}
var email: String {
return _email
}
var profilePicURL: String {
return _profilePicture
}
var provider: String {
return _provider
}
init(name: String, img: String, email: String, provider: String) {
self._name = name
self._profilePicture = img
self._email = email
self._provider = provider
}
init(userID: String, userData: Dictionary<String, String>) {
self._userID = userID
if let name = userData["name"] {
self._name = name
}
if let img = userData["picture"] {
self._profilePicture = img
}
if let email = userData["email"] {
self._email = email
}
if let provider = userData["provider"] {
self._provider = provider
}
}
}
| mit | 455b9609c392f09d2f77a1dad30f43e6 | 21.457627 | 70 | 0.548679 | 4.446309 | false | false | false | false |
saraheolson/PokeMongo | PokeMongo/GameScene.swift | 1 | 3521 | //
// GameScene.swift
// PokeMongo
//
// Created by Floater on 8/21/16.
// Copyright © 2016 SarahEOlson. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
var entities = [GKEntity]()
var graphs = [String : GKGraph]()
private var lastUpdateTime : TimeInterval = 0
private var label : SKLabelNode?
private var spinnyNode : SKShapeNode?
override func sceneDidLoad() {
self.lastUpdateTime = 0
// Get label node from scene and store it for use later
self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode
if let label = self.label {
label.alpha = 0.0
label.run(SKAction.fadeIn(withDuration: 2.0))
}
// Create shape node to use during mouse interaction
let w = (self.size.width + self.size.height) * 0.05
self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.3)
if let spinnyNode = self.spinnyNode {
spinnyNode.lineWidth = 2.5
spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(M_PI), duration: 1)))
spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5),
SKAction.fadeOut(withDuration: 0.5),
SKAction.removeFromParent()]))
}
}
func touchDown(atPoint pos : CGPoint) {
if let n = self.spinnyNode?.copy() as! SKShapeNode? {
n.position = pos
n.strokeColor = SKColor.green
self.addChild(n)
}
}
func touchMoved(toPoint pos : CGPoint) {
if let n = self.spinnyNode?.copy() as! SKShapeNode? {
n.position = pos
n.strokeColor = SKColor.blue
self.addChild(n)
}
}
func touchUp(atPoint pos : CGPoint) {
if let n = self.spinnyNode?.copy() as! SKShapeNode? {
n.position = pos
n.strokeColor = SKColor.red
self.addChild(n)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let label = self.label {
label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut")
}
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
// Initialize _lastUpdateTime if it has not already been
if (self.lastUpdateTime == 0) {
self.lastUpdateTime = currentTime
}
// Calculate time since last update
let dt = currentTime - self.lastUpdateTime
// Update entities
for entity in self.entities {
entity.update(deltaTime: dt)
}
self.lastUpdateTime = currentTime
}
}
| mit | 82c00140ce3127cccfb756efa678a1d6 | 31 | 107 | 0.570455 | 4.455696 | false | false | false | false |
Brightify/ReactantUI | Sources/Tokenizer/Util/Parsing/Implementation/ConditionParser.swift | 1 | 5351 | //
// ConditionParser.swift
// Example
//
// Created by Robin Krenecky on 30/04/2018.
//
import Foundation
extension ConditionParser {
fileprivate func toBinaryOperation(token: Lexer.Token) -> ConditionBinaryOperation? {
switch token {
case .identifier(let candidate) where candidate.lowercased() == "and":
return .and
case .identifier(let candidate) where candidate.lowercased() == "or":
return .or
case .colon:
guard let nextToken = peekNextToken() else { return nil }
switch nextToken {
case .identifier("lt"):
return .less
case .identifier("gt"):
return .greater
case .identifier("lte"):
return .lessEqual
case .identifier("gte"):
return .greaterEqual
default:
return nil
}
default:
return nil
}
}
}
// this parser uses recursive descent
// each level of functions presents a precedence
// `parseExpression` takes care of the lowest priority operators
// `parseFactor` on the other hand parses the indivisible condition parts
// EBNF as of making this parser:
// CONDITION := '[' EXPRESSION ']'
// EXPRESSION := TERM [ or TERM ]
// TERM := COMPARISON [ and COMPARISON ]
// COMPARISON := FACTOR [ ( == | != | ':gt' | ':gte' | ':lt' | 'lte' ) FACTOR ]
// FACTOR := [ '!' ] ( '(' EXPRESSION ')' | IDENTIFIER | FLOAT_NUMBER )
// FLOAT_NUMBER := { same as Swift's `Float` }
// IDENTIFIER := { all cases in the ConditionStatement enum }
class ConditionParser: BaseParser<Condition> {
override func parseSingle() throws -> Condition {
return try parseExpression()
}
private func parseExpression() throws -> Condition {
var resultCondition = try parseTerm()
while let token = peekToken(),
let operation = toBinaryOperation(token: token),
case .or = operation {
try popToken()
resultCondition = .binary(operation, resultCondition, try parseTerm())
}
return resultCondition
}
private func parseTerm() throws -> Condition {
var resultCondition = try parseComparison()
while let token = peekToken(),
let operation = toBinaryOperation(token: token),
case .and = operation {
try popToken()
resultCondition = .binary(operation, resultCondition, try parseComparison())
}
return resultCondition
}
private func parseComparison() throws -> Condition {
var resultCondition = try parseFactor()
while let token = peekToken() {
if case .equals(let equals, _) = token {
try popToken()
let rhsCondition = try parseFactor()
let mergedCondition = try mergeComparison(lhsCondition: resultCondition, rhsCondition: rhsCondition)
resultCondition = equals ? mergedCondition : .unary(.negation, mergedCondition)
} else if let binaryOperation = toBinaryOperation(token: token) {
switch binaryOperation {
case .less, .lessEqual, .greater, .greaterEqual:
break
default:
return resultCondition
}
try popTokens(2) // because of the colon and the identifier after the colon (e.g. :gt)
let rhsCondition = try parseFactor()
resultCondition = .binary(binaryOperation, resultCondition, rhsCondition)
} else {
return resultCondition
}
}
return resultCondition
}
private func mergeComparison(lhsCondition: Condition, rhsCondition: Condition) throws -> Condition {
let mergedCondition: Condition
if case .statement(let lhsStatement) = lhsCondition,
case .statement(let rhsStatement) = rhsCondition,
let mergedStatement = lhsStatement.mergeWith(statement: rhsStatement) {
mergedCondition = .statement(mergedStatement)
} else {
mergedCondition = .binary(.equal, lhsCondition, rhsCondition)
}
return mergedCondition
}
private func parseFactor() throws -> Condition {
guard let token = peekToken() else { throw ConditionError("No tokens left to parse.") }
switch token {
case .exclamation:
try popToken()
return try parseFactor().negation
case .parensOpen:
try popToken()
let parsedCondition = Condition.unary(.none, try parseExpression())
guard try matchToken(.parensClose) else { throw ConditionError("Unmatched parenthesis occured in the condition.") }
return parsedCondition
case .identifier(let identifier):
try popToken()
guard let statement = ConditionStatement(identifier: identifier) else {
throw ConditionError("Identifier `\(identifier)` is not valid condition statement.")
}
return .statement(statement)
case .number(let number, _):
try popToken()
return .statement(.number(number))
default:
throw ConditionError("Unknown factor: \(token)")
}
}
}
| mit | 50bddb53e8820e6a7be93bf00853b419 | 36.159722 | 127 | 0.595029 | 5.072038 | false | false | false | false |
bizz84/SwiftyStoreKit | SwiftyStoreKit-iOS-Demo/AppDelegate.swift | 1 | 2889 | //
// AppDelegate.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 03/09/2015.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import SwiftyStoreKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
setupIAP()
return true
}
func setupIAP() {
SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
for purchase in purchases {
switch purchase.transaction.transactionState {
case .purchased, .restored:
let downloads = purchase.transaction.downloads
if !downloads.isEmpty {
SwiftyStoreKit.start(downloads)
} else if purchase.needsFinishTransaction {
// Deliver content from server, then:
SwiftyStoreKit.finishTransaction(purchase.transaction)
}
print("\(purchase.transaction.transactionState.debugDescription): \(purchase.productId)")
case .failed, .purchasing, .deferred:
break // do nothing
@unknown default:
break // do nothing
}
}
}
SwiftyStoreKit.updatedDownloadsHandler = { downloads in
// contentURL is not nil if downloadState == .finished
let contentURLs = downloads.compactMap { $0.contentURL }
if contentURLs.count == downloads.count {
print("Saving: \(contentURLs)")
SwiftyStoreKit.finishTransaction(downloads[0].transaction)
}
}
}
}
| mit | a2ac0ac2b4d78fec21c900c3883ce451 | 38.575342 | 151 | 0.649706 | 5.440678 | false | false | false | false |
remobjects/ElementsSamples | Silver/Echoes/WPF/Sorter/Window1.xaml.swift | 1 | 3113 | import System.Collections.Generic
import System.Linq
import System.Windows
import System.Windows.Controls
import System.Windows.Data
import System.Windows.Documents
import System.Windows.Media
import System.Windows.Navigation
import System.Windows.Shapes
import System.Windows.Media.Animation
public class Window1 {
public init() {
InitializeComponent();
FillGrid();
}
var fRectangles: Rectangle[]!
var fPositions: Double[]!
let fRandom = Random()
let fLoColor = [Colors.Blue, Colors.Green, Colors.Yellow, Colors.Pink, Colors.Coral, Colors.Cyan, Colors.Salmon]
let fHiColor = [Colors.LightBlue, Colors.LightGreen, Colors.LightYellow, Colors.LightPink , Colors.LightCoral, Colors.LightCyan, Colors.LightSalmon]
func Randomize(_ sender: System.Object!, _ e: System.Windows.RoutedEventArgs!) {
FillGrid();
}
func Sort(_ sender: System.Object!, _ e: System.Windows.RoutedEventArgs!) {
var lDelay = 0;
Sort(0, fRectangles.Length - 1, &lDelay);
}
private func FillGrid() {
MainCanvas.Children.Clear();
fRectangles = Rectangle[](50);
fPositions = Double[](50);
var lWidth = Width / 52.0;
for i in 0 ..< 50 {
var r = Rectangle();
r.HorizontalAlignment = HorizontalAlignment.Stretch;
r.VerticalAlignment = VerticalAlignment.Bottom;
r.Fill = LinearGradientBrush(fLoColor[i % count(fLoColor)], fHiColor[i % count(fHiColor)], 20);
r.Height = fRandom.NextDouble() * (Height - 80) + 10;
r.Width = lWidth;
Canvas.SetLeft(r, i * r.Width);
Canvas.SetTop(r, -r.Height);
r.Opacity = 0.75;
Grid.SetColumn(r, i);
fRectangles[i] = r;
fPositions[i] = i * r.Width;
MainCanvas.Children.Add(r);
}
}
private func Sort(_ aLeft: Integer, _ aRight: Integer, inout _ aDelay: Int) {
var aLeft = aLeft;
while aLeft < aRight {
var L = aLeft - 1;
var R = aRight + 1;
var Pivot = fRectangles[(aLeft + aRight) / 2].Height;
while true {
repeat {
R -= 1;
} while fRectangles[R].Height > Pivot;
repeat {
L += 1;
} while fRectangles[L].Height < Pivot;
if L < R {
Switch(L, R, aDelay);
aDelay = aDelay + 1;
} else {
break;
}
}
if aLeft < R {
Sort(aLeft, R, &aDelay);
}
aLeft = R + 1;
}
}
private func Switch(_ aOne: Integer, _ aTwo: Integer, _ aDelay: Integer) {
var lDuration = Duration(TimeSpan(0, 0, 0, 0, 200)) // 0.5 second
var lStartDelay = TimeSpan(0, 0, 0, aDelay / 4, (aDelay % 4) * 250); // 0.5 second
var lAnim1 = DoubleAnimation();
lAnim1.Duration = lDuration;
lAnim1.BeginTime = lStartDelay;
lAnim1.To = fPositions[aTwo];
var lAnim2 = DoubleAnimation();
lAnim2.Duration = lDuration;
lAnim2.BeginTime = lStartDelay;
lAnim2.To = fPositions[aOne];
fRectangles[aOne].BeginAnimation(Canvas.LeftProperty, lAnim1, HandoffBehavior.Compose);
fRectangles[aTwo].BeginAnimation(Canvas.LeftProperty, lAnim2, HandoffBehavior.Compose);
var r = fRectangles[aOne];
fRectangles[aOne] = fRectangles[aTwo];
fRectangles[aTwo] = r;
}
} | mit | 885d9ff6afc35aa92dc546a454b871ff | 25.794643 | 149 | 0.650916 | 3.029211 | false | false | false | false |
songzhw/2iOS | iOS_Swift/iOS_Swift/biz/basiclesson/chat/ChatRegisterViewController.swift | 1 | 1289 | import UIKit
import Firebase
import MBProgressHUD
// [email protected] ; 123qwe
// ref: https://firebase.google.com/docs/auth/ios/password-auth#swift_2
class ChatRegisterViewController : UIViewController {
@IBOutlet weak var tfEmail: UITextField!
@IBOutlet weak var tfPwd: UITextField!
@IBAction func registerPressed(_ sender: UIButton) {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.label.text = "waiting.."
if let email = tfEmail.text, let pwd = tfPwd.text {
Auth.auth().createUser(withEmail: email, password: pwd) { result, optionalError in
hud.mode = .text
if let error = optionalError {
print("register error = \(error.localizedDescription)")
hud.label.text = error.localizedDescription
//localized意味着显示当前手机上的语言. (只有msg, 没有ErrorCode这些其它的因素). 要是密码过短, 那这个消息就是:"The password must be 6 characters long or more."
} else {
// self.navigationController?.popViewController(animated: true)
self.performSegue(withIdentifier: "RegisterToChat", sender: self)
hud.label.text = "register succ!"
}
hud.hide(animated: true, afterDelay: 1)
}
}
}
}
| apache-2.0 | 9bf831bda767972b9867fcf88f5c1ff4 | 33.714286 | 130 | 0.662551 | 4.063545 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Blockchain/FeatureApp/RootView/RootView.swift | 1 | 9465 | // Copyright © 2021 Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import BlockchainNamespace
import ComposableArchitecture
import ComposableNavigation
import DIKit
import ErrorsUI
import FeatureAppUI
import FeatureInterestUI
import Localization
import MoneyKit
import SwiftUI
struct Tab: Hashable, Identifiable, Codable {
var id: AnyHashable { tag }
var tag: Tag.Reference
var name: String
var ux: UX.Dialog?
var url: URL?
var icon: Icon
}
extension Tab: CustomStringConvertible {
var description: String { tag.string }
}
extension Tab {
var ref: Tag.Reference { tag }
// swiftlint:disable force_try
// OA Add support for pathing directly into a reference
// e.g. ref.descendant(blockchain.ux.type.story, \.entry)
func entry() -> Tag.Reference {
try! ref.tag.as(blockchain.ux.type.story).entry[].ref(to: ref.context)
}
}
let _app = app
struct RootView: View {
var app: AppProtocol = _app
let store: Store<RootViewState, RootViewAction>
@ObservedObject private var viewStore: ViewStore<RootViewState, RootViewAction>
init(store: Store<RootViewState, RootViewAction>) {
self.store = store
viewStore = ViewStore(store)
setupApperance()
}
func setupApperance() {
UITabBar.appearance().backgroundImage = UIImage()
UITabBar.appearance().barTintColor = .white
UITabBar.appearance().tintColor = .brandPrimary
}
var body: some View {
Group {
TabView(selection: viewStore.binding(\.$tab)) {
tabs(in: viewStore)
}
.overlay(
FloatingActionButton(isOn: viewStore.binding(\.$fab.isOn).animation(.spring()))
.identity(blockchain.ux.frequent.action)
.background(
Circle()
.fill(Color.semantic.background)
.padding(Spacing.padding1)
)
.pulse(enabled: viewStore.fab.animate, inset: 8)
.padding([.leading, .trailing], 24.pt)
.offset(y: 6.pt)
.contentShape(Rectangle())
.background(Color.white.invisible())
.if(viewStore.hideFAB, then: { view in view.hidden() }),
alignment: .bottom
)
.ignoresSafeArea(.keyboard, edges: .bottom)
}
.bottomSheet(
isPresented: viewStore.binding(\.$isAppModeSwitcherPresented).animation(.spring()),
content: {
IfLetStore(
store.scope(
state: \.appModeSwitcherState,
action: RootViewAction.appModeSwitcherAction
),
then: { store in
AppModeSwitcherView(store: store)
}
)
}
)
.bottomSheet(isPresented: viewStore.binding(\.$fab.isOn).animation(.spring())) {
IfLetStore(store.scope(state: \.fab.data)) { store in
WithViewStore(store) { viewStore in
FrequentActionView(
list: viewStore.list,
buttons: viewStore.buttons
)
}
}
}
.onReceive(app.on(blockchain.ux.home.tab.select)) { event in
do {
try viewStore.send(.tab(event.reference.context.decode(blockchain.ux.home.tab.id)))
} catch {
app.post(error: error)
}
}
.onChange(of: viewStore.tab) { tab in
app.post(event: tab.tag)
}
.onAppear {
app.post(event: viewStore.tab.tag)
}
.onAppear {
viewStore.send(.onAppear)
}
.onDisappear {
viewStore.send(.onDisappear)
}
.navigationRoute(in: store)
.app(app)
}
func tabs(in viewStore: ViewStore<RootViewState, RootViewAction>) -> some View {
ForEach(viewStore.tabs ?? []) { tab in
tabItem(tab) {
switch tab.tag {
case blockchain.ux.user.portfolio:
PortfolioView(store: store.stateless)
case blockchain.ux.prices:
PricesView(store: store.stateless)
case blockchain.ux.frequent.action:
Icon.blockchain
.frame(width: 32.pt, height: 32.pt)
case blockchain.ux.buy_and_sell:
BuySellView(selectedSegment: viewStore.binding(\.$buyAndSell.segment))
case blockchain.ux.user.rewards:
RewardsView()
case blockchain.ux.user.activity:
ActivityView()
case blockchain.ux.maintenance:
maintenance(tab)
case blockchain.ux.nft.collection:
AssetListViewController()
case blockchain.ux.web:
if let url = tab.url {
WebView(url: url)
} else {
maintenance(tab)
}
default:
#if DEBUG
fatalError("Unhandled \(tab)")
#else
maintenance(tab)
#endif
}
}
}
}
@ViewBuilder func maintenance(_ tab: Tab) -> some View {
if let ux = tab.ux {
ErrorView(
ux: UX.Error(nabu: ux),
dismiss: {}
)
}
}
@ViewBuilder func tabItem<Content>(
_ tab: Tab,
@ViewBuilder content: @escaping () -> Content
) -> some View where Content: View {
PrimaryNavigationView {
content()
.primaryNavigation(
leading: leadingViews,
title: viewStore.appSwitcherEnabled ? "" : tab.name.localized(),
trailing: trailingViews
)
}
.tabItem {
Label(
title: {
Text(tab.name.localized())
.typography(.micro)
},
icon: { tab.icon.image }
)
.identity(tab.entry())
}
.tag(tab.ref)
.identity(tab.ref)
}
@ViewBuilder func trailingViews() -> some View {
Group {
referrals()
.if(!viewStore.referralState.isVisible, then: { view in view.hidden() })
QR()
if viewStore.appSwitcherEnabled {
account()
}
}
}
@ViewBuilder func leadingViews() -> some View {
Group {
if viewStore.appSwitcherEnabled, let appMode = viewStore.appMode {
appModeSwitcher(with: appMode)
} else {
account()
}
}
}
@ViewBuilder func referrals() -> some View {
let onReferralTapAction: () -> Void = {
viewStore.send(.onReferralTap)
}
IconButton(icon: Icon.giftboxHighlighted.renderingMode(.original), action: onReferralTapAction)
.if(
!viewStore.referralState.isHighlighted,
then: { view in view.update(icon: Icon.giftbox) }
)
.identity(blockchain.ux.referral.entry)
}
@ViewBuilder func appModeSwitcher(with appMode: AppMode) -> some View {
AppModeSwitcherButton(
appMode: appMode,
action: {
viewStore.send(.onAppModeSwitcherTapped)
}
)
.identity(blockchain.ux.switcher.entry)
}
@ViewBuilder func QR() -> some View {
WithViewStore(store.stateless) { viewStore in
IconButton(icon: .qrCode) {
viewStore.send(.enter(into: .QR, context: .none))
}
.identity(blockchain.ux.scan.QR.entry)
}
}
@ViewBuilder func account() -> some View {
WithViewStore(store) { viewStore in
IconButton(icon: .user) {
viewStore.send(.enter(into: .account, context: .none))
}
.overlay(Badge(count: viewStore.unreadSupportMessageCount))
.identity(blockchain.ux.user.account.entry)
}
}
}
// swiftlint:disable empty_count
struct Badge: View {
let count: Int
var body: some View {
if count > 0 {
ZStack(alignment: .topTrailing) {
Color.clear
Text(count.description)
.typography(.micro.bold())
.foregroundColor(.semantic.light)
.padding(4)
.background(Color.semantic.error)
.clipShape(Circle())
.alignmentGuide(.top) { $0[.bottom] }
.alignmentGuide(.trailing) { $0[.trailing] - $0.width * 0.2 }
}
}
}
}
extension Color {
/// A workaround to ensure taps are not passed through to the view behind
func invisible() -> Color {
opacity(0.001)
}
}
extension View {
@ViewBuilder
func identity(_ tag: Tag.Event, in context: Tag.Context = [:]) -> some View {
id(tag.description)
.accessibility(identifier: tag.description)
}
}
| lgpl-3.0 | 2202ca8445e4e066a2ca422b6e7d1f5a | 30.029508 | 103 | 0.514899 | 4.813835 | false | false | false | false |
allbto/ios-angular-waythere | ios/WayThere/Pods/Nimble/Nimble/Matchers/BeLessThan.swift | 78 | 1533 | import Foundation
/// A Nimble matcher that succeeds when the actual value is less than the expected value.
public func beLessThan<T: Comparable>(expectedValue: T?) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be less than <\(stringify(expectedValue))>"
return actualExpression.evaluate() < expectedValue
}
}
/// A Nimble matcher that succeeds when the actual value is less than the expected value.
public func beLessThan(expectedValue: NMBComparable?) -> NonNilMatcherFunc<NMBComparable> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be less than <\(stringify(expectedValue))>"
let actualValue = actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == NSComparisonResult.OrderedAscending
return matches
}
}
public func <<T: Comparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beLessThan(rhs))
}
public func <(lhs: Expectation<NMBComparable>, rhs: NMBComparable?) {
lhs.to(beLessThan(rhs))
}
extension NMBObjCMatcher {
public class func beLessThanMatcher(expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage, location in
let expr = actualExpression.cast { $0 as! NMBComparable? }
return beLessThan(expected).matches(expr, failureMessage: failureMessage)
}
}
}
| mit | 3b47cefae7ef5c4530126c8ac673a968 | 41.583333 | 122 | 0.725375 | 5.093023 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Objects/data types/enumerable/XGTrainerClass.swift | 1 | 2342 | //
// XGTrainerClass.swift
// XG Tool
//
// Created by StarsMmd on 16/06/2015.
// Copyright (c) 2015 StarsMmd. All rights reserved.
//
import Foundation
let kFirstTrainerClassDataOffset = CommonIndexes.TrainerClasses.startOffset
let kSizeOfTrainerClassEntry = 0x0C
let kNumberOfTrainerClasses = CommonIndexes.NumberOfTrainerClasses.value
// Prize money is payout * max pokemon level * 2
let kTrainerClassPayoutOffset = 0x00
let kTrainerClassNameIDOffset = 0x04
final class XGTrainerClass: NSObject, Codable {
var payout = 0
var nameID = 0
var index = 0
var name : XGString {
get {
return XGFiles.common_rel.stringTable.stringSafelyWithID(self.nameID)
}
}
var startOffset : Int {
get {
return kFirstTrainerClassDataOffset + (self.index * kSizeOfTrainerClassEntry)
}
}
var dictionaryRepresentation : [String : AnyObject] {
get {
var dictRep = [String : AnyObject]()
dictRep["name"] = self.name.string as AnyObject?
dictRep["payout"] = self.payout as AnyObject?
return dictRep
}
}
var readableDictionaryRepresentation : [String : AnyObject] {
get {
var dictRep = [String : AnyObject]()
dictRep["payout"] = self.payout as AnyObject?
return ["\(self.index) " + self.name.string : dictRep as AnyObject]
}
}
init(index: Int) {
super.init()
self.index = index
let rel = XGFiles.common_rel.data!
let start = self.startOffset
self.payout = rel.get2BytesAtOffset(start + kTrainerClassPayoutOffset)
self.nameID = rel.getWordAtOffset(start + kTrainerClassNameIDOffset).int
}
func save() {
let rel = XGFiles.common_rel.data!
let start = self.startOffset
rel.replaceWordAtOffset(start + kTrainerClassNameIDOffset, withBytes: UInt32(self.nameID))
rel.replace2BytesAtOffset(start + kTrainerClassPayoutOffset, withBytes: self.payout)
rel.save()
}
}
extension XGTrainerClass: XGEnumerable {
var enumerableName: String {
return name.string
}
var enumerableValue: String? {
return String(format: "%02d", index)
}
static var className: String {
return "Trainer Classes"
}
static var allValues: [XGTrainerClass] {
var values = [XGTrainerClass]()
for i in 0 ..< CommonIndexes.NumberOfTrainerClasses.value {
values.append(XGTrainerClass(index: i))
}
return values
}
}
| gpl-2.0 | 8f99ddc368d37beb357cfabe9c151fa1 | 18.196721 | 92 | 0.704526 | 3.379509 | false | false | false | false |
CodeInventorGroup/CIComponentKit | Sources/CIComponentKit/CICButton.swift | 1 | 8748 | //
// CICButton.swift
// CIComponentKit
//
// Created by ManoBoo on 2017/11/22.
// Copyright © 2017年 club.codeinventor. All rights reserved.
// UIControl自定义Button,添加多种状态支持
import UIKit
/// CICButton的状态
///
/// - normal: 正常状态
/// - selected: 选中
/// - highlighted: 高亮
/// - disabled: 不可用
/// - loading: 加载中(常见于网络请求)
//public enum CICButtonState: Int {
// case normal = 0
//
// case selected
//
// case highlighted
//
// case disabled
//
// case loading
//}
//UIControlState
public struct CICButtonState: OptionSet, Hashable {
public static let normal = CICButtonState.init(rawValue: 1)
public static let selected = CICButtonState.init(rawValue: 2)
public static let highlighted = CICButtonState.init(rawValue: 4)
public static let disabled = CICButtonState.init(rawValue: 8)
public static let loading = CICButtonState.init(rawValue: 32)
public var rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public var hashValue: Int {
return rawValue.hashValue
}
public static func == (lhs: CICButtonState, rhs: CICButtonState) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
/// 默认提供的image title布局位置
public enum CICButtonLayout {
case leftImage // rightTitle
case topImage // bottomTitle
case bottomImage // topTitle
case rightImage // leftTitle
}
/// CICButton style
public struct CICButtonStyle {
var title: String?
var titleColor: UIColor?
var titleShadowColor: UIColor?
var font: UIFont?
var image: UIImage?
var backgroundImage: UIImage?
var attributeString: NSAttributedString?
}
public class CICButton: CICUIView {
open var state: CICButtonState = .normal {
didSet {
renderState()
}
}
/// 是否被选中
open var isSelected: Bool {
return state == .selected
}
/// 返回当前的样式及标题等
open var currentStyle: CICButtonStyle? {
return stateMapStyle[state]
}
/// 默认图片在左边
open var currentLayout: CICButtonLayout = .leftImage
open var titleInsets: UIEdgeInsets = .zero
open var imageInsets: UIEdgeInsets = .zero
/// 布局, 默认为nil, 若使用该自定义布局, `currentLayout` 将无效
open var layoutMaker: ((CICButton) -> Void)?
/// 加载中点击按钮是否响应
var isEnabledWhenLoading = false
typealias CICButtonHandler = ((CICButton) -> Void)
private var stateMapStyle = [CICButtonState: CICButtonStyle]()
var control: UIControl = UIControl()
var backgroundImageView = UIImageView()
open var imageView = UIImageView()
open var titleLabel = UILabel()
var activityView = UIActivityIndicatorView.init(style: UIActivityIndicatorView.Style.white)
init() {
super.init(frame: .zero)
initSubviews()
}
public override init(frame: CGRect) {
super.init(frame: frame)
initSubviews()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initSubviews() {
addSubview(backgroundImageView)
addSubview(imageView)
titleLabel.textColor(UIButton.appearance().tintColor ?? .black)
.font(UIFont.cic.systemFont)
addSubview(titleLabel)
activityView.isHidden = true
addSubview(activityView)
addSubview(control)
stateMapStyle = [.normal: CICButtonStyle(),
.selected: CICButtonStyle(),
.highlighted: CICButtonStyle(),
.disabled: CICButtonStyle(),
.loading: CICButtonStyle()]
}
func render() {
renderState()
if let layoutMaker = layoutMaker {
layoutMaker(self)
} else {
// 展开默认布局
imageView.sizeToFit()
titleLabel.sizeToFit()
switch currentLayout {
case .leftImage:
imageView.x(imageInsets.left).y(imageInsets.top)
titleLabel.x(imageView.cic.right + titleInsets.left).y(titleInsets.top)
case .rightImage:
titleLabel.x(titleInsets.left).y(titleInsets.top)
imageView.x(titleLabel.cic.right + imageInsets.left).y(imageInsets.top)
case .topImage:
imageView.y(imageInsets.top)
titleLabel.y(imageView.cic.bottom + imageInsets.bottom + titleInsets.top)
case .bottomImage:
titleLabel.y(titleInsets.top)
imageView.y(titleLabel.cic.bottom + titleInsets.bottom)
}
}
}
func renderState() {
guard let style = stateMapStyle[state] else {
return
}
backgroundImageView.image = style.backgroundImage
imageView.image = style.image
if let attributeString = style.attributeString {
titleLabel.attributedText = attributeString
} else {
titleLabel.text(style.title)
.textColor(style.titleColor ?? .black)
.font(style.font ?? UIFont.cic.systemFont)
}
if state == .loading {
activityView.startAnimating()
}
activityView.isHidden = !(state == .loading)
}
public override func sizeThatFits(_ size: CGSize) -> CGSize {
super.sizeThatFits(size)
render()
var fitSize = size
switch currentLayout {
case .leftImage, .rightImage:
fitSize.width = CGFloat.maximum(titleLabel.cic.right + titleInsets.right,
imageView.cic.right + imageInsets.right)
fitSize.height = CGFloat.maximum(titleLabel.cic.bottom + titleInsets.bottom,
imageView.cic.bottom + imageInsets.bottom)
titleLabel.centerY(fitSize.height / 2.0)
imageView.centerY(fitSize.height / 2.0)
case .topImage, .bottomImage:
fitSize.height = CGFloat.maximum(titleLabel.cic.bottom + titleInsets.bottom,
imageView.cic.bottom + imageInsets.bottom)
fitSize.width = CGFloat.maximum(titleLabel.cic.right + titleInsets.right,
imageView.cic.right + imageInsets.right)
titleLabel.centerX(fitSize.width / 2.0)
imageView.centerX(fitSize.width / 2.0)
}
return fitSize
}
public override func layoutSubviews() {
super.layoutSubviews()
control.frame(self.bounds)
renderState()
if let layoutMaker = layoutMaker {
layoutMaker(self)
}
}
}
// MARK: - add CICButtonState support
extension CICButton {
public func setTitle(_ title: String = "", for state: CICButtonState) {
stateMapStyle[state]?.title = title
}
public func setTitleColor(_ color: UIColor?, for state: CICButtonState) {
stateMapStyle[state]?.titleColor = color
}
public func setTitleShadowColor(_ color: UIColor?, for state: CICButtonState) {
stateMapStyle[state]?.titleShadowColor = color
}
public func setImage(_ image: UIImage?, for state: CICButtonState) {
stateMapStyle[state]?.image = image
}
public func setBackgroundImage(_ image: UIImage?, for state: CICButtonState) {
stateMapStyle[state]?.backgroundImage = image
}
@available(iOS 6.0, *)
public func setAttributedTitle(_ title: NSAttributedString?, for state: CICButtonState) {
stateMapStyle[state]?.attributeString = title
}
public func title(for state: CICButtonState) -> String? {
return stateMapStyle[state]?.title
}
public func titleColor(for state: CICButtonState) -> UIColor? {
return stateMapStyle[state]?.titleColor
}
public func titleShadowColor(for state: CICButtonState) -> UIColor? {
return stateMapStyle[state]?.titleShadowColor
}
public func image(for state: CICButtonState) -> UIImage? {
return stateMapStyle[state]?.image
}
public func backgroundImage(for state: CICButtonState) -> UIImage? {
return stateMapStyle[state]?.backgroundImage
}
@available(iOS 6.0, *)
public func attributedTitle(for state: CICButtonState) -> NSAttributedString? {
return stateMapStyle[state]?.attributeString
}
}
extension CICButton {
public func addHandler(for event: UIControl.Event, handler: @escaping ((UIControl) -> Void)) {
control.addHandler(for: event, handler: handler)
}
}
| mit | 7bae562e52ed3302564d60c52893e968 | 30.065455 | 98 | 0.621327 | 4.605391 | false | false | false | false |
Jnosh/swift | test/SILOptimizer/inout_deshadow_integration.swift | 18 | 3082 | // RUN: %target-swift-frontend %s -emit-sil | %FileCheck %s
// This is an integration check for the inout-deshadow pass, verifying that it
// deshadows the inout variables in certain cases. These test should not be
// very specific (as they are running the parser, silgen and other sil
// diagnostic passes), they should just check the inout shadow got removed.
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_dead
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_dead(a: inout Int) {
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_returned(a: inout Int) -> Int {
return a
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_stored
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_stored(a: inout Int) {
a = 12
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_trivial_type_stored_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_trivial_type_stored_returned(a: inout Int) -> Int {
a = 12
return a
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_dead
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_dead(a: inout String) {
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_returned(a: inout String) -> String {
return a
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_stored
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_stored(a: inout String) {
a = "x"
}
// CHECK-LABEL: sil hidden @{{.*}}exploded_nontrivial_type_stored_returned
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
func exploded_nontrivial_type_stored_returned(a: inout String) -> String {
a = "x"
return a
}
// Use an external function so inout deshadowing cannot see its body.
@_silgen_name("takesNoEscapeClosure")
func takesNoEscapeClosure(fn : () -> Int)
struct StructWithMutatingMethod {
var x = 42
// We should be able to deshadow this. The closure is capturing self, but it
// is itself noescape.
mutating func mutatingMethod() {
takesNoEscapeClosure { x = 42; return x }
}
mutating func testStandardLibraryOperators() {
if x != 4 || x != 0 {
testStandardLibraryOperators()
}
}
}
// CHECK-LABEL: sil hidden @_T026inout_deshadow_integration24StructWithMutatingMethodV08mutatingG0{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout StructWithMutatingMethod) -> () {
// CHECK-NOT: alloc_box
// CHECK-NOT: alloc_stack
// CHECK: }
// CHECK-LABEL: sil hidden @_T026inout_deshadow_integration24StructWithMutatingMethodV28testStandardLibraryOperators{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout StructWithMutatingMethod) -> () {
// CHECK-NOT: alloc_box $<τ_0_0> { var τ_0_0 } <StructWithMutatingMethod>
// CHECK-NOT: alloc_stack $StructWithMutatingMethod
// CHECK: }
| apache-2.0 | b052d257c9b88423728a2ceb078a40e1 | 28.333333 | 199 | 0.698052 | 3.5 | false | false | false | false |
linkedin/LayoutKit | LayoutKitSampleApp/MenuViewController.swift | 3 | 2174 | // Copyright 2016 LinkedIn Corp.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import UIKit
/// The main menu for the sample app.
class MenuViewController: UITableViewController {
private let reuseIdentifier = " "
private let viewControllers: [UIViewController.Type] = [
BenchmarkViewController.self,
FeedScrollViewController.self,
FeedCollectionViewController.self,
FeedTableViewController.self,
StackViewController.self,
NestedCollectionViewController.self,
ForegroundMiniProfileViewController.self,
BackgroundMiniProfileViewController.self,
OverlayViewController.self,
BatchUpdatesCollectionViewController.self,
BatchUpdatesTableViewController.self
]
convenience init() {
self.init(style: .grouped)
title = "Menu"
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewControllers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
cell.textLabel?.text = String(describing: viewControllers[indexPath.row])
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let viewController = viewControllers[indexPath.row].init()
viewController.title = String(describing: viewController)
navigationController?.pushViewController(viewController, animated: true)
}
}
| apache-2.0 | 489cda99ed9c49ff2d6e2e0afa704b80 | 38.527273 | 131 | 0.726771 | 5.435 | false | false | false | false |
joelrorseth/AtMe | AtMe/BlockedUsersViewController.swift | 1 | 5020 | //
// BlockedUsersViewController.swift
// AtMe
//
// Created by Joel Rorseth on 2017-08-03.
// Copyright © 2017 Joel Rorseth. All rights reserved.
//
import UIKit
class BlockedUsersViewController: UITableViewController {
lazy var databaseManager = DatabaseController()
lazy var authManager = AuthController()
var blockedUsers: [UserProfile] = []
/**
Called when the view is done loading in the view controller.
*/
override func viewDidLoad() {
super.viewDidLoad()
// Immediately ask AuthController for blocked users to populate
// Insert these into table view directly since it will return asynchronously
authManager.findCurrentUserBlockedUsers(completion: { user in
self.blockedUsers.append(user)
self.tableView.insertRows(at: [IndexPath(row: self.blockedUsers.count - 1, section: 0)], with: .automatic)
})
self.title = "Blocked"
self.tableView.tableFooterView = UIView()
}
// MARK: - Table view
/**
Determine the number of sections in the table view.
*/
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
/**
Determine the number of rows in a given section of the table view.
*/
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if blockedUsers.count == 0 {
// Create a custom label / view to display when empty
let label = UILabel(frame: tableView.frame)
label.font = Constants.Fonts.emptyViewMessageFont
label.backgroundColor = UIColor.groupTableViewBackground
label.textColor = UIColor.darkGray
label.text = Constants.Messages.noBlockedUsersMessage
label.textAlignment = NSTextAlignment.center
label.translatesAutoresizingMaskIntoConstraints = false
label.sizeToFit()
tableView.backgroundView = label
tableView.separatorStyle = UITableViewCellSeparatorStyle.none
} else {
// Restore to normal look when content is available
tableView.backgroundView = nil
tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
}
return blockedUsers.count
}
/**
Determine the contents of a table view cell at a given index path.
*/
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.CellIdentifiers.blockedUserCell, for: indexPath) as! BlockedUserCell
// Important: Set delegate for button so this view controller knows about taps
cell.blockUserCellDelegate = self
cell.unblockButton.layer.cornerRadius = Constants.Radius.regularRadius
// Extract user info from relevant data source record
cell.nameLabel.text = blockedUsers[indexPath.row].name
cell.usernameLabel.text = "@" + blockedUsers[indexPath.row].username
let uid = blockedUsers[indexPath.row].uid
let path = "displayPictures/\(uid)/\(uid).JPG"
// Also important: Set uid and username for use in the cell delegate
cell.uid = uid
cell.username = blockedUsers[indexPath.row].username
// Download the image into the display picture image view
databaseManager.downloadImage(into: cell.displayPictureImageView, from: path, completion: { _ in
cell.displayPictureImageView.layer.masksToBounds = true
cell.displayPictureImageView.layer.cornerRadius = cell.displayPictureImageView.frame.size.width / 2
})
return cell
}
}
extension BlockedUsersViewController: BlockedUserCellDelegate {
/**
Handle unblocking the selected user and removing them from the table.
- parameters:
- button: A reference to the button which was selected to trigger this change.
- uid: The uid of the user selected to be unblocked.
- username: The username of the user selected to be unblocked.
*/
func didTapUnblock(button: UIButton, uid: String, username: String) {
UIView.animate(withDuration: 0.2, animations: {
button.backgroundColor = UIColor.groupTableViewBackground
button.alpha = 0.0
}, completion: { _ in
// Unblock the user and remove that row from table and data source
self.authManager.unblockUser(uid: uid, username: username)
for (index, user) in self.blockedUsers.enumerated() {
if (uid == user.uid) {
self.blockedUsers.remove(at: index)
self.tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
}
}
})
}
}
| apache-2.0 | a3f15dc05e727fecafcfba2c92075d6c | 35.369565 | 143 | 0.639968 | 5.277603 | false | false | false | false |
Tj3n/TVNExtensions | Rx/QLPreviewController+Rx.swift | 1 | 2697 | //
// QLPreviewController+Rx.swift
// TVNExtensions
//
// Created by TienVu on 3/5/19.
//
import Foundation
import RxSwift
import RxCocoa
import QuickLook
public protocol RxQLPreviewControllerDataSourceType {
associatedtype Element
func previewController(_ controller: QLPreviewController, observedEvent: Event<Element>) -> Void
}
public class RxQLPreviewControllerDataSource<I: QLPreviewItem>: QLPreviewControllerDataSource, RxQLPreviewControllerDataSourceType {
public typealias Element = [I]
var items = [I]()
public init() {
}
public func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return items.count
}
public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return items[index]
}
public func previewController(_ controller: QLPreviewController, observedEvent: Event<[I]>) {
Binder(self) { dataSource, items in
dataSource.items = items
controller.reloadData()
}
.on(observedEvent)
}
}
extension Reactive where Base: QLPreviewController {
public var delegate: DelegateProxy<QLPreviewController, QLPreviewControllerDelegate> {
return RxQLPreviewControllerDelegateProxy.proxy(for: base)
}
public func items<
DataSource: RxQLPreviewControllerDataSourceType & QLPreviewControllerDataSource,
O: ObservableType>
(dataSource: DataSource)
-> (_ source: O)
-> Disposable
where DataSource.Element == O.Element {
return { source in
let unregisterDelegate = RxQLPreviewControllerDataSourceProxy
.installForwardDelegate(dataSource,
retainDelegate: true,
onProxyForObject: self.base)
let subscription = source
.observeOn(MainScheduler())
.catchError { error in
return Observable.empty()
}
.concat(Observable.never())
.takeUntil(self.base.rx.deallocated)
.subscribe({ [weak controller = self.base](event) in
guard let controller = controller else { return }
dataSource.previewController(controller, observedEvent: event)
})
return Disposables.create {
subscription.dispose()
unregisterDelegate.dispose()
}
}
}
}
| mit | 4d39d247ef55c249c9606dbae0ae0bf5 | 32.7125 | 132 | 0.589544 | 6.10181 | false | false | false | false |
jjjjaren/jCode | jCode/Classes/UserDefaults/UserPreferences.swift | 1 | 1689 | //
// UserPreferences.swift
// HamblinTech
//
// Created by Jaren Hamblin on 3/6/17.
// Copyright © 2017 Jaren Hamblin Healthcare, Inc. All rights reserved.
//
import Foundation
public class UserPreferences {
public let userIdentifier: String
public let userDefaults: UserDefaults
fileprivate struct Constants {
static let preferenceTouchId = "com.app.PreferenceTouchId"
}
public init(userIdentifier: String) {
self.userIdentifier = userIdentifier
self.userDefaults = UserDefaults(suiteName: userIdentifier)!
}
// MARK: - Default User Preference Instance Properties
/// Touch ID preference
public var isTouchIdEnabled: Bool {
get {
let value = userDefaults.bool(forKey: Constants.preferenceTouchId)
return value
}
set {
userDefaults.set(newValue, forKey: Constants.preferenceTouchId)
userDefaults.synchronize()
}
}
// MARK: - Default User Preference Static Methods
/// Returns the Touch ID preference
public static func getTouchIdPreference(for userIdentifier: String?) -> Bool {
guard let userIdentifier = userIdentifier else { return false }
let value = UserPreferences(userIdentifier: userIdentifier).isTouchIdEnabled
return value
}
/// Updates the Touch ID preference
public static func setTouchID(enabled: Bool, for userIdentifier: String?) {
guard let userIdentifier = userIdentifier else { return }
UserPreferences(userIdentifier: userIdentifier).isTouchIdEnabled = enabled
}
}
| mit | 91080effc585c4766fa0d6bf4bfba57c | 26.225806 | 84 | 0.652251 | 5.462783 | false | false | false | false |
TH-Brandenburg/University-Evaluation-iOS | Pods/ImageViewer/ImageViewer/Source/ImageViewer/ImageViewer.swift | 1 | 21441 | //
// ImageViewer.swift
// Money
//
// Created by Kristian Angyal on 06/10/2015.
// Copyright © 2015 Mail Online. All rights reserved.
//
import UIKit
import AVFoundation
/*
Features:
- double tap to toggle betweeen Aspect Fit & Aspect Fill zoom factor
- manual pinch to zoom up to approx. 4x the size of full-sized image
- rotation support
- swipe to dismiss
- initiation and completion blocks to support a case where the original image node should be hidden or unhidden alongside show and dismiss animations
Usage:
- Initialize ImageViewer, set optional initiation and completion blocks, and present by calling "presentImageViewer".
How it works:
- Gets presented modally via convenience UIViewControler extension, using custom modal presentation that is enforced internally.
- Displays itself in full screen (nothing is visible at that point, but it's there, trust me...)
- Makes a screenshot of the displaced view that can be any UIView (or subclass) really, but UIImageView is the most probable choice.
- Puts this screenshot into a new UIImageView and matches its position and size to the displaced view.
- Sets the target size and position for the UIImageView to aspectFit size and centered while kicking in the black overlay.
- Animates the image view into the scroll view (that serves as zooming canvas) and reaches final position and size.
- Immediately tries to get a full-sized version of the image from imageProvider.
- If successful, replaces the screenshot in the image view with probably a higher-res image.
- Gets dismissed either via Close button, or via "swipe up/down" gesture.
- While being "closed", image is animated back to it's "original" position which is a rect that matches to the displaced view's position
which overall gives us the illusion of the UI element returning to its original place.
*/
public final class ImageViewer: UIViewController, UIScrollViewDelegate, UIViewControllerTransitioningDelegate {
/// UI
private var scrollView = UIScrollView()
private var overlayView = UIView()
private var closeButton = UIButton()
private var imageView = UIImageView()
private let displacedView: UIView
private var applicationWindow: UIWindow? {
return UIApplication.sharedApplication().delegate?.window?.flatMap { $0 }
}
/// LOCAL STATE
private var parentViewFrameInOurCoordinateSystem = CGRectZero
private var isAnimating = false
private var shouldRotate = false
private var isSwipingToDismiss = false
private var dynamicTransparencyActive = false
private let imageProvider: ImageProvider
/// LOCAL CONFIG
private let configuration: ImageViewerConfiguration
private var initialCloseButtonOrigin = CGPointZero
private var closeButtonSize = CGSize(width: 50, height: 50)
private let closeButtonPadding = 8.0
private let showDuration = 0.25
private let dismissDuration = 0.25
private let showCloseButtonDuration = 0.2
private let hideCloseButtonDuration = 0.05
private let zoomDuration = 0.2
private let thresholdVelocity: CGFloat = 1000 // Based on UX experiments
private let cutOffVelocity: CGFloat = 1000000 // we simply need some sufficiently large number, nobody can swipe faster than that
/// TRANSITIONS
private let presentTransition: ImageViewerPresentTransition
private let dismissTransition: ImageViewerDismissTransition
private let swipeToDismissTransition: ImageViewerSwipeToDismissTransition
/// LIFE CYCLE BLOCKS
/// Executed right before the image animation into its final position starts.
public var showInitiationBlock: (Void -> Void)?
/// Executed as the last step after all the show animations.
public var showCompletionBlock: (Void -> Void)?
/// Executed as the first step before the button's close action starts.
public var closeButtonActionInitiationBlock: (Void -> Void)?
/// Executed as the last step for close button's close action.
public var closeButtonActionCompletionBlock: (Void -> Void)?
/// Executed as the first step for swipe to dismiss action.
public var swipeToDismissInitiationBlock: (Void -> Void)?
/// Executed as the last step for swipe to dismiss action.
public var swipeToDismissCompletionBlock: (Void -> Void)?
/// Executed as the last step when the ImageViewer is dismissed (either via the close button, or swipe)
public var dismissCompletionBlock: (Void -> Void)?
/// INTERACTIONS
private let doubleTapRecognizer = UITapGestureRecognizer()
private let panGestureRecognizer = UIPanGestureRecognizer()
// MARK: - Deinit
deinit {
scrollView.removeObserver(self, forKeyPath: "contentOffset")
}
// MARK: - Initializers
public init(imageProvider: ImageProvider, configuration: ImageViewerConfiguration, displacedView: UIView) {
self.imageProvider = imageProvider
self.configuration = configuration
self.displacedView = displacedView
self.presentTransition = ImageViewerPresentTransition(duration: showDuration)
self.dismissTransition = ImageViewerDismissTransition(duration: dismissDuration)
self.swipeToDismissTransition = ImageViewerSwipeToDismissTransition()
super.init(nibName: nil, bundle: nil)
transitioningDelegate = self
modalPresentationStyle = .Custom
extendedLayoutIncludesOpaqueBars = true
overlayView.autoresizingMask = [.None]
configureCloseButton()
configureImageView()
configureScrollView()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Configuration
private func configureCloseButton() {
let closeButtonAssets = configuration.closeButtonAssets
closeButton.setImage(closeButtonAssets.normal, forState: UIControlState.Normal)
closeButton.setImage(closeButtonAssets.highlighted, forState: UIControlState.Highlighted)
closeButton.alpha = 0.0
closeButton.addTarget(self, action: #selector(ImageViewer.close(_:)), forControlEvents: .TouchUpInside)
}
private func configureGestureRecognizers() {
doubleTapRecognizer.addTarget(self, action: #selector(ImageViewer.scrollViewDidDoubleTap(_:)))
doubleTapRecognizer.numberOfTapsRequired = 2
scrollView.addGestureRecognizer(doubleTapRecognizer)
panGestureRecognizer.addTarget(self, action: #selector(ImageViewer.scrollViewDidPan(_:)))
view.addGestureRecognizer(panGestureRecognizer)
}
private func configureImageView() {
parentViewFrameInOurCoordinateSystem = CGRectIntegral(applicationWindow!.convertRect(displacedView.bounds, fromView: displacedView))
imageView.frame = parentViewFrameInOurCoordinateSystem
imageView.contentMode = .ScaleAspectFit
imageView.image = screenshotFromView(displacedView)
}
private func configureScrollView() {
scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
scrollView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
scrollView.decelerationRate = 0.5
scrollView.contentInset = UIEdgeInsetsZero
scrollView.contentOffset = CGPointZero
scrollView.contentSize = imageView.frame.size
scrollView.minimumZoomScale = 1
scrollView.delegate = self
}
func createViewHierarchy() {
view.addSubview(overlayView)
view.addSubview(imageView)
view.addSubview(scrollView)
view.addSubview(closeButton)
}
// MARK: - View Lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
createViewHierarchy()
}
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
shouldRotate = true
}
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
scrollView.frame = view.bounds
let originX = -view.bounds.width
let originY = -view.bounds.height
let width = view.bounds.width * 4
let height = view.bounds.height * 4
overlayView.frame = CGRect(origin: CGPoint(x: originX, y: originY), size: CGSize(width: width, height: height))
closeButton.frame = CGRect(origin: CGPoint(x: view.bounds.size.width - CGFloat(closeButtonPadding) - closeButtonSize.width, y: CGFloat(closeButtonPadding)), size: closeButtonSize)
if shouldRotate {
shouldRotate = false
rotate()
}
}
// MARK: - Transitioning Delegate
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return presentTransition
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return isSwipingToDismiss ? swipeToDismissTransition : dismissTransition
}
// MARK: - Animations
func close(sender: AnyObject) {
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
func rotate() {
guard UIDevice.currentDevice().orientation.isFlat == false &&
isAnimating == false else { return }
isAnimating = true
UIView.animateWithDuration(hideCloseButtonDuration, animations: { self.closeButton.alpha = 0.0 })
let aspectFitSize = aspectFitContentSize(forBoundingSize: rotationAdjustedBounds().size, contentSize: displacedView.frame.size)
UIView.animateWithDuration(showDuration, animations: { () -> Void in
if isPortraitOnly() {
self.view.transform = rotationTransform()
}
self.view.bounds = rotationAdjustedBounds()
self.imageView.bounds = CGRect(origin: CGPointZero, size: aspectFitSize)
self.imageView.center = self.scrollView.center
self.scrollView.contentSize = self.imageView.bounds.size
self.scrollView.setZoomScale(1.0, animated: false)
}) { (finished) -> Void in
if (finished) {
self.isAnimating = false
self.scrollView.maximumZoomScale = maximumZoomScale(forBoundingSize: rotationAdjustedBounds().size, contentSize: self.imageView.bounds.size)
UIView.animateWithDuration(self.showCloseButtonDuration, animations: { self.closeButton.alpha = 1.0 })
}
}
}
func showAnimation(duration: NSTimeInterval, completion: ((Bool) -> Void)?) {
guard isAnimating == false else { return }
isAnimating = true
showInitiationBlock?()
displacedView.hidden = true
overlayView.alpha = 0.0
overlayView.backgroundColor = UIColor.blackColor()
UIView.animateWithDuration(duration, animations: {
self.view.transform = rotationTransform()
self.overlayView.alpha = 1.0
self.view.bounds = rotationAdjustedBounds()
let aspectFitSize = aspectFitContentSize(forBoundingSize: rotationAdjustedBounds().size, contentSize: self.configuration.imageSize)
self.imageView.bounds = CGRect(origin: CGPointZero, size: aspectFitSize)
self.imageView.center = rotationAdjustedCenter(self.view)
self.scrollView.contentSize = self.imageView.bounds.size
}) { (finished) -> Void in
completion?(finished)
if finished {
if isPortraitOnly() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ImageViewer.rotate), name: UIDeviceOrientationDidChangeNotification, object: nil)
}
self.applicationWindow!.windowLevel = UIWindowLevelStatusBar + 1
self.scrollView.addSubview(self.imageView)
self.imageProvider.provideImage { [weak self] image in
self?.imageView.image = image
}
self.isAnimating = false
self.scrollView.maximumZoomScale = maximumZoomScale(forBoundingSize: rotationAdjustedBounds().size, contentSize: self.imageView.bounds.size)
UIView.animateWithDuration(self.showCloseButtonDuration, animations: { self.closeButton.alpha = 1.0 })
self.configureGestureRecognizers()
self.showCompletionBlock?()
self.displacedView.hidden = false
}
}
}
func closeAnimation(duration: NSTimeInterval, completion: ((Bool) -> Void)?) {
guard (self.isAnimating == false) else { return }
isAnimating = true
closeButtonActionInitiationBlock?()
displacedView.hidden = true
UIView.animateWithDuration(hideCloseButtonDuration, animations: { self.closeButton.alpha = 0.0 })
UIView.animateWithDuration(duration, animations: {
self.scrollView.zoomScale = self.scrollView.minimumZoomScale
self.overlayView.alpha = 0.0
self.closeButton.alpha = 0.0
self.view.transform = CGAffineTransformIdentity
self.view.bounds = (self.applicationWindow?.bounds)!
self.imageView.frame = CGRectIntegral(self.applicationWindow!.convertRect(self.displacedView.bounds, fromView: self.displacedView))
}) { (finished) -> Void in
completion?(finished)
if finished {
NSNotificationCenter.defaultCenter().removeObserver(self)
self.applicationWindow!.windowLevel = UIWindowLevelNormal
self.displacedView.hidden = false
self.isAnimating = false
self.closeButtonActionCompletionBlock?()
self.dismissCompletionBlock?()
}
}
}
func swipeToDismissAnimation(withVerticalTouchPoint verticalTouchPoint: CGFloat, targetOffset: CGFloat, verticalVelocity: CGFloat, completion: ((Bool) -> Void)?) {
/// In units of "vertical velocity". for example if we have a vertical velocity of 50 units (which are points really) per second
/// and the distance to travel is 175 units, then our spring velocity is 3.5. I.e. we will travel 3.5 units in 1 second.
let springVelocity = fabs(verticalVelocity / (targetOffset - verticalTouchPoint))
/// How much time it will take to travel the remaining distance given the above speed.
let expectedDuration = NSTimeInterval( fabs(targetOffset - verticalTouchPoint) / fabs(verticalVelocity))
UIView.animateWithDuration(expectedDuration, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: springVelocity, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
self.scrollView.setContentOffset(CGPoint(x: 0, y: targetOffset), animated: false)
}, completion: { (finished) -> Void in
completion?(finished)
if finished {
NSNotificationCenter.defaultCenter().removeObserver(self)
self.view.transform = CGAffineTransformIdentity
self.view.bounds = (self.applicationWindow?.bounds)!
self.imageView.frame = self.parentViewFrameInOurCoordinateSystem
self.overlayView.alpha = 0.0
self.closeButton.alpha = 0.0
self.isAnimating = false
self.isSwipingToDismiss = false
self.dynamicTransparencyActive = false
self.swipeToDismissCompletionBlock?()
self.dismissCompletionBlock?()
}
})
}
private func swipeToDismissCanceledAnimation() {
UIView.animateWithDuration(zoomDuration, animations: { () -> Void in
self.scrollView.setContentOffset(CGPointZero, animated: false)
}, completion: { (finished) -> Void in
if finished {
self.applicationWindow!.windowLevel = UIWindowLevelStatusBar + 1
self.isAnimating = false
self.isSwipingToDismiss = false
self.dynamicTransparencyActive = false
}
})
}
// MARK: - Interaction Handling
func scrollViewDidDoubleTap(recognizer: UITapGestureRecognizer) {
let touchPoint = recognizer.locationOfTouch(0, inView: imageView)
let aspectFillScale = aspectFillZoomScale(forBoundingSize: rotationAdjustedBounds().size, contentSize: imageView.bounds.size)
if (scrollView.zoomScale == 1.0 || scrollView.zoomScale > aspectFillScale) {
let zoomingRect = zoomRect(ForScrollView: scrollView, scale: aspectFillScale, center: touchPoint)
UIView.animateWithDuration(zoomDuration, animations: {
self.scrollView.zoomToRect(zoomingRect, animated: false)
})
}
else {
UIView.animateWithDuration(zoomDuration, animations: {
self.scrollView.setZoomScale(1.0, animated: false)
})
}
}
func scrollViewDidPan(recognizer: UIPanGestureRecognizer) {
guard scrollView.zoomScale == scrollView.minimumZoomScale else { return }
if isSwipingToDismiss == false {
swipeToDismissInitiationBlock?()
displacedView.hidden = false
}
isSwipingToDismiss = true
dynamicTransparencyActive = true
let targetOffsetToReachEdge = (view.bounds.height / 2) + (imageView.bounds.height / 2)
let lastTouchPoint = recognizer.translationInView(view)
let verticalVelocity = recognizer.velocityInView(view).y
switch recognizer.state {
case .Began:
applicationWindow!.windowLevel = UIWindowLevelNormal
fallthrough
case .Changed:
scrollView.setContentOffset(CGPoint(x: 0, y: -lastTouchPoint.y), animated: false)
case .Ended:
handleSwipeToDismissEnded(verticalVelocity, lastTouchPoint: lastTouchPoint, targetOffset: targetOffsetToReachEdge)
default:
break
}
}
func handleSwipeToDismissEnded(verticalVelocity: CGFloat, lastTouchPoint: CGPoint, targetOffset: CGFloat) {
let velocity = abs(verticalVelocity)
switch velocity {
case 0 ..< thresholdVelocity:
swipeToDismissCanceledAnimation()
case thresholdVelocity ... cutOffVelocity:
let offset = (verticalVelocity > 0) ? -targetOffset : targetOffset
let touchPoint = (verticalVelocity > 0) ? -lastTouchPoint.y : lastTouchPoint.y
swipeToDismissTransition.setParameters(touchPoint, targetOffset: offset, verticalVelocity: verticalVelocity)
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
default: break
}
}
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
public func scrollViewDidZoom(scrollView: UIScrollView) {
imageView.center = contentCenter(forBoundingSize: scrollView.bounds.size, contentSize: scrollView.contentSize)
}
// MARK: - KVO
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) {
if (dynamicTransparencyActive == true && keyPath == "contentOffset") {
let transparencyMultiplier: CGFloat = 10
let velocityMultiplier: CGFloat = 300
let distanceToEdge = (scrollView.bounds.height / 2) + (imageView.bounds.height / 2)
overlayView.alpha = 1 - fabs(scrollView.contentOffset.y / distanceToEdge)
closeButton.alpha = 1 - fabs(scrollView.contentOffset.y / distanceToEdge) * transparencyMultiplier
let newY = CGFloat(closeButtonPadding) - abs(scrollView.contentOffset.y / distanceToEdge) * velocityMultiplier
closeButton.frame = CGRect(origin: CGPoint(x: closeButton.frame.origin.x, y: newY), size: closeButton.frame.size)
}
}
} | apache-2.0 | eef86877460a6713c22f32a7732f8da1 | 42.227823 | 224 | 0.656157 | 5.726496 | false | false | false | false |
KarlWarfel/nutshell-ios | Nutshell/Utilities and Extensions/UIApplicationExtension.swift | 1 | 1466 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import Foundation
import UIKit
extension UIApplication {
class func appVersion() -> String {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
}
class func appBuild() -> String {
return NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey as String) as! String
}
// class func versionBuildServer() -> String {
// let version = appVersion(), build = appBuild()
//
// var serverName: String = ""
// for server in servers {
// if (server.1 == baseURL) {
// serverName = server.0
// break
// }
// }
//
// return serverName.isEmpty ? "v.\(version) (\(build))" : "v.\(version) (\(build)) on \(serverName)"
// }
} | bsd-2-clause | acd2f39005d4e7caa5603626e26e4282 | 33.928571 | 108 | 0.657572 | 4.5387 | false | false | false | false |
tranhieutt/Swiftz | Swiftz/StringExt.swift | 1 | 5557 | //
// StringExt.swift
// Swiftz
//
// Created by Maxwell Swadling on 8/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
/// An enum representing the possible values a string can match against.
public enum StringMatcher {
/// The empty string.
case Nil
/// A cons cell.
case Cons(Character, String)
}
extension String {
/// Returns an array of strings at newlines.
public func lines() -> [String] {
return self.componentsSeparatedByString("\n")
}
/// Concatenates an array of strings into a single string containing newlines between each
/// element.
public static func unlines(xs : [String]) -> String {
return xs.reduce("", combine: { "\($0)\($1)\n" })
}
/// Appends a character onto the front of a string.
public static func cons(head : Character, tail : String) -> String {
return String(head) + tail
}
/// Creates a string of n repeating characters.
public static func replicate(n : UInt, value : Character) -> String {
var l = ""
for _ in 0..<n {
l = String.cons(value, tail: l)
}
return l
}
/// Destructures a string. If the string is empty the result is .Nil, otherwise the result is
/// .Cons(head, tail).
public func match() -> StringMatcher {
if self.characters.count == 0 {
return .Nil
} else if self.characters.count == 1 {
return .Cons(self[self.startIndex], "")
}
return .Cons(self[self.startIndex], self[self.startIndex.successor()..<self.endIndex])
}
/// Returns a string containing the characters of the receiver in reverse order.
public func reverse() -> String {
return self.reduce(flip(String.cons), initial: "")
}
/// Maps a function over the characters of a string and returns a new string of those values.
public func map(f : Character -> Character) -> String {
switch self.match() {
case .Nil:
return ""
case let .Cons(hd, tl):
return String(f(hd)) + tl.map(f)
}
}
/// Removes characters from the receiver that do not satisfy a given predicate.
public func filter(p : Character -> Bool) -> String {
switch self.match() {
case .Nil:
return ""
case let .Cons(x, xs):
return p(x) ? (String(x) + xs.filter(p)) : xs.filter(p)
}
}
/// Applies a binary operator to reduce the characters of the receiver to a single value.
public func reduce<B>(f : B -> Character -> B, initial : B) -> B {
switch self.match() {
case .Nil:
return initial
case let .Cons(x, xs):
return xs.reduce(f, initial: f(initial)(x))
}
}
/// Applies a binary operator to reduce the characters of the receiver to a single value.
public func reduce<B>(f : (B, Character) -> B, initial : B) -> B {
switch self.match() {
case .Nil:
return initial
case let .Cons(x, xs):
return xs.reduce(f, initial: f(initial, x))
}
}
/// Takes two lists and returns true if the first string is a prefix of the second string.
public func isPrefixOf(r : String) -> Bool {
switch (self.match(), r.match()) {
case (.Cons(let x, let xs), .Cons(let y, let ys)) where (x == y):
return xs.isPrefixOf(ys)
case (.Nil, _):
return true
default:
return false
}
}
/// Takes two lists and returns true if the first string is a suffix of the second string.
public func isSuffixOf(r : String) -> Bool {
return self.reverse().isPrefixOf(r.reverse())
}
/// Takes two lists and returns true if the first string is contained entirely anywhere in the
/// second string.
public func isInfixOf(r : String) -> Bool {
func tails(l : String) -> [String] {
return l.reduce({ x, y in
return [String.cons(y, tail: x.first!)] + x
}, initial: [""])
}
return tails(r).any(self.isPrefixOf)
}
/// Takes two strings and drops items in the first from the second. If the first string is not a
/// prefix of the second string this function returns Nothing.
public func stripPrefix(r : String) -> Optional<String> {
switch (self.match(), r.match()) {
case (.Nil, _):
return .Some(r)
case (.Cons(let x, let xs), .Cons(let y, _)) where x == y:
return xs.stripPrefix(xs)
default:
return .None
}
}
/// Takes two strings and drops items in the first from the end of the second. If the first
/// string is not a suffix of the second string this function returns nothing.
public func stripSuffix(r : String) -> Optional<String> {
return self.reverse().stripPrefix(r.reverse()).map({ $0.reverse() })
}
}
extension String : Monoid {
public typealias M = String
public static var mempty : String {
return ""
}
public func op(other : String) -> String {
return self + other
}
}
public func <>(l : String, r : String) -> String {
return l + r
}
extension String : Functor {
public typealias A = Character
public typealias B = Character
public typealias FB = String
public func fmap(f : Character -> Character) -> String {
return self.map(f)
}
}
public func <^> (f : Character -> Character, l : String) -> String {
return l.fmap(f)
}
extension String : Pointed {
public static func pure(x : Character) -> String {
return String(x)
}
}
extension String : Applicative {
public typealias FAB = [Character -> Character]
public func ap(a : [Character -> Character]) -> String {
return a.map(self.map).reduce("", combine: +)
}
}
public func <*> (f : Array<(Character -> Character)>, l : String) -> String {
return l.ap(f)
}
extension String : Monad {
public func bind(f : Character -> String) -> String {
return Array(self.characters).map(f).reduce("", combine: +)
}
}
public func >>- (l : String, f : Character -> String) -> String {
return l.bind(f)
}
| bsd-3-clause | 5e3c99e8fa1d7aa3999b654b42bcaa11 | 26.240196 | 98 | 0.656829 | 3.292062 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab3Sell/views/SLVPhotoSelectionCell.swift | 1 | 2707 | //
// SLVPhotoSelectionCell.swift
// selluv-ios
//
// Created by 조백근 on 2016. 12. 1..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
import Foundation
import UIKit
class SLVPhotoSelectionCell: UICollectionViewCell {
@IBOutlet weak var thumnail: UIImageView! {
didSet {
thumnail.clipsToBounds = true
}
}
@IBOutlet weak var remove: UIButton!
@IBOutlet weak var modify: UIButton!
var path: IndexPath?
var photoMode:PhotoControllerMode = .default
var controlBlock: PhotoControlBlock?
var isViewer: Bool = false {
didSet {
if isViewer == true {
self.modify.isHidden = true
self.remove.isHidden = true
} else {
self.modify.isHidden = false
self.remove.isHidden = false
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
}
public func thumbnailFrame() -> CGRect {
let bounds = contentView.bounds
let viewWidth = bounds.size.width
let viewHeight = bounds.size.height
let cellWidth = viewWidth * 0.571
let cellHeight = viewHeight * 0.733
let padding_y = (viewHeight - cellHeight)/2
let padding_x = (viewWidth - cellWidth)/2
let rect = CGRect(x: padding_x, y: 8, width: cellWidth, height: cellHeight)
return rect
}
func checkEditingImage() {
let model = TempInputInfoModel.shared.currentModel
let photoItem: MyPhoto?
switch self.photoMode {
case .default :
photoItem = model.photoList[path!.row]
break
case .demage :
photoItem = model.demagePhotoList[path!.row]
break
case .accessory :
photoItem = model.accessoryPhotoList[path!.row]
break
default :
photoItem = nil
break
}
if let item = photoItem {
if item.customFrame != .zero {
if item.editingImage() != nil {
thumnail.image = item.editingImage()!
}
}
}
}
func onControlBlock( block: @escaping PhotoControlBlock) {
self.controlBlock = block
}
@IBAction func touchRemove(_ sender: Any) {
self.controlBlock!(path!, true)
}
@IBAction func touchModify(_ sender: Any) {
self.controlBlock!(path!, false)
}
}
| mit | b784ac3a9381f08708dc054469ddcb7a | 25.194175 | 83 | 0.554485 | 4.659758 | false | false | false | false |
apptentive/apptentive-ios | add_photo_library_usage_description.swift | 1 | 4422 | #!/usr/bin/swift
import Foundation
func addPhotoLibraryUsageDescription(to plistURL: URL, forLanguage language: String) {
let usageDescriptions = [
"ar": "يُتيح ذلك إرفاق الصور بالرسائل.",
"da": "Dette giver mulighed for, at billeder kan vedhæftes beskeder.",
"de": "Dies erlaubt das Anhängen von Bildern an einer Nachricht",
"el": "Αυτό επιτρέπει στις εικόνες να επισυναφθούν στα μηνύματα.",
"en": "This allows images to be attached to messages.",
"es": "Esto permite adjuntar fotografías a los mensajes.",
"fr-CA": "Ceci permet que des images soient ajoutées en pièce jointe aux messages.",
"fr": "Ceci permet aux images d'être incluses aux messages.",
"it": "Ciò consente di allegare immagini ai messaggi.",
"ja": "これによって画像をメッセージに添付できます。",
"ko": "이렇게 하면 이미지를 메시지에 첨부할 수 있습니다.",
"nl": "Hiermee kunnen afbeeldingen aan berichten worden bijgevoegd.",
"pl": "To pozwala na załączanie zdjęć do wiadomości.",
"pt-BR": "Isso permite que as imagens sejam anexadas às mensagens.",
"pt": "Isto permite que imagens sejam anexadas a mensagens.",
"ru": "Это позволяет прикреплять изображения к сообщениям.",
"sv": "Detta gör att bilder kan bifogas i meddelanden.",
"tr": "Bu, mesajlara görüntü eklenmesini sağlar.",
"zh-Hans": "这能让图片作为消息的附件。",
"zh-Hant": "這能讓圖片作為消息的附件。"
]
guard let usageDescription = usageDescriptions[language] else {
print("Warning: This script is missing a localization for language code “\(language)”")
return;
}
guard let plist = NSMutableDictionary(contentsOf: plistURL) else {
print("Warning: Unable to open plist file for language code “\(language)”")
return
}
let usageDescriptionKey: NSString = "NSPhotoLibraryUsageDescription"
guard plist.object(forKey: usageDescriptionKey) == nil else {
print("Warning: plist for language “\(language)” has an existing value for \(usageDescriptionKey) that will not be replaced")
return;
}
print("Info: Adding photo library usage description for language “\(language)” (“\(usageDescription)”)")
plist.setObject(usageDescription, forKey: usageDescriptionKey)
plist.write(to: plistURL, atomically: true)
}
guard CommandLine.arguments.count == 2 else {
print("Usage: \(CommandLine.arguments[0]) path/to/Info.plist")
exit(1)
}
let path = CommandLine.arguments[1]
let infoPlistURL = URL(fileURLWithPath: path, isDirectory: true)
guard infoPlistURL.lastPathComponent == "Info.plist", FileManager.default.fileExists(atPath: infoPlistURL.path) else {
print("Error: First argument must be a path to your project's Info.plist file.")
exit(1)
}
let parentURL = infoPlistURL.deletingLastPathComponent()
let isLocalized = parentURL.lastPathComponent == "Base.lproj"
if isLocalized {
do {
let children = try FileManager.default.contentsOfDirectory(at: parentURL.deletingLastPathComponent(), includingPropertiesForKeys: nil, options: [])
for child in children where child.pathExtension == "lproj" {
let language = child.deletingPathExtension().lastPathComponent
if language == "Base" {
continue
}
let localizedInfoPlistURL = child.appendingPathComponent("Info.plist")
guard FileManager.default.fileExists(atPath: localizedInfoPlistURL.path) else {
print("Warning: Info.plist file is missing for language \(language)")
continue
}
addPhotoLibraryUsageDescription(to: localizedInfoPlistURL, forLanguage: language)
}
}
catch let error as NSError {
print("Error: Unable to find contents of URL \(parentURL) (\(error.description))")
}
}
guard let basePlist = NSDictionary(contentsOf: infoPlistURL) else {
print("Error: Unable to open base plist file “\(infoPlistURL)”")
exit(1)
}
guard let region = basePlist.object(forKey: "CFBundleDevelopmentRegion") as? String else {
print("Error: Unable to get development region from base plist file “\(infoPlistURL)”")
exit(1)
}
guard let language = region.components(separatedBy: "_").first else {
print("Error: Unable to get language from region code “\(region)”")
exit(1)
}
addPhotoLibraryUsageDescription(to: infoPlistURL, forLanguage: language)
| bsd-3-clause | 9b6b03cb919d7a206ece3ff2ef4b8f86 | 36.4 | 152 | 0.730676 | 3.159754 | false | false | false | false |
lyimin/SwiftExtension | String+LC.swift | 1 | 1291 | //
// String.swift
// EmaTechProject
//
// Created by 梁亦明 on 2017/2/10.
// Copyright © 2017年 xiaoming.com. All rights reserved.
//
import Foundation
extension String {
/// 获取字符串长度
var length: Int {
return characters.count
}
/// 获取子字符串索引
func indexOfString(target: String) -> Int {
let range = self.rangeOfString(target)
if let range = range {
return self.startIndex.distanceTo(range.startIndex)
} else {
return self.length
}
}
/// 判断字符串是否为空
var isEmpty: Bool {
if self == "" {
return true
}
return false
}
// 计算文字宽高
func size(withFont font: UIFont, maxSize size: CGSize) -> CGSize {
let attrs = [NSFontAttributeName: font]
return (self as NSString).boundingRectWithSize(size, options: .UsesLineFragmentOrigin, attributes: attrs, context: nil).size
}
subscript (r: Range<Int>) -> String {
get {
let startIndex = self.startIndex.advancedBy(r.startIndex)
let endIndex = self.startIndex.advancedBy(r.endIndex)
return self[startIndex..<endIndex]
}
}
}
| mit | e3b08ac21ddd94f3f771331bd0cc6401 | 22.056604 | 132 | 0.56874 | 4.395683 | false | false | false | false |
amoriello/trust-line-ios | Trustline/DataControllerHelper.swift | 1 | 3781 | //
// CoreData.swift
// Trustline
//
// Created by matt on 09/11/2015.
// Copyright © 2015 amoriello.hutti. All rights reserved.
//
import Foundation
import CoreData
protocol NamedCDComponent : class {
@nonobjc static var ComponentName: String { get }
}
extension CDAccount : NamedCDComponent {
@nonobjc static let ComponentName = "CDAccount"
}
extension CDProfile : NamedCDComponent {
@nonobjc static let ComponentName = "CDProfile"
}
extension CDSecurityQA : NamedCDComponent {
@nonobjc static let ComponentName = "CDSecurityQA"
}
extension CDSettings : NamedCDComponent {
@nonobjc static let ComponentName = "CDSettings"
}
extension CDStrength : NamedCDComponent {
@nonobjc static let ComponentName = "CDStrength"
}
extension CDPairedToken : NamedCDComponent {
@nonobjc static let ComponentName = "CDPairedToken"
}
extension CDUsageInfo : NamedCDComponent {
@nonobjc static let ComponentName = "CDUsageInfo"
}
extension CDLogin : NamedCDComponent {
@nonobjc static let ComponentName = "CDLogin"
}
func createCDObject<T:NamedCDComponent>(managedContext: NSManagedObjectContext) -> T {
let objEntity = NSEntityDescription.entityForName(T.ComponentName, inManagedObjectContext: managedContext)!
let obj = NSManagedObject(entity: objEntity, insertIntoManagedObjectContext: managedContext) as! T
return obj
}
enum TryResult<T> {
case Value(T)
case Error(ErrorType)
}
func safeTry<T>(block: () throws -> T) -> TryResult<T> {
do {
let value = try block()
return TryResult.Value(value)
} catch {
return TryResult.Error(error)
}
}
func loadCDObjects<T:NamedCDComponent>(managedContext: NSManagedObjectContext) -> [T]? {
let fetchRequest = NSFetchRequest(entityName: T.ComponentName);
let result = safeTry { try managedContext.executeFetchRequest(fetchRequest) as! [T] }
switch result {
case .Value(let value):
return value
case .Error(let error):
print("Error fecthing \(T.ComponentName): \(error)");
return nil
}
}
class Default {
class func Profile(managedCtx: NSManagedObjectContext) -> CDProfile {
let profile : CDProfile = createCDObject(managedCtx)
profile.creation = NSDate()
profile.name = "default"
profile.accounts = Set<CDAccount>()
let settings = Default.Settings(forProfile: profile, managedCtx: managedCtx)
profile.settings = settings;
return profile
}
private class func Settings(forProfile profile: CDProfile, managedCtx: NSManagedObjectContext) -> CDSettings {
let settings : CDSettings = createCDObject(managedCtx)
settings.useiCloud = false;
settings.layoutOption = CDSettings.KeyboardLayoutOptions.EnglishUS
settings.strengths = Default.Strengths(settings, managedCtx: managedCtx)
settings.profile = profile
return settings;
}
private class func Strengths(defaultSettings: CDSettings, managedCtx: NSManagedObjectContext) -> Set<CDStrength> {
let createStrength = { (nbChars: Int16, description: String, settings: CDSettings) -> CDStrength in
let strength : CDStrength = createCDObject(managedCtx)
strength.nbChars = nbChars
strength.pickerDescription = description
strength.settings = [defaultSettings]
return strength
}
let serious = createStrength(8, "Serious (8)", defaultSettings)
let strong = createStrength(15, "Strong (15)", defaultSettings)
let insane = createStrength(25, "Insane (25)", defaultSettings)
let ludicrous = createStrength(40, "Ludicrous (40)", defaultSettings)
return [serious, strong, insane, ludicrous]
}
}
class AccountHelper {
private class func decryptAccounts(encryptedAccounts: [CDAccount], token: Token) -> [CDAccount]? {
return nil
}
}
| mit | 0b01a59640465661b729a68d8218f0a2 | 25.068966 | 116 | 0.721693 | 4.099783 | false | false | false | false |
samsymons/Photon | Tests/BufferTests.swift | 1 | 1783 | // BufferTests.swift
// Copyright (c) 2017 Sam Symons
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Cocoa
import XCTest
import Photon
final class BufferTests: XCTestCase {
func testInitialization() {
let buffer = Buffer(width: 100, height: 100)
XCTAssertEqual(buffer.pixelData.count, 100 * 100)
}
func testSubscripts() {
let buffer = Buffer(width: 100, height: 100)
let pixel = PixelData(r: 255, g: 255, b: 255)
buffer[(50, 50)] = pixel
XCTAssertEqual(buffer[(50, 50)], pixel)
}
func testIteration() {
var iterationCount = 0
let buffer = Buffer(width: 10, height: 10)
for _ in buffer {
iterationCount += 1
}
XCTAssertEqual(iterationCount, buffer.size)
}
}
| mit | e2d92efd605378c3c273e5b31e08f91c | 32.641509 | 80 | 0.725182 | 4.306763 | false | true | false | false |
manavgabhawala/swift | test/IRGen/sil_witness_tables.swift | 1 | 3890 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-module -o %t %S/sil_witness_tables_external_conformance.swift
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -assume-parsing-unqualified-ownership-sil -I %t -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
import sil_witness_tables_external_conformance
// FIXME: This should be a SIL test, but we can't parse sil_witness_tables
// yet.
protocol A {}
protocol P {
associatedtype Assoc: A
static func staticMethod()
func instanceMethod()
}
protocol Q : P {
func qMethod()
}
protocol QQ {
func qMethod()
}
struct AssocConformer: A {}
struct Conformer: Q, QQ {
typealias Assoc = AssocConformer
static func staticMethod() {}
func instanceMethod() {}
func qMethod() {}
}
// CHECK: [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE:@_T039sil_witness_tables_external_conformance17ExternalConformerVAA0F1PAAWP]] = external global i8*, align 8
// CHECK: [[CONFORMER_Q_WITNESS_TABLE:@_T018sil_witness_tables9ConformerVAA1QAAWP]] = hidden constant [2 x i8*] [
// CHECK: i8* bitcast ([4 x i8*]* [[CONFORMER_P_WITNESS_TABLE:@_T018sil_witness_tables9ConformerVAA1PAAWP]] to i8*),
// CHECK: i8* bitcast (void (%T18sil_witness_tables9ConformerV*, %swift.type*, i8**)* @_T018sil_witness_tables9ConformerVAA1QA2aDP7qMethod{{[_0-9a-zA-Z]*}}FTW to i8*)
// CHECK: ]
// CHECK: [[CONFORMER_P_WITNESS_TABLE]] = hidden constant [4 x i8*] [
// CHECK: i8* bitcast (%swift.type* ()* @_T018sil_witness_tables14AssocConformerVMa to i8*),
// CHECK: i8* bitcast (i8** ()* @_T018sil_witness_tables14AssocConformerVAA1AAAWa to i8*)
// CHECK: i8* bitcast (void (%swift.type*, %swift.type*, i8**)* @_T018sil_witness_tables9ConformerVAA1PA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW to i8*),
// CHECK: i8* bitcast (void (%T18sil_witness_tables9ConformerV*, %swift.type*, i8**)* @_T018sil_witness_tables9ConformerVAA1PA2aDP14instanceMethod{{[_0-9a-zA-Z]*}}FTW to i8*)
// CHECK: ]
// CHECK: [[CONFORMER2_P_WITNESS_TABLE:@_T018sil_witness_tables10Conformer2VAA1PAAWP]] = hidden constant [4 x i8*]
struct Conformer2: Q {
typealias Assoc = AssocConformer
static func staticMethod() {}
func instanceMethod() {}
func qMethod() {}
}
// CHECK-LABEL: define hidden swiftcc void @_T018sil_witness_tables7erasureAA2QQ_pAA9ConformerV1c_tF(%T18sil_witness_tables2QQP* noalias nocapture sret)
// CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T18sil_witness_tables2QQP, %T18sil_witness_tables2QQP* %0, i32 0, i32 2
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* [[CONFORMER_QQ_WITNESS_TABLE:@_T0.*WP]], i32 0, i32 0), i8*** [[WITNESS_TABLE_ADDR]], align 8
func erasure(c c: Conformer) -> QQ {
return c
}
// CHECK-LABEL: define hidden swiftcc void @_T018sil_witness_tables15externalErasure0a1_b1_c1_D12_conformance9ExternalP_pAC0G9ConformerV1c_tF(%T39sil_witness_tables_external_conformance9ExternalPP* noalias nocapture sret)
// CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T39sil_witness_tables_external_conformance9ExternalPP, %T39sil_witness_tables_external_conformance9ExternalPP* %0, i32 0, i32 2
// CHECK-NEXT: store i8** [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE]], i8*** %2, align 8
func externalErasure(c c: ExternalConformer) -> ExternalP {
return c
}
// FIXME: why do these have different linkages?
// CHECK-LABEL: define hidden %swift.type* @_T018sil_witness_tables14AssocConformerVMa()
// CHECK: ret %swift.type* bitcast (i64* getelementptr inbounds {{.*}} @_T018sil_witness_tables14AssocConformerVMf, i32 0, i32 1) to %swift.type*)
// CHECK-LABEL: define hidden i8** @_T018sil_witness_tables9ConformerVAA1PAAWa()
// CHECK: ret i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @_T018sil_witness_tables9ConformerVAA1PAAWP, i32 0, i32 0)
| apache-2.0 | e1115e262dede6eb2b2a96da7b784d26 | 47.625 | 221 | 0.717481 | 3.204283 | false | false | false | false |
hsavit1/LeetCode-Solutions-in-Swift | Solutions/Solutions/Hard/Hard_076_Minimum_Window_Substring.swift | 1 | 2731 | /*
https://leetcode.com/problems/minimum-window-substring/
#76 Minimum Window Substring
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = "ADOBECODEBANC"
T = "ABC"
Minimum window is "BANC".
Note:
If there is no such window in S that covers all characters in T, return the emtpy string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
Inspired by @heleifz at https://leetcode.com/discuss/10337/accepted-o-n-solution
*/
import Foundation
private extension String {
subscript (index: Int) -> Character {
return self[advance(self.startIndex, index)]
}
}
struct Hard_076_Minimum_Window_Substring {
static func minWindow(s s: String, t: String) -> String {
if s.isEmpty || t.isEmpty {
return ""
}
var count = t.characters.count
var charCountDict: Dictionary<Character, Int> = Dictionary()
var charFlagDict: Dictionary<Character, Bool> = Dictionary()
for var ii = 0; ii < count; ii++ {
if let charCount = charCountDict[t[ii]] {
charCountDict[t[ii]] = charCount + 1
} else {
charCountDict[t[ii]] = 1
}
charFlagDict[t[ii]] = true
}
var i = -1
var j = 0
var minLen = Int.max
var minIdx = 0
while i < s.characters.count && j < s.characters.count {
if count > 0 {
i++
if i == s.characters.count {
continue
}
if let charCount = charCountDict[s[i]] {
charCountDict[s[i]] = charCount - 1
} else {
charCountDict[s[i]] = -1
}
if charFlagDict[s[i]] == true && charCountDict[s[i]] >= 0 {
count--
}
} else {
if minLen > i - j + 1 {
minLen = i - j + 1
minIdx = j
}
if let charCount = charCountDict[s[j]] {
charCountDict[s[j]] = charCount + 1
} else {
charCountDict[s[j]] = 1
}
if charFlagDict[s[j]] == true && charCountDict[s[j]] > 0 {
count++
}
j++
}
}
if minLen == Int.max {
return ""
}
let range = Range<String.Index>(start:advance(s.startIndex, minIdx), end:advance(s.startIndex, minIdx + minLen))
return s.substringWithRange(range)
}
} | mit | 401ba53f62b20b1fedcefb669755ceae | 30.402299 | 124 | 0.508239 | 4.144158 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/ios-sdk/WatsonDeveloperCloudTests/AuthenticationTests.swift | 1 | 4244 | /**
* Copyright IBM Corporation 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import XCTest
@testable import WatsonDeveloperCloud
class AuthenticationTests: XCTestCase {
private let timeout: NSTimeInterval = 30.0
override func setUp() {
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testFacebookOAuth() {
let facebookExpectation: XCTestExpectation = expectationWithDescription("Facebook Authentication")
// identify credentials file
let bundle = NSBundle(forClass: self.dynamicType)
guard let url = bundle.pathForResource("Credentials", ofType: "plist") else {
XCTFail("Unable to locate credentials file.")
return
}
// load credentials from file
let dict = NSDictionary(contentsOfFile: url)
guard let credentials = dict as? Dictionary<String, String> else {
XCTFail("Unable to read credentials file.")
return
}
// read Dialog username
guard let fbToken = credentials["FacebookOAuth"] else {
XCTFail("Unable to read the Facebook OAuth token.")
return
}
guard let tokenURL = credentials["FacebookOAuthURL"] else {
XCTFail("Unable to read the token URL.")
return
}
let fbAuthentication = FacebookAuthenticationStrategy(
tokenURL: tokenURL,
fbToken: fbToken
)
fbAuthentication.refreshToken {
error in
XCTAssertNotNil(fbAuthentication.token)
XCTAssertNil(error)
Log.sharedLogger.info("Received a Watson token \(fbAuthentication.token)")
facebookExpectation.fulfill()
}
waitForExpectationsWithTimeout(timeout) {
error in XCTAssertNil(error, "Timeout")
}
}
func testFacebookOAuthBadCredentials() {
let facebookNegativeExpectation: XCTestExpectation =
expectationWithDescription("Facebook Negative Authentication")
// identify credentials file
let bundle = NSBundle(forClass: self.dynamicType)
guard let url = bundle.pathForResource("Credentials", ofType: "plist") else {
XCTFail("Unable to locate credentials file.")
return
}
// load credentials from file
let dict = NSDictionary(contentsOfFile: url)
guard let credentials = dict as? Dictionary<String, String> else {
XCTFail("Unable to read credentials file.")
return
}
guard let tokenURL = credentials["FacebookOAuthURL"] else {
XCTFail("Unable to read the token URL.")
return
}
let fbAuthentication = FacebookAuthenticationStrategy(
tokenURL: tokenURL,
fbToken: "SomeBogusOAuthTokenGoesHere"
)
fbAuthentication.refreshToken {
error in
XCTAssertNil(fbAuthentication.token)
XCTAssertNotNil(error)
Log.sharedLogger.info("Received a Watson token \(fbAuthentication.token)")
facebookNegativeExpectation.fulfill()
}
waitForExpectationsWithTimeout(timeout) {
error in XCTAssertNil(error, "Timeout")
}
}
} | mit | b67c0ffea4e4fb7b13f760d82e16f423 | 30.213235 | 111 | 0.59213 | 5.886269 | false | true | false | false |
jgainfort/FRPlayer | FRPlayer/PlayerViewController.swift | 1 | 2544 | //
// PlayerViewController.swift
// FRPlayer
//
// Created by John Gainfort Jr on 3/29/17.
// Copyright © 2017 John Gainfort Jr. All rights reserved.
//
import UIKit
import AVFoundation
import ReSwift
import RxSwift
import RxGesture
class PlayerViewController: UIViewController {
@IBOutlet weak var playerView: PlayerView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var controlbarContainerView: UIView!
typealias StoreSubscriberStateType = State
let disposeBag = DisposeBag()
let viewModel: PlayerViewModel = PlayerViewModel()
override var prefersStatusBarHidden: Bool {
return viewModel.controlbarHidden.value
}
override func viewDidLoad() {
super.viewDidLoad()
addObservers()
if let url = URL(string: "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8") {
playerView.viewModel = viewModel
playerView.initPlayer(withUrl: url, autoPlay: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
removeObservers()
}
private func addTapGestureRecognizer() {
playerView.rx.tapGesture()
.when(.recognized)
.subscribe(
onNext: { [weak self] _ in
self?.viewModel.removeControlbarHiddenTimer()
self?.viewModel.showHideControlbar(hidden: false)
}
)
.addDisposableTo(disposeBag)
}
private func addObservers() {
addTapGestureRecognizer()
viewModel.addControlbarHiddenTimer()
viewModel.buffering.asObservable()
.distinctUntilChanged()
.map({ buffering in !buffering })
.bindTo(activityIndicator.rx.isHidden)
.addDisposableTo(disposeBag)
viewModel.controlbarHidden.asObservable()
.distinctUntilChanged()
.do(onNext: { [weak self] hidden in
if !hidden {
self?.viewModel.removeControlbarHiddenTimer()
self?.viewModel.addControlbarHiddenTimer()
}
self?.setNeedsStatusBarAppearanceUpdate()
})
.bindTo(controlbarContainerView.rx.isHidden)
.addDisposableTo(disposeBag)
}
private func removeObservers() {
// remove any observers
viewModel.removeControlbarHiddenTimer()
}
}
| mit | 72941d928968cc5a54b2ac3c3f9cd665 | 27.897727 | 101 | 0.611876 | 5.492441 | false | false | false | false |
aksalj/Helium | Helium/HeliumShareExtension/ShareViewController.swift | 1 | 1676 | //
// ShareViewController.swift
// Share
//
// Created by Kyle Carson on 10/30/15.
// Copyright © 2015 Jaden Geller. All rights reserved.
//
import Cocoa
class ShareViewController: NSViewController {
override var nibName: String? {
return "ShareViewController"
}
override func viewDidLoad() {
if let item = self.extensionContext!.inputItems.first as? NSExtensionItem,
let attachment = item.attachments?.first as? NSItemProvider
where attachment.hasItemConformingToTypeIdentifier("public.url")
{
attachment.loadItemForTypeIdentifier("public.url", options: nil)
{
(url, error) in
if let url = url as? NSURL,
let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)
{
components.scheme = "helium"
let heliumURL = components.URL!
NSWorkspace.sharedWorkspace().openURL( heliumURL )
}
}
self.extensionContext!.completeRequestReturningItems(nil, completionHandler: nil)
return
}
let error = NSError(domain: NSCocoaErrorDomain, code: NSURLErrorBadURL, userInfo: nil)
self.extensionContext!.cancelRequestWithError(error)
}
@IBAction func send(sender: AnyObject?) {
let outputItem = NSExtensionItem()
// Complete implementation by setting the appropriate value on the output item
let outputItems = [outputItem]
self.extensionContext!.completeRequestReturningItems(outputItems, completionHandler: nil)
}
@IBAction func cancel(sender: AnyObject?) {
let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil)
self.extensionContext!.cancelRequestWithError(cancelError)
}
}
| mit | 4850292a12b128d47305aa82c2533454 | 26.459016 | 98 | 0.721791 | 4.384817 | false | false | false | false |
bugitapp/bugit | bugit/IntroGuide/Step1ViewController.swift | 1 | 1328 | //
// Step1ViewController.swift
// bugit
//
// Created by Ernest on 11/30/16.
// Copyright © 2016 BugIt App. All rights reserved.
//
import UIKit
class Step1ViewController: ViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Remove navigation back button title
self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil)
// Make UINavigationBar transparent
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeNext))
swipeRight.direction = .left
self.view.addGestureRecognizer(swipeRight)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
@IBAction func handleSwipeNext(sender: UITapGestureRecognizer? = nil) {
self.performSegue(withIdentifier: "Step2Segue", sender: self)
}
}
| apache-2.0 | 3b5dc6aaa30b86511f96d4340f0ce212 | 30.595238 | 111 | 0.680482 | 5.203922 | false | false | false | false |
kaideyi/KDYSample | KYChat/KYChat/Helper/Extension/UIKit/UITableView+ChatAdditions.swift | 1 | 2546 | //
// UITableView+ChatAdditions.swift
// TSWeChat
//
// Created by Hilen on 1/29/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import UIKit
extension UITableView {
func reloadData(_ completion: @escaping ()->()) {
UIView.animate(withDuration: 0, animations: {
self.reloadData()
}, completion:{ _ in
completion()
})
}
func insertRowsAtBottom(_ rows: [IndexPath]) {
// 保证 insert row 不闪屏
UIView.setAnimationsEnabled(false)
CATransaction.begin()
CATransaction.setDisableActions(true)
self.beginUpdates()
self.insertRows(at: rows, with: .none)
self.endUpdates()
self.scrollToRow(at: rows[0], at: .bottom, animated: false)
CATransaction.commit()
UIView.setAnimationsEnabled(true)
}
func totalRows() -> Int {
var i = 0
var rowCount = 0
while i < self.numberOfSections {
rowCount += self.numberOfRows(inSection: i)
i += 1
}
return rowCount
}
var lastIndexPath: IndexPath? {
if (self.totalRows()-1) > 0{
return IndexPath(row: self.totalRows()-1, section: 0)
} else {
return nil
}
}
// 插入数据后调用
func scrollBottomWithoutFlashing() {
guard let indexPath = self.lastIndexPath else {
return
}
UIView.setAnimationsEnabled(false)
CATransaction.begin()
CATransaction.setDisableActions(true)
self.scrollToRow(at: indexPath, at: .bottom, animated: false)
CATransaction.commit()
UIView.setAnimationsEnabled(true)
}
// 键盘动画结束后调用
func scrollBottomToLastRow() {
guard let indexPath = self.lastIndexPath else {
return
}
self.scrollToRow(at: indexPath, at: .bottom, animated: false)
}
func scrollToBottom(_ animated: Bool) {
let bottomOffset = CGPoint(x: 0, y: self.contentSize.height - self.bounds.size.height)
if self.contentSize.height - self.bounds.size.height < 0.0 {
return
}
self.setContentOffset(bottomOffset, animated: animated)
}
var isContentInsetBottomZero: Bool {
get { return self.contentInset.bottom == 0 }
}
func resetContentInsetAndScrollIndicatorInsets() {
self.contentInset = UIEdgeInsets.zero
self.scrollIndicatorInsets = UIEdgeInsets.zero
}
}
| mit | edc425eb8ae0534674fe6ea27902b924 | 26.811111 | 94 | 0.589692 | 4.66108 | false | false | false | false |
zisko/swift | benchmark/single-source/Queue.swift | 1 | 3374 | //===--- RangeAssignment.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let QueueGeneric = BenchmarkInfo(
name: "QueueGeneric",
runFunction: run_QueueGeneric,
tags: [.validation, .api],
setUpFunction: { buildWorkload() },
tearDownFunction: nil)
public let QueueConcrete = BenchmarkInfo(
name: "QueueConcrete",
runFunction: run_QueueConcrete,
tags: [.validation, .api],
setUpFunction: { buildWorkload() },
tearDownFunction: nil)
// TODO: remove when there is a native equivalent in the std lib
extension RangeReplaceableCollection where Self: BidirectionalCollection {
@_inlineable
public mutating func popLast() -> Element? {
if isEmpty { return nil}
else { return removeLast() }
}
}
public struct Queue<Storage: RangeReplaceableCollection>
where Storage: BidirectionalCollection {
public typealias Element = Storage.Element
internal var _in: Storage
internal var _out: Storage
public init() {
_in = Storage()
_out = Storage()
}
}
extension Queue {
public mutating func enqueue(_ newElement: Element) {
_in.append(newElement)
}
public mutating func dequeue() -> Element? {
if _out.isEmpty {
_out.append(contentsOf: _in.reversed())
_in.removeAll()
}
return _out.popLast()
}
}
func testQueue<Elements: Collection>(elements: Elements)
where Elements.Element: Equatable {
var q = Queue<[Elements.Element]>()
for x in elements { q.enqueue(x) }
let results = sequence(state: q) { $0.dequeue() }
let i = results.reduce(0, { i,_ in i &+ 1 })
for x in elements { q.enqueue(x) }
let j = results.reduce(i, { i,_ in i &+ 1 })
CheckResults(j == elements.count*2)
}
let n = 10_000
let workload = (0..<n).map { "\($0): A long enough string to defeat the SSO, or so I hope." }
public func buildWorkload() {
let contents = workload
_ = contents.reduce(0) { $0 + $1.count }
}
@inline(never)
func run_QueueGeneric(_ scale: Int) {
for _ in 0..<scale {
testQueue(elements: workload)
}
}
public struct ConcreteQueue {
internal var _in: [String]
internal var _out: [String]
public init() {
_in = Array()
_out = Array()
}
}
extension ConcreteQueue {
public mutating func enqueue(_ newElement: String) {
_in.append(newElement)
}
public mutating func dequeue() -> String? {
if _out.isEmpty {
_out.append(contentsOf: _in.reversed())
_in.removeAll()
}
return _out.popLast()
}
}
func testConcreteQueue(elements: [String]) {
var q = ConcreteQueue()
for x in elements { q.enqueue(x) }
let results = sequence(state: q) { $0.dequeue() }
let i = results.reduce(0, { i,_ in i &+ 1 })
for x in elements { q.enqueue(x) }
let j = results.reduce(i, { i,_ in i &+ 1 })
CheckResults(j == elements.count*2)
}
@inline(never)
func run_QueueConcrete(_ scale: Int) {
for _ in 0..<scale {
testConcreteQueue(elements: workload)
}
}
| apache-2.0 | 4ef400b520de7efabae3b91897f88266 | 24.560606 | 93 | 0.637819 | 3.821065 | false | false | false | false |
scottrhoyt/Noonian | Tests/NoonianKitTests/Android/Commands/AndroidCommandTests.swift | 1 | 2902 | //
// AndroidCommandTests.swift
// Noonian
//
// Created by Scott Hoyt on 11/6/16.
// Copyright © 2016 Scott Hoyt. All rights reserved.
//
import XCTest
@testable import NoonianKit
import Commandant
import Result
class AndroidCommandTests: XCTestCase {
// MARK: - Mocks
enum InternalError: Error {
case someError
}
struct TestCommand: AndroidCommand {
typealias Options = TestOptions
let verb = "test"
let function = "test"
var error: Error?
func run(_ options: TestOptions, paths: SDKPathBuilder) throws {
if let error = error {
throw error
}
}
}
struct TestOptions: OptionsProtocol {
static func evaluate(_ m: CommandMode) -> Result<AndroidCommandTests.TestOptions, CommandantError<NoonianKitError>> {
return .success(TestOptions())
}
}
// MARK: - Tests
override func setUp() {
super.setUp()
clearAndroidHome()
}
func testAndroidHomeNotDefinedThrows() {
Environment().unset(for: "ANDROID_HOME")
do {
_ = try TestCommand().androidHome()
} catch NoonianKitError.androidHomeNotDefined {
return
} catch {
XCTFail("Should have thrown an androidHomeNotDefined")
}
XCTFail("Should have thrown an error")
}
func testRunSuccessfully() {
let command = TestCommand()
let result: Result<(), NoonianKitError> = command.run(TestOptions())
switch result {
case .success:
return
default:
XCTFail("Should have been a success")
}
}
func testRunWithNoonianError() {
var command = TestCommand()
command.error = NoonianKitError.androidHomeNotDefined
let result: Result<(), NoonianKitError> = command.run(TestOptions())
switch result {
case .failure(NoonianKitError.androidHomeNotDefined):
return
default:
XCTFail("Should have failed with a NoonianKitError")
}
}
func testRunWithInternalError() {
var command = TestCommand()
command.error = InternalError.someError
let result: Result<(), NoonianKitError> = command.run(TestOptions())
switch result {
case .failure(NoonianKitError.internalError(InternalError.someError)):
return
default:
XCTFail("Should have failed with an internalError")
}
}
}
#if os(Linux)
extension AndroidCommandTests {
static var allTests = [
("testAndroidHomeNotDefinedThrows", testAndroidHomeNotDefinedThrows),
("testRunSuccessfully", testRunSuccessfully),
("testRunWithNoonianError", testRunWithNoonianError),
("testRunWithInternalError", testRunWithInternalError),
]
}
#endif
| mit | f18f2b81d544cc1ee02e2bc4f1fde475 | 26.367925 | 125 | 0.610134 | 4.795041 | false | true | false | false |
belatrix/iOSAllStarsRemake | AllStars/AllStars/Entities/ErrorResponse.swift | 1 | 895 | //
// ErrorResponse.swift
// AllStars
//
// Created by Flavio Franco Tunqui on 6/16/16.
// Copyright © 2016 Belatrix SF. All rights reserved.
//
import UIKit
class ErrorResponse: NSObject {
var state : NSNumber? {
didSet {
verifySessionValid()
}
}
var message : String?
// Validate if Session is Expired or the user is forbidden for the service
// If so, close the session and ask for login again
func verifySessionValid () {
if let state = self.state?.integerValue where state == 401 {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.logOut()
if self.message == "invalid_token".localized {
self.message = "session_expired".localized
}
}
}
} | mit | 16e4888d2d88526bb6d4aeaffd991d4a | 24.571429 | 88 | 0.565996 | 4.939227 | false | false | false | false |
lorentey/swift | test/PlaygroundTransform/control-flow.swift | 9 | 1446 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -force-single-frontend-invocation -module-name PlaygroundSupport -emit-module-path %t/PlaygroundSupport.swiftmodule -parse-as-library -c -o %t/PlaygroundSupport.o %S/Inputs/SilentPCMacroRuntime.swift %S/Inputs/PlaygroundsRuntime.swift
// RUN: %target-build-swift -Xfrontend -playground -o %t/main -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -o %t/main2 -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-codesign %t/main2
// RUN: %target-run %t/main2 | %FileCheck %s
// REQUIRES: executable_test
import PlaygroundSupport
var a = true
if (a) {
5
} else {
7
}
for i in 0..<3 {
i
}
// CHECK: [{{.*}}] __builtin_log[a='true']
// CHECK-NEXT: [{{.*}}] __builtin_log_scope_entry
// CHECK-NEXT: [{{.*}}] __builtin_log[='5']
// CHECK-NEXT: [{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [{{.*}}] __builtin_log_scope_entry
// CHECK-NEXT: [{{.*}}] __builtin_log[='0']
// CHECK-NEXT: [{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [{{.*}}] __builtin_log_scope_entry
// CHECK-NEXT: [{{.*}}] __builtin_log[='1']
// CHECK-NEXT: [{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [{{.*}}] __builtin_log_scope_entry
// CHECK-NEXT: [{{.*}}] __builtin_log[='2']
// CHECK-NEXT: [{{.*}}] __builtin_log_scope_exit
| apache-2.0 | 7e734b87fddc20ccfce107f00f056931 | 38.081081 | 262 | 0.63278 | 3.09636 | false | false | false | false |
VerachadW/RealmObjectEditor | Realm Object Editor/FileContentGenerator.swift | 1 | 9853 | //
// FileContentGenerator.swift
// Realm Object Editor
//
// Created by Ahmed Ali on 1/20/15.
// Copyright (c) 2015 Ahmed Ali. All rights reserved.
//
import Foundation
import AddressBook
class FileContentGenerator {
var content = ""
var entity: EntityDescriptor
var lang: LangModel
init(entity: EntityDescriptor, lang: LangModel)
{
self.entity = entity
self.lang = lang
}
func getFielContent() -> String
{
appendCopyrights(entity.name, fileExtension: lang.fileExtension)
appendStaticImports()
appendRelationshipImports()
content += lang.modelDefinition
content += lang.modelStart
content.replace(EntityName, by: entity.name)
if count(entity.superClassName) == 0{
content.replace(ParentName, by: lang.defaultSuperClass)
}else{
content.replace(ParentName, by: entity.superClassName)
}
appendAttributes()
appendRelationships()
if lang.primaryKeyDefination != nil{
appendPrimaryKey(lang.primaryKeyDefination)
}
if lang.indexedAttributesDefination != nil && lang.forEachIndexedAttribute != nil{
appendIndexedAttributes(lang.indexedAttributesDefination, forEachIndexedAttribute: lang.forEachIndexedAttribute)
}
if lang.ignoredProperties != nil && lang.forEachIgnoredProperty != nil{
appendIgnoredProperties(lang.ignoredProperties, forEachIgnoredProperty: lang.forEachIgnoredProperty)
}
if lang.getter != nil && lang.setter != nil{
appendGettersAndSetters(lang.getter, setter: lang.setter)
}
content += lang.modelEnd
content.replace(EntityName, by: entity.name)
return content
}
//MARK: - Setter and Getters
func appendGettersAndSetters(getter: String, setter: String)
{
let types = lang.dataTypes.toDictionary()
for attr in entity.attributes{
appendDefination(getter, attrName: attr.name, attrType: types[attr.type.techName]!)
appendDefination(setter, attrName: attr.name, attrType: types[attr.type.techName]!)
}
for relationship in entity.relationships{
var type = relationship.destinationName
if relationship.toMany && lang.toManyRelationType != nil{
var relationshipType = lang.toManyRelationType
relationshipType.replace(RelationshipType, by: type)
type = relationshipType
}
appendDefination(getter, attrName: relationship.name, attrType: type)
appendDefination(setter, attrName: relationship.name, attrType: type)
}
}
func appendDefination(defination: String, attrName: String, attrType: String)
{
var def = defination
def.replace(AttrName, by: attrName)
def.replace(AttrType, by: attrType)
def.replace(CapitalizedAttrName, by: attrName.uppercaseFirstChar())
content += def
}
//MARK: - Ignored properties
func appendIgnoredProperties(ignoredPropertiesDef: String, forEachIgnoredProperty: String)
{
let types = lang.dataTypes.toDictionary()
var ignoredAttrs = ""
for attr in entity.attributes{
if attr.ignored{
var ignored = forEachIgnoredProperty
ignored.replace(AttrName, by: attr.name)
ignored.replace(AttrType, by: types[attr.type.techName]!)
ignoredAttrs += ignored
}
}
if count(ignoredAttrs) > 0{
var ignoredAttrDef = ignoredPropertiesDef
ignoredAttrDef.replace(IgnoredAttributes, by: ignoredAttrs)
content += ignoredAttrDef
}
}
//MARK: - Primary Key
func appendPrimaryKey(primaryKeyDef: String)
{
let types = lang.dataTypes.toDictionary()
for attr in entity.attributes{
if attr.isPrimaryKey{
var def = primaryKeyDef
def.replace(AttrName, by: attr.name)
def.replace(AttrType, by: types[attr.type.techName]!)
content += def
break
}
}
}
//MARK: - Index Attributes
func appendIndexedAttributes(indexAttributesDefination: String, forEachIndexedAttribute: String)
{
let types = lang.dataTypes.toDictionary()
var indexedAttrs = ""
for attr in entity.attributes{
if attr.indexed{
var indexed = forEachIndexedAttribute
indexed.replace(AttrName, by: attr.name)
indexed.replace(AttrType, by: types[attr.type.techName]!)
indexedAttrs += indexed
}
}
if count(indexedAttrs) > 0{
var indexedAttrDef = indexAttributesDefination
indexedAttrDef.replace(IndexedAttributes, by: indexedAttrs)
content += indexedAttrDef
}
}
//MARK: - Relationships
func appendRelationships()
{
for relationship in entity.relationships{
var relationshipDef = ""
if relationship.toMany{
relationshipDef = lang.toManyRelationshipDefination
}else{
relationshipDef = lang.toOneRelationshipDefination
}
relationshipDef.replace(RelationshipName, by: relationship.name)
relationshipDef.replace(RelationshipType, by: relationship.destinationName)
content += relationshipDef
}
}
//MARK: - Attributes
func appendAttributes()
{
let types = lang.dataTypes.toDictionary()
for attr in entity.attributes{
var attrDefination = ""
if lang.attributeDefinationWithDefaultValue != nil && count(lang.attributeDefinationWithDefaultValue) > 0 && attr.hasDefault{
attrDefination = lang.attributeDefinationWithDefaultValue
var defValue = defaultValueForAttribute(attr, types: types)
attrDefination.replace(AttrDefaultValue, by: defValue)
}else{
attrDefination = lang.attributeDefination
}
attrDefination.replace(AttrName, by: attr.name)
attrDefination.replace(AttrType, by: types[attr.type.techName]!)
var annotations = ""
if attr.indexed{
if lang.indexAnnotaion != nil{
annotations += lang.indexAnnotaion
}
}
if attr.ignored{
if lang.ignoreAnnotaion != nil{
annotations += lang.ignoreAnnotaion
}
}
attrDefination.replace(Annotations, by: annotations)
content += attrDefination
}
}
func defaultValueForAttribute(attribute: AttributeDescriptor, types: [String : String]) -> String
{
var defValue = attribute.defaultValue
if defValue == NoDefaultValue{
if let def = types["\(attribute.type.techName)DefaultValue"]{
defValue = def
}else{
defValue = ""
}
}else{
if var quoutedValue = types["\(attribute.type.techName)QuotedValue"]{
quoutedValue.replace(QuotedValue, by: attribute.defaultValue)
defValue = quoutedValue
}
}
return defValue
}
//MARK: Imports
func appendStaticImports()
{
if lang.staticImports != nil{
content += lang.staticImports
}
}
func appendRelationshipImports()
{
if lang.relationsipImports != nil{
for r in entity.relationships{
var relationshipImport = lang.relationsipImports
relationshipImport.replace(RelationshipType, by: r.destinationName)
content += relationshipImport
}
}
}
//MARK: - Copyrights
func appendCopyrights(fileName: String, fileExtension: String)
{
content += "//\n//\t\(fileName).\(fileExtension)\n"
if let me = ABAddressBook.sharedAddressBook()?.me(){
if let firstName = me.valueForProperty(kABFirstNameProperty as String) as? String{
content += "//\n//\tCreate by \(firstName)"
if let lastName = me.valueForProperty(kABLastNameProperty as String) as? String{
content += " \(lastName)"
}
}
content += " on \(getTodayFormattedDay())\n//\tCopyright © \(getYear())"
if let organization = me.valueForProperty(kABOrganizationProperty as String) as? String{
content += " \(organization)"
}
content += ". All rights reserved.\n"
}
content += "//\tModel file Generated using Realm Object Editor: https://github.com/Ahmed-Ali/RealmObjectEditor\n\n"
}
/**
Returns the current year as String
*/
func getYear() -> String
{
return "\(NSCalendar.currentCalendar().component(.CalendarUnitYear, fromDate: NSDate()))"
}
/**
Returns today date in the format dd/mm/yyyy
*/
func getTodayFormattedDay() -> String
{
let components = NSCalendar.currentCalendar().components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: NSDate())
return "\(components.day)/\(components.month)/\(components.year)"
}
} | mit | 46215a12d6476101ae2f699fc0425df6 | 33.33101 | 143 | 0.580491 | 5.123245 | false | false | false | false |
beckasaurus/skin-ios | skin/skin/DailyViewController.swift | 1 | 1792 | //
// DailyViewController.swift
// skin
//
// Created by Becky on 1/30/18.
// Copyright © 2018 Becky Henderson. All rights reserved.
//
import UIKit
// TODO:
// If current day, get UV index forecast
// load next
// load previous
// load daily rating/pic
protocol DateChangeable {
func didChangeDate(to date: Date)
}
class DailyViewController: UIViewController {
@IBOutlet weak var nextDay: UIButton!
@IBOutlet weak var previousDay: UIButton!
@IBOutlet weak var logDate: UILabel!
@IBOutlet weak var uvIndex: UILabel!
var date: Date = Date()
var dateFormatter: DateFormatter?
weak var routineLog: DailyRoutineLogViewController?
weak var status: DailyStatusViewController?
override func viewDidLoad() {
setupDateFormatter()
loadLog(for: date)
}
func setupDateFormatter() {
if dateFormatter == nil {
dateFormatter = DateFormatter()
dateFormatter?.dateStyle = .short
dateFormatter?.timeStyle = .none
}
}
func loadLog(for date: Date) {
logDate.text = dateFormatter?.string(from: date)
let isDateToday = Calendar.current.isDateInToday(date)
if isDateToday {
loadUVIndex()
}
status?.didChangeDate(to: date)
routineLog?.didChangeDate(to: date)
}
func loadUVIndex() {
//hit api to get uv index using today's date and location
let forecastedIndex = 7
uvIndex.text = "UV Index: \(forecastedIndex)"
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "dailyStatusSegue" {
status = (segue.destination as! DailyStatusViewController)
} else if segue.identifier == "dailyRoutineLogSegue" {
routineLog = (segue.destination as! DailyRoutineLogViewController)
}
}
@IBAction func previousDate(sender: UIButton) {
}
@IBAction func nextDate(sender: UIButton) {
}
}
| mit | f584c8564af532e4db7a3f8539c83fbf | 20.841463 | 69 | 0.71971 | 3.603622 | false | false | false | false |
sgr-ksmt/TMABTester | Demo/ViewController.swift | 1 | 1052 | //
// ViewController.swift
// Demo
//
// Created by Suguru Kishimoto on 2016/04/07.
// Copyright © 2016年 Timers Inc. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet private weak var label: UILabel!
private lazy var tester = SampleABTester()
override func viewDidLoad() {
super.viewDidLoad()
// tester.resetPattern()
tester.addTest(.ChangeLabel) { [weak self] pattern, parameters in
let type = parameters?["type"] as? String
let num = parameters?["num"] as? Int
let text = "Pattern is \(pattern.rawValue)" + (type.map { "_\($0)" } ?? "") + (num.map { "_\($0)" } ?? "")
self?.label.text = text
}
tester.execute(.ChangeLabel, parameters: ["num": 100])
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | d8bb907b3cd2917b5aea9e6f8ebd7edc | 28.138889 | 118 | 0.603432 | 4.316872 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.