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
dongxiexidu/AdvertScollViewExample
AdvertScollViewExample/ViewController.swift
1
3132
// // ViewController.swift // AdvertScollViewExample // // Created by fashion on 2017/10/10. // Copyright © 2017年 shangZhu. All rights reserved. // import UIKit class ViewController: UIViewController ,AdvertScrollViewDelegate { @IBOutlet weak var advertScrollViewTop: AdvertScrollView! @IBOutlet var advertScrollView: AdvertScrollView! @IBOutlet var advertScrollViewCenter: AdvertScrollView! @IBOutlet var advertScrollView2: AdvertScrollView! @IBOutlet var advertScrollViewBottom: AdvertScrollView! // required init?(coder aDecoder: NSCoder) { // super.init(coder: aDecoder) // } override func viewDidLoad() { super.viewDidLoad() // top advertScrollViewTop.titles = ["京东、天猫等 app 首页常见的广告滚动视图", "采用代理设计模式进行封装, 可进行事件点击处理", "建议在 github 上下载"] advertScrollViewTop.titleColor = UIColor.red advertScrollViewTop.textAlignment = .center // 例二 advertScrollView.signImages = ["hot", "", "activity"] advertScrollView.titles = ["京东、天猫等 app 首页常见的广告滚动视图", "采用代理设计模式进行封装, 可进行事件点击处理", "建议在 github 上下载"] // center advertScrollViewCenter.titleColor = UIColor.green advertScrollViewCenter.scrollTimeInterval = 5 advertScrollViewCenter.titles = ["京东、天猫等 app 首页常见的广告滚动视图", "采用代理设计模式进行封装, 可进行事件点击处理", "建议在 github 上下载"] advertScrollViewCenter.titleFont = UIFont.systemFont(ofSize: 14) advertScrollViewCenter.delegate = self // 例四 let topTitleArr = ["聚惠女王节,香米更低价满150减10", "HTC新品首发,预约送大礼包", "挑食进口生鲜,满199减20"] let signImageArr = ["hot", "", "activity"] let bottomTitleArr = ["满150减10+满79减5", "12期免息+免费试用", "领券满199减20+进口直达"] advertScrollView2.advertScrollViewStyle = AdvertScrollViewStyle.more advertScrollView2.topTitles = topTitleArr advertScrollView2.bottomSignImages = signImageArr advertScrollView2.bottomTitles = bottomTitleArr advertScrollView2.bottomTitleColor = UIColor.red // bottom advertScrollViewBottom.advertScrollViewStyle = AdvertScrollViewStyle.more advertScrollViewBottom.topSignImages = ["dot", "dot", "dot"] advertScrollViewBottom.topTitles = ["聚惠女王节,香米更低价满150减10", "HTC新品首发,预约送大礼包", "“挑食”进口生鲜,满199减20"] advertScrollViewBottom.bottomSignImages = ["dot", "dot", "dot"] advertScrollViewBottom.bottomTitles = ["满150减10+满79减5", "12期免息+免费试用", "领券满199减20+进口直达"] } func advertScrollView(advertScrollView: AdvertScrollView, index: NSInteger) { print(index) } }
mit
215984ef66ec7802950ff706e5d7981a
37.838235
111
0.675502
3.488771
false
false
false
false
NeoXant/rpn-swift
rpn/main.swift
1
917
// main.swift // Convert infix notation to Reverse Polish Notation! // // Licensed under MIT License. See LICENSE for more info. // Copyright (c) 2017, Michał "NeoXant" Kolarczyk. func expToArray(_ exp: String) -> [String] { var returnArray = [String]() var temp = "" for char in exp.characters { if RPN.operatorPriority(String(char)) >= 0 { if !temp.isEmpty { returnArray.append(temp) temp.removeAll(keepingCapacity: false) } returnArray.append(String(char)) } else if char != " " { temp.append(char) } } if !temp.isEmpty { returnArray.append(temp) } return returnArray } var expressions: [String] = CommandLine.arguments expressions.remove(at: 0) // remove first argument (file name) for exp in expressions { let rpn = RPN(expToArray(exp)) print(rpn.rpnString) }
mit
6a5a68a237739c7ee68af53f900bd2cd
26.757576
62
0.606987
3.93133
false
false
false
false
matrix-org/matrix-ios-sdk
MatrixSDK/Crypto/Recovery/MXRecoveryServiceDependencies.swift
1
1446
// // Copyright 2022 The Matrix.org Foundation C.I.C // // 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 @objcMembers public class MXRecoveryServiceDependencies: NSObject { public let credentials: MXCredentials public let backup: MXKeyBackup? public let secretStorage: MXSecretStorage public let secretStore: MXCryptoSecretStore public let crossSigning: MXCrossSigning public let cryptoQueue: DispatchQueue public init( credentials: MXCredentials, backup: MXKeyBackup?, secretStorage: MXSecretStorage, secretStore: MXCryptoSecretStore, crossSigning: MXCrossSigning, cryptoQueue: DispatchQueue ) { self.credentials = credentials self.backup = backup self.secretStorage = secretStorage self.secretStore = secretStore self.crossSigning = crossSigning self.cryptoQueue = cryptoQueue } }
apache-2.0
870e8b25b8f96dedc8c5ed2c8137572e
32.627907
75
0.7213
4.649518
false
false
false
false
gbasile/Trail
Example/Tests/Tests.swift
1
1176
// https://github.com/Quick/Quick import Quick import Nimble import Trail class TableOfContentsSpec: QuickSpec { override func spec() { describe("it passes these tests") { it("can do maths") { expect(2) == 2 } it("can read") { expect("number") == "number" } it("will eventually pass") { expect("time").toEventually( equal("time") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
0f9f283671a7a71115c5011d0b58901e
22.4
63
0.364103
5.46729
false
false
false
false
laurentVeliscek/AudioKit
Examples/iOS/SporthEditor/SporthEditor/SporthEditorBrain.swift
2
1173
// // SporthEditorBrain.swift // SporthEditor // // Created by Kanstantsin Linou on 7/12/16. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation import AudioKit class SporthEditorBrain { var generator: AKOperationGenerator? var knownCodes = [String : String]() var rows: Int { return knownCodes.count } var names: [String] { return Array(knownCodes.keys) } func run(code: String) { generator?.stop() AudioKit.stop() generator = AKOperationGenerator() { _ in return AKOperation(code) } AudioKit.output = generator AudioKit.start() generator?.start() } func stop() { generator?.stop() } func save(name: String, code: String) { let fileName = name + FileUtilities.fileExtension let filePath = FileUtilities.filePath(fileName) do { try code.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding) knownCodes[name] = code NSLog("Saving was completed successfully") } catch { NSLog("Error during saving the file") } } }
mit
bc5a763925c56c53e58ca36a4a732dd8
21.980392
92
0.609215
4.439394
false
false
false
false
wireapp/wire-ios-sync-engine
Tests/Source/Synchronization/Strategies/AssetDeletionRequestStrategyTests.swift
1
5373
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 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 // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // @testable import WireSyncEngine import WireDataModel class AssetDeletionRequestStrategyTests: MessagingTest { private var sut: AssetDeletionRequestStrategy! private var mockApplicationStatus: MockApplicationStatus! fileprivate var mockIdentifierProvider: MockIdentifierProvider! override func setUp() { super.setUp() mockApplicationStatus = MockApplicationStatus() mockApplicationStatus.mockSynchronizationState = .online mockIdentifierProvider = MockIdentifierProvider() sut = AssetDeletionRequestStrategy( context: syncMOC, applicationStatus: mockApplicationStatus, identifierProvider: mockIdentifierProvider ) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) } override func tearDown() { XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) mockApplicationStatus = nil mockIdentifierProvider = nil sut = nil super.tearDown() } func testThatItCreatesNoRequestWhenThereIsNoIdentifier() { // When let request = sut.nextRequest(for: .v0) // Then XCTAssertNil(request) } func testThatItCreatesARequestIfThereIsAnIdentifier_V0() { testThatItCreatesARequestIfThereIsAnIdentifier(for: .v0) } func testThatItCreatesARequestIfThereIsAnIdentifier_V1() { testThatItCreatesARequestIfThereIsAnIdentifier(for: .v1) } func testThatItCreatesARequestIfThereIsAnIdentifier_V2() { testThatItCreatesARequestIfThereIsAnIdentifier(for: .v2) } func testThatItCallsDidDeleteIdentifierOnSuccess() { // Given let identifier = UUID.create().transportString() mockIdentifierProvider.nextIdentifier = identifier guard let request = sut.nextRequest(for: .v0) else { return XCTFail("No request created") } // When let response = ZMTransportResponse(payload: nil, httpStatus: 200, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue) request.complete(with: response) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // Then XCTAssertEqual(mockIdentifierProvider.deletedIdentifiers.count, 1) XCTAssertEqual(mockIdentifierProvider.deletedIdentifiers.first, identifier) XCTAssert(mockIdentifierProvider.failedToDeleteIdentifiers.isEmpty) } func testThatItCallsDidFailToDeleteIdentifierOnPermamentError() { // Given let identifier = UUID.create().transportString() mockIdentifierProvider.nextIdentifier = identifier guard let request = sut.nextRequest(for: .v0) else { return XCTFail("No request created") } // When let response = ZMTransportResponse(payload: nil, httpStatus: 403, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue) request.complete(with: response) XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) // Then XCTAssertEqual(mockIdentifierProvider.failedToDeleteIdentifiers.count, 1) XCTAssertEqual(mockIdentifierProvider.failedToDeleteIdentifiers.first, identifier) XCTAssert(mockIdentifierProvider.deletedIdentifiers.isEmpty) } } // MARK: Helper Method extension AssetDeletionRequestStrategyTests { func testThatItCreatesARequestIfThereIsAnIdentifier(for apiVersion: APIVersion) { // Given let domain = "example.domain.com" BackendInfo.domain = domain let identifier = UUID.create().transportString() mockIdentifierProvider.nextIdentifier = identifier // When let request = sut.nextRequest(for: apiVersion) // Then let expectedPath: String switch apiVersion { case .v0: expectedPath = "/assets/v3/\(identifier)" case .v1: expectedPath = "/v1/assets/v3/\(identifier)" case .v2: expectedPath = "/v2/assets/\(domain)/\(identifier)" } XCTAssertNotNil(request) XCTAssertEqual(request?.method, .methodDELETE) XCTAssertEqual(request?.path, expectedPath) XCTAssertNil(request?.payload) } } // MARK: - Helper private class MockIdentifierProvider: AssetDeletionIdentifierProviderType { var nextIdentifier: String? var deletedIdentifiers = [String]() var failedToDeleteIdentifiers = [String]() func nextIdentifierToDelete() -> String? { return nextIdentifier } func didDelete(identifier: String) { deletedIdentifiers.append(identifier) } func didFailToDelete(identifier: String) { failedToDeleteIdentifiers.append(identifier) } }
gpl-3.0
c3dc69b9d47e7aa84b5d61f7248b0de4
33.664516
137
0.704448
5.15643
false
true
false
false
seandavidmcgee/HumanKontactBeta
src/Pods/TKSubmitTransition/SubmitTransition/Classes/TransitionSubmitButton.swift
1
3927
import Foundation import UIKit let PINK = UIColor(red:0.992157, green: 0.215686, blue: 0.403922, alpha: 1) let DARK_PINK = UIColor(red:0.798012, green: 0.171076, blue: 0.321758, alpha: 1) @IBDesignable public class TKTransitionSubmitButton : UIButton, UIViewControllerTransitioningDelegate { public var didEndFinishAnimation : (()->())? = nil let springGoEase = CAMediaTimingFunction(controlPoints: 0.45, -0.36, 0.44, 0.92) let shrinkCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) let expandCurve = CAMediaTimingFunction(controlPoints: 0.95, 0.02, 1, 0.05) let shrinkDuration: CFTimeInterval = 0.1 lazy var spiner: SpinerLayer! = { let s = SpinerLayer(frame: self.frame) self.layer.addSublayer(s) return s }() @IBInspectable public var highlightedBackgroundColor: UIColor? = DARK_PINK { didSet { self.setBackgroundColor() } } @IBInspectable public var normalBackgroundColor: UIColor? = PINK { didSet { self.setBackgroundColor() } } var cachedTitle: String? public override init(frame: CGRect) { super.init(frame: frame) self.setup() } override public var highlighted: Bool { didSet { self.setBackgroundColor() } } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.setup() } func setup() { self.layer.cornerRadius = self.frame.height / 2 self.clipsToBounds = true self.setBackgroundColor() } func setBackgroundColor() { if (highlighted) { self.backgroundColor = highlightedBackgroundColor } else { self.backgroundColor = normalBackgroundColor } } public func startLoadingAnimation() { self.cachedTitle = titleForState(.Normal) self.setTitle("", forState: .Normal) self.shrink() NSTimer.schedule(delay: shrinkDuration - 0.25) { timer in self.spiner.animation() } } public func startFinishAnimation(delay: NSTimeInterval, completion:(()->())?) { NSTimer.schedule(delay: delay) { timer in self.didEndFinishAnimation = completion self.expand() self.spiner.stopAnimation() } } public func animate(duration: NSTimeInterval, completion:(()->())?) { startLoadingAnimation() startFinishAnimation(duration, completion: completion) } public override func animationDidStop(anim: CAAnimation, finished flag: Bool) { let a = anim as! CABasicAnimation if a.keyPath == "transform.scale" { didEndFinishAnimation?() NSTimer.schedule(delay: 1) { timer in self.returnToOriginalState() } } } func returnToOriginalState() { self.layer.removeAllAnimations() self.setTitle(self.cachedTitle, forState: .Normal) } func shrink() { let shrinkAnim = CABasicAnimation(keyPath: "bounds.size.width") shrinkAnim.fromValue = frame.width shrinkAnim.toValue = frame.height shrinkAnim.duration = shrinkDuration shrinkAnim.timingFunction = shrinkCurve shrinkAnim.fillMode = kCAFillModeForwards shrinkAnim.removedOnCompletion = false layer.addAnimation(shrinkAnim, forKey: shrinkAnim.keyPath) } func expand() { let expandAnim = CABasicAnimation(keyPath: "transform.scale") expandAnim.fromValue = 1.0 expandAnim.toValue = 26.0 expandAnim.timingFunction = expandCurve expandAnim.duration = 0.3 expandAnim.delegate = self expandAnim.fillMode = kCAFillModeForwards expandAnim.removedOnCompletion = false layer.addAnimation(expandAnim, forKey: expandAnim.keyPath) } }
mit
5aedc499a221906efa0a65179a305ba6
29.92126
89
0.632289
4.686158
false
false
false
false
gregomni/swift
test/SILOptimizer/access_enforcement_options.swift
9
1852
// RUN: %target-swift-frontend -Onone -emit-sil -parse-as-library %s | %FileCheck %s --check-prefix=CHECK --check-prefix=NONE // RUN: %target-swift-frontend -Osize -emit-sil -parse-as-library %s | %FileCheck %s --check-prefix=CHECK --check-prefix=OPT // RUN: %target-swift-frontend -O -emit-sil -parse-as-library %s | %FileCheck %s --check-prefix=CHECK --check-prefix=OPT // RUN: %target-swift-frontend -Ounchecked -emit-sil -parse-as-library %s | %FileCheck %s --check-prefix=CHECK --check-prefix=UNCHECKED @inline(never) func takesInoutAndEscaping(_: inout Int, _ f: @escaping () -> ()) { f() } @inline(never) func escapeClosure(_ f: @escaping () -> ()) -> () -> () { return f } public func accessIntTwice() { var x = 0 takesInoutAndEscaping(&x, escapeClosure({ x = 3 })) } // accessIntTwice() // CHECK-LABEL: sil @$s26access_enforcement_options0A8IntTwiceyyF : $@convention(thin) () -> () { // CHECK: [[BOX:%.*]] = alloc_box ${ var Int }, var, name "x" // CHECK: [[PROJ:%.*]] = project_box [[BOX]] : ${ var Int }, 0 // NONE: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[PROJ]] : $*Int // OPT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[PROJ]] : $*Int // UNCHECKED-NOT: = begin_access // CHECK-LABEL: } // end sil function '$s26access_enforcement_options0A8IntTwiceyyF' // closure #1 in accessIntTwice() // CHECK-LABEL: sil {{.*}}@$s26access_enforcement_options0A8IntTwiceyyFyycfU_ : $@convention(thin) (@guaranteed { var Int }) -> () { // CHECK: bb0(%0 : ${ var Int }): // CHECK: [[PROJ:%.*]] = project_box %0 : ${ var Int }, 0 // NONE: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[PROJ]] : $*Int // OPT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[PROJ]] : $*Int // UNCHECKED-NOT: = begin_access // CHECK-LABEL: } // end sil function '$s26access_enforcement_options0A8IntTwiceyyFyycfU_'
apache-2.0
0ee390fe5f4c474595e8b85cd27f78e3
49.054054
135
0.638769
3.117845
false
false
false
false
terhechte/SourceKittenDaemon
Sources/SourceKittenDaemon/Completer/Completer.swift
1
5259
// // Completer.swift // SourceKittenDaemon // // Created by Benedikt Terhechte on 12/11/15. // Copyright © 2015 Benedikt Terhechte. All rights reserved. // import Foundation import SourceKittenFramework #if os(Linux) import FileSystemWatcher #endif private func pingSKD() { NotificationCenter.default.post(name: Notification.Name(rawValue: "skdrefresh"), object: nil) } class FileSystemEventsWrapper { #if os(Linux) func pingAux(event: FileSystemEvent) { pingSKD() } let myWatcher : FileSystemWatcher public init(delay: Int, paths toWatch: [String]) { myWatcher = FileSystemWatcher(deferringDelay: Double(delay)) myWatcher.watch( paths: toWatch, for: [FileSystemEventType.inAllEvents], thenInvoke: pingAux) myWatcher.start() } deinit { myWatcher.stop() } #else let eventStream: FSEventStreamRef public init(delay: Int, paths toWatch: [String]) { self.eventStream = FSEventStreamCreate( kCFAllocatorDefault, { (_, _, _, _, _, _) in pingSKD() }, nil, toWatch as CFArray, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), CFTimeInterval(delay), FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagNoDefer))! let runLoop = RunLoop.main FSEventStreamScheduleWithRunLoop(eventStream, runLoop.getCFRunLoop(), RunLoop.Mode.default as CFString) FSEventStreamStart(eventStream) } deinit { FSEventStreamInvalidate(eventStream) } #endif } /** This keeps the connection to the XPC via SourceKitten and is being called from the Completion Server to perform completions. */ class Completer { // The project parser var project: Project // Need to monitor changes to the .pbxproject and re-fetch // project settings. let fsEventWrapper : FileSystemEventsWrapper init(project: Project) { self.project = project self.fsEventWrapper = FileSystemEventsWrapper(delay: 2, paths: [project.projectFile.path]) print("[INFO] Monitoring \(project.projectFile.path) for changes") NotificationCenter.default.addObserver( forName: NSNotification.Name(rawValue: "skdrefresh"), object: nil, queue: nil) { _ in print("[INFO] Refreshing project due to change in: \(project.projectFile.path)") do { try self.refresh() } catch (let e as CustomStringConvertible) { print("[ERR] Refresh failed: \(e.description)") } catch (_) { print("[ERR] Refresh failed: unknown reason") } } } deinit { } func refresh() throws { self.project = try project.reissue() } func complete(_ url: URL, offset: Int) -> CompletionResult { let path = url.path guard let file = File(path: path) else { return .failure(message: "Could not read file") } let frameworkSearchPaths: [String] = project.frameworkSearchPaths.reduce([]) { $0 + ["-F", $1] } let customSwiftCompilerFlags: [String] = project.customSwiftCompilerFlags let preprocessorFlags: [String] = project.gccPreprocessorDefinitions .reduce([]) { $0 + ["-Xcc", "-D\($1)"] } let sourceFiles: [String] = self.sourceFiles() // Ugly mutation because `[] + [..] + [..] + [..]` = 'Too complex to solve in reasonable time' var compilerArgs: [String] = [] compilerArgs = compilerArgs + ["-module-name", project.moduleName] compilerArgs = compilerArgs + ["-sdk", project.sdkRoot] if let platformTarget = project.platformTarget { compilerArgs = compilerArgs + ["-target", platformTarget] } compilerArgs = compilerArgs + frameworkSearchPaths compilerArgs = compilerArgs + customSwiftCompilerFlags compilerArgs = compilerArgs + preprocessorFlags compilerArgs = compilerArgs + ["-c"] compilerArgs = compilerArgs + [path] compilerArgs = compilerArgs + ["-j4"] compilerArgs = compilerArgs + sourceFiles let contents = file.contents let request = Request.codeCompletionRequest( file: path, contents: contents, offset: ByteCount(offset), arguments: compilerArgs) do { let response = try CodeCompletionItem.parse(response: request.send()) return .success(result: response) } catch let e { return .failure(message: e.localizedDescription) } } func sourceFiles() -> [String] { return project.sourceObjects .map({ (o: ProjectObject) -> String? in o.relativePath.absoluteURL(forProject: project)?.path }) .filter({ $0 != nil }).map({ $0! }) } }
mit
f0334186eef9bb14b7abb9d002594f89
30.674699
112
0.583682
4.895717
false
false
false
false
devpunk/cartesian
cartesian/View/DrawProject/Store/VDrawProjectStoreContentButtons.swift
1
3357
import UIKit class VDrawProjectStoreContentButtons:UIView { private weak var controller:CDrawProject! private let kButtonMargin:CGFloat = 1 private let kButtonWidth:CGFloat = 148 convenience init(controller:CDrawProject) { self.init() clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false backgroundColor = UIColor(white:0.88, alpha:1) self.controller = controller let buttonStore:UIButton = UIButton() buttonStore.translatesAutoresizingMaskIntoConstraints = false buttonStore.clipsToBounds = true buttonStore.backgroundColor = UIColor.white buttonStore.setTitle( NSLocalizedString("VDrawProjectStoreContentButtons_buttonStore", comment:""), for:UIControlState.normal) buttonStore.setTitleColor( UIColor.cartesianBlue, for:UIControlState.normal) buttonStore.setTitleColor( UIColor(white:0, alpha:0.1), for:UIControlState.highlighted) buttonStore.titleLabel!.font = UIFont.bolder(size:15) buttonStore.addTarget( self, action:#selector(actionStore(sender:)), for:UIControlEvents.touchUpInside) let buttonCancel:UIButton = UIButton() buttonCancel.translatesAutoresizingMaskIntoConstraints = false buttonCancel.clipsToBounds = true buttonCancel.backgroundColor = UIColor.white buttonCancel.setTitle( NSLocalizedString("VDrawProjectStoreContentButtons_buttonCancel", comment:""), for:UIControlState.normal) buttonCancel.setTitleColor( UIColor(white:0.7, alpha:1), for:UIControlState.normal) buttonCancel.setTitleColor( UIColor(white:0, alpha:0.1), for:UIControlState.highlighted) buttonCancel.titleLabel!.font = UIFont.bolder(size:15) buttonCancel.addTarget( self, action:#selector(self.actionCancel(sender:)), for:UIControlEvents.touchUpInside) addSubview(buttonStore) addSubview(buttonCancel) NSLayoutConstraint.topToTop( view:buttonCancel, toView:self, constant:kButtonMargin) NSLayoutConstraint.bottomToBottom( view:buttonCancel, toView:self) NSLayoutConstraint.leftToLeft( view:buttonCancel, toView:self, constant:kButtonMargin) NSLayoutConstraint.width( view:buttonCancel, constant:kButtonWidth) NSLayoutConstraint.topToTop( view:buttonStore, toView:self, constant:kButtonMargin) NSLayoutConstraint.bottomToBottom( view:buttonStore, toView:self) NSLayoutConstraint.rightToRight( view:buttonStore, toView:self, constant:-kButtonMargin) NSLayoutConstraint.width( view:buttonStore, constant:kButtonWidth) } //MARK: actions func actionStore(sender button:UIButton) { controller.openStore() } func actionCancel(sender button:UIButton) { controller.viewProject.viewStore?.animateClose() } }
mit
039c66f0afe594f6a5f568c9f8f4537a
32.57
90
0.627644
5.807958
false
false
false
false
groovelab/SwiftBBS
SwiftBBS/SwiftBBS/BbsDetailTableViewCell.swift
1
1691
// // BbsDetailTableViewCell.swift // SwiftBBS // // Created by Takeo Namba on 2016/01/17. // Copyright GrooveLab // import UIKit class BbsDetailTableViewCell: UITableViewCell { var item: [String: Any]? { didSet { guard let item = item else { return } if let comment = item["comment"] as? String { commentLabel.text = comment } if let userName = item["userName"] as? String { userNameLabel.text = userName } if let createdAt = item["createdAt"] as? String { createdAtLabel.text = createdAt } } } @IBOutlet weak private var commentLabel: UILabel! @IBOutlet weak private var userNameLabel: UILabel! @IBOutlet weak private var createdAtLabel: UILabel! @IBOutlet weak private var topMarginConstraint: NSLayoutConstraint! @IBOutlet weak private var middleMarginConstraint: NSLayoutConstraint! @IBOutlet weak private var bottomMarginConstraint: NSLayoutConstraint! @IBOutlet weak private var leftMarginConstraint: NSLayoutConstraint! @IBOutlet weak private var rightMarginConstraint: NSLayoutConstraint! func fittingSizeForWith(width: CGFloat) -> CGSize { let commentLabelSize = commentLabel.sizeThatFits(CGSize(width: width - leftMarginConstraint.constant - rightMarginConstraint.constant, height: CGFloat.max)) let cellHeight = topMarginConstraint.constant + commentLabelSize.height + middleMarginConstraint.constant + userNameLabel.frame.height + bottomMarginConstraint.constant return CGSize(width: width, height: cellHeight) } }
mit
0637df46bd0bbb9f05e4d1863af2049d
38.325581
176
0.675931
5.219136
false
false
false
false
nixzhu/SuperPreview
SuperPreview/ScalingImageView.swift
1
3473
// // ScalingImageView.swift // SuperPreview // // Created by NIX on 2016/11/28. // Copyright © 2016年 nixWork. All rights reserved. // import UIKit class ScalingImageView: UIScrollView { lazy var imageView: UIImageView = { let view = UIImageView() view.contentMode = .scaleAspectFill view.clipsToBounds = true return view }() var image: UIImage? { didSet { image.flatMap { setup(with: $0) } } } var mode: PhotoDisplayMode = .normal var isLongImage: Bool { guard let realImageSize = realImageSize else { return false } return realImageSize.height > bounds.height } private var realImageSize: CGSize? // MARK: Init override init(frame: CGRect) { super.init(frame: frame) self.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.showsVerticalScrollIndicator = false self.showsHorizontalScrollIndicator = false self.bouncesZoom = true self.decelerationRate = UIScrollViewDecelerationRateFast self.addSubview(imageView) self.clipsToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Setup private func setup(with image: UIImage) { update(with: image) } private func update(with image: UIImage) { imageView.transform = CGAffineTransform.identity imageView.image = image realImageSize = image.size if mode == .longImagefullScreen { let imageRatio = image.size.height / image.size.width if imageRatio > bounds.height / bounds.width { realImageSize = CGSize(width: bounds.width, height: bounds.width * imageRatio) } } imageView.frame = CGRect(origin: CGPoint.zero, size: realImageSize!) contentSize = realImageSize! updateZoomScale(with: image) centerContent() } private func updateZoomScale(with image: UIImage) { let scrollViewFrame = bounds let imageSize = realImageSize ?? image.size let widthScale = scrollViewFrame.width / imageSize.width let heightScale = scrollViewFrame.height / imageSize.height let minScale = min(widthScale, heightScale) minimumZoomScale = minScale maximumZoomScale = minScale * 4 if (imageSize.height / imageSize.width) > (scrollViewFrame.height / scrollViewFrame.width) { if mode == .longImagefullScreen { minimumZoomScale = 1 } maximumZoomScale = max(maximumZoomScale, widthScale) } zoomScale = minimumZoomScale panGestureRecognizer.isEnabled = mode == .longImagefullScreen } private func centerContent() { var horizontalInset: CGFloat = 0 var verticalInset: CGFloat = 0 if contentSize.width < bounds.width { horizontalInset = (bounds.width - contentSize.width) * 0.5 } if contentSize.height < bounds.height { verticalInset = (bounds.height - contentSize.height) * 0.5 } if let scale = window?.screen.scale, scale < 2 { horizontalInset = floor(horizontalInset) verticalInset = floor(verticalInset) } contentInset = UIEdgeInsets(top: verticalInset, left: horizontalInset, bottom: verticalInset, right: horizontalInset) } }
mit
83909a53496ca3d554bde51ec7edb87d
30.545455
125
0.632853
5.036284
false
false
false
false
NemProject/NEMiOSApp
NEMWallet/Application/Transaction/TransactionSendViewController.swift
1
29990
// // TransactionSendViewController.swift // // This file is covered by the LICENSE file in the root of this project. // Copyright (c) 2016 NEM // import UIKit import Contacts import SwiftyJSON 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 rhs < lhs } } /** The view controller that lets the user send transactions from the current account or the accounts the current account is a cosignatory of. */ final class TransactionSendViewController: UIViewController, UIScrollViewDelegate { // MARK: - View Controller Properties var recipientAddress: String? var amount: Double? var userSetFee: Double? var message: String? fileprivate var account: Account? fileprivate var accountData: AccountData? fileprivate var activeAccountData: AccountData? fileprivate var willEncrypt = false fileprivate var accountChooserViewController: UIViewController? fileprivate var preparedTransaction: Transaction? fileprivate var sendingTransaction = false fileprivate var suggestions = [String: String]() fileprivate var contacts = [CNContact]() // MARK: - View Controller Outlets @IBOutlet weak var customScrollView: UIScrollView! @IBOutlet weak var contentView: UIView! @IBOutlet weak var transactionAccountChooserButton: AccountChooserButton! @IBOutlet weak var transactionSenderHeadingLabel: UILabel! @IBOutlet weak var transactionSenderLabel: UILabel! @IBOutlet weak var transactionRecipientHeadingLabel: UILabel! @IBOutlet weak var transactionRecipientTextField: AutoCompleteTextField! @IBOutlet weak var transactionAmountHeadingLabel: UILabel! @IBOutlet weak var transactionAmountTextField: UITextField! @IBOutlet weak var transactionMessageHeadingLabel: UILabel! @IBOutlet weak var transactionMessageTextField: UITextField! @IBOutlet weak var transactionEncryptionButton: UIButton! @IBOutlet weak var transactionFeeHeadingLabel: UILabel! @IBOutlet weak var transactionFeeTextField: UITextField! @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var customNavigationItem: UINavigationItem! @IBOutlet weak var viewTopConstraint: NSLayoutConstraint! @IBOutlet weak var transactionSendButton: UIBarButtonItem! // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() self.navigationBar.delegate = self transactionSendButton.isEnabled = false transactionFeeTextField.isEnabled = Constants.activeNetwork == Constants.testNetwork ? true : false account = AccountManager.sharedInstance.activeAccount guard account != nil else { print("Critical: Account not available!") return } updateViewControllerAppearance() fetchAccountData(forAccount: account!) if recipientAddress != nil { transactionRecipientTextField.text = recipientAddress } if amount != nil { transactionAmountTextField.text = "\(amount!)" } if message != nil { transactionMessageTextField.text = message } calculateTransactionFee() handleTextFieldInterfaces() fetchContacts() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() viewTopConstraint.constant = self.navigationBar.frame.height } private func handleTextFieldInterfaces() { transactionRecipientTextField.onTextChange = { [weak self] text in if !text.isEmpty { self?.setSuggestions() } } transactionRecipientTextField.onSelect = { [weak self] text, indexpath in self?.transactionRecipientTextField.text = self?.suggestions[text] } } // MARK: - View Controller Helper Methods /// Updates the appearance (coloring, titles) of the view controller. fileprivate func updateViewControllerAppearance() { customNavigationItem.title = "NEW_TRANSACTION".localized() transactionSenderHeadingLabel.text = "FROM".localized() + ":" transactionRecipientHeadingLabel.text = "TO".localized() + ":" transactionAmountHeadingLabel.text = "AMOUNT".localized() + ":" transactionMessageHeadingLabel.text = "MESSAGE".localized() + ":" transactionFeeHeadingLabel.text = "FEE".localized() + ":" transactionSendButton.title = "SEND".localized() transactionRecipientTextField.placeholder = "ENTER_ADDRESS".localized() transactionAmountTextField.placeholder = "ENTER_AMOUNT".localized() transactionMessageTextField.placeholder = "EMPTY_MESSAGE".localized() transactionFeeTextField.placeholder = "ENTER_FEE".localized() transactionAccountChooserButton.setImage(#imageLiteral(resourceName: "DropDown").imageWithColor(UIColor(red: 90.0/255.0, green: 179.0/255.0, blue: 232.0/255.0, alpha: 1)), for: UIControlState()) transactionRecipientTextField.autoCompleteTextFont = UIFont.systemFont(ofSize: 14) transactionRecipientTextField.autoCompleteCellHeight = 35.0 transactionRecipientTextField.maximumAutoCompleteCount = 20 transactionRecipientTextField.hidesWhenSelected = true transactionRecipientTextField.hidesWhenEmpty = true transactionRecipientTextField.enableAttributedText = false } /** Shows an alert view controller with the provided alert message. - Parameter message: The message that should get shown. - Parameter completion: An optional action that should get performed on completion. */ fileprivate func showAlert(withMessage message: String, completion: ((Void) -> Void)? = nil) { let alert = UIAlertController(title: "INFO".localized(), message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertActionStyle.default, handler: { (action) -> Void in alert.dismiss(animated: true, completion: nil) completion?() })) present(alert, animated: true, completion: nil) } /** Updates the form with the fetched account details. - Parameter accountData: The account data with which the form should get updated. */ fileprivate func updateForm(withAccountData accountData: AccountData, forMultisigAccount: Bool = false) { if accountData.cosignatoryOf.count > 0 || forMultisigAccount == true { transactionAccountChooserButton.isHidden = false transactionSenderLabel.isHidden = true transactionAccountChooserButton.setTitle(accountData.title ?? accountData.address, for: UIControlState()) } else { transactionAccountChooserButton.isHidden = true transactionSenderLabel.isHidden = false transactionSenderLabel.text = accountData.title ?? accountData.address } let amountAttributedString = NSMutableAttributedString(string: "\("AMOUNT".localized()) (\("BALANCE".localized()): ", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 17, weight: UIFontWeightLight)]) amountAttributedString.append(NSMutableAttributedString(string: "\((accountData.balance / 1000000).format())", attributes: [NSForegroundColorAttributeName: UIColor(red: 90.0/255.0, green: 179.0/255.0, blue: 232.0/255.0, alpha: 1), NSFontAttributeName: UIFont.systemFont(ofSize: 17)])) amountAttributedString.append(NSMutableAttributedString(string: " XEM):", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 17, weight: UIFontWeightLight)])) transactionAmountHeadingLabel.attributedText = amountAttributedString } /** Fetches the account data (balance, cosignatories, etc.) for the current account from the active NIS. - Parameter account: The current account for which the account data should get fetched. */ fileprivate func fetchAccountData(forAccount account: Account) { NEMProvider.request(NEM.accountData(accountAddress: account.address)) { [weak self] (result) in switch result { case let .success(response): do { let _ = try response.filterSuccessfulStatusCodes() let json = JSON(data: response.data) var accountData = try json.mapObject(AccountData.self) if accountData.publicKey == "" { accountData.publicKey = account.publicKey } DispatchQueue.main.async { self?.accountData = accountData self?.updateForm(withAccountData: accountData) self?.transactionSendButton.isEnabled = true } } catch { DispatchQueue.main.async { print("Failure: \(response.statusCode)") } } case let .failure(error): DispatchQueue.main.async { print(error) } } } } /** Fetches the account data (balance, cosignatories, etc.) for the account from the active NIS. - Parameter accountAddress: The address of the account for which the account data should get fetched. */ fileprivate func fetchAccountData(forAccountWithAddress accountAddress: String) { NEMProvider.request(NEM.accountData(accountAddress: accountAddress)) { [weak self] (result) in switch result { case let .success(response): do { let _ = try response.filterSuccessfulStatusCodes() let json = JSON(data: response.data) let accountData = try json.mapObject(AccountData.self) DispatchQueue.main.async { self?.finishPreparingTransaction(withRecipientPublicKey: accountData.publicKey) } } catch { DispatchQueue.main.async { print("Failure: \(response.statusCode)") self?.showAlert(withMessage: "TRANSACTION_ANOUNCE_FAILED".localized()) self?.sendingTransaction = false } } case let .failure(error): DispatchQueue.main.async { print(error) self?.showAlert(withMessage: "TRANSACTION_ANOUNCE_FAILED".localized()) self?.sendingTransaction = false } } } } /** Signs and announces a new transaction to the NIS. - Parameter transaction: The transaction object that should get signed and announced. */ fileprivate func announceTransaction(_ transaction: Transaction) { let requestAnnounce = TransactionManager.sharedInstance.signTransaction(transaction, account: account!) NEMProvider.request(NEM.announceTransaction(requestAnnounce: requestAnnounce)) { [weak self] (result) in switch result { case let .success(response): do { let _ = try response.filterSuccessfulStatusCodes() let responseJSON = JSON(data: response.data) try self?.validateAnnounceTransactionResult(responseJSON) DispatchQueue.main.async { self?.showAlert(withMessage: "TRANSACTION_ANOUNCE_SUCCESS".localized()) self?.transactionAmountTextField.text = "" self?.transactionMessageTextField.text = "" self?.willEncrypt = false self?.transactionEncryptionButton.backgroundColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1) self?.transactionEncryptionButton.isEnabled = self?.activeAccountData?.address == self?.accountData?.address self?.calculateTransactionFee() } } catch TransactionAnnounceValidation.failure(let errorMessage) { DispatchQueue.main.async { print("Failure: \(response.statusCode)") self?.showAlert(withMessage: errorMessage) } } catch { DispatchQueue.main.async { print("Failure: \(response.statusCode)") self?.showAlert(withMessage: "TRANSACTION_ANOUNCE_FAILED".localized()) } } case let .failure(error): DispatchQueue.main.async { print(error) self?.showAlert(withMessage: "TRANSACTION_ANOUNCE_FAILED".localized()) } } self?.sendingTransaction = false } } /** Validates the response (announce transaction result object) of the NIS regarding the announcement of the transaction. - Parameter responseJSON: The response of the NIS JSON formatted. - Throws: - TransactionAnnounceValidation.Failure if the announcement of the transaction wasn't successful. */ fileprivate func validateAnnounceTransactionResult(_ responseJSON: JSON) throws { guard let responseCode = responseJSON["code"].int else { throw TransactionAnnounceValidation.failure(errorMessage: "TRANSACTION_ANOUNCE_FAILED".localized()) } let responseMessage = responseJSON["message"].stringValue switch responseCode { case 1: return default: throw TransactionAnnounceValidation.failure(errorMessage: responseMessage) } } /// Calculates the fee for the transaction and updates the transaction fee text field accordingly. fileprivate func calculateTransactionFee() { var transactionAmountString = transactionAmountTextField.text!.replacingOccurrences(of: " ", with: "") var transactionAmount = Double(transactionAmountString) ?? 0.0 if transactionAmount < 0.000001 && transactionAmount != 0 { transactionAmountTextField.text = "0" transactionAmount = 0 } var transactionFee = 0.0 transactionFee = TransactionManager.sharedInstance.calculateFee(forTransactionWithAmount: transactionAmount) let transactionMessageByteArray = transactionMessageTextField.text!.hexadecimalStringUsingEncoding(String.Encoding.utf8)!.asByteArray() let transactionMessageLength = transactionMessageTextField.text!.hexadecimalStringUsingEncoding(String.Encoding.utf8)!.asByteArray().count if transactionMessageLength != 0 { transactionFee += TransactionManager.sharedInstance.calculateFee(forTransactionWithMessage: transactionMessageByteArray, isEncrypted: willEncrypt) } let transactionFeeAttributedString = NSMutableAttributedString(string: "\("FEE".localized()): (\("MIN".localized()) ", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 17, weight: UIFontWeightLight)]) transactionFeeAttributedString.append(NSMutableAttributedString(string: "\(transactionFee)", attributes: [ NSForegroundColorAttributeName: UIColor(red: 90.0/255.0, green: 179.0/255.0, blue: 232.0/255.0, alpha: 1), NSFontAttributeName: UIFont.systemFont(ofSize: 17)])) transactionFeeAttributedString.append(NSMutableAttributedString(string: " XEM)", attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 17, weight: UIFontWeightLight)])) transactionFeeHeadingLabel.attributedText = transactionFeeAttributedString if userSetFee == nil || Constants.activeNetwork == Constants.mainNetwork { transactionFeeTextField.text = "\(transactionFee)" } } /** Finishes preparing the transaction and initiates the announcement of the final transaction. - Parameter recipientPublicKey: The public key of the transaction recipient. */ fileprivate func finishPreparingTransaction(withRecipientPublicKey recipientPublicKey: String) { let transactionMessageText = transactionMessageTextField.text!.hexadecimalStringUsingEncoding(String.Encoding.utf8) ?? String() var transactionMessageByteArray: [UInt8] = transactionMessageText.asByteArray() if willEncrypt { var transactionEncryptedMessageByteArray: [UInt8] = Array(repeating: 0, count: 32) transactionEncryptedMessageByteArray = TransactionManager.sharedInstance.encryptMessage(transactionMessageByteArray, senderEncryptedPrivateKey: account!.privateKey, recipientPublicKey: recipientPublicKey) transactionMessageByteArray = transactionEncryptedMessageByteArray } let transactionMessage = Message(type: willEncrypt ? MessageType.encrypted : MessageType.unencrypted, payload: transactionMessageByteArray, message: transactionMessageTextField.text!) (preparedTransaction as! TransferTransaction).message = transactionMessage // Check if the transaction is a multisig transaction if activeAccountData!.publicKey != account!.publicKey { let multisigTransaction = MultisigTransaction(version: (preparedTransaction as! TransferTransaction).version, timeStamp: (preparedTransaction as! TransferTransaction).timeStamp, fee: Int(0.15 * 1000000), deadline: (preparedTransaction as! TransferTransaction).deadline, signer: account!.publicKey, innerTransaction: (preparedTransaction as! TransferTransaction)) announceTransaction(multisigTransaction!) return } announceTransaction((preparedTransaction as! TransferTransaction)) } /// Fetches all contacts and reloads the table view with the fetched content. fileprivate func fetchContacts() { AddressBookManager.sharedInstance.contacts { [weak self] (contacts) in self?.contacts = contacts } } /// Filters all contacts with an account address from the contacts. open func filterContacts() -> [String: String] { var filteredContacts = [String: String]() for contact in contacts { for emailAddress in contact.emailAddresses where emailAddress.label == "NEM" { filteredContacts["\(contact.givenName) \(contact.familyName)"] = emailAddress.value as String } } return filteredContacts } /// Sets all suggestions for the recipient text field. fileprivate func setSuggestions() { guard transactionRecipientTextField.text != nil else { return } let searchText = transactionRecipientTextField.text!.lowercased() var autoCompleteStrings = [String]() let accounts = AccountManager.sharedInstance.accounts() for account in accounts { suggestions[account.title] = account.address } let contacts = filterContacts() for contact in contacts { suggestions[contact.key] = contact.value } let filteredSuggestions = suggestions.filter { let fullName = "\($0.key) \($0.value)".lowercased() return fullName.contains(searchText) } for filteredSuggestion in filteredSuggestions { autoCompleteStrings.append(filteredSuggestion.key) } if autoCompleteStrings.count == 0 { transactionRecipientTextField.autoCompleteTableView?.isHidden = true transactionRecipientTextField.autoCompleteStrings = nil } else { transactionRecipientTextField.autoCompleteStrings = autoCompleteStrings } } // MARK: - View Controller Outlet Actions @IBAction func chooseAccount(_ sender: UIButton) { if accountChooserViewController == nil { var accounts = accountData!.cosignatoryOf ?? [] accounts.append(accountData!) let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) let accountChooserViewController = mainStoryboard.instantiateViewController(withIdentifier: "AccountChooserViewController") as! AccountChooserViewController accountChooserViewController.view.frame = CGRect(x: contentView.frame.origin.x, y: customScrollView.frame.origin.y + 60, width: contentView.frame.width, height: contentView.frame.height - 60) accountChooserViewController.view.layer.opacity = 0 accountChooserViewController.delegate = self accountChooserViewController.accounts = accounts self.accountChooserViewController = accountChooserViewController if accounts.count > 0 { transactionSendButton.isEnabled = false view.addSubview(accountChooserViewController.view) UIView.animate(withDuration: 0.2, animations: { accountChooserViewController.view.layer.opacity = 1 }) } } else { accountChooserViewController!.view.removeFromSuperview() accountChooserViewController!.removeFromParentViewController() accountChooserViewController = nil transactionSendButton.isEnabled = true } } @IBAction func toggleEncryptionSetting(_ sender: UIButton) { willEncrypt = !willEncrypt sender.backgroundColor = (willEncrypt) ? UIColor(red: 90.0/255.0, green: 179.0/255.0, blue: 232.0/255.0, alpha: 1) : UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1) calculateTransactionFee() } @IBAction func createTransaction(_ sender: UIBarButtonItem) { guard sendingTransaction == false else { return } guard transactionRecipientTextField.text != nil else { return } guard transactionAmountTextField.text != nil else { return } guard transactionMessageTextField.text != nil else { return } guard transactionFeeTextField.text != nil else { return } if activeAccountData == nil { activeAccountData = accountData } sendingTransaction = true let transactionVersion = 1 let transactionTimeStamp = Int(TimeManager.sharedInstance.currentNetworkTime) let transactionAmount = Double(transactionAmountTextField.text!) ?? 0.0 var transactionFee = Double(transactionFeeTextField.text!) ?? 0.0 let transactionRecipient = transactionRecipientTextField.text!.replacingOccurrences(of: "-", with: "") let transactionMessageText = transactionMessageTextField.text!.hexadecimalStringUsingEncoding(String.Encoding.utf8) ?? String() let transactionMessageByteArray: [UInt8] = transactionMessageText.asByteArray() let transactionDeadline = Int(TimeManager.sharedInstance.currentNetworkTime + Constants.transactionDeadline) let transactionSigner = activeAccountData!.publicKey calculateTransactionFee() if transactionAmount < 0.000001 && transactionAmount != 0 { transactionAmountTextField!.text = "0" sendingTransaction = false return } if transactionFee < Double(transactionFeeTextField.text!) { transactionFee = Double(transactionFeeTextField.text!)! } guard TransactionManager.sharedInstance.validateAccountAddress(transactionRecipient) else { showAlert(withMessage: "ACCOUNT_ADDRESS_INVALID".localized()) sendingTransaction = false return } guard (activeAccountData!.balance / 1000000) > transactionAmount else { showAlert(withMessage: "ACCOUNT_NOT_ENOUGHT_MONEY".localized()) sendingTransaction = false return } guard TransactionManager.sharedInstance.validateHexadecimalString(transactionMessageText) == true else { showAlert(withMessage: "NOT_A_HEX_STRING".localized()) sendingTransaction = false return } if willEncrypt { if transactionMessageByteArray.count > 976 { showAlert(withMessage: "VALIDAATION_MESSAGE_LEANGTH".localized()) sendingTransaction = false return } } else { if transactionMessageByteArray.count > 1024 { showAlert(withMessage: "VALIDAATION_MESSAGE_LEANGTH".localized()) sendingTransaction = false return } } let transaction = TransferTransaction(version: transactionVersion, timeStamp: transactionTimeStamp, amount: transactionAmount * 1000000, fee: Int(transactionFee * 1000000), recipient: transactionRecipient, message: nil, deadline: transactionDeadline, signer: transactionSigner!) let alert = UIAlertController(title: "INFO".localized(), message: "Are you sure you want to send this transaction to \(transactionRecipient.nemAddressNormalised())?", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertActionStyle.destructive, handler: { [weak self] (action) -> Void in alert.dismiss(animated: true, completion: nil) if self != nil { self!.preparedTransaction = transaction self?.fetchAccountData(forAccountWithAddress: transactionRecipient) } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { [weak self] (action) in self?.sendingTransaction = false return })) present(alert, animated: true, completion: nil) } @IBAction func textFieldEditingChanged(_ sender: UITextField) { calculateTransactionFee() } @IBAction func userDefinedFee(_ sender: UITextField) { if Constants.activeNetwork == Constants.testNetwork { userSetFee = Double(transactionFeeTextField.text!) ?? nil } } @IBAction func textFieldReturnKeyToched(_ sender: UITextField) { switch sender { case transactionRecipientTextField: transactionAmountTextField.becomeFirstResponder() case transactionAmountTextField : transactionMessageTextField.becomeFirstResponder() case transactionMessageTextField : transactionFeeTextField.becomeFirstResponder() default : sender.becomeFirstResponder() } calculateTransactionFee() } @IBAction func textFieldEditingEnd(_ sender: UITextField) { calculateTransactionFee() } @IBAction func endTyping(_ sender: AutoCompleteTextField) { calculateTransactionFee() sender.becomeFirstResponder() } @IBAction func cancel(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } } // MARK: - Account Chooser Delegate extension TransactionSendViewController: AccountChooserDelegate { func didChooseAccount(_ accountData: AccountData) { activeAccountData = accountData accountChooserViewController?.view.removeFromSuperview() accountChooserViewController?.removeFromParentViewController() accountChooserViewController = nil transactionSendButton.isEnabled = true transactionEncryptionButton.isEnabled = activeAccountData?.address == self.accountData?.address if activeAccountData?.address != self.accountData?.address { willEncrypt = false transactionEncryptionButton.backgroundColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1) } updateForm(withAccountData: accountData, forMultisigAccount: true) } } // MARK: - Navigation Bar Delegate extension TransactionSendViewController: UINavigationBarDelegate { func position(for bar: UIBarPositioning) -> UIBarPosition { return .topAttached } }
mit
1dd585743230ada793f08286d30ab94f
42.08908
374
0.63001
5.704775
false
false
false
false
Nyx0uf/MPDRemote
src/iOS/views/MiniPlayerView.swift
1
13382
// MiniPlayerView.swift // Copyright (c) 2017 Nyx0uf // // 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 let baseHeight = CGFloat(44.0) final class MiniPlayerView : UIView { // MARK: - Public properties // Singletion instance static let shared = MiniPlayerView(frame: .zero) // Visible flag private(set) var visible = false private(set) var fullyVisible = false // Player should stay hidden, regardless of playback status var stayHidden = false // Album cover private(set) var imageView: UIImageView! // MARK: - Private properties private var blurEffectView: UIVisualEffectView! // Queue's track list private var tableView: TracksListTableView! // Dummy acessible view for title private var accessibleView: UIView! // Track title private var lblTitle: AutoScrollLabel! // Track artist private var lblArtist: UILabel! // Play/pause button private var btnPlay: UIButton! // View to indicate track progression private var progressView: UIView! // MARK: - Initializers override init(frame f: CGRect) { let headerHeight: CGFloat let marginTop: CGFloat if #available(iOS 11, *) { if let bottom = UIApplication.shared.keyWindow?.safeAreaInsets.bottom { headerHeight = baseHeight + bottom marginTop = (UIApplication.shared.keyWindow?.safeAreaInsets.top)! < 20 ? 20 : (UIApplication.shared.keyWindow?.safeAreaInsets.top)! } else { headerHeight = baseHeight marginTop = 20.0 } } else { headerHeight = baseHeight marginTop = 20.0 } let frame = CGRect(0.0, (UIApplication.shared.keyWindow?.frame.height)! + headerHeight, (UIApplication.shared.keyWindow?.frame.width)!, (UIApplication.shared.keyWindow?.frame.height)! - marginTop - baseHeight) super.init(frame: frame) self.backgroundColor = #colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 0) // Top shadow self.layer.shadowPath = UIBezierPath(rect: CGRect(-2.0, 5.0, frame.width + 4.0, 4.0)).cgPath self.layer.shadowRadius = 3.0 self.layer.shadowOpacity = 1.0 self.layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor self.layer.masksToBounds = false self.isAccessibilityElement = false // Blur background let blurEffect = UIBlurEffect(style: .light) self.blurEffectView = UIVisualEffectView(effect: blurEffect) self.blurEffectView.frame = CGRect(.zero, frame.size.width, headerHeight) self.addSubview(self.blurEffectView) self.imageView = UIImageView(frame: CGRect(0.0, 0.0, headerHeight, headerHeight)) self.imageView.backgroundColor = #colorLiteral(red: 0.1298420429, green: 0.1298461258, blue: 0.1298439503, alpha: 1) self.imageView.isUserInteractionEnabled = true self.blurEffectView.contentView.addSubview(self.imageView) // Vibrancy over the play/pause button let vibrancyEffectView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect)) vibrancyEffectView.frame = CGRect(frame.right - headerHeight, 0.0, headerHeight, headerHeight) self.blurEffectView.contentView.addSubview(vibrancyEffectView) // Play / pause button self.btnPlay = UIButton(type: .custom) self.btnPlay.frame = CGRect(6.0, 6.0, 32.0, 32.0) self.btnPlay.setImage(#imageLiteral(resourceName: "btn-play").withRenderingMode(.alwaysTemplate), for: .normal) self.btnPlay.addTarget(self, action: #selector(MiniPlayerView.changePlaybackAction(_:)), for: .touchUpInside) self.btnPlay.tag = PlayerStatus.stopped.rawValue self.btnPlay.isAccessibilityElement = true vibrancyEffectView.contentView.addSubview(self.btnPlay) // Dummy accessibility view self.accessibleView = UIView(frame: CGRect(self.imageView.right, 0.0, vibrancyEffectView.left - self.imageView.right, headerHeight)) self.accessibleView.backgroundColor = #colorLiteral(red: 1, green: 0.99997437, blue: 0.9999912977, alpha: 0) self.accessibleView.isAccessibilityElement = true self.blurEffectView.contentView.addSubview(self.accessibleView) // Title self.lblTitle = AutoScrollLabel(frame: CGRect(self.imageView.right + 5.0, 2.0, ((vibrancyEffectView.left + 5.0) - (self.imageView.right + 5.0)), 18.0)) self.lblTitle.textAlignment = .center self.lblTitle.font = UIFont(name: "GillSans-Bold", size: 14.0) self.lblTitle.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) self.lblTitle.isAccessibilityElement = false self.blurEffectView.contentView.addSubview(self.lblTitle) // Artist self.lblArtist = UILabel(frame: CGRect(self.imageView.right + 5.0, self.lblTitle.bottom + 2.0, self.lblTitle.width, 16.0)) self.lblArtist.textAlignment = .center self.lblArtist.font = UIFont(name: "GillSans", size: 12.0) self.lblArtist.textColor = #colorLiteral(red: 0.1298420429, green: 0.1298461258, blue: 0.1298439503, alpha: 1) self.lblArtist.isAccessibilityElement = false self.blurEffectView.contentView.addSubview(self.lblArtist) // Progress self.progressView = UIView(frame: CGRect(0.0, 0.0, 0.0, 1.0)) self.progressView.isAccessibilityElement = false self.addSubview(self.progressView) // Tableview self.tableView = TracksListTableView(frame: CGRect(0.0, headerHeight, frame.width, frame.height - headerHeight), style: .plain) self.tableView.delegate = self self.addSubview(self.tableView) // Single tap to request full player view let singleTap = UITapGestureRecognizer() singleTap.numberOfTapsRequired = 1 singleTap.numberOfTouchesRequired = 1 singleTap.addTarget(self, action: #selector(singleTap(_:))) if UIDevice.current.isiPhoneX() { self.imageView.addGestureRecognizer(singleTap) } else { self.addGestureRecognizer(singleTap) } let doubleTap = UITapGestureRecognizer() doubleTap.numberOfTapsRequired = 2 doubleTap.numberOfTouchesRequired = 1 doubleTap.addTarget(self, action: #selector(doubleTap(_:))) if UIDevice.current.isiPhoneX() { self.imageView.addGestureRecognizer(doubleTap) } else { self.addGestureRecognizer(doubleTap) } singleTap.require(toFail: doubleTap) NotificationCenter.default.addObserver(self, selector: #selector(playingTrackNotification(_:)), name: .currentPlayingTrack, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(playerStatusChangedNotification(_:)), name: .playerStatusChanged, object: nil) APP_DELEGATE().window?.addSubview(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Public func setInfoFromTrack(_ track: Track, ofAlbum album: Album) { lblTitle.text = track.name lblArtist.text = track.artist guard let url = album.localCoverURL else {return} if let image = UIImage.loadFromFileURL(url) { let x = KawaiiColors(image: image) x.analyze() progressView.backgroundColor = x.dominantColor imageView.image = image.scaled(toSize: CGSize(imageView.width * UIScreen.main.scale, imageView.height * UIScreen.main.scale)) } else { let sizeAsData = Settings.shared.data(forKey: kNYXPrefCoversSize)! let cropSize = NSKeyedUnarchiver.unarchiveObject(with: sizeAsData) as! NSValue if album.path != nil { let op = CoverOperation(album: album, cropSize: cropSize.cgSizeValue) op.callback = {(cover: UIImage, thumbnail: UIImage) in DispatchQueue.main.async { self.setInfoFromTrack(track, ofAlbum: album) } } OperationManager.shared.addOperation(op) } else { MusicDataSource.shared.getPathForAlbum(album) { let op = CoverOperation(album: album, cropSize: cropSize.cgSizeValue) op.callback = {(cover: UIImage, thumbnail: UIImage) in DispatchQueue.main.async { self.setInfoFromTrack(track, ofAlbum: album) } } OperationManager.shared.addOperation(op) } } } } func show(_ animated: Bool = true) { NotificationCenter.default.post(name: .miniPlayerViewWillShow, object: nil) let w = UIApplication.shared.keyWindow! UIView.animate(withDuration: animated ? 0.35 : 0.0, delay: 0.0, options: UIViewAnimationOptions(), animations: { self.y = w.frame.height - self.blurEffectView.height }, completion: { finished in self.visible = true NotificationCenter.default.post(name: .miniPlayerViewDidShow, object: nil) }) } func hide(_ animated: Bool = true) { NotificationCenter.default.post(name: .miniPlayerViewWillHide, object: nil) let w = UIApplication.shared.keyWindow! UIView.animate(withDuration: animated ? 0.35 : 0.0, delay: 0.0, options: UIViewAnimationOptions(), animations: { self.y = w.frame.height + self.blurEffectView.height }, completion: { finished in self.visible = false NotificationCenter.default.post(name: .miniPlayerViewDidHide, object: nil) }) } // MARK: - Buttons actions @objc func changePlaybackAction(_ sender: UIButton?) { if btnPlay.tag == PlayerStatus.playing.rawValue { btnPlay.setImage(#imageLiteral(resourceName: "btn-play").withRenderingMode(.alwaysTemplate), for: .normal) btnPlay.accessibilityLabel = NYXLocalizedString("lbl_play") } else { btnPlay.setImage(#imageLiteral(resourceName: "btn-pause").withRenderingMode(.alwaysTemplate), for: .normal) btnPlay.accessibilityLabel = NYXLocalizedString("lbl_pause") } PlayerController.shared.togglePause() } // MARK: - Gestures @objc func singleTap(_ gesture: UITapGestureRecognizer) { if gesture.state == .ended { NotificationCenter.default.post(name: .miniPlayerShouldExpand, object: nil) } } @objc func doubleTap(_ gesture: UITapGestureRecognizer) { if fullyVisible == false { PlayerController.shared.getSongsOfCurrentQueue { DispatchQueue.main.async { self.tableView.tracks = PlayerController.shared.listTracksInQueue } } let w = UIApplication.shared.keyWindow! UIView.animate(withDuration: 0.35, delay: 0.0, options: UIViewAnimationOptions(), animations: { self.y = w.frame.height - self.height }, completion: { finished in self.fullyVisible = true }) } else { let w = UIApplication.shared.keyWindow! UIView.animate(withDuration: 0.35, delay: 0.0, options: UIViewAnimationOptions(), animations: { self.y = w.frame.height - self.blurEffectView.height }, completion: { finished in self.fullyVisible = false }) } } // MARK: - Notifications @objc func playingTrackNotification(_ aNotification: Notification) { if let infos = aNotification.userInfo { // Player not visible and should be if visible == false && stayHidden == false { show() } let track = infos[kPlayerTrackKey] as! Track let album = infos[kPlayerAlbumKey] as! Album let elapsed = infos[kPlayerElapsedKey] as! Int if track.name != lblTitle.text { setInfoFromTrack(track, ofAlbum: album) } let ratio = width / CGFloat(track.duration.seconds) UIView.animate(withDuration: 0.5) { self.progressView.width = ratio * CGFloat(elapsed) } accessibleView.accessibilityLabel = "\(track.name) \(NYXLocalizedString("lbl_by")) \(track.artist)\n\((100 * elapsed) / Int(track.duration.seconds))% \(NYXLocalizedString("lbl_played"))" } } @objc func playerStatusChangedNotification(_ aNotification: Notification) { if let infos = aNotification.userInfo { let state = infos[kPlayerStatusKey] as! Int if state == PlayerStatus.playing.rawValue { btnPlay.setImage(#imageLiteral(resourceName: "btn-pause").withRenderingMode(.alwaysTemplate), for: .normal) btnPlay.accessibilityLabel = NYXLocalizedString("lbl_pause") } else { btnPlay.setImage(#imageLiteral(resourceName: "btn-play").withRenderingMode(.alwaysTemplate), for: .normal) btnPlay.accessibilityLabel = NYXLocalizedString("lbl_play") } btnPlay.tag = state } } } // MARK: - UITableViewDelegate extension MiniPlayerView : UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: { tableView.deselectRow(at: indexPath, animated: true) }) // Toggle play / pause for the current track if let currentPlayingTrack = PlayerController.shared.currentTrack { let selectedTrack = self.tableView.tracks[indexPath.row] if selectedTrack == currentPlayingTrack { PlayerController.shared.togglePause() return } } PlayerController.shared.playTrackAtPosition(UInt32(indexPath.row)) } }
mit
d658912fd752315e1fb34f9b69bfce1c
34.215789
211
0.735615
3.739033
false
false
false
false
drahot/BSImagePicker
Pod/Classes/Controller/ZoomAnimator.swift
1
5133
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // 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 UIImageViewModeScaleAspect final class ZoomAnimator : NSObject, UIViewControllerAnimatedTransitioning { var sourceImageView: UIImageView? var destinationImageView: UIImageView? func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { // Get to and from view controller if let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to), let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from), let sourceImageView = sourceImageView, let destinationImageView = destinationImageView{ let containerView = transitionContext.containerView // Disable selection so we don't select anything while the push animation is running fromViewController.view?.isUserInteractionEnabled = false // Setup views sourceImageView.isHidden = true destinationImageView.isHidden = true toViewController.view.alpha = 0.0 fromViewController.view.alpha = 1.0 containerView.backgroundColor = toViewController.view.backgroundColor // Setup scaling image let scalingFrame = containerView.convert(sourceImageView.frame, from: sourceImageView.superview) let scalingImage = UIImageViewModeScaleAspect(frame: scalingFrame) scalingImage.contentMode = sourceImageView.contentMode scalingImage.image = sourceImageView.image //Init image scale let destinationFrame = toViewController.view.convert(destinationImageView.bounds, from: destinationImageView.superview) if destinationImageView.contentMode == .scaleAspectFit { scalingImage.initToScaleAspectFit(toFrame: destinationFrame) } else { scalingImage.initToScaleAspectFill(toFrame: destinationFrame) } // Add views to container view containerView.addSubview(toViewController.view) containerView.addSubview(scalingImage) // Animate UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: UIView.AnimationOptions(), animations: { () -> Void in // Fade in fromViewController.view.alpha = 0.0 toViewController.view.alpha = 1.0 if destinationImageView.contentMode == .scaleAspectFit { scalingImage.animaticToScaleAspectFit() } else { scalingImage.animaticToScaleAspectFill() } }, completion: { (finished) -> Void in // Finish image scaling and remove image view if destinationImageView.contentMode == .scaleAspectFit { scalingImage.animateFinishToScaleAspectFit() } else { scalingImage.animateFinishToScaleAspectFill() } scalingImage.removeFromSuperview() // Unhide destinationImageView.isHidden = false sourceImageView.isHidden = false fromViewController.view.alpha = 1.0 // Finish transition transitionContext.completeTransition(!transitionContext.transitionWasCancelled) // Enable selection again fromViewController.view?.isUserInteractionEnabled = true }) } } }
mit
f6f04739b5bfb72cafa5d6bc8b7d8df1
48.825243
314
0.640881
6.359356
false
false
false
false
arthurschiller/ARKit-LeapMotion
Mac App/Bluetooth/LeapMotionGesturePeripheral.swift
1
5171
// // LeapMotionGesturePeripheral.swift // Mac App // // Created by Arthur Schiller on 28.07.17. // import CoreBluetooth class LeapMotionGesturePeripheral: NSObject { private let manager: CBPeripheralManager private let services: [CBMutableService] private let peripheralName: String private var subscribers: [CBUUID:[CBCentral]] = [:] private var servicesAdded = false init(name: String, manager: CBPeripheralManager, services: [CBMutableService]) { self.peripheralName = name self.manager = manager self.services = services super.init() self.manager.delegate = self } private var handDataString: String = "" { didSet { updateValue(forCharacteristic: LeapMotionGestureService.hand) } } func set(handDataString: String) { self.handDataString = handDataString } private func updateValue(forCharacteristic uuid: CBUUID) { guard let centrals = subscribers[uuid], !centrals.isEmpty, let value = value(forCharacteristic: uuid), let characteristic = (myBluetoothService?.characteristics?.filter { $0.uuid == uuid })?.last as? CBMutableCharacteristic else { return } manager.updateValue(value, for: characteristic, onSubscribedCentrals: centrals) print("updating value: \(value)") } func startAdvertising() { manager.stopAdvertising() let UUIDs: [CBUUID] = services.map { $0.uuid } let advData: [String: Any] = [CBAdvertisementDataServiceUUIDsKey: UUIDs, CBAdvertisementDataLocalNameKey: peripheralName, CBAdvertisementDataIsConnectable: NSNumber(value: true)] manager.startAdvertising(advData) } func stopAdvertising() { print("Advertising stopped") manager.stopAdvertising() } func value(forCharacteristic uuid: CBUUID) -> Data? { switch uuid { case LeapMotionGestureService.hand: return handDataString.data(using: .utf8) default: return nil } } convenience init(name: String = "LeapMotionGestureService preferences") { let service = CBMutableService(type: LeapMotionGestureService.uuid, primary: true) let characteristics = LeapMotionGestureService.characteristics.map { CBMutableCharacteristic(type: $0, properties: [.read, .notify], value: nil, permissions: .readable) } service.characteristics = characteristics let serialQueue = DispatchQueue(label: "io.swifting.bluetooth.queue", attributes: []) let manager = CBPeripheralManager(delegate: nil, queue: serialQueue) self.init(name: name, manager: manager, services: [service]) } var myBluetoothService: CBMutableService? { return services.filter { $0.uuid == LeapMotionGestureService.uuid }.last } } extension LeapMotionGesturePeripheral: CBPeripheralManagerDelegate { public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { let state = peripheral.state guard state == .poweredOn, !servicesAdded else { return } services.forEach { manager.add($0) } servicesAdded = true } public func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { guard error == nil else { return } print("Advertising started") } public func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) { print("\nSubscribed \(central) to change notification of \(characteristic) ") var centrals = subscribers[characteristic.uuid] ?? [] centrals.append(central) subscribers[characteristic.uuid] = centrals } public func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) { print("\nSubscribed \(central) was removed from change notification of \(characteristic)") guard var centrals = subscribers[characteristic.uuid], let index = centrals.index(of: central) else { return } centrals.remove(at: index) subscribers[characteristic.uuid] = centrals } public func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) { var error: CBATTError.Code = CBATTError.insufficientResources if let data = self.value(forCharacteristic: request.characteristic.uuid) { if request.offset > data.count { error = CBATTError.invalidOffset } else { let range: Range<Int> = request.offset..<data.count request.value = data.subdata(in: range) error = CBATTError.success } } print("\n\n READ REQUEST: \n\(request.characteristic.description) \n\(error)\n\n") peripheral.respond(to: request, withResult: error) } }
mit
b934fe895c9f8b9e1024a69b50801ca1
38.174242
143
0.649971
5.109684
false
false
false
false
MrAlek/Swift-NSFetchedResultsController-Trickery
CoreDataTrickerySwift/FetchControllerDelegate.swift
1
3129
// // FetchControllerDelegate.swift // CoreDataTrickerySwift // // Created by Alek Astrom on 2014-08-04. // Copyright (c) 2014 Apps and Wonders. All rights reserved. // import CoreData import UIKit open class FetchControllerDelegate: NSObject, NSFetchedResultsControllerDelegate { fileprivate var sectionsBeingAdded: [Int] = [] fileprivate var sectionsBeingRemoved: [Int] = [] fileprivate unowned let tableView: UITableView open var onUpdate: ((_ cell: UITableViewCell, _ object: AnyObject) -> Void)? open var ignoreNextUpdates: Bool = false init(tableView: UITableView) { self.tableView = tableView } open func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { if ignoreNextUpdates { return } sectionsBeingAdded = [] sectionsBeingRemoved = [] tableView.beginUpdates() } open func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { if ignoreNextUpdates { return } switch type { case .insert: sectionsBeingAdded.append(sectionIndex) tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade) case .delete: sectionsBeingRemoved.append(sectionIndex) self.tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade) default: return } } open func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { if ignoreNextUpdates { return } switch type { case .insert: tableView.insertRows(at: [newIndexPath!], with: .automatic) case .delete: tableView.deleteRows(at: [indexPath!], with: .automatic) case .update: if let indexPath = indexPath, let cell = tableView.cellForRow(at: indexPath) { onUpdate?(cell, anObject as AnyObject) } case .move: // Stupid and ugly, rdar://17684030 if !sectionsBeingAdded.contains(newIndexPath!.section) && !sectionsBeingRemoved.contains(indexPath!.section) { tableView.moveRow(at: indexPath!, to: newIndexPath!) onUpdate?(tableView.cellForRow(at: indexPath!)!, anObject as AnyObject) } else { tableView.deleteRows(at: [indexPath!], with: .fade) tableView.insertRows(at: [newIndexPath!], with: .fade) } @unknown default: break } } open func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { if !ignoreNextUpdates { tableView.endUpdates() } ignoreNextUpdates = false } }
mit
4c021e63948c20ea24875c963fa57e47
34.556818
215
0.630872
5.538053
false
false
false
false
taikhoanthunghiemcuatoi/mac
swift2/CollectionViewDemo1/CollectionViewDemo1/FlickrSearcher.swift
1
5920
// // FlickrSearcher.swift // flickrSearch // // Created by Richard Turton on 31/07/2014. // Modified by John Difool on 10/01/2015. // Copyright (c) 2014 Razeware. All rights reserved. // import Foundation import UIKit let apiKey = "255702f37957715afc964fc416b9791d" struct FlickrSearchResults { let searchTerm : String let searchResults : [FlickrPhoto] } class FlickrPhoto : Equatable { var thumbnail : UIImage? var largeImage : UIImage? let photoID : String let farm : Int let server : String let secret : String init (photoID:String,farm:Int, server:String, secret:String) { self.photoID = photoID self.farm = farm self.server = server self.secret = secret } func flickrImageURL(size:String = "m") -> NSURL { return NSURL(string: "https://farm\(farm).staticflickr.com/\(server)/\(photoID)_\(secret)_\(size).jpg")! } func loadLargeImage(completion: (flickrPhoto:FlickrPhoto, error: NSError?) -> Void) { let loadURL = flickrImageURL("b") let loadRequest = NSURLRequest(URL:loadURL) let loadSession = NSURLSession.sharedSession() let task = loadSession.dataTaskWithRequest(loadRequest, completionHandler: {data, response, error in if error != nil { completion(flickrPhoto: self, error: error) return } if data != nil { let returnedImage = UIImage(data: data!) self.largeImage = returnedImage completion(flickrPhoto: self, error: nil) return } completion(flickrPhoto: self, error: nil) }) task.resume() } func sizeToFillWidthOfSize(size:CGSize) -> CGSize { if thumbnail == nil { return size } let imageSize = thumbnail!.size var returnSize = size let aspectRatio = imageSize.width / imageSize.height returnSize.height = returnSize.width / aspectRatio if returnSize.height > size.height { returnSize.height = size.height returnSize.width = size.height * aspectRatio } return returnSize } } func == (lhs: FlickrPhoto, rhs: FlickrPhoto) -> Bool { return lhs.photoID == rhs.photoID } class Flickr { func searchFlickrForTerm(searchTerm: String, completion : (results: FlickrSearchResults?, error : NSError?) -> Void) { let searchURL = flickrSearchURLForSearchTerm(searchTerm) let searchRequest = NSURLRequest(URL: searchURL) let searchSession = NSURLSession.sharedSession() let task = searchSession.dataTaskWithRequest(searchRequest, completionHandler: {data, response, error in if error != nil { completion(results: nil,error: error) return } do { let resultsDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! NSDictionary switch (resultsDictionary["stat"] as! String) { case "ok": print("Results processed OK") case "fail": let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:resultsDictionary["message"]!]) completion(results: nil, error: APIError) return default: let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Uknown API response"]) completion(results: nil, error: APIError) return } let photosContainer = resultsDictionary["photos"] as! NSDictionary let photosReceived = photosContainer["photo"] as! [NSDictionary] let flickrPhotos : [FlickrPhoto] = photosReceived.map { photoDictionary in let photoID = photoDictionary["id"] as? String ?? "" let farm = photoDictionary["farm"] as? Int ?? 0 let server = photoDictionary["server"] as? String ?? "" let secret = photoDictionary["secret"] as? String ?? "" let flickrPhoto = FlickrPhoto(photoID: photoID, farm: farm, server: server, secret: secret) let imageData = NSData(contentsOfURL: flickrPhoto.flickrImageURL()) flickrPhoto.thumbnail = UIImage(data: imageData!) return flickrPhoto } dispatch_async(dispatch_get_main_queue(), { completion(results:FlickrSearchResults(searchTerm: searchTerm, searchResults: flickrPhotos), error: nil) }) } catch let JSONError as NSError { completion(results: nil, error: JSONError) return } }) task.resume() } private func flickrSearchURLForSearchTerm(searchTerm:String) -> NSURL { let escapedTerm = searchTerm.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! let URLString = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(apiKey)&text=\(escapedTerm)&per_page=20&format=json&nojsoncallback=1" print("escapedTeam: \(escapedTerm)"); print("URLString: \(URLString)"); return NSURL(string: URLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)! } }
apache-2.0
83213aa4851222071e26b27df8b2731a
35.325153
170
0.564865
5.416285
false
false
false
false
maximedegreve/TinyFaces
Sources/App/Tools/SendInBlue/SendInBlue.swift
1
665
import Vapor final class SendInBlue { let apiUrl = URI(string: "https://api.sendinblue.com/v3/smtp/email") func sendEmail(email: SendInBlueEmail, client: Client) -> EventLoopFuture<Bool> { let sendInBlueKey = Environment.sendInBlueKey let request = client.post(self.apiUrl) { req in req.headers = [ "Content-type": "application/json", "api-key": sendInBlueKey ] try req.content.encode(email) } return request.flatMap { (response) -> EventLoopFuture<Bool> in return request.eventLoop.future(response.status.code == 201) } } }
mit
2f08d456faf873fbd1cc760c4aaf65eb
25.6
85
0.596992
4.006024
false
false
false
false
lllyyy/LY
U17-master/U17/U17/Procedure/Home/View/UComicCHead.swift
1
2074
// // UComicCHead.swift // U17 // // Created by charles on 2017/11/7. // Copyright © 2017年 None. All rights reserved. // import UIKit typealias UComicCHeadMoreActionClosure = ()->Void protocol UComicCHeadDelegate: class { func comicCHead(_ comicCHead: UComicCHead, moreAction button: UIButton) } class UComicCHead: UBaseCollectionReusableView { weak var delegate: UComicCHeadDelegate? private var moreActionClosure: UComicCHeadMoreActionClosure? lazy var iconView: UIImageView = { return UIImageView() }() lazy var titleLabel: UILabel = { let tl = UILabel() tl.font = UIFont.systemFont(ofSize: 14) tl.textColor = .black return tl }() lazy var moreButton: UIButton = { let mn = UIButton(type: .system) mn.setTitle("•••", for: .normal) mn.setTitleColor(UIColor.lightGray, for: .normal) mn.titleLabel?.font = UIFont.systemFont(ofSize: 12) mn.addTarget(self, action: #selector(moreAction), for: .touchUpInside) return mn }() @objc func moreAction(button: UIButton) { delegate?.comicCHead(self, moreAction: button) guard let closure = moreActionClosure else { return } closure() } func moreActionClosure(_ closure: UComicCHeadMoreActionClosure?) { moreActionClosure = closure } override func configUI() { addSubview(iconView) iconView.snp.makeConstraints { $0.left.equalToSuperview().offset(5) $0.centerY.equalToSuperview() $0.width.height.equalTo(40) } addSubview(titleLabel) titleLabel.snp.makeConstraints { $0.left.equalTo(iconView.snp.right).offset(5) $0.centerY.height.equalTo(iconView) $0.width.equalTo(200) } addSubview(moreButton) moreButton.snp.makeConstraints { $0.top.right.bottom.equalToSuperview() $0.width.equalTo(40) } } }
mit
32b2a86625ab1a48f6798d1bd4a53c05
26.171053
78
0.607748
4.35654
false
false
false
false
ryanipete/AmericanChronicle
AmericanChronicle/Code/Modules/Search/SearchInteractor.swift
1
2124
// MARK: - // MARK: SearchInteractorInterface protocol SearchInteractorInterface: AnyObject { var delegate: SearchInteractorDelegate? { get set } func fetchNextPageOfResults(_ parameters: SearchParameters) func cancelLastSearch() } // MARK: - // MARK: SearchInteractorDelegate protocol SearchInteractorDelegate: AnyObject { func searchDidFinishWithResult(_ result: Result<SearchResults, SearchError>) } // MARK: - // MARK: SearchInteractor class final class SearchInteractor: SearchInteractorInterface { // MARK: Properties weak var delegate: SearchInteractorDelegate? private let searchFactory: DelayedSearchFactoryInterface private var activeSearch: DelayedSearchInterface? // MARK: Init methods init(searchFactory: DelayedSearchFactoryInterface = DelayedSearchFactory()) { self.searchFactory = searchFactory } // MARK: SearchInteractorInterface methods func fetchNextPageOfResults(_ parameters: SearchParameters) { if parameters == activeSearch?.parameters { if isSearchInProgress() { // There is already a search in progress for these parameters. let msg = "Tried to start a search that is already ongoing. Taking no action.".localized() delegate?.searchDidFinishWithResult(.failure(.duplicateRequest(msg))) return } } // Calling cancel() on delayedSearch can sometimes trigger the completion // synchronously, and the delegate might then call isSearchInProgress to see if // it can hide the progress indicator. Wait to start this chain of events until // the new delayedSearch has been created. let oldActiveSearch = activeSearch activeSearch = searchFactory.fetchMoreResults(parameters) { [weak self] result in self?.delegate?.searchDidFinishWithResult(result) } oldActiveSearch?.cancel() } func isSearchInProgress() -> Bool { activeSearch?.isSearchInProgress() ?? false } func cancelLastSearch() { activeSearch?.cancel() } }
mit
48bb881dc63706b4ba8718dfb8628755
31.181818
106
0.69209
5.244444
false
false
false
false
youngsoft/TangramKit
TangramKitDemo/FlowLayoutDemo/FLLTest8ViewController.swift
1
9919
// // FLLTest8ViewController.swift // TangramKit // // Created by apple on 16/7/18. // Copyright © 2016年 youngsoft. All rights reserved. // import UIKit /** *8.FlowLayout - Flex space */ class FLLTest8ViewController: UIViewController { var vertLayout:TGFlowLayout! = nil var horzLayout:TGFlowLayout! = nil var vertLayout2:TGFlowLayout! = nil var horzLayout2:TGFlowLayout! = nil override func loadView() { /* 这个例子主要用于展示流式布局的间距的可伸缩性。当我们布局视图中的子视图的宽度或者高度为固定值,但是其中的间距又希望是可以伸缩的,那么就可以借助流式布局提供的方法 tg_setSubviews(size:CGFloat, minSpace:CGFloat, maxSpace:CGFloat = CGFloat.greatestFiniteMagnitude, centered:Bool = false, inSizeClass type:TGSizeClassType = TGSizeClassType.default) 来设置子视图的尺寸,以及最小和最大的间距值。并且当布局视图中子视图的间距小于最小值时会自动调整子视图的尺寸来满足这个最小的间距。 对于垂直流式布局来说,这个方法只用于设置子视图的宽度和水平间距。 对于水平流式布局来说,这个方法只用于设置子视图的高度和垂直间距。 你可以在这个界面中尝试一下屏幕的旋转,看看布局为了支持横屏和竖屏而进行的布局调整,以便达到最完美的布局效果。 */ self.edgesForExtendedLayout = UIRectEdge(rawValue:0) //设置视图控制器中的视图尺寸不延伸到导航条或者工具条下面。您可以注释这句代码看看效果。 //这里的根视图是一个每列只有一个子视图的垂直流式布局,效果就相当于垂直线性布局了。 let rootLayout = TGFlowLayout(.vert, arrangedCount: 1) rootLayout.tg_gravity = .fill //这里将tg_gravity设置为.fill表明子视图的宽度和高度都将平分这个流式布局,可见一个简单的属性设置就可以很容易的实现子视图的尺寸的设置,而不需要编写太复杂的约束。 rootLayout.tg_space = 10 rootLayout.backgroundColor = .white self.view = rootLayout //数量约束流式布局 let vertLayout = TGFlowLayout(.vert, arrangedCount: 4) vertLayout.tg_padding = UIEdgeInsets.init(top: 5, left: 0, bottom: 5, right: 0) vertLayout.backgroundColor = CFTool.color(5) vertLayout.tg_vspace = 20 vertLayout.tg_gravity = TGGravity.vert.fill //因为上面tg_setSubviews设置了固定宽度,这个属性设置子视图的高度是填充满子布局视图,因此系统内部会自动设置每个子视图的高度,如果你不设置这个属性,那么你就需要在下面分别为每个子视图设置高度。 rootLayout.addSubview(vertLayout) self.vertLayout = vertLayout for i in 0 ..< 14 { let label = UILabel() //label.tg_height.equal(60) 因为子视图的宽度在布局视图的tg_setSubviews中设置了,你也可以在这里单独为每个子视图设置高度,当然如果你的父布局视图使用了tg_gravity来设置填充属性的话,那么子视图是不需要单独设置高度尺寸的。 label.text = "\(i)" //[NSString stringWithFormat:@"%d", i]; label.textAlignment = .center label.backgroundColor = CFTool.color(2) vertLayout.addSubview(label) } let horzLayout = TGFlowLayout(.horz, arrangedCount: 4) horzLayout.tg_padding = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5) horzLayout.backgroundColor = CFTool.color(6) horzLayout.tg_hspace = 20 horzLayout.tg_gravity = TGGravity.horz.fill //因为上面tg_setSubviews设置了固定高度,这个属性设置子视图的宽度是填充满子布局视图,因此系统内部会自动设置每个子视图的宽度,如果你不设置这个属性,那么你就需要在下面分别为每个子视图设置宽度。 rootLayout.addSubview(horzLayout) self.horzLayout = horzLayout for i in 0 ..< 14 { let label = UILabel() //label.tg_height.equal(60) 因为子视图的高度在布局视图的setSubviewsSize:minSpace:maxSpace:中设置了,你也可以在这里单独为每个子视图设置宽度,当然如果你的父布局视图使用了gravity来设置填充属性的话,那么子视图是不需要单独设置宽度尺寸的。 label.text = "\(i)" //[NSString stringWithFormat:@"%d", i]; label.textAlignment = .center label.backgroundColor = CFTool.color(3) horzLayout.addSubview(label) } //内容约束流式布局 let vertLayout2 = TGFlowLayout(.vert, arrangedCount: 0) vertLayout2.tg_padding = UIEdgeInsets.init(top: 5, left: 0, bottom: 5, right: 0) vertLayout2.backgroundColor = CFTool.color(5) vertLayout2.tg_vspace = 20 vertLayout2.tg_gravity = TGGravity.vert.fill //因为上面tg_setSubviews设置了固定宽度,这个属性设置子视图的高度是填充满子布局视图,因此系统内部会自动设置每个子视图的高度,如果你不设置这个属性,那么你就需要在下面分别为每个子视图设置高度。 rootLayout.addSubview(vertLayout2) self.vertLayout2 = vertLayout2 for i in 0 ..< 14 { let label = UILabel() //label.tg_height.equal(60) 因为子视图的宽度在布局视图的tg_setSubviews中设置了,你也可以在这里单独为每个子视图设置高度,当然如果你的父布局视图使用了tg_gravity来设置填充属性的话,那么子视图是不需要单独设置高度尺寸的。 label.text = "\(i)" //[NSString stringWithFormat:@"%d", i]; label.textAlignment = .center label.backgroundColor = CFTool.color(2) vertLayout2.addSubview(label) } let horzLayout2 = TGFlowLayout(.horz, arrangedCount: 0) horzLayout2.tg_padding = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5) horzLayout2.backgroundColor = CFTool.color(6) horzLayout2.tg_hspace = 20 horzLayout2.tg_gravity = TGGravity.horz.fill //因为上面tg_setSubviews设置了固定高度,这个属性设置子视图的宽度是填充满子布局视图,因此系统内部会自动设置每个子视图的宽度,如果你不设置这个属性,那么你就需要在下面分别为每个子视图设置宽度。 rootLayout.addSubview(horzLayout2) self.horzLayout2 = horzLayout2 for i in 0 ..< 14 { let label = UILabel() //label.tg_height.equal(60) 因为子视图的高度在布局视图的setSubviewsSize:minSpace:maxSpace:中设置了,你也可以在这里单独为每个子视图设置宽度,当然如果你的父布局视图使用了gravity来设置填充属性的话,那么子视图是不需要单独设置宽度尺寸的。 label.text = "\(i)" //[NSString stringWithFormat:@"%d", i]; label.textAlignment = .center label.backgroundColor = CFTool.color(3) horzLayout2.addSubview(label) } //这个垂直流式布局中,每个子视图之间的水平间距是浮动的,并且子视图的宽度是固定为60。间距最小为10,最大不限制。 vertLayout.tg_setSubviews(size:60, minSpace:10) //这个水平流式布局中,每个子视图之间的垂直间距是浮动的,并且子视图的高度是固定为60。间距最小为10,最大不限制。 horzLayout.tg_setSubviews(size:60, minSpace:10) //这个垂直流式布局中,每个子视图之间的水平间距是浮动的,并且子视图的宽度是固定为60。间距最小为10,最大不限制。 vertLayout2.tg_setSubviews(size:60, minSpace:10) //这个水平流式布局中,每个子视图之间的垂直间距是浮动的,并且子视图的高度是固定为60。间距最小为10,最大不限制。 horzLayout2.tg_setSubviews(size:60, minSpace:10) } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "center off", style: UIBarButtonItem.Style.plain, target: self, action: #selector(handleCenterOnOff(sender:))) } @objc func handleCenterOnOff(sender:UIBarButtonItem) { if sender.title == "center off" { sender.title = "center on" self.vertLayout.tg_setSubviews(size: 60, minSpace: 10, centered:true) self.horzLayout.tg_setSubviews(size: 60, minSpace: 10, centered:true) self.vertLayout2.tg_setSubviews(size: 60, minSpace: 10, centered:true) self.horzLayout2.tg_setSubviews(size: 60, minSpace: 10, centered:true) } else { sender.title = "center off" self.vertLayout.tg_setSubviews(size: 60, minSpace: 10, centered:false) self.horzLayout.tg_setSubviews(size: 60, minSpace: 10, centered:false) self.vertLayout2.tg_setSubviews(size: 60, minSpace: 10, centered:false) self.horzLayout2.tg_setSubviews(size: 60, minSpace: 10, centered:false) } self.vertLayout.tg_layoutAnimationWithDuration(0.3) self.horzLayout.tg_layoutAnimationWithDuration(0.3) self.vertLayout2.tg_layoutAnimationWithDuration(0.3) self.horzLayout2.tg_layoutAnimationWithDuration(0.3) } }
mit
eac63d73f83380f68b83b22f293de755
42.112426
190
0.659758
3.304308
false
false
false
false
artursDerkintis/YouTube
YouTube/VideoController.swift
1
19089
// // VideoController.swift // YouTube // // Created by Arturs Derkintis on 1/4/16. // Copyright © 2016 Starfly. All rights reserved. // import UIKit import NVActivityIndicatorView import JavaScriptCore import XCDYouTubeKit import AVKit import SwiftyUserDefaults class VideoController: UIViewController{ var contentView : VideoView! var playerView : PlayerView! var controlView : ControlView! var pictureInPictureController: AVPictureInPictureController! var timer : NSTimer? var canceled = false var timeObserverToken: AnyObject? var activityInd : NVActivityIndicatorView! lazy var player = AVPlayer() var videoQualityHD : Bool = Defaults.boolForKey("quality") { didSet{ Defaults.setBool(videoQualityHD, forKey: "quality") self.loadVideo() } } var possibleQualities = Dictionary<UInt, NSURL>() var delegate : VideoDelegate? var playerItem: AVPlayerItem? = nil { didSet { /* If needed, configure player item here before associating it with a player (example: adding outputs, setting text style rules, selecting media options) */ player.replaceCurrentItemWithPlayerItem(playerItem) if playerItem == nil { cleanUpPlayerPeriodicTimeObserver() } else { setupPlayerPeriodicTimeObserver() } } } var videoDetails : VideoDetails? var progressBar : ProgressBar! var bottomPro : BottomProgress! override func viewDidLoad() { super.viewDidLoad() self.view = VideoView() view.backgroundColor = .clearColor() contentView = VideoView(frame: .zero) contentView.backgroundColor = UIColor.whiteColor() contentView.layer.shadowOffset = CGSize(width: 0.5, height: 13) contentView.layer.shadowOpacity = 0.17 contentView.layer.shadowRadius = 11 contentView.layer.shadowColor = UIColor.blackColor().CGColor contentView.layer.shouldRasterize = true contentView.layer.rasterizationScale = UIScreen.mainScreen().scale view.addSubview(contentView) contentView.snp_makeConstraints { (make) -> Void in make.top.left.equalTo(38) make.right.equalTo(-38) make.height.equalTo(self.view.snp_height).offset(-38) } playerView = PlayerView() playerView.backgroundColor = UIColor.blackColor() contentView.addSubview(playerView) playerView.snp_makeConstraints { (make) -> Void in make.top.left.equalTo(15) make.bottom.right.equalTo(-15) } activityInd = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), type: .BallSpinFadeLoader, color: .whiteColor(), size: CGSize(width: 30, height: 30)) contentView.addSubview(activityInd) activityInd.snp_makeConstraints { (make) -> Void in make.centerX.equalTo(contentView.snp_centerX) make.centerY.equalTo(contentView.snp_centerY) } activityInd.hidesWhenStopped = true bottomPro = BottomProgress(frame: .zero) contentView.addSubview(bottomPro) bottomPro.snp_makeConstraints { (make) -> Void in make.left.equalTo(15) make.right.bottom.equalTo(-15) make.height.equalTo(2) } controlView = ControlView(frame: .zero) contentView.addSubview(controlView) controlView.snp_makeConstraints { (make) -> Void in make.top.right.bottom.left.equalTo(0) } controlView.setButtonActions(self) controlView.qualityButton.selected = videoQualityHD progressBar = ProgressBar(frame: .zero) progressBar.slider.addTarget(self, action: "seek:", forControlEvents: .ValueChanged) controlView.addSubview(progressBar) progressBar.snp_makeConstraints { (make) -> Void in make.left.equalTo(15) make.bottom.right.equalTo(-15) make.height.equalTo(50) } let tap = UITapGestureRecognizer(target: self, action: "tap:") contentView.addGestureRecognizer(tap) addObserver(self, forKeyPath: "player.currentItem.duration", options: .New, context: nil) addObserver(self, forKeyPath: "player.rate", options: [.New, .Initial], context: nil) addObserver(self, forKeyPath: "player.currentItem.status", options: [.New, .Initial], context: nil) // Do any additional setup after loading the view. } var currentTime: Double { get { return CMTimeGetSeconds(player.currentTime()) } set { let newTime = CMTimeMakeWithSeconds(newValue, 1) player.seekToTime(newTime, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero) } } func seek(slider : Slider){ timer?.invalidate() currentTime = slider.decProgress } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "player.currentItem.duration"{ let newDuration: CMTime if let newDurationAsValue = change?[NSKeyValueChangeNewKey] as? NSValue { newDuration = newDurationAsValue.CMTimeValue } else { newDuration = kCMTimeZero } let hasValidDuration = newDuration.isNumeric && newDuration.value != 0 let newDurationSeconds = hasValidDuration ? CMTimeGetSeconds(newDuration) : 0.0 progressBar.slider.maxValue = Double(newDurationSeconds) bottomPro.maxValue = Double(newDurationSeconds) progressBar.duration.text = hasValidDuration ? secondsToHoursMinutesSeconds(newDurationSeconds) : "--:--" let currentTime = CMTimeGetSeconds(player.currentTime()) progressBar.slider.value = hasValidDuration ? Double(currentTime / newDurationSeconds) : 0.0 bottomPro.value = hasValidDuration ? Double(currentTime / newDurationSeconds) : 0.0 progressBar.curentTime.text = hasValidDuration ? secondsToHoursMinutesSeconds(currentTime) : "--:--" controlView.hidden = !hasValidDuration progressBar.enabled = hasValidDuration }else if keyPath == "player.rate" { // Update playPauseButton type. let newRate = (change?[NSKeyValueChangeNewKey] as! NSNumber).doubleValue controlView.playPauseButton.tag = newRate == 0.0 ? 0 : 1 controlView.playPauseButton.selected = newRate == 0.0 ? false : true if let duration = player.currentItem?.duration{ if newRate == 0.0 && player.currentTime() == duration{ controlView.playPauseButton.setImage(UIImage(named: "replay"), forState: .Normal) controlView.playPauseButton.tag = 909 } } }else if keyPath == "player.currentItem.status" { let newStatus: AVPlayerItemStatus if let newStatusAsNumber = change?[NSKeyValueChangeNewKey] as? NSNumber { newStatus = AVPlayerItemStatus(rawValue: newStatusAsNumber.integerValue)! } else { newStatus = .Unknown } if newStatus == .Failed { } else if newStatus == .ReadyToPlay { //player.play() activityInd.stopAnimation() showStuff() if let asset = player.currentItem?.asset { if pictureInPictureController == nil { setupPictureInPicturePlayback() } } } } } private func setupPlayerPeriodicTimeObserver() { guard timeObserverToken == nil else { return } let time = CMTimeMake(1, 10) timeObserverToken = player.addPeriodicTimeObserverForInterval(time, queue:dispatch_get_main_queue()) { [weak self] time in self?.bottomPro.value = Double(CMTimeGetSeconds(time)) self?.progressBar.slider.value = Double(CMTimeGetSeconds(time)) self?.progressBar.curentTime.text = secondsToHoursMinutesSeconds(CMTimeGetSeconds(time)) } } private func cleanUpPlayerPeriodicTimeObserver() { if let timeObserverToken = timeObserverToken { player.removeTimeObserver(timeObserverToken) self.timeObserverToken = nil } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) playerView.playerLayer.player = player //playVideo("JLf9q36UsBk") } func tap(sender : UITapGestureRecognizer){ showStuff() } func changeQuality(sender: UIButton){ timer?.invalidate() timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "hideStuff", userInfo: nil, repeats: false) sender.selected = !sender.selected videoQualityHD = sender.selected } func full(sender: UIButton){ timer?.invalidate() timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "hideStuff", userInfo: nil, repeats: false) if let mainViewController = UIApplication.sharedApplication().delegate?.window??.rootViewController{ if sender.tag == 0{ sender.selected = true sender.tag = 1 mainViewController.view.addSubview(self.contentView) let rect = self.view.convertRect(self.contentView.frame, toView: mainViewController.view) self.contentView.frame = rect print("\(rect), \(self.contentView.frame)") self.contentView.snp_updateConstraints(closure: { (make) -> Void in make.top.left.right.bottom.equalTo(0) }) self.playerView.snp_updateConstraints(closure: { (make) -> Void in make.top.left.right.bottom.equalTo(0) }) UIView.animateWithDuration(0.5, animations: { () -> Void in mainViewController.view.layoutIfNeeded() }) }else if sender.tag == 1{ sender.selected = false sender.tag = 0 self.view.superview?.bringSubviewToFront(self.view) self.view.addSubview(self.contentView) self.contentView.snp_removeConstraints() self.contentView.snp_makeConstraints(closure: { (make) -> Void in make.left.equalTo(-340) make.top.equalTo(0) make.right.equalTo(0) make.height.equalTo(self.contentView.frame.height) }) self.view.layoutIfNeeded() self.contentView.snp_updateConstraints(closure: { (make) -> Void in make.top.left.equalTo(38) make.right.equalTo(-38) make.height.equalTo(self.view.snp_height).offset(-38) }) self.playerView.snp_updateConstraints { (make) -> Void in make.top.left.equalTo(15) make.bottom.right.equalTo(-15) } UIView.animateWithDuration(0.5, animations: { () -> Void in self.view.layoutIfNeeded() }, completion: { (fin) -> Void in if let set = self.view.superview?.viewWithTag(90){ self.view.superview?.bringSubviewToFront(set) } }) }} } func pip(){ if pictureInPictureController != nil{ if pictureInPictureController.pictureInPictureActive { pictureInPictureController.stopPictureInPicture() showStuff() } else { hideStuff() pictureInPictureController.startPictureInPicture() } } } var operation : XCDYouTubeOperation? var qualities = [XCDYouTubeVideoQuality.Small240.rawValue, XCDYouTubeVideoQuality.Medium360.rawValue, XCDYouTubeVideoQuality.HD720.rawValue] func loadVideoWith(id : String){ activityInd.startAnimation() hideStuff() operation?.cancel() operation = XCDYouTubeClient.defaultClient().getVideoWithIdentifier(id, completionHandler: { (video, error) -> Void in if let video = video{ self.possibleQualities.removeAll() for q in self.qualities{ let number = NSNumber(unsignedInteger: q) if let streamURL = video.streamURLs[number]{ self.possibleQualities[q] = streamURL } } self.loadVideo() } }) } func favorite(){ if let det = self.videoDetails{ DataHelper.sharedInstance.saveFavorite(det) delay(1.0) { () -> () in DataHelper.sharedInstance.favorited(det.id!) { (enabled) -> Void in self.controlView.bookmarkButton.enabled = !enabled } } } } private func loadVideo(){ hideStuff() activityInd.startAnimation() let currentTimeCache = currentTime self.controlView.qualityButton.enabled = true if possibleQualities[XCDYouTubeVideoQuality.Small240.rawValue] != nil && possibleQualities[XCDYouTubeVideoQuality.HD720.rawValue] == nil && possibleQualities[XCDYouTubeVideoQuality.Medium360.rawValue] == nil{ self.controlView.qualityButton.enabled = false self.playerItem = AVPlayerItem(URL: possibleQualities[XCDYouTubeVideoQuality.Small240.rawValue]!) }else if possibleQualities[XCDYouTubeVideoQuality.Small240.rawValue] != nil && possibleQualities[XCDYouTubeVideoQuality.HD720.rawValue] == nil && possibleQualities[XCDYouTubeVideoQuality.Medium360.rawValue] != nil{ if videoQualityHD{ self.playerItem = AVPlayerItem(URL: possibleQualities[XCDYouTubeVideoQuality.Medium360.rawValue]!) }else{ self.playerItem = AVPlayerItem(URL: possibleQualities[XCDYouTubeVideoQuality.Small240.rawValue]!) } }else if possibleQualities[XCDYouTubeVideoQuality.Small240.rawValue] != nil && possibleQualities[XCDYouTubeVideoQuality.HD720.rawValue] != nil && possibleQualities[XCDYouTubeVideoQuality.Medium360.rawValue] != nil{ if videoQualityHD{ self.playerItem = AVPlayerItem(URL: possibleQualities[XCDYouTubeVideoQuality.HD720.rawValue]!) }else{ self.playerItem = AVPlayerItem(URL: possibleQualities[XCDYouTubeVideoQuality.Medium360.rawValue]!) } } currentTime = currentTimeCache } private func setupPictureInPicturePlayback() { if AVPictureInPictureController.isPictureInPictureSupported() { pictureInPictureController = AVPictureInPictureController(playerLayer: playerView.playerLayer) }else { controlView.pipButton.enabled = false } } func showStuff(){ UIView.animateWithDuration(0.3, animations: { () -> Void in self.controlView.alpha = 1.0 }) { (fin) -> Void in } timer?.invalidate() timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "hideStuff", userInfo: nil, repeats: false) } func hideStuff(){ UIView.animateWithDuration(0.3, delay: 0.0, options: [UIViewAnimationOptions.BeginFromCurrentState], animations: { () -> Void in self.controlView.alpha = self.player.rate == 0.0 ? 1.0 : 0.0 }, completion: nil) } func closeVideo(){ player.pause() player.replaceCurrentItemWithPlayerItem(nil) currentTime = 0.0 delegate?.hide() delegate?.removeDescription() } func playVideo(videoDetails : VideoDetails){ controlView.tag = 0 player.pause() player.replaceCurrentItemWithPlayerItem(nil) currentTime = 0.0 controlView.playPauseButton.setImage(UIImage(named: "play"), forState: .Normal) loadVideoWith(videoDetails.id!) self.videoDetails = videoDetails controlView.playPauseButton.selected = false controlView.playPauseButton.tag = 0 controlView.alpha = 0.0 delegate?.show() DataHelper.sharedInstance.favorited(videoDetails.id!) { (enabled) -> Void in self.controlView.bookmarkButton.enabled = !enabled } } func play(sender : UIButton){ timer?.invalidate() if sender.tag == 0{ sender.tag = 1 timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "hideStuff", userInfo: nil, repeats: false) sender.selected = true playerView.player?.play() }else if sender.tag == 1{ sender.selected = false playerView.player?.pause() sender.tag = 0 }else if sender.tag == 909{ sender.tag = 1 timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "hideStuff", userInfo: nil, repeats: false) let newTime = CMTimeMakeWithSeconds(0.0, 1) sender.setImage(UIImage(named: "play"), forState: .Normal) playerView.player?.seekToTime(newTime) playerView.player?.play() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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
53c1e1657b23e5bc7de33898d9dde378
37.796748
223
0.591838
5.251169
false
false
false
false
BalestraPatrick/Tweetometer
Carthage/Checkouts/ActiveLabel.swift/ActiveLabelDemo/ViewController.swift
2
3629
// // ViewController.swift // ActiveLabelDemo // // Created by Johannes Schickling on 9/4/15. // Copyright © 2015 Optonaut. All rights reserved. // import UIKit import ActiveLabel class ViewController: UIViewController { let label = ActiveLabel() override func viewDidLoad() { super.viewDidLoad() let customType = ActiveType.custom(pattern: "\\sare\\b") //Looks for "are" let customType2 = ActiveType.custom(pattern: "\\sit\\b") //Looks for "it" let customType3 = ActiveType.custom(pattern: "\\ssupports\\b") //Looks for "supports" label.enabledTypes.append(customType) label.enabledTypes.append(customType2) label.enabledTypes.append(customType3) label.urlMaximumLength = 31 label.customize { label in label.text = "This is a post with #multiple #hashtags and a @userhandle. Links are also supported like" + " this one: http://optonaut.co. Now it also supports custom patterns -> are\n\n" + "Let's trim a long link: \nhttps://twitter.com/twicket_app/status/649678392372121601" label.numberOfLines = 0 label.lineSpacing = 4 label.textColor = UIColor(red: 102.0/255, green: 117.0/255, blue: 127.0/255, alpha: 1) label.hashtagColor = UIColor(red: 85.0/255, green: 172.0/255, blue: 238.0/255, alpha: 1) label.mentionColor = UIColor(red: 238.0/255, green: 85.0/255, blue: 96.0/255, alpha: 1) label.URLColor = UIColor(red: 85.0/255, green: 238.0/255, blue: 151.0/255, alpha: 1) label.URLSelectedColor = UIColor(red: 82.0/255, green: 190.0/255, blue: 41.0/255, alpha: 1) label.handleMentionTap { self.alert("Mention", message: $0) } label.handleHashtagTap { self.alert("Hashtag", message: $0) } label.handleURLTap { self.alert("URL", message: $0.absoluteString) } //Custom types label.customColor[customType] = UIColor.purple label.customSelectedColor[customType] = UIColor.green label.customColor[customType2] = UIColor.magenta label.customSelectedColor[customType2] = UIColor.green label.configureLinkAttribute = { (type, attributes, isSelected) in var atts = attributes switch type { case customType3: atts[NSAttributedStringKey.font] = isSelected ? UIFont.boldSystemFont(ofSize: 16) : UIFont.boldSystemFont(ofSize: 14) default: () } return atts } label.handleCustomTap(for: customType) { self.alert("Custom type", message: $0) } label.handleCustomTap(for: customType2) { self.alert("Custom type", message: $0) } label.handleCustomTap(for: customType3) { self.alert("Custom type", message: $0) } } label.frame = CGRect(x: 20, y: 40, width: view.frame.width - 40, height: 300) view.addSubview(label) // 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. } func alert(_ title: String, message: String) { let vc = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) vc.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil)) present(vc, animated: true, completion: nil) } }
mit
b7e85b2e90392a8651d83fd9dd30f715
40.227273
137
0.614939
4.099435
false
false
false
false
thilong/SwiftReeder
SwiftReeder/UI/DefaultFeedListViewController.swift
2
3261
// // DefaultFeedListViewController.swift // SwiftReeder // // Created by Thilong on 14/6/4. // Copyright (c) 2014年 thilong. All rights reserved. // import UIKit class DefaultFeedListViewController: UIViewController , UITableViewDataSource,UITableViewDelegate { var tableView : UITableView? ; var defaultData : Array<Feed> = [Feed(name:"网易新闻",url:"http://news.163.com/special/00011K6L/rss_newstop.xml"), Feed(name:"网易科技",url:"http://tech.163.com/special/000944OI/headlines.xml"), Feed(name:"网易NBA",url:"http://sports.163.com/special/00051K7F/rss_sportslq.xml"), Feed(name:"网易英超",url:"http://sports.163.com/special/00051K7F/rss_sportsyc.xml"), Feed(name:"网易娱乐",url:"http://ent.163.com/special/00031K7Q/rss_toutiao.xml"), Feed(name:"网易电影",url:"http://ent.163.com/special/00031K7Q/rss_entmovie.xml"), Feed(name:"网易互联网",url:"http://tech.163.com/special/000944OI/hulianwang.xml"), Feed(name:"网易IT界",url:"http://tech.163.com/special/000944OI/kejiyejie.xml"), Feed(name:"网易汽车",url:"http://auto.163.com/special/00081K7D/rsstoutiao.xml"), Feed(name:"网易数码",url:"http://tech.163.com/digi/special/00161K7K/rss_digixj.xml"), Feed(name:"网易笔记本",url:"http://tech.163.com/digi/special/00161K7K/rss_diginote.xml"), Feed(name:"网易手机",url:"http://mobile.163.com/special/001144R8/mobile163_copy.xml"), Feed(name:"网易时尚",url:"http://lady.163.com/special/00261R8C/ladyrss1.xml"), Feed(name:"网易星运",url:"http://lady.163.com/special/00261R8C/ladyrss4.xml"), Feed(name:"网易游戏",url:"http://game.163.com/special/003144N4/rss_gametop.xml"), Feed(name:"网易旅游",url:"http://travel.163.com/special/00061K7R/rss_hline.xml")]; override func viewDidLoad(){ self.title = "Feeds"; self.view.backgroundColor = UIColor.whiteColor(); var tableFrame : CGRect = self.view.bounds; self.tableView = UITableView(frame:tableFrame); self.view.addSubview(tableView); tableView!.dataSource = (self as? UITableViewDataSource); tableView!.delegate = self; } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{ return defaultData.count; } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{ let cellReuseId = "cell_DefaultFeedListCell" ; var cell : UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(cellReuseId) as? UITableViewCell; if !cell{ cell = UITableViewCell(style: UITableViewCellStyle.Default,reuseIdentifier: cellReuseId); cell.selectionStyle = UITableViewCellSelectionStyle.None; } cell.textLabel.text = defaultData[indexPath.row].name?; return cell; } func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){ var data = defaultData[indexPath.row]; FeedManager.sharedManager().addFeed(data); self.navigationController.popViewControllerAnimated(true); } }
apache-2.0
3a623c579410b249bb31048c13531473
47.953125
115
0.674433
3.484983
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/00348-llvm-densemapbase-llvm-smalldensemap-std-pair-swift-cantype.swift
1
607
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 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 // RUN: not %target-swift-frontend %s -typecheck func compose<T, AnyObject.B == A: a { struct d: NSManagedObject { let f = a(t: String { d: NSManagedObject { } deinit { } typealias e = c, b in a { struct Q<T>(f: Array<T) { } } } b.c: A.h = nil func b> Int {
apache-2.0
86d30d6b9c09cce9c30a3d1f50a2450c
26.590909
79
0.701812
3.281081
false
false
false
false
rnystrom/GitHawk
Classes/Issues/Referenced/IssueReferencedModel.swift
1
2469
// // IssueReferencedModel.swift // Freetime // // Created by Ryan Nystrom on 7/9/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit import StyledTextKit import DateAgo final class IssueReferencedModel: ListDiffable { enum State: Int { case open case closed case merged } let id: String let owner: String let repo: String let number: Int let pullRequest: Bool let state: State let date: Date let title: String let actor: String let string: StyledTextRenderer init( id: String, owner: String, repo: String, number: Int, pullRequest: Bool, state: State, date: Date, title: String, actor: String, contentSizeCategory: UIContentSizeCategory, width: CGFloat ) { self.id = id self.owner = owner self.repo = repo self.number = number self.pullRequest = pullRequest self.state = state self.date = date self.title = title self.actor = actor let builder = StyledTextBuilder(styledText: StyledText( style: Styles.Text.secondary.with(foreground: Styles.Colors.Gray.medium.color) )) .save() .add(styledText: StyledText(text: actor, style: Styles.Text.secondaryBold.with(attributes: [ MarkdownAttribute.username: actor, .foregroundColor: Styles.Colors.Gray.dark.color ]) )) .restore() .add(text: NSLocalizedString(" referenced ", comment: "")) .save() .add(text: date.agoString(.long), attributes: [MarkdownAttribute.details: DateDetailsFormatter().string(from: date)]) .restore() .add(text: "\n") .save() .add(styledText: StyledText(text: title, style: Styles.Text.secondaryBold)) .restore() .add(text: " #\(number)") self.string = StyledTextRenderer( string: builder.build(), contentSizeCategory: contentSizeCategory, inset: IssueReferencedCell.inset ).warm(width: width) } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return id as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { return true } }
mit
852bc6ef777e53ddb9dc0f74bd89e602
25.537634
129
0.581848
4.718929
false
false
false
false
tehprofessor/SwiftyFORM
Source/Cells/TextFieldCell.swift
1
11348
// MIT license. Copyright (c) 2014 SwiftyFORM. All rights reserved. import UIKit public class CustomTextField: UITextField { public func configure() { backgroundColor = UIColor.whiteColor() autocapitalizationType = .Sentences autocorrectionType = .Default spellCheckingType = .No returnKeyType = .Done clearButtonMode = .WhileEditing } } public enum TextCellState { case NoMessage case TemporaryMessage(message: String) case PersistentMessage(message: String) } public class TextFieldFormItemCellSizes { public let titleLabelFrame: CGRect public let textFieldFrame: CGRect public let errorLabelFrame: CGRect public let cellHeight: CGFloat public init(titleLabelFrame: CGRect, textFieldFrame: CGRect, errorLabelFrame: CGRect, cellHeight: CGFloat) { self.titleLabelFrame = titleLabelFrame self.textFieldFrame = textFieldFrame self.errorLabelFrame = errorLabelFrame self.cellHeight = cellHeight } } public struct TextFieldFormItemCellModel { var title: String = "" var toolbarMode: ToolbarMode = .Simple var placeholder: String = "" var keyboardType: UIKeyboardType = .Default var returnKeyType: UIReturnKeyType = .Default var autocorrectionType: UITextAutocorrectionType = .No var autocapitalizationType: UITextAutocapitalizationType = .None var spellCheckingType: UITextSpellCheckingType = .No var secureTextEntry = false var model: TextFieldFormItem! = nil var valueDidChange: String -> Void = { (value: String) in DLog("value \(value)") } } public class TextFieldFormItemCell: UITableViewCell, UITextFieldDelegate, CellHeightProvider { public let model: TextFieldFormItemCellModel public let titleLabel = UILabel() public let textField = CustomTextField() public let errorLabel = UILabel() public var state: TextCellState = .NoMessage public init(model: TextFieldFormItemCellModel) { self.model = model super.init(style: .Default, reuseIdentifier: nil) self.addGestureRecognizer(tapGestureRecognizer) selectionStyle = .None titleLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) textField.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) errorLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2) errorLabel.textColor = UIColor.redColor() errorLabel.numberOfLines = 0 textField.configure() textField.delegate = self textField.addTarget(self, action: "valueDidChange:", forControlEvents: UIControlEvents.EditingChanged) contentView.addSubview(titleLabel) contentView.addSubview(textField) contentView.addSubview(errorLabel) titleLabel.text = model.title textField.placeholder = model.placeholder textField.autocapitalizationType = model.autocapitalizationType textField.autocorrectionType = model.autocorrectionType textField.keyboardType = model.keyboardType textField.returnKeyType = model.returnKeyType textField.spellCheckingType = model.spellCheckingType textField.secureTextEntry = model.secureTextEntry if self.model.toolbarMode == .Simple { textField.inputAccessoryView = toolbar } updateErrorLabel(model.model.liveValidateValueText()) // titleLabel.backgroundColor = UIColor.blueColor() // textField.backgroundColor = UIColor.greenColor() // errorLabel.backgroundColor = UIColor.yellowColor() clipsToBounds = true } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public lazy var toolbar: SimpleToolbar = { let instance = SimpleToolbar() weak var weakSelf = self instance.jumpToPrevious = { if let cell = weakSelf { cell.gotoPrevious() } } instance.jumpToNext = { if let cell = weakSelf { cell.gotoNext() } } instance.dismissKeyboard = { if let cell = weakSelf { cell.dismissKeyboard() } } return instance }() public func updateToolbarButtons() { if model.toolbarMode == .Simple { toolbar.updateButtonConfiguration(self) } } public func gotoPrevious() { DLog("make previous cell first responder") form_makePreviousCellFirstResponder() } public func gotoNext() { DLog("make next cell first responder") form_makeNextCellFirstResponder() } public func dismissKeyboard() { DLog("dismiss keyboard") resignFirstResponder() } public func handleTap(sender: UITapGestureRecognizer) { textField.becomeFirstResponder() } public lazy var tapGestureRecognizer: UITapGestureRecognizer = { let gr = UITapGestureRecognizer(target: self, action: "handleTap:") return gr }() public enum TitleWidthMode { case Auto case Assign(width: CGFloat) } public var titleWidthMode: TitleWidthMode = .Auto public func compute(cellWidth: CGFloat) -> TextFieldFormItemCellSizes { var titleLabelFrame = CGRectZero var textFieldFrame = CGRectZero var errorLabelFrame = CGRectZero var cellHeight: CGFloat = 0 var area: CGRect = CGRectZero let veryTallCell = CGRectMake(0, 0, cellWidth, CGFloat.max) switch UIDevice.currentDevice().userInterfaceIdiom { case .Pad: area = veryTallCell.insetBy(dx: 48, dy: 0) default: area = veryTallCell.insetBy(dx: 16, dy: 0) } let (topRect, _) = area.divide(44, fromEdge: .MinYEdge) if true { let size = titleLabel.sizeThatFits(area.size) var titleLabelWidth = size.width switch titleWidthMode { case .Auto: break case let .Assign(width): let w = CGFloat(width) if w > titleLabelWidth { titleLabelWidth = w } } var (slice, remainder) = topRect.divide(titleLabelWidth, fromEdge: .MinXEdge) titleLabelFrame = slice (_, remainder) = remainder.divide(10, fromEdge: .MinXEdge) remainder.size.width += 4 textFieldFrame = remainder cellHeight = ceil(textFieldFrame.height) } if true { let size = errorLabel.sizeThatFits(area.size) // DLog("error label size \(size)") if size.height > 0.1 { var r = topRect r.origin.y = topRect.maxY - 6 let (slice, _) = r.divide(size.height, fromEdge: .MinYEdge) errorLabelFrame = slice cellHeight = ceil(errorLabelFrame.maxY + 10) } } return TextFieldFormItemCellSizes(titleLabelFrame: titleLabelFrame, textFieldFrame: textFieldFrame, errorLabelFrame: errorLabelFrame, cellHeight: cellHeight) } public override func layoutSubviews() { super.layoutSubviews() //DLog("layoutSubviews") let sizes: TextFieldFormItemCellSizes = compute(bounds.width) titleLabel.frame = sizes.titleLabelFrame textField.frame = sizes.textFieldFrame errorLabel.frame = sizes.errorLabelFrame } public func valueDidChange(sender: AnyObject?) { //DLog("did change") model.valueDidChange(textField.text ?? "") let result: ValidateResult = model.model.liveValidateValueText() switch result { case .Valid: DLog("valid") case .HardInvalid: DLog("hard invalid") case .SoftInvalid: DLog("soft invalid") } } public func setValueWithoutSync(value: String) { DLog("set value \(value)") textField.text = value validateAndUpdateErrorIfNeeded(value, shouldInstallTimer: false, checkSubmitRule: false) } // Hide the keyboard when the user taps the return key in this UITextField public func textFieldShouldReturn(textField: UITextField) -> Bool { let s = textField.text ?? "" let isTextValid = validateAndUpdateErrorIfNeeded(s, shouldInstallTimer: true, checkSubmitRule: true) if isTextValid { textField.resignFirstResponder() } return false } public func updateErrorLabel(result: ValidateResult) { switch result { case .Valid: errorLabel.text = nil case .HardInvalid(let message): errorLabel.text = message case .SoftInvalid(let message): errorLabel.text = message } } public var lastResult: ValidateResult? public var hideErrorMessageAfterFewSecondsTimer: NSTimer? public func invalidateTimer() { if let timer = hideErrorMessageAfterFewSecondsTimer { timer.invalidate() hideErrorMessageAfterFewSecondsTimer = nil } } public func installTimer() { invalidateTimer() let timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "timerUpdate", userInfo: nil, repeats: false) hideErrorMessageAfterFewSecondsTimer = timer } // Returns true when valid // Returns false when invalid public func validateAndUpdateErrorIfNeeded(text: String, shouldInstallTimer: Bool, checkSubmitRule: Bool) -> Bool { let tableView: UITableView? = form_tableView() let result: ValidateResult = model.model.validateText(text, checkHardRule: true, checkSoftRule: true, checkSubmitRule: checkSubmitRule) if let lastResult = lastResult { if lastResult == result { switch result { case .Valid: //DLog("same valid") return true case .HardInvalid: //DLog("same hard invalid") invalidateTimer() if shouldInstallTimer { installTimer() } return false case .SoftInvalid: //DLog("same soft invalid") invalidateTimer() if shouldInstallTimer { installTimer() } return true } } } lastResult = result switch result { case .Valid: //DLog("different valid") if let tv = tableView { tv.beginUpdates() errorLabel.text = nil setNeedsLayout() tv.endUpdates() invalidateTimer() } return true case let .HardInvalid(message): //DLog("different hard invalid") if let tv = tableView { tv.beginUpdates() errorLabel.text = message setNeedsLayout() tv.endUpdates() invalidateTimer() if shouldInstallTimer { installTimer() } } return false case let .SoftInvalid(message): //DLog("different soft invalid") if let tv = tableView { tv.beginUpdates() errorLabel.text = message setNeedsLayout() tv.endUpdates() invalidateTimer() if shouldInstallTimer { installTimer() } } return true } } public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let textFieldString: NSString = textField.text ?? "" let s = textFieldString.stringByReplacingCharactersInRange(range, withString:string) let valid = validateAndUpdateErrorIfNeeded(s, shouldInstallTimer: true, checkSubmitRule: false) return valid } public func timerUpdate() { invalidateTimer() //DLog("timer update") let s = textField.text ?? "" validateAndUpdateErrorIfNeeded(s, shouldInstallTimer: false, checkSubmitRule: false) } public func reloadPersistentValidationState() { invalidateTimer() //DLog("reload persistent message") let s = textField.text ?? "" validateAndUpdateErrorIfNeeded(s, shouldInstallTimer: false, checkSubmitRule: true) } public func form_cellHeight(indexPath: NSIndexPath, tableView: UITableView) -> CGFloat { let sizes: TextFieldFormItemCellSizes = compute(bounds.width) let value = sizes.cellHeight //DLog("compute height of row: \(value)") return value } public func textFieldDidBeginEditing(textField: UITextField) { updateToolbarButtons() } // MARK: UIResponder public override func canBecomeFirstResponder() -> Bool { return true } public override func becomeFirstResponder() -> Bool { return textField.becomeFirstResponder() } public override func resignFirstResponder() -> Bool { return textField.resignFirstResponder() } }
mit
cce9f38478e2a30a7f42f72a42804a9b
26.148325
159
0.731406
4.082014
false
false
false
false
Pursuit92/antlr4
runtime/Swift/Antlr4/org/antlr/v4/runtime/dfa/DFA.swift
3
6658
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ public class DFA: CustomStringConvertible { /** A set of all DFA states. Use {@link java.util.Map} so we can get old state back * ({@link java.util.Set} only allows you to see if it's there). */ public final var states: HashMap<DFAState, DFAState?> = HashMap<DFAState, DFAState?>() public /*volatile*/ var s0: DFAState? public final var decision: Int /** From which ATN state did we create this DFA? */ public let atnStartState: DecisionState /** * {@code true} if this DFA is for a precedence decision; otherwise, * {@code false}. This is the backing field for {@link #isPrecedenceDfa}. */ private final var precedenceDfa: Bool public convenience init(_ atnStartState: DecisionState) { self.init(atnStartState, 0) } public init(_ atnStartState: DecisionState, _ decision: Int) { self.atnStartState = atnStartState self.decision = decision var precedenceDfa: Bool = false if atnStartState is StarLoopEntryState { if (atnStartState as! StarLoopEntryState).precedenceRuleDecision { precedenceDfa = true let precedenceState: DFAState = DFAState(ATNConfigSet()) precedenceState.edges = [DFAState]() //new DFAState[0]; precedenceState.isAcceptState = false precedenceState.requiresFullContext = false self.s0 = precedenceState } } self.precedenceDfa = precedenceDfa } /** * Gets whether this DFA is a precedence DFA. Precedence DFAs use a special * start state {@link #s0} which is not stored in {@link #states}. The * {@link org.antlr.v4.runtime.dfa.DFAState#edges} array for this start state contains outgoing edges * supplying individual start states corresponding to specific precedence * values. * * @return {@code true} if this is a precedence DFA; otherwise, * {@code false}. * @see org.antlr.v4.runtime.Parser#getPrecedence() */ public final func isPrecedenceDfa() -> Bool { return precedenceDfa } /** * Get the start state for a specific precedence value. * * @param precedence The current precedence. * @return The start state corresponding to the specified precedence, or * {@code null} if no start state exists for the specified precedence. * * @throws IllegalStateException if this is not a precedence DFA. * @see #isPrecedenceDfa() */ ////@SuppressWarnings("null") public final func getPrecedenceStartState(_ precedence: Int) throws -> DFAState? { if !isPrecedenceDfa() { throw ANTLRError.illegalState(msg: "Only precedence DFAs may contain a precedence start state.") } // s0.edges is never null for a precedence DFA // if (precedence < 0 || precedence >= s0!.edges!.count) { if precedence < 0 || s0 == nil || s0!.edges == nil || precedence >= s0!.edges!.count { return nil } return s0!.edges![precedence] } /** * Set the start state for a specific precedence value. * * @param precedence The current precedence. * @param startState The start state corresponding to the specified * precedence. * * @throws IllegalStateException if this is not a precedence DFA. * @see #isPrecedenceDfa() */ ////@SuppressWarnings({"SynchronizeOnNonFinalField", "null"}) public final func setPrecedenceStartState(_ precedence: Int, _ startState: DFAState) throws { if !isPrecedenceDfa() { throw ANTLRError.illegalState(msg: "Only precedence DFAs may contain a precedence start state.") } guard let s0 = s0,let edges = s0.edges , precedence >= 0 else { return } // synchronization on s0 here is ok. when the DFA is turned into a // precedence DFA, s0 will be initialized once and not updated again synced(s0) { // s0.edges is never null for a precedence DFA if precedence >= edges.count { let increase = [DFAState?](repeating: nil, count: (precedence + 1 - edges.count)) s0.edges = edges + increase //Array( self.s0!.edges![0..<precedence + 1]) //s0.edges = Arrays.copyOf(s0.edges, precedence + 1); } s0.edges[precedence] = startState } } /** * Sets whether this is a precedence DFA. * * @param precedenceDfa {@code true} if this is a precedence DFA; otherwise, * {@code false} * * @throws UnsupportedOperationException if {@code precedenceDfa} does not * match the value of {@link #isPrecedenceDfa} for the current DFA. * * @deprecated This method no longer performs any action. */ ////@Deprecated public final func setPrecedenceDfa(_ precedenceDfa: Bool) throws { if precedenceDfa != isPrecedenceDfa() { throw ANTLRError.unsupportedOperation(msg: "The precedenceDfa field cannot change after a DFA is constructed.") } } /** * Return a list of all states in this DFA, ordered by state number. */ public func getStates() -> Array<DFAState> { var result: Array<DFAState> = Array<DFAState>(states.keys) result = result.sorted { $0.stateNumber < $1.stateNumber } return result } public var description: String { return toString(Vocabulary.EMPTY_VOCABULARY) } public func toString() -> String { return description } /** * @deprecated Use {@link #toString(org.antlr.v4.runtime.Vocabulary)} instead. */ ////@Deprecated public func toString(_ tokenNames: [String?]?) -> String { if s0 == nil { return "" } let serializer: DFASerializer = DFASerializer(self, tokenNames) return serializer.toString() } public func toString(_ vocabulary: Vocabulary) -> String { if s0 == nil { return "" } let serializer: DFASerializer = DFASerializer(self, vocabulary) return serializer.toString() } public func toLexerString() -> String { if s0 == nil { return "" } let serializer: DFASerializer = LexerDFASerializer(self) return serializer.toString() } }
bsd-3-clause
a3717a050ef47b81a55b0f72ce22df3b
32.457286
123
0.61535
4.412194
false
false
false
false
memexapp/memex-swift-sdk
Example/Tests/BaseTestCase.swift
1
1347
import UIKit import XCTest import MemexSwiftSDK class BaseTestCase: XCTestCase { var memex: Memex! struct Constants { static let appToken = "memexAPPtest" static let timeout: TimeInterval = 30 } func mockEmail() -> String { return "\(UUID().uuidString)@memex.co" } func mockPassword() -> String { return "\(UUID().uuidString)\(UUID().uuidString.lowercased())" } func prepareSDK(authorize: Bool = false, completion: @escaping (_ memex: Memex, _ myself: User?) -> ()) { self.memex = Memex(appToken: Constants.appToken, environment: .local, verbose: true) self.memex.prepare { error in XCTAssertNil(error, "nonnil error") self.memex.logout { error in XCTAssertNil(error, "nonnil error") if !authorize { completion(self.memex, nil) } else { let user = User() let onboardingToken = UUID().uuidString self.memex.createUser(user: user, onboardingToken: onboardingToken, completion: { (newUser, error) in XCTAssertNil(error, "nonnil error") self.memex.loginUserWithOnboardingToken(token: onboardingToken, completion: { (retryToken, error) in XCTAssertNil(error, "nonnil error") completion(self.memex, newUser) }) }) } } } } }
mit
c85de19cd7ebb89c5a77556f28fca2ef
28.933333
112
0.617669
4.27619
false
true
false
false
OSzhou/MyTestDemo
PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-Crypto.git--5196635702121641122/Sources/PerfectCrypto.swift
1
766
// // PerfectCrypto.swift // PerfectCrypto // // Created by Kyle Jessup on 2017-02-07. // Copyright (C) 2017 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2017 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // public enum PerfectCrypto { public static var isInitialized: Bool = { return OpenSSLInternal.isInitialized }() } public struct CryptoError: Error { public let code: Int public let msg: String }
apache-2.0
95167ba17d27ad33bfc9299b4c64abb1
23.709677
80
0.56658
4.505882
false
false
false
false
iChirag/iHelperClass
iHelperClass/ViewController.swift
1
6153
// // ViewController.swift // iHelperClass // // Created by Chirag Lukhi on 16/09/14. // Copyright (c) 2014 iChirag. All rights reserved. // import UIKit class ViewController: UIViewController,iHelperClassDelegate { override func viewDidLoad() { super.viewDidLoad() // 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: All buttons clicked @IBAction func btnCallGetws_clicked(sender: AnyObject) { let objHelper:iHelperClass = iHelperClass() ///Developer can call directly URL with query string by passing nil to parameters as below : // objHelper.iHelperAPI_GET("http://api.geonames.org/citiesJSON?north = 44.1&south = -9.9&east = -22.4&west = 55.2&lang = de&username = demo", parameters: nil,apiIdentifier: "get_identifier",delegate: self) //Developer can call url and parameter separately as well as follow : let dicParam:NSMutableDictionary = NSMutableDictionary() dicParam.setObject("44.1", forKey: "north" as NSCopying) dicParam.setObject("-9.9", forKey: "south" as NSCopying) dicParam.setObject("-22.4", forKey: "east" as NSCopying) dicParam.setObject("55.2", forKey: "west" as NSCopying) dicParam.setObject("de", forKey: "lang" as NSCopying) dicParam.setObject("demo", forKey: "username" as NSCopying) objHelper.iHelperAPI_GET(urlMethodOrFile: "http://api.geonames.org/citiesJSON", parameters: dicParam,apiIdentifier: "get_identifier",delegate: self) } @IBAction func btnCallPOSTws_clicked(sender: AnyObject) { let objHelper:iHelperClass = iHelperClass() let dicParam:NSMutableDictionary = NSMutableDictionary() dicParam.setObject("44.1", forKey: "north" as NSCopying) dicParam.setObject("-9.9", forKey: "south" as NSCopying) dicParam.setObject("-22.4", forKey: "east" as NSCopying) dicParam.setObject("55.2", forKey: "west" as NSCopying) dicParam.setObject("de", forKey: "lang" as NSCopying) dicParam.setObject("demo", forKey: "username" as NSCopying) objHelper.iHelperAPI_POST(urlMethodOrFile: "http://api.geonames.org/citiesJSON", parameters: dicParam,apiIdentifier: "post_identifier",delegate: self) } @IBAction func btnImageUploadingws_clicked(sender: AnyObject) { let dicParam:NSMutableDictionary = NSMutableDictionary() dicParam.setObject("ichirag", forKey: "firstname" as NSCopying) dicParam.setObject("[email protected]", forKey: "email" as NSCopying) dicParam.setObject("chirag123", forKey: "password" as NSCopying) dicParam.setObject("ios", forKey: "device_type" as NSCopying) dicParam.setObject("JKJKKJKJKJKJKJKJ", forKey: "device_token" as NSCopying) dicParam.setObject("1", forKey: "gender" as NSCopying) dicParam.setObject("register", forKey: "method" as NSCopying) dicParam.setObject("1", forKey: "reg_type" as NSCopying) dicParam.setObject("1", forKey: "latitude" as NSCopying) dicParam.setObject("1", forKey: "longitude" as NSCopying) dicParam.setObject("Asia/Kolkata", forKey: "timezone" as NSCopying) dicParam.setObject("Surat", forKey: "location" as NSCopying) let dicImgParam:NSMutableDictionary = NSMutableDictionary() let dataImg = UIImageJPEGRepresentation(UIImage(named:"testing.jpg")!, 1) dicImgParam.setObject(dataImg as Any, forKey: "profilephoto" as NSCopying)//you can upload image,video,doc,xls,pdf or anyfile type of objects here as NSData object let objHelper:iHelperClass = iHelperClass() objHelper.iHelperAPI_FileUpload(urlMethodOrFile: "<ANY URL>/webservice.php", parameters: dicParam, parametersImage: dicImgParam, apiIdentifier: "IMAGE", delegate: self) } @IBAction func btnCallwsAsJSON_clicked(sender: AnyObject) { let objHelper:iHelperClass = iHelperClass() let strJSON :String = "{\"userId\" : \"13645\"}" objHelper.iHelperAPI_JSON(urlMethodOrFile: "<ANY URL>", json: strJSON, apiIdentifier: "JSON", delegate: self) } // MARK: iHelperClassDelegate func iHelperResponseSuccess(ihelper: iHelperClass) { if(ihelper.apiIdentifier == "get_identifier") { let stringJson = String(data: ihelper.responseData! as Data, encoding: String.Encoding.utf8) print("wenservice GET response >>> \(String(describing: stringJson))") } if(ihelper.apiIdentifier == "post_identifier") { let stringJson = String(data: ihelper.responseData! as Data, encoding: String.Encoding.utf8) print("wenservice POST response >>> \(String(describing: stringJson))") } if(ihelper.apiIdentifier == "JSON") { let stringJson = String(data: ihelper.responseData! as Data, encoding: String.Encoding.utf8) print("json response >>>> \(String(describing: stringJson))") } if(ihelper.apiIdentifier == "IMAGE") { let stringJson = String(data: ihelper.responseData! as Data, encoding: String.Encoding.utf8) print("IMAGE response >>>> \(String(describing: stringJson))") } } func iHelperResponseFail(error: NSError) { print("error : \(error)") let alert = UIAlertController(title: "Error", message: "ERROR : \(error)", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } }
mit
675213c31031561f1d982cfaeb1c80b0
38.442308
213
0.633512
4.330049
false
false
false
false
adrfer/swift
test/Constraints/casts_objc.swift
14
1570
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify %s // REQUIRES: objc_interop import Foundation struct NotClass {} class SomeClass {} func nsobject_as_class_cast<T>(x: NSObject, _: T) { let _ = x is AnyObject.Type let _ = x as! AnyObject.Type let _ = x as? AnyObject.Type let _ = x is Any.Type let _ = x as! Any.Type let _ = x as? Any.Type let _ = x is SomeClass.Type let _ = x as! SomeClass.Type let _ = x as? SomeClass.Type let _ = x is T.Type let _ = x as! T.Type let _ = x as? T.Type let _ = x is NotClass.Type // expected-warning{{cast from 'NSObject' to unrelated type 'NotClass.Type' always fails}} let _ = x as! NotClass.Type // expected-warning{{cast from 'NSObject' to unrelated type 'NotClass.Type' always fails}} let _ = x as? NotClass.Type // expected-warning{{cast from 'NSObject' to unrelated type 'NotClass.Type' always fails}} } // <rdar://problem/20294245> QoI: Error message mentions value rather than key for subscript func test(a : CFString!, b : CFString) { var dict = NSMutableDictionary() let object = NSObject() dict[a] = object // expected-error {{argument type 'CFString!' does not conform to expected type 'NSCopying'}} dict[b] = object // expected-error {{argument type 'CFString' does not conform to expected type 'NSCopying'}} } // <rdar://problem/22507759> QoI: poor error message for invalid unsafeDowncast() let r22507759: NSObject! = "test" let _: NSString! = unsafeDowncast(r22507759) // expected-error {{generic parameter 'T' could not be inferred}}
apache-2.0
64ed05a0d183745f4c627b792c5cb13e
32.404255
120
0.682803
3.45815
false
false
false
false
actilot/ACMaterialDesignIcons
ACMaterialDesignIconCodes.swift
1
64995
// // ACMaterialDesignIconCodes.swift // // // Created by Axel Ros Campaña on 9/5/17. // // import Foundation public struct ACMaterialDesignIconCode { // Web Application public static var md_3d_rotation : String = "\u{f101}"; public static var md_airplane_off : String = "\u{f102}"; public static var md_airplane : String = "\u{f103}"; public static var md_album : String = "\u{f104}"; public static var md_archive : String = "\u{f105}"; public static var md_assignment_account : String = "\u{f106}"; public static var md_assignment_alert : String = "\u{f107}"; public static var md_assignment_check : String = "\u{f108}"; public static var md_assignment_o : String = "\u{f109}"; public static var md_assignment_return : String = "\u{f10a}"; public static var md_assignment_returned : String = "\u{f10b}"; public static var md_assignment : String = "\u{f10c}"; public static var md_attachment_alt : String = "\u{f10d}"; public static var md_attachment : String = "\u{f10e}"; public static var md_audio : String = "\u{f10f}"; public static var md_badge_check : String = "\u{f110}"; public static var md_balance_wallet : String = "\u{f111}"; public static var md_balance : String = "\u{f112}"; public static var md_battery_alert : String = "\u{f113}"; public static var md_battery_flash : String = "\u{f114}"; public static var md_battery_unknown : String = "\u{f115}"; public static var md_battery : String = "\u{f116}"; public static var md_bike : String = "\u{f117}"; public static var md_block_alt : String = "\u{f118}"; public static var md_block : String = "\u{f119}"; public static var md_boat : String = "\u{f11a}"; public static var md_book_image : String = "\u{f11b}"; public static var md_book : String = "\u{f11c}"; public static var md_bookmark_outline : String = "\u{f11d}"; public static var md_bookmark : String = "\u{f11e}"; public static var md_brush : String = "\u{f11f}"; public static var md_bug : String = "\u{f120}"; public static var md_bus : String = "\u{f121}"; public static var md_cake : String = "\u{f122}"; public static var md_car_taxi : String = "\u{f123}"; public static var md_car_wash : String = "\u{f124}"; public static var md_car : String = "\u{f125}"; public static var md_card_giftcard : String = "\u{f126}"; public static var md_card_membership : String = "\u{f127}"; public static var md_card_travel : String = "\u{f128}"; public static var md_card : String = "\u{f129}"; public static var md_case_check : String = "\u{f12a}"; public static var md_case_download : String = "\u{f12b}"; public static var md_case_play : String = "\u{f12c}"; public static var md_case : String = "\u{f12d}"; public static var md_cast_connected : String = "\u{f12e}"; public static var md_cast : String = "\u{f12f}"; public static var md_chart_donut : String = "\u{f130}"; public static var md_chart : String = "\u{f131}"; public static var md_city_alt : String = "\u{f132}"; public static var md_city : String = "\u{f133}"; public static var md_close_circle_o : String = "\u{f134}"; public static var md_close_circle : String = "\u{f135}"; public static var md_close : String = "\u{f136}"; public static var md_cocktail : String = "\u{f137}"; public static var md_code_setting : String = "\u{f138}"; public static var md_code_smartphone : String = "\u{f139}"; public static var md_code : String = "\u{f13a}"; public static var md_coffee : String = "\u{f13b}"; public static var md_collection_bookmark : String = "\u{f13c}"; public static var md_collection_case_play : String = "\u{f13d}"; public static var md_collection_folder_image : String = "\u{f13e}"; public static var md_collection_image_o : String = "\u{f13f}"; public static var md_collection_image : String = "\u{f140}"; public static var md_collection_item_1 : String = "\u{f141}"; public static var md_collection_item_2 : String = "\u{f142}"; public static var md_collection_item_3 : String = "\u{f143}"; public static var md_collection_item_4 : String = "\u{f144}"; public static var md_collection_item_5 : String = "\u{f145}"; public static var md_collection_item_6 : String = "\u{f146}"; public static var md_collection_item_7 : String = "\u{f147}"; public static var md_collection_item_8 : String = "\u{f148}"; public static var md_collection_item_9_plus : String = "\u{f149}"; public static var md_collection_item_9 : String = "\u{f14a}"; public static var md_collection_item : String = "\u{f14b}"; public static var md_collection_music : String = "\u{f14c}"; public static var md_collection_pdf : String = "\u{f14d}"; public static var md_collection_plus : String = "\u{f14e}"; public static var md_collection_speaker : String = "\u{f14f}"; public static var md_collection_text : String = "\u{f150}"; public static var md_collection_video : String = "\u{f151}"; public static var md_compass : String = "\u{f152}"; public static var md_cutlery : String = "\u{f153}"; public static var md_delete : String = "\u{f154}"; public static var md_dialpad : String = "\u{f155}"; public static var md_dns : String = "\u{f156}"; public static var md_drink : String = "\u{f157}"; public static var md_edit : String = "\u{f158}"; public static var md_email_open : String = "\u{f159}"; public static var md_email : String = "\u{f15a}"; public static var md_eye_off : String = "\u{f15b}"; public static var md_eye : String = "\u{f15c}"; public static var md_eyedropper : String = "\u{f15d}"; public static var md_favorite_outline : String = "\u{f15e}"; public static var md_favorite : String = "\u{f15f}"; public static var md_filter_list : String = "\u{f160}"; public static var md_fire : String = "\u{f161}"; public static var md_flag : String = "\u{f162}"; public static var md_flare : String = "\u{f163}"; public static var md_flash_auto : String = "\u{f164}"; public static var md_flash_off : String = "\u{f165}"; public static var md_flash : String = "\u{f166}"; public static var md_flip : String = "\u{f167}"; public static var md_flower_alt : String = "\u{f168}"; public static var md_flower : String = "\u{f169}"; public static var md_font : String = "\u{f16a}"; public static var md_fullscreen_alt : String = "\u{f16b}"; public static var md_fullscreen_exit : String = "\u{f16c}"; public static var md_fullscreen : String = "\u{f16d}"; public static var md_functions : String = "\u{f16e}"; public static var md_gas_station : String = "\u{f16f}"; public static var md_gesture : String = "\u{f170}"; public static var md_globe_alt : String = "\u{f171}"; public static var md_globe_lock : String = "\u{f172}"; public static var md_globe : String = "\u{f173}"; public static var md_graduation_cap : String = "\u{f174}"; public static var md_group : String = "\u{f3e9}"; public static var md_home : String = "\u{f175}"; public static var md_hospital_alt : String = "\u{f176}"; public static var md_hospital : String = "\u{f177}"; public static var md_hotel : String = "\u{f178}"; public static var md_hourglass_alt : String = "\u{f179}"; public static var md_hourglass_outline : String = "\u{f17a}"; public static var md_hourglass : String = "\u{f17b}"; public static var md_http : String = "\u{f17c}"; public static var md_image_alt : String = "\u{f17d}"; public static var md_image_o : String = "\u{f17e}"; public static var md_image : String = "\u{f17f}"; public static var md_inbox : String = "\u{f180}"; public static var md_invert_colors_off : String = "\u{f181}"; public static var md_invert_colors : String = "\u{f182}"; public static var md_key : String = "\u{f183}"; public static var md_label_alt_outline : String = "\u{f184}"; public static var md_label_alt : String = "\u{f185}"; public static var md_label_heart : String = "\u{f186}"; public static var md_label : String = "\u{f187}"; public static var md_labels : String = "\u{f188}"; public static var md_lamp : String = "\u{f189}"; public static var md_landscape : String = "\u{f18a}"; public static var md_layers_off : String = "\u{f18b}"; public static var md_layers : String = "\u{f18c}"; public static var md_library : String = "\u{f18d}"; public static var md_link : String = "\u{f18e}"; public static var md_lock_open : String = "\u{f18f}"; public static var md_lock_outline : String = "\u{f190}"; public static var md_lock : String = "\u{f191}"; public static var md_mail_reply_all : String = "\u{f192}"; public static var md_mail_reply : String = "\u{f193}"; public static var md_mail_send : String = "\u{f194}"; public static var md_mall : String = "\u{f195}"; public static var md_map : String = "\u{f196}"; public static var md_menu : String = "\u{f197}"; public static var md_money_box : String = "\u{f198}"; public static var md_money_off : String = "\u{f199}"; public static var md_money : String = "\u{f19a}"; public static var md_more_vert : String = "\u{f19b}"; public static var md_more : String = "\u{f19c}"; public static var md_movie_alt : String = "\u{f19d}"; public static var md_movie : String = "\u{f19e}"; public static var md_nature_people : String = "\u{f19f}"; public static var md_nature : String = "\u{f1a0}"; public static var md_navigation : String = "\u{f1a1}"; public static var md_open_in_browser : String = "\u{f1a2}"; public static var md_open_in_new : String = "\u{f1a3}"; public static var md_palette : String = "\u{f1a4}"; public static var md_parking : String = "\u{f1a5}"; public static var md_pin_account : String = "\u{f1a6}"; public static var md_pin_assistant : String = "\u{f1a7}"; public static var md_pin_drop : String = "\u{f1a8}"; public static var md_pin_help : String = "\u{f1a9}"; public static var md_pin_off : String = "\u{f1aa}"; public static var md_pin : String = "\u{f1ab}"; public static var md_pizza : String = "\u{f1ac}"; public static var md_plaster : String = "\u{f1ad}"; public static var md_power_setting : String = "\u{f1ae}"; public static var md_power : String = "\u{f1af}"; public static var md_print : String = "\u{f1b0}"; public static var md_puzzle_piece : String = "\u{f1b1}"; public static var md_quote : String = "\u{f1b2}"; public static var md_railway : String = "\u{f1b3}"; public static var md_receipt : String = "\u{f1b4}"; public static var md_refresh_alt : String = "\u{f1b5}"; public static var md_refresh_sync_alert : String = "\u{f1b6}"; public static var md_refresh_sync_off : String = "\u{f1b7}"; public static var md_refresh_sync : String = "\u{f1b8}"; public static var md_refresh : String = "\u{f1b9}"; public static var md_roller : String = "\u{f1ba}"; public static var md_ruler : String = "\u{f1bb}"; public static var md_scissors : String = "\u{f1bc}"; public static var md_screen_rotation_lock : String = "\u{f1bd}"; public static var md_screen_rotation : String = "\u{f1be}"; public static var md_search_for : String = "\u{f1bf}"; public static var md_search_in_file : String = "\u{f1c0}"; public static var md_search_in_page : String = "\u{f1c1}"; public static var md_search_replace : String = "\u{f1c2}"; public static var md_search : String = "\u{f1c3}"; public static var md_seat : String = "\u{f1c4}"; public static var md_settings_square : String = "\u{f1c5}"; public static var md_settings : String = "\u{f1c6}"; public static var md_shape : String = "\u{f3eb}"; public static var md_shield_check : String = "\u{f1c7}"; public static var md_shield_security : String = "\u{f1c8}"; public static var md_shopping_basket : String = "\u{f1c9}"; public static var md_shopping_cart_plus : String = "\u{f1ca}"; public static var md_shopping_cart : String = "\u{f1cb}"; public static var md_sign_in : String = "\u{f1cc}"; public static var md_sort_amount_asc : String = "\u{f1cd}"; public static var md_sort_amount_desc : String = "\u{f1ce}"; public static var md_sort_asc : String = "\u{f1cf}"; public static var md_sort_desc : String = "\u{f1d0}"; public static var md_spellcheck : String = "\u{f1d1}"; public static var md_spinner : String = "\u{f3ec}"; public static var md_storage : String = "\u{f1d2}"; public static var md_store_24 : String = "\u{f1d3}"; public static var md_store : String = "\u{f1d4}"; public static var md_subway : String = "\u{f1d5}"; public static var md_sun : String = "\u{f1d6}"; public static var md_tab_unselected : String = "\u{f1d7}"; public static var md_tab : String = "\u{f1d8}"; public static var md_tag_close : String = "\u{f1d9}"; public static var md_tag_more : String = "\u{f1da}"; public static var md_tag : String = "\u{f1db}"; public static var md_thumb_down : String = "\u{f1dc}"; public static var md_thumb_up_down : String = "\u{f1dd}"; public static var md_thumb_up : String = "\u{f1de}"; public static var md_ticket_star : String = "\u{f1df}"; public static var md_toll : String = "\u{f1e0}"; public static var md_toys : String = "\u{f1e1}"; public static var md_traffic : String = "\u{f1e2}"; public static var md_translate : String = "\u{f1e3}"; public static var md_triangle_down : String = "\u{f1e4}"; public static var md_triangle_up : String = "\u{f1e5}"; public static var md_truck : String = "\u{f1e6}"; public static var md_turning_sign : String = "\u{f1e7}"; public static var md_ungroup : String = "\u{f3ed}"; public static var md_wallpaper : String = "\u{f1e8}"; public static var md_washing_machine : String = "\u{f1e9}"; public static var md_window_maximize : String = "\u{f1ea}"; public static var md_window_minimize : String = "\u{f1eb}"; public static var md_window_restore : String = "\u{f1ec}"; public static var md_wrench : String = "\u{f1ed}"; public static var md_zoom_in : String = "\u{f1ee}"; public static var md_zoom_out : String = "\u{f1ef}"; // Notifications public static var md_alert_circle_o : String = "\u{f1f0}"; public static var md_alert_circle : String = "\u{f1f1}"; public static var md_alert_octagon : String = "\u{f1f2}"; public static var md_alert_polygon : String = "\u{f1f3}"; public static var md_alert_triangle : String = "\u{f1f4}"; public static var md_help_outline : String = "\u{f1f5}"; public static var md_help : String = "\u{f1f6}"; public static var md_info_outline : String = "\u{f1f7}"; public static var md_info : String = "\u{f1f8}"; public static var md_notifications_active : String = "\u{f1f9}"; public static var md_notifications_add : String = "\u{f1fa}"; public static var md_notifications_none : String = "\u{f1fb}"; public static var md_notifications_off : String = "\u{f1fc}"; public static var md_notifications_paused : String = "\u{f1fd}"; public static var md_notifications : String = "\u{f1fe}"; // Person public static var md_account_add : String = "\u{f1ff}"; public static var md_account_box_mail : String = "\u{f200}"; public static var md_account_box_o : String = "\u{f201}"; public static var md_account_box_phone : String = "\u{f202}"; public static var md_account_box : String = "\u{f203}"; public static var md_account_calendar : String = "\u{f204}"; public static var md_account_circle : String = "\u{f205}"; public static var md_account_o : String = "\u{f206}"; public static var md_account : String = "\u{f207}"; public static var md_accounts_add : String = "\u{f208}"; public static var md_accounts_alt : String = "\u{f209}"; public static var md_accounts_list_alt : String = "\u{f20a}"; public static var md_accounts_list : String = "\u{f20b}"; public static var md_accounts_outline : String = "\u{f20c}"; public static var md_accounts : String = "\u{f20d}"; public static var md_face : String = "\u{f20e}"; public static var md_female : String = "\u{f20f}"; public static var md_male_alt : String = "\u{f210}"; public static var md_male_female : String = "\u{f211}"; public static var md_male : String = "\u{f212}"; public static var md_mood_bad : String = "\u{f213}"; public static var md_mood : String = "\u{f214}"; public static var md_run : String = "\u{f215}"; public static var md_walk : String = "\u{f216}"; // File public static var md_cloud_box : String = "\u{f217}"; public static var md_cloud_circle : String = "\u{f218}"; public static var md_cloud_done : String = "\u{f219}"; public static var md_cloud_download : String = "\u{f21a}"; public static var md_cloud_off : String = "\u{f21b}"; public static var md_cloud_outline_alt : String = "\u{f21c}"; public static var md_cloud_outline : String = "\u{f21d}"; public static var md_cloud_upload : String = "\u{f21e}"; public static var md_cloud : String = "\u{f21f}"; public static var md_download : String = "\u{f220}"; public static var md_file_plus : String = "\u{f221}"; public static var md_file_text : String = "\u{f222}"; public static var md_file : String = "\u{f223}"; public static var md_folder_outline : String = "\u{f224}"; public static var md_folder_person : String = "\u{f225}"; public static var md_folder_star_alt : String = "\u{f226}"; public static var md_folder_star : String = "\u{f227}"; public static var md_folder : String = "\u{f228}"; public static var md_gif : String = "\u{f229}"; public static var md_upload : String = "\u{f22a}"; // Editor public static var md_border_all : String = "\u{f22b}"; public static var md_border_bottom : String = "\u{f22c}"; public static var md_border_clear : String = "\u{f22d}"; public static var md_border_color : String = "\u{f22e}"; public static var md_border_horizontal : String = "\u{f22f}"; public static var md_border_inner : String = "\u{f230}"; public static var md_border_left : String = "\u{f231}"; public static var md_border_outer : String = "\u{f232}"; public static var md_border_right : String = "\u{f233}"; public static var md_border_style : String = "\u{f234}"; public static var md_border_top : String = "\u{f235}"; public static var md_border_vertical : String = "\u{f236}"; public static var md_copy : String = "\u{f237}"; public static var md_crop : String = "\u{f238}"; public static var md_format_align_center : String = "\u{f239}"; public static var md_format_align_justify : String = "\u{f23a}"; public static var md_format_align_left : String = "\u{f23b}"; public static var md_format_align_right : String = "\u{f23c}"; public static var md_format_bold : String = "\u{f23d}"; public static var md_format_clear_all : String = "\u{f23e}"; public static var md_format_clear : String = "\u{f23f}"; public static var md_format_color_fill : String = "\u{f240}"; public static var md_format_color_reset : String = "\u{f241}"; public static var md_format_color_text : String = "\u{f242}"; public static var md_format_indent_decrease : String = "\u{f243}"; public static var md_format_indent_increase : String = "\u{f244}"; public static var md_format_italic : String = "\u{f245}"; public static var md_format_line_spacing : String = "\u{f246}"; public static var md_format_list_bulleted : String = "\u{f247}"; public static var md_format_list_numbered : String = "\u{f248}"; public static var md_format_ltr : String = "\u{f249}"; public static var md_format_rtl : String = "\u{f24a}"; public static var md_format_size : String = "\u{f24b}"; public static var md_format_strikethrough_s : String = "\u{f24c}"; public static var md_format_strikethrough : String = "\u{f24d}"; public static var md_format_subject : String = "\u{f24e}"; public static var md_format_underlined : String = "\u{f24f}"; public static var md_format_valign_bottom : String = "\u{f250}"; public static var md_format_valign_center : String = "\u{f251}"; public static var md_format_valign_top : String = "\u{f252}"; public static var md_redo : String = "\u{f253}"; public static var md_select_all : String = "\u{f254}"; public static var md_space_bar : String = "\u{f255}"; public static var md_text_format : String = "\u{f256}"; public static var md_transform : String = "\u{f257}"; public static var md_undo : String = "\u{f258}"; public static var md_wrap_text : String = "\u{f259}"; // Comment public static var md_comment_alert : String = "\u{f25a}"; public static var md_comment_alt_text : String = "\u{f25b}"; public static var md_comment_alt : String = "\u{f25c}"; public static var md_comment_edit : String = "\u{f25d}"; public static var md_comment_image : String = "\u{f25e}"; public static var md_comment_list : String = "\u{f25f}"; public static var md_comment_more : String = "\u{f260}"; public static var md_comment_outline : String = "\u{f261}"; public static var md_comment_text_alt : String = "\u{f262}"; public static var md_comment_text : String = "\u{f263}"; public static var md_comment_video : String = "\u{f264}"; public static var md_comment : String = "\u{f265}"; public static var md_comments : String = "\u{f266}"; // Form public static var md_check_all : String = "\u{f267}"; public static var md_check_circle_u : String = "\u{f268}"; public static var md_check_circle : String = "\u{f269}"; public static var md_check_square : String = "\u{f26a}"; public static var md_check : String = "\u{f26b}"; public static var md_circle_o : String = "\u{f26c}"; public static var md_circle : String = "\u{f26d}"; public static var md_dot_circle_alt : String = "\u{f26e}"; public static var md_dot_circle : String = "\u{f26f}"; public static var md_minus_circle_outline : String = "\u{f270}"; public static var md_minus_circle : String = "\u{f271}"; public static var md_minus_square : String = "\u{f272}"; public static var md_minus : String = "\u{f273}"; public static var md_plus_circle_o_duplicate : String = "\u{f274}"; public static var md_plus_circle_o : String = "\u{f275}"; public static var md_plus_circle : String = "\u{f276}"; public static var md_plus_square : String = "\u{f277}"; public static var md_plus : String = "\u{f278}"; public static var md_square_o : String = "\u{f279}"; public static var md_star_circle : String = "\u{f27a}"; public static var md_star_half : String = "\u{f27b}"; public static var md_star_outline : String = "\u{f27c}"; public static var md_star : String = "\u{f27d}"; // Hardware public static var md_bluetooth_connected : String = "\u{f27e}"; public static var md_bluetooth_off : String = "\u{f27f}"; public static var md_bluetooth_search : String = "\u{f280}"; public static var md_bluetooth_setting : String = "\u{f281}"; public static var md_bluetooth : String = "\u{f282}"; public static var md_camera_add : String = "\u{f283}"; public static var md_camera_alt : String = "\u{f284}"; public static var md_camera_bw : String = "\u{f285}"; public static var md_camera_front : String = "\u{f286}"; public static var md_camera_mic : String = "\u{f287}"; public static var md_camera_party_mode : String = "\u{f288}"; public static var md_camera_rear : String = "\u{f289}"; public static var md_camera_roll : String = "\u{f28a}"; public static var md_camera_switch : String = "\u{f28b}"; public static var md_camera : String = "\u{f28c}"; public static var md_card_alert : String = "\u{f28d}"; public static var md_card_off : String = "\u{f28e}"; public static var md_card_sd : String = "\u{f28f}"; public static var md_card_sim : String = "\u{f290}"; public static var md_desktop_mac : String = "\u{f291}"; public static var md_desktop_windows : String = "\u{f292}"; public static var md_device_hub : String = "\u{f293}"; public static var md_devices_off : String = "\u{f294}"; public static var md_devices : String = "\u{f295}"; public static var md_dock : String = "\u{f296}"; public static var md_floppy : String = "\u{f297}"; public static var md_gamepad : String = "\u{f298}"; public static var md_gps_dot : String = "\u{f299}"; public static var md_gps_off : String = "\u{f29a}"; public static var md_gps : String = "\u{f29b}"; public static var md_headset_mic : String = "\u{f29c}"; public static var md_headset : String = "\u{f29d}"; public static var md_input_antenna : String = "\u{f29e}"; public static var md_input_composite : String = "\u{f29f}"; public static var md_input_hdmi : String = "\u{f2a0}"; public static var md_input_power : String = "\u{f2a1}"; public static var md_input_svideo : String = "\u{f2a2}"; public static var md_keyboard_hide : String = "\u{f2a3}"; public static var md_keyboard : String = "\u{f2a4}"; public static var md_laptop_chromebook : String = "\u{f2a5}"; public static var md_laptop_mac : String = "\u{f2a6}"; public static var md_laptop : String = "\u{f2a7}"; public static var md_mic_off : String = "\u{f2a8}"; public static var md_mic_outline : String = "\u{f2a9}"; public static var md_mic_setting : String = "\u{f2aa}"; public static var md_mic : String = "\u{f2ab}"; public static var md_mouse : String = "\u{f2ac}"; public static var md_network_alert : String = "\u{f2ad}"; public static var md_network_locked : String = "\u{f2ae}"; public static var md_network_off : String = "\u{f2af}"; public static var md_network_outline : String = "\u{f2b0}"; public static var md_network_setting : String = "\u{f2b1}"; public static var md_network : String = "\u{f2b2}"; public static var md_phone_bluetooth : String = "\u{f2b3}"; public static var md_phone_end : String = "\u{f2b4}"; public static var md_phone_forwarded : String = "\u{f2b5}"; public static var md_phone_in_talk : String = "\u{f2b6}"; public static var md_phone_locked : String = "\u{f2b7}"; public static var md_phone_missed : String = "\u{f2b8}"; public static var md_phone_msg : String = "\u{f2b9}"; public static var md_phone_paused : String = "\u{f2ba}"; public static var md_phone_ring : String = "\u{f2bb}"; public static var md_phone_setting : String = "\u{f2bc}"; public static var md_phone_sip : String = "\u{f2bd}"; public static var md_phone : String = "\u{f2be}"; public static var md_portable_wifi_changes : String = "\u{f2bf}"; public static var md_portable_wifi_off : String = "\u{f2c0}"; public static var md_portable_wifi : String = "\u{f2c1}"; public static var md_radio : String = "\u{f2c2}"; public static var md_reader : String = "\u{f2c3}"; public static var md_remote_control_alt : String = "\u{f2c4}"; public static var md_remote_control : String = "\u{f2c5}"; public static var md_router : String = "\u{f2c6}"; public static var md_scanner : String = "\u{f2c7}"; public static var md_smartphone_android : String = "\u{f2c8}"; public static var md_smartphone_download : String = "\u{f2c9}"; public static var md_smartphone_erase : String = "\u{f2ca}"; public static var md_smartphone_info : String = "\u{f2cb}"; public static var md_smartphone_iphone : String = "\u{f2cc}"; public static var md_smartphone_landscape_lock : String = "\u{f2cd}"; public static var md_smartphone_landscape : String = "\u{f2ce}"; public static var md_smartphone_lock : String = "\u{f2cf}"; public static var md_smartphone_portrait_lock : String = "\u{f2d0}"; public static var md_smartphone_ring : String = "\u{f2d1}"; public static var md_smartphone_setting : String = "\u{f2d2}"; public static var md_smartphone_setup : String = "\u{f2d3}"; public static var md_smartphone : String = "\u{f2d4}"; public static var md_speaker : String = "\u{f2d5}"; public static var md_tablet_android : String = "\u{f2d6}"; public static var md_tablet_mac : String = "\u{f2d7}"; public static var md_tablet : String = "\u{f2d8}"; public static var md_tv_alt_play : String = "\u{f2d9}"; public static var md_tv_list : String = "\u{f2da}"; public static var md_tv_play : String = "\u{f2db}"; public static var md_tv : String = "\u{f2dc}"; public static var md_usb : String = "\u{f2dd}"; public static var md_videocam_off : String = "\u{f2de}"; public static var md_videocam_switch : String = "\u{f2df}"; public static var md_videocam : String = "\u{f2e0}"; public static var md_watch : String = "\u{f2e1}"; public static var md_wifi_alt_2 : String = "\u{f2e2}"; public static var md_wifi_alt : String = "\u{f2e3}"; public static var md_wifi_info : String = "\u{f2e4}"; public static var md_wifi_lock : String = "\u{f2e5}"; public static var md_wifi_off : String = "\u{f2e6}"; public static var md_wifi_outline : String = "\u{f2e7}"; public static var md_wifi : String = "\u{f2e8}"; // Directonal public static var md_arrow_left_bottom : String = "\u{f2e9}"; public static var md_arrow_left : String = "\u{f2ea}"; public static var md_arrow_merge : String = "\u{f2eb}"; public static var md_arrow_missed : String = "\u{f2ec}"; public static var md_arrow_right_top : String = "\u{f2ed}"; public static var md_arrow_right : String = "\u{f2ee}"; public static var md_arrow_split : String = "\u{f2ef}"; public static var md_arrows : String = "\u{f2f0}"; public static var md_caret_down_circle : String = "\u{f2f1}"; public static var md_caret_down : String = "\u{f2f2}"; public static var md_caret_left_circle : String = "\u{f2f3}"; public static var md_caret_left : String = "\u{f2f4}"; public static var md_caret_right_circle : String = "\u{f2f5}"; public static var md_caret_right : String = "\u{f2f6}"; public static var md_caret_up_circle : String = "\u{f2f7}"; public static var md_caret_up : String = "\u{f2f8}"; public static var md_chevron_down : String = "\u{f2f9}"; public static var md_chevron_left : String = "\u{f2fa}"; public static var md_chevron_right : String = "\u{f2fb}"; public static var md_chevron_up : String = "\u{f2fc}"; public static var md_forward : String = "\u{f2fd}"; public static var md_long_arrow_down : String = "\u{f2fe}"; public static var md_long_arrow_left : String = "\u{f2ff}"; public static var md_long_arrow_return : String = "\u{f300}"; public static var md_long_arrow_right : String = "\u{f301}"; public static var md_long_arrow_tab : String = "\u{f302}"; public static var md_long_arrow_up : String = "\u{f303}"; public static var md_rotate_ccw : String = "\u{f304}"; public static var md_rotate_cw : String = "\u{f305}"; public static var md_rotate_left : String = "\u{f306}"; public static var md_rotate_right : String = "\u{f307}"; public static var md_square_down : String = "\u{f308}"; public static var md_square_right : String = "\u{f309}"; public static var md_swap_alt : String = "\u{f30a}"; public static var md_swap_vertical_circle : String = "\u{f30b}"; public static var md_swap_vertical : String = "\u{f30c}"; public static var md_swap : String = "\u{f30d}"; public static var md_trending_down : String = "\u{f30e}"; public static var md_trending_flat : String = "\u{f30f}"; public static var md_trending_up : String = "\u{f310}"; public static var md_unfold_less : String = "\u{f311}"; public static var md_unfold_more : String = "\u{f312}"; // View public static var md_apps : String = "\u{f313}"; public static var md_grid_off : String = "\u{f314}"; public static var md_grid : String = "\u{f315}"; public static var md_view_agenda : String = "\u{f316}"; public static var md_view_array : String = "\u{f317}"; public static var md_view_carousel : String = "\u{f318}"; public static var md_view_column : String = "\u{f319}"; public static var md_view_comfy : String = "\u{f31a}"; public static var md_view_compact : String = "\u{f31b}"; public static var md_view_dashboard : String = "\u{f31c}"; public static var md_view_day : String = "\u{f31d}"; public static var md_view_headline : String = "\u{f31e}"; public static var md_view_list_alt : String = "\u{f31f}"; public static var md_view_list : String = "\u{f320}"; public static var md_view_module : String = "\u{f321}"; public static var md_view_quilt : String = "\u{f322}"; public static var md_view_stream : String = "\u{f323}"; public static var md_view_subtitles : String = "\u{f324}"; public static var md_view_toc : String = "\u{f325}"; public static var md_view_web : String = "\u{f326}"; public static var md_view_week : String = "\u{f327}"; public static var md_widgets : String = "\u{f328}"; // Date / Time public static var md_alarm_check : String = "\u{f329}"; public static var md_alarm_off : String = "\u{f32a}"; public static var md_alarm_plus : String = "\u{f32b}"; public static var md_alarm_snooze : String = "\u{f32c}"; public static var md_alarm : String = "\u{f32d}"; public static var md_calendar_alt : String = "\u{f32e}"; public static var md_calendar_check : String = "\u{f32f}"; public static var md_calendar_close : String = "\u{f330}"; public static var md_calendar_note : String = "\u{f331}"; public static var md_calendar : String = "\u{f332}"; public static var md_time_countdown : String = "\u{f333}"; public static var md_time_interval : String = "\u{f334}"; public static var md_time_restore_setting : String = "\u{f335}"; public static var md_time_restore : String = "\u{f336}"; public static var md_time : String = "\u{f337}"; public static var md_timer_off : String = "\u{f338}"; public static var md_timer : String = "\u{f339}"; // Socialpublic static var md_500px : String = "\u{f3ee}"; public static var md_8tracks : String = "\u{f3ef}"; public static var md_amazon : String = "\u{f3f0}"; public static var md_android : String = "\u{f33b}"; public static var md_android_alt : String = "\u{f33a}"; public static var md_apple : String = "\u{f33c}"; public static var md_behance : String = "\u{f33d}"; public static var md_blogger : String = "\u{f3f1}"; public static var md_codepen : String = "\u{f33e}"; public static var md_delicious : String = "\u{f3f2}"; public static var md_disqus : String = "\u{f3f3}"; public static var md_dribbble : String = "\u{f33f}"; public static var md_dropbox : String = "\u{f340}"; public static var md_evernote : String = "\u{f341}"; public static var md_facebook : String = "\u{f343}"; public static var md_facebook_box : String = "\u{f342}"; public static var md_flattr : String = "\u{f3f4}"; public static var md_flickr : String = "\u{f3f5}"; public static var md_github : String = "\u{f345}"; public static var md_github_alt : String = "\u{f3f6}"; public static var md_github_box : String = "\u{f344}"; public static var md_google : String = "\u{f34e}"; public static var md_google_drive : String = "\u{f346}"; public static var md_google_earth : String = "\u{f347}"; public static var md_google_glass : String = "\u{f348}"; public static var md_google_maps : String = "\u{f349}"; public static var md_google_old : String = "\u{f3f7}"; public static var md_google_pages : String = "\u{f34a}"; public static var md_google_play : String = "\u{f34b}"; public static var md_google_plus : String = "\u{f34d}"; public static var md_google_plus_box : String = "\u{f34c}"; public static var md_instagram : String = "\u{f34f}"; public static var md_language_css3 : String = "\u{f350}"; public static var md_language_html5 : String = "\u{f351}"; public static var md_language_javascript : String = "\u{f352}"; public static var md_language_python : String = "\u{f354}"; public static var md_language_python_alt : String = "\u{f353}"; public static var md_lastfm : String = "\u{f355}"; public static var md_linkedin : String = "\u{f3f8}"; public static var md_linkedin_box : String = "\u{f356}"; public static var md_odnoklassniki : String = "\u{f3f9}"; public static var md_outlook : String = "\u{f3fa}"; public static var md_paypal : String = "\u{f357}"; public static var md_paypal_alt : String = "\u{f3fb}"; public static var md_pinterest : String = "\u{f3fc}"; public static var md_pinterest_box : String = "\u{f358}"; public static var md_playstation : String = "\u{f3fd}"; public static var md_pocket : String = "\u{f359}"; public static var md_polymer : String = "\u{f35a}"; public static var md_reddit : String = "\u{f3fe}"; public static var md_rss : String = "\u{f3ea}"; public static var md_share : String = "\u{f35b}"; public static var md_sideshare : String = "\u{f400}"; public static var md_skype : String = "\u{f3ff}"; public static var md_soundcloud : String = "\u{f401}"; public static var md_stack_overflow : String = "\u{f35c}"; public static var md_steam : String = "\u{f35e}"; public static var md_steam_square : String = "\u{f35d}"; public static var md_tumblr : String = "\u{f402}"; public static var md_twitch : String = "\u{f403}"; public static var md_twitter : String = "\u{f360}"; public static var md_twitter_box : String = "\u{f35f}"; public static var md_vimeo : String = "\u{f404}"; public static var md_vk : String = "\u{f361}"; public static var md_whatsapp : String = "\u{f405}"; public static var md_wikipedia : String = "\u{f362}"; public static var md_windows : String = "\u{f363}"; public static var md_xbox : String = "\u{f406}"; public static var md_yahoo : String = "\u{f407}"; public static var md_youtube : String = "\u{f409}"; public static var md_youtube_play : String = "\u{f408}"; // Image public static var md_aspect_ratio_alt : String = "\u{f364}"; public static var md_aspect_ratio : String = "\u{f365}"; public static var md_blur_circular : String = "\u{f366}"; public static var md_blur_linear : String = "\u{f367}"; public static var md_blur_off : String = "\u{f368}"; public static var md_blur : String = "\u{f369}"; public static var md_brightness_2 : String = "\u{f36a}"; public static var md_brightness_3 : String = "\u{f36b}"; public static var md_brightness_4 : String = "\u{f36c}"; public static var md_brightness_5 : String = "\u{f36d}"; public static var md_brightness_6 : String = "\u{f36e}"; public static var md_brightness_7 : String = "\u{f36f}"; public static var md_brightness_auto : String = "\u{f370}"; public static var md_brightness_setting : String = "\u{f371}"; public static var md_broken_image : String = "\u{f372}"; public static var md_center_focus_strong : String = "\u{f373}"; public static var md_center_focus_weak : String = "\u{f374}"; public static var md_compare : String = "\u{f375}"; public static var md_crop_16_9 : String = "\u{f376}"; public static var md_crop_3_2 : String = "\u{f377}"; public static var md_crop_5_4 : String = "\u{f378}"; public static var md_crop_7_5 : String = "\u{f379}"; public static var md_crop_din : String = "\u{f37a}"; public static var md_crop_free : String = "\u{f37b}"; public static var md_crop_landscape : String = "\u{f37c}"; public static var md_crop_portrait : String = "\u{f37d}"; public static var md_crop_square : String = "\u{f37e}"; public static var md_exposure_alt : String = "\u{f37f}"; public static var md_exposure : String = "\u{f380}"; public static var md_filter_b_and_w : String = "\u{f381}"; public static var md_filter_center_focus : String = "\u{f382}"; public static var md_filter_frames : String = "\u{f383}"; public static var md_filter_tilt_shift : String = "\u{f384}"; public static var md_gradient : String = "\u{f385}"; public static var md_grain : String = "\u{f386}"; public static var md_graphic_eq : String = "\u{f387}"; public static var md_hdr_off : String = "\u{f388}"; public static var md_hdr_strong : String = "\u{f389}"; public static var md_hdr_weak : String = "\u{f38a}"; public static var md_hdr : String = "\u{f38b}"; public static var md_iridescent : String = "\u{f38c}"; public static var md_leak_off : String = "\u{f38d}"; public static var md_leak : String = "\u{f38e}"; public static var md_looks : String = "\u{f38f}"; public static var md_loupe : String = "\u{f390}"; public static var md_panorama_horizontal : String = "\u{f391}"; public static var md_panorama_vertical : String = "\u{f392}"; public static var md_panorama_wide_angle : String = "\u{f393}"; public static var md_photo_size_select_large : String = "\u{f394}"; public static var md_photo_size_select_small : String = "\u{f395}"; public static var md_picture_in_picture : String = "\u{f396}"; public static var md_slideshow : String = "\u{f397}"; public static var md_texture : String = "\u{f398}"; public static var md_tonality : String = "\u{f399}"; public static var md_vignette : String = "\u{f39a}"; public static var md_wb_auto : String = "\u{f39b}"; // Audio / Video public static var md_eject_alt : String = "\u{f39c}"; public static var md_eject : String = "\u{f39d}"; public static var md_equalizer : String = "\u{f39e}"; public static var md_fast_forward : String = "\u{f39f}"; public static var md_fast_rewind : String = "\u{f3a0}"; public static var md_forward_10 : String = "\u{f3a1}"; public static var md_forward_30 : String = "\u{f3a2}"; public static var md_forward_5 : String = "\u{f3a3}"; public static var md_hearing : String = "\u{f3a4}"; public static var md_pause_circle_outline : String = "\u{f3a5}"; public static var md_pause_circle : String = "\u{f3a6}"; public static var md_pause : String = "\u{f3a7}"; public static var md_play_circle_outline : String = "\u{f3a8}"; public static var md_play_circle : String = "\u{f3a9}"; public static var md_play : String = "\u{f3aa}"; public static var md_playlist_audio : String = "\u{f3ab}"; public static var md_playlist_plus : String = "\u{f3ac}"; public static var md_repeat_one : String = "\u{f3ad}"; public static var md_repeat : String = "\u{f3ae}"; public static var md_replay_10 : String = "\u{f3af}"; public static var md_replay_30 : String = "\u{f3b0}"; public static var md_replay_5 : String = "\u{f3b1}"; public static var md_replay : String = "\u{f3b2}"; public static var md_shuffle : String = "\u{f3b3}"; public static var md_skip_next : String = "\u{f3b4}"; public static var md_skip_previous : String = "\u{f3b5}"; public static var md_stop : String = "\u{f3b6}"; public static var md_surround_sound : String = "\u{f3b7}"; public static var md_tune : String = "\u{f3b8}"; public static var md_volume_down : String = "\u{f3b9}"; public static var md_volume_mute : String = "\u{f3ba}"; public static var md_volume_off : String = "\u{f3bb}"; public static var md_volume_up : String = "\u{f3bc}"; // Numbers public static var md_n_1_square : String = "\u{f3bd}"; public static var md_n_2_square : String = "\u{f3be}"; public static var md_n_3_square : String = "\u{f3bf}"; public static var md_n_4_square : String = "\u{f3c0}"; public static var md_n_5_square : String = "\u{f3c1}"; public static var md_n_6_square : String = "\u{f3c2}"; public static var md_neg_1 : String = "\u{f3c3}"; public static var md_neg_2 : String = "\u{f3c4}"; public static var md_plus_1 : String = "\u{f3c5}"; public static var md_plus_2 : String = "\u{f3c6}"; public static var md_sec_10 : String = "\u{f3c7}"; public static var md_sec_3 : String = "\u{f3c8}"; public static var md_zero : String = "\u{f3c9}"; // Others public static var md_airline_seat_flat_angled : String = "\u{f3ca}"; public static var md_airline_seat_flat : String = "\u{f3cb}"; public static var md_airline_seat_individual_suite : String = "\u{f3cc}"; public static var md_airline_seat_legroom_extra : String = "\u{f3cd}"; public static var md_airline_seat_legroom_normal : String = "\u{f3ce}"; public static var md_airline_seat_legroom_reduced : String = "\u{f3cf}"; public static var md_airline_seat_recline_extra : String = "\u{f3d0}"; public static var md_airline_seat_recline_normal : String = "\u{f3d1}"; public static var md_airplay : String = "\u{f3d2}"; public static var md_closed_caption : String = "\u{f3d3}"; public static var md_confirmation_number : String = "\u{f3d4}"; public static var md_developer_board : String = "\u{f3d5}"; public static var md_disc_full : String = "\u{f3d6}"; public static var md_explicit : String = "\u{f3d7}"; public static var md_flight_land : String = "\u{f3d8}"; public static var md_flight_takeoff : String = "\u{f3d9}"; public static var md_flip_to_back : String = "\u{f3da}"; public static var md_flip_to_front : String = "\u{f3db}"; public static var md_group_work : String = "\u{f3dc}"; public static var md_hd : String = "\u{f3dd}"; public static var md_hq : String = "\u{f3de}"; public static var md_markunread_mailbox : String = "\u{f3df}"; public static var md_memory : String = "\u{f3e0}"; public static var md_nfc : String = "\u{f3e1}"; public static var md_play_for_work : String = "\u{f3e2}"; public static var md_power_input : String = "\u{f3e3}"; public static var md_present_to_all : String = "\u{f3e4}"; public static var md_satellite : String = "\u{f3e5}"; public static var md_tap_and_play : String = "\u{f3e6}"; public static var md_vibration : String = "\u{f3e7}"; public static var md_voicemail : String = "\u{f3e8}"; }
mit
18d75e77302ecb3583c127af8fa4b742
78.260976
92
0.455657
4.024895
false
false
false
false
mapsme/omim
iphone/Maps/UI/Welcome/PromoDiscovery/PromoDiscoveryPresenter.swift
5
2088
protocol IPromoRouterPresenter: IWelcomePresenter { } class PromoDiscoveryPresenter { private weak var viewController: IWelcomeView? private let router: IPromoDiscoveryRouter private let campaign: PromoDiscoveryCampaign private var statType: String = "" init(viewController: IWelcomeView, router: IPromoDiscoveryRouter, campaign: PromoDiscoveryCampaign) { self.viewController = viewController self.router = router self.campaign = campaign; } } extension PromoDiscoveryPresenter: IPromoRouterPresenter { func configure() { switch campaign.group { case .discoverCatalog: viewController?.setTitleImage(UIImage(named: "img_onboarding_subscribeguides")) viewController?.setTitle(L("new_onboarding_step5.1_header")) viewController?.setText(L("new_onboarding_step5.1_message")) viewController?.setNextButtonTitle(L("new_onboarding_step5.1_button")) statType = kStatOnboardingCatalog case .buySubscription: viewController?.setTitleImage(UIImage(named: "img_onboarding_subscribeguides")) viewController?.setTitle(L("new_onboarding_step5.1_header")) viewController?.setText(L("new_onboarding_step5.2_message")) viewController?.setNextButtonTitle(L("new_onboarding_step5.2_button")) statType = kStatOnboardingSubscription case .downloadSamples: viewController?.setTitleImage(UIImage(named: "img_onboarding_samples")) viewController?.setTitle(L("new_onboarding_step5.1_header")) viewController?.setText(L("new_onboarding_step5.3_message")) viewController?.setNextButtonTitle(L("new_onboarding_step5.3_button")) statType = kStatOnboardingSample } } func onAppear() { Statistics.logEvent(kStatOnboardingScreenShow, withParameters: [kStatType: statType]) } func onNext() { router.presentNext() Statistics.logEvent(kStatOnboardingScreenAccept, withParameters: [kStatType: statType]) } func onClose() { router.dissmiss() Statistics.logEvent(kStatOnboardingScreenDecline, withParameters: [kStatType: statType]) } }
apache-2.0
225ab181f33c7aaef07ea082e96c0fcf
35.631579
92
0.743295
4.368201
false
false
false
false
kwkhaw/SwiftAnyPic
SwiftAnyPic/PAPBaseTextCell.swift
1
16305
import UIKit import FormatterKit import CoreGraphics import ParseUI var timeFormatter: TTTTimeIntervalFormatter? /*! Layout constants */ private let vertBorderSpacing: CGFloat = 8.0 private let vertElemSpacing: CGFloat = 0.0 private let horiBorderSpacing: CGFloat = 8.0 private let horiBorderSpacingBottom: CGFloat = 9.0 private let horiElemSpacing: CGFloat = 5.0 private let vertTextBorderSpacing: CGFloat = 10.0 private let avatarX: CGFloat = horiBorderSpacing private let avatarY: CGFloat = vertBorderSpacing private let avatarDim: CGFloat = 33.0 private let nameX: CGFloat = avatarX+avatarDim+horiElemSpacing private let nameY: CGFloat = vertTextBorderSpacing private let nameMaxWidth: CGFloat = 200.0 private let timeX: CGFloat = avatarX+avatarDim+horiElemSpacing class PAPBaseTextCell: PFTableViewCell { var horizontalTextSpace: Int = 0 var _delegate: PAPBaseTextCellDelegate? /*! Unfortunately, objective-c does not allow you to redefine the type of a property, so we cannot set the type of the delegate here. Doing so would mean that the subclass of would not be able to define new delegate methods (which we do in PAPActivityCell). */ // var delegate: PAPBaseTextCellDelegate? { // get { // return _delegate // } // // set { // _delegate = newValue // } // } /*! The cell's views. These shouldn't be modified but need to be exposed for the subclass */ var mainView: UIView? var nameButton: UIButton? var avatarImageButton: UIButton? var avatarImageView: PAPProfileImageView? var contentLabel: UILabel? var timeLabel: UILabel? var separatorImage: UIImageView? var hideSeparator: Bool = false // True if the separator shouldn't be shown // MARK:- NSObject override init(style: UITableViewCellStyle, reuseIdentifier: String?) { // Initialization code cellInsetWidth = 0.0 super.init(style: style, reuseIdentifier: reuseIdentifier) if timeFormatter == nil { timeFormatter = TTTTimeIntervalFormatter() } hideSeparator = false self.clipsToBounds = true horizontalTextSpace = Int(PAPBaseTextCell.horizontalTextSpaceForInsetWidth(cellInsetWidth)) self.opaque = true self.selectionStyle = UITableViewCellSelectionStyle.None self.accessoryType = UITableViewCellAccessoryType.None self.backgroundColor = UIColor.clearColor() mainView = UIView(frame: self.contentView.frame) mainView!.backgroundColor = UIColor.whiteColor() self.avatarImageView = PAPProfileImageView() self.avatarImageView!.backgroundColor = UIColor.clearColor() self.avatarImageView!.opaque = true self.avatarImageView!.layer.cornerRadius = 16.0 self.avatarImageView!.layer.masksToBounds = true mainView!.addSubview(self.avatarImageView!) self.nameButton = UIButton(type: UIButtonType.Custom) self.nameButton!.backgroundColor = UIColor.clearColor() if reuseIdentifier == "ActivityCell" { self.nameButton!.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) self.nameButton!.setTitleColor(UIColor(red: 114.0/255.0, green: 114.0/255.0, blue: 114.0/255.0, alpha: 1.0), forState: UIControlState.Highlighted) } else { self.nameButton!.setTitleColor(UIColor(red: 34.0/255.0, green: 34.0/255.0, blue: 34.0/255.0, alpha: 1.0), forState: UIControlState.Normal) self.nameButton!.setTitleColor(UIColor(red: 114.0/255.0, green: 114.0/255.0, blue: 114.0/255.0, alpha: 1.0), forState: UIControlState.Highlighted) } self.nameButton!.titleLabel!.font = UIFont.boldSystemFontOfSize(13) self.nameButton!.titleLabel!.lineBreakMode = NSLineBreakMode.ByTruncatingTail self.nameButton!.addTarget(self, action: #selector(PAPBaseTextCell.didTapUserButtonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) mainView!.addSubview(self.nameButton!) self.contentLabel = UILabel() self.contentLabel!.font = UIFont.systemFontOfSize(13.0) if reuseIdentifier == "ActivityCell" { self.contentLabel!.textColor = UIColor.whiteColor() } else { self.contentLabel!.textColor = UIColor(red: 34.0/255.0, green: 34.0/255.0, blue: 34.0/255.0, alpha: 1.0) } self.contentLabel!.numberOfLines = 0 self.contentLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping self.contentLabel!.backgroundColor = UIColor.clearColor() mainView!.addSubview(self.contentLabel!) self.timeLabel = UILabel() self.timeLabel!.font = UIFont.systemFontOfSize(11) self.timeLabel!.textColor = UIColor(red: 114.0/255.0, green: 114.0/255.0, blue: 114.0/255.0, alpha: 1.0) self.timeLabel!.backgroundColor = UIColor.clearColor() mainView!.addSubview(self.timeLabel!) self.avatarImageButton = UIButton(type: UIButtonType.Custom) self.avatarImageButton!.backgroundColor = UIColor.clearColor() self.avatarImageButton!.addTarget(self, action: #selector(PAPBaseTextCell.didTapUserButtonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) mainView!.addSubview(self.avatarImageButton!) self.separatorImage = UIImageView(image: UIImage(named: "SeparatorComments.png")!.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 1, 0, 1))) //[mainView addSubview:separatorImage]; self.contentView.addSubview(mainView!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- UIView override func layoutSubviews() { super.layoutSubviews() mainView!.frame = CGRectMake(cellInsetWidth, self.contentView.frame.origin.y, self.contentView.frame.size.width-2*cellInsetWidth, self.contentView.frame.size.height) // Layout avatar image self.avatarImageView!.frame = CGRectMake(avatarX, avatarY + 5.0, avatarDim, avatarDim) self.avatarImageButton!.frame = CGRectMake(avatarX, avatarY + 5.0, avatarDim, avatarDim) // Layout the name button let nameSize: CGSize = self.nameButton!.titleLabel!.text!.boundingRectWithSize(CGSizeMake(nameMaxWidth, CGFloat.max), options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin], // word wrap? attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(13.0)], context: nil).size self.nameButton!.frame = CGRectMake(nameX, nameY + 6.0, nameSize.width, nameSize.height) // Layout the content let contentSize: CGSize = self.contentLabel!.text!.boundingRectWithSize(CGSizeMake(CGFloat(horizontalTextSpace), CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(13.0)], context: nil).size self.contentLabel!.frame = CGRectMake(nameX, vertTextBorderSpacing + 6.0, contentSize.width, contentSize.height) // Layout the timestamp label let timeSize: CGSize = self.timeLabel!.text!.boundingRectWithSize(CGSizeMake(CGFloat(horizontalTextSpace), CGFloat.max), options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin], attributes: [NSFontAttributeName: UIFont.systemFontOfSize(11.0)], context: nil).size self.timeLabel!.frame = CGRectMake(timeX, contentLabel!.frame.origin.y + contentLabel!.frame.size.height + vertElemSpacing, timeSize.width, timeSize.height) // Layour separator self.separatorImage!.frame = CGRectMake(0, self.frame.size.height-1, self.frame.size.width-cellInsetWidth*2, 1) self.separatorImage!.hidden = hideSeparator } // MARK:- Delegate methods /* Inform delegate that a user image or name was tapped */ func didTapUserButtonAction(sender: AnyObject) { if self.delegate != nil && self.delegate!.respondsToSelector(#selector(PAPBaseTextCellDelegate.cell(_:didTapUserButton:))) { self.delegate!.cell(self, didTapUserButton: self.user!) } } // MARK:- PAPBaseTextCell /* Static helper to get the height for a cell if it had the given name and content */ class func heightForCellWithName(name: String, contentString content: String) -> CGFloat { return PAPBaseTextCell.heightForCellWithName(name, contentString: content, cellInsetWidth: 0) } /* Static helper to get the height for a cell if it had the given name, content and horizontal inset */ class func heightForCellWithName(name: String, contentString content: String, cellInsetWidth cellInset: CGFloat) -> CGFloat { // FIXME: Why nameSize is used before as the argument at the same time???? let nameSize: CGSize = name.boundingRectWithSize(nameSize, let nameSize: CGSize = name.boundingRectWithSize(CGSizeMake(nameMaxWidth, CGFloat.max), options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin], attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(13.0)], context: nil).size let paddedString: String = PAPBaseTextCell.padString(content, withFont: UIFont.systemFontOfSize(13), toWidth: nameSize.width) let horizontalTextSpace: CGFloat = PAPBaseTextCell.horizontalTextSpaceForInsetWidth(cellInset) let contentSize: CGSize = paddedString.boundingRectWithSize(CGSizeMake(horizontalTextSpace, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, // word wrap? attributes: [NSFontAttributeName: UIFont.systemFontOfSize(13.0)], context: nil).size let singleLineHeight: CGFloat = "test".boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(13.0)], context: nil).size.height // Calculate the added height necessary for multiline text. Ensure value is not below 0. let multilineHeightAddition: CGFloat = (contentSize.height - singleLineHeight) > 0 ? (contentSize.height - singleLineHeight) : 0 return horiBorderSpacing + avatarDim + horiBorderSpacingBottom + multilineHeightAddition } /* Static helper to obtain the horizontal space left for name and content after taking the inset and image in consideration */ class func horizontalTextSpaceForInsetWidth(insetWidth: CGFloat) -> CGFloat { return (320-(insetWidth*2)) - (horiBorderSpacing+avatarDim+horiElemSpacing+horiBorderSpacing) } /* Static helper to pad a string with spaces to a given beginning offset */ class func padString(string: String, withFont font: UIFont, toWidth width: CGFloat) -> String { // Find number of spaces to pad var paddedString = "" while (true) { paddedString += " " let resultSize: CGSize = paddedString.boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max), options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin], attributes: [NSFontAttributeName: font], context: nil).size if resultSize.width >= width { break } } // Add final spaces to be ready for first word paddedString += " \(string)" return paddedString } /*! The user represented in the cell */ var user: PFUser? { didSet { // Set name button properties and avatar image if PAPUtility.userHasProfilePictures(self.user!) { self.avatarImageView!.setFile(self.user!.objectForKey(kPAPUserProfilePicSmallKey) as? PFFile) } else { self.avatarImageView!.setImage(PAPUtility.defaultProfilePicture()!) } self.nameButton!.setTitle(self.user!.objectForKey(kPAPUserDisplayNameKey) as? String, forState: UIControlState.Normal) self.nameButton!.setTitle(self.user!.objectForKey(kPAPUserDisplayNameKey) as? String, forState:UIControlState.Highlighted) // If user is set after the contentText, we reset the content to include padding if self.contentLabel!.text != nil { self.setContentText(self.contentLabel!.text!) } self.setNeedsDisplay() } } func setContentText(contentString: String) { // If we have a user we pad the content with spaces to make room for the name if self.user != nil { let nameSize: CGSize = self.nameButton!.titleLabel!.text!.boundingRectWithSize(CGSizeMake(nameMaxWidth, CGFloat.max), options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin], attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(13.0)], context: nil).size let paddedString: String = PAPBaseTextCell.padString(contentString, withFont: UIFont.systemFontOfSize(13), toWidth: nameSize.width) self.contentLabel!.text = paddedString } else { // Otherwise we ignore the padding and we'll add it after we set the user self.contentLabel!.text = contentString } self.setNeedsDisplay() } func setDate(date: NSDate) { // Set the label with a human readable time self.timeLabel!.text = timeFormatter!.stringForTimeIntervalFromDate(NSDate(), toDate: date) self.setNeedsDisplay() } /*! The horizontal inset of the cell */ var cellInsetWidth: CGFloat { didSet { // Change the mainView's frame to be insetted by insetWidth and update the content text space mainView!.frame = CGRectMake(cellInsetWidth, mainView!.frame.origin.y, mainView!.frame.size.width-2*cellInsetWidth, mainView!.frame.size.height) horizontalTextSpace = Int(PAPBaseTextCell.horizontalTextSpaceForInsetWidth(cellInsetWidth)) self.setNeedsDisplay() } } /* Since we remove the compile-time check for the delegate conforming to the protocol in order to allow inheritance, we add run-time checks. */ var delegate: PAPBaseTextCellDelegate? { get { return _delegate } set { // FIXME: any other way to check? if _delegate?.hash != newValue!.hash { _delegate = newValue } } } func hideSeparator(hide: Bool) { hideSeparator = hide } } @objc protocol PAPBaseTextCellDelegate: NSObjectProtocol { /*! Sent to the delegate when a user button is tapped @param aUser the PFUser of the user that was tapped */ func cell(cellView: PAPBaseTextCell, didTapUserButton aUser: PFUser) }
cc0-1.0
f081abd432ad5c40b4a85bc6f2a8ca3a
49.639752
176
0.639558
5.120917
false
false
false
false
ip3r/Cart
Cart/Core/UIKit/TableView/TableView.swift
1
1599
// // TableView.swift // Cart // // Created by Jens Meder on 12.06.17. // Copyright © 2017 Jens Meder. All rights reserved. // import UIKit internal final class TableView: ViewDelegate { private let tableView: Memory<UITableView?> private let delegate: UITableViewDelegate private let dataSource: UITableViewDataSource private let editing: Bool // MARK: Init internal convenience init(tableView: Memory<UITableView?>, dataSource: UITableViewDataSource, delegate: UITableViewDelegate) { self.init( tableView: tableView, dataSource: dataSource, delegate: delegate, editing: false ) } internal required init(tableView: Memory<UITableView?>, dataSource: UITableViewDataSource, delegate: UITableViewDelegate, editing: Bool) { self.tableView = tableView self.dataSource = dataSource self.delegate = delegate self.editing = editing } // MARK: ViewDelegate func loadView(viewController: UIViewController) { tableView.value = UITableView() tableView.value?.dataSource = dataSource tableView.value?.delegate = delegate viewController.view = tableView.value } func viewDidLoad(viewController: UIViewController) { tableView.value?.setEditing(editing, animated: false) } func viewWillAppear(viewController: UIViewController, animated: Bool) { if let selectedRow = tableView.value?.indexPathForSelectedRow { tableView.value?.deselectRow(at: selectedRow, animated: false) } tableView.value?.reloadData() } }
mit
5ce13e4cb8c98999592cba1af957a71e
28.592593
142
0.69587
4.962733
false
false
false
false
juanm95/Soundwich
Quaggify/UIView+Extension.swift
2
3634
// // UIView+Extension.swift // Quaggify // // Created by Jonathan Bijos on 31/01/17. // Copyright © 2017 Quaggie. All rights reserved. // import UIKit extension UIView { public func addConstraintsWithFormat(_ format: String, views: UIView...) { var viewsDictionary = [String: UIView]() for (index, view) in views.enumerated() { let key = "v\(index)" viewsDictionary[key] = view view.translatesAutoresizingMaskIntoConstraints = false } addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary)) } public func fillSuperview() { translatesAutoresizingMaskIntoConstraints = false if let superview = superview { leftAnchor.constraint(equalTo: superview.leftAnchor).isActive = true rightAnchor.constraint(equalTo: superview.rightAnchor).isActive = true topAnchor.constraint(equalTo: superview.topAnchor).isActive = true bottomAnchor.constraint(equalTo: superview.bottomAnchor).isActive = true } } public func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) { translatesAutoresizingMaskIntoConstraints = false _ = anchorWithReturnAnchors(top, left: left, bottom: bottom, right: right, topConstant: topConstant, leftConstant: leftConstant, bottomConstant: bottomConstant, rightConstant: rightConstant, widthConstant: widthConstant, heightConstant: heightConstant) } public func anchorWithReturnAnchors(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] { translatesAutoresizingMaskIntoConstraints = false var anchors = [NSLayoutConstraint]() if let top = top { anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant)) } if let left = left { anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant)) } if let bottom = bottom { anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant)) } if let right = right { anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant)) } if widthConstant > 0 { anchors.append(widthAnchor.constraint(equalToConstant: widthConstant)) } if heightConstant > 0 { anchors.append(heightAnchor.constraint(equalToConstant: heightConstant)) } anchors.forEach({$0.isActive = true}) return anchors } public func anchorCenterXToSuperview(constant: CGFloat = 0) { translatesAutoresizingMaskIntoConstraints = false if let anchor = superview?.centerXAnchor { centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true } } public func anchorCenterYToSuperview(constant: CGFloat = 0) { translatesAutoresizingMaskIntoConstraints = false if let anchor = superview?.centerYAnchor { centerYAnchor.constraint(equalTo: anchor, constant: constant).isActive = true } } public func anchorCenterSuperview() { anchorCenterXToSuperview() anchorCenterYToSuperview() } }
mit
9bae4d7e10e95c4ac45e76bdef39b1ed
38.48913
370
0.71924
5.124118
false
false
false
false
Jude309307972/JudeTest
Calculator/CalculatorBrain.swift
1
2170
// // CalculatorBrain.swift // Calculator // // Created by 徐遵成 on 15/10/3. // Copyright © 2015年 Jude. All rights reserved. // import Foundation class CalculatorBrain { init() { knownOps["×"] = Op.BinaryOperation("×"){$0 * $1} knownOps["÷"] = Op.BinaryOperation("÷"){$1 / $0} knownOps["+"] = Op.BinaryOperation("+"){$0 + $1} knownOps["−"] = Op.BinaryOperation("−"){$1 - $0} knownOps["√"] = Op.UnaryOperation("√"){sqrt($0) } } private enum Op { case Operand(Double) case UnaryOperation(String,Double ->Double) case BinaryOperation(String,(Double,Double) ->Double) } private var opStack = [Op]() func pushOperand(operand:Double){ opStack.append(Op.Operand(operand)) } private var knownOps = [String:Op]() //var knownOps = Dictionary<String,Op>() func performOperation(symbol:String) { let option = knownOps[symbol] } private func evaluate(ops:[Op]) -> (result:Double?,remainingOps:[Op]){ var remainingOps = ops if !ops.isEmpty{ let op = remainingOps.removeLast() switch op { case .Operand(let operand): return (operand,remainingOps) case .UnaryOperation(_, let operation): let operandEvaluation = evaluate(remainingOps) if let operand = operandEvaluation.result { return (operation(operand),operandEvaluation.remainingOps) } case .BinaryOperation(_, let operation): let op1Evaluation = evaluate(remainingOps) if let operand1 = op1Evaluation.result { let op2Evaluation = evaluate(op1Evaluation.remainingOps) if let operand2 = op2Evaluation.result{ return (operation(operand1,operand2),op2Evaluation.remainingOps) } } } } return (nil,ops) } func evaluate()-> Double?{ let (result,remainder) = evaluate(opStack) return result } }
apache-2.0
ed649bba6cfa55718894f371627f86d3
30.602941
88
0.550954
4.449275
false
false
false
false
tkremenek/swift
stdlib/public/core/BidirectionalCollection.swift
10
15604
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// A collection that supports backward as well as forward traversal. /// /// Bidirectional collections offer traversal backward from any valid index, /// not including a collection's `startIndex`. Bidirectional collections can /// therefore offer additional operations, such as a `last` property that /// provides efficient access to the last element and a `reversed()` method /// that presents the elements in reverse order. In addition, bidirectional /// collections have more efficient implementations of some sequence and /// collection methods, such as `suffix(_:)`. /// /// Conforming to the BidirectionalCollection Protocol /// ================================================== /// /// To add `BidirectionalProtocol` conformance to your custom types, implement /// the `index(before:)` method in addition to the requirements of the /// `Collection` protocol. /// /// Indices that are moved forward and backward in a bidirectional collection /// move by the same amount in each direction. That is, for any index `i` into /// a bidirectional collection `c`: /// /// - If `i >= c.startIndex && i < c.endIndex`, /// `c.index(before: c.index(after: i)) == i`. /// - If `i > c.startIndex && i <= c.endIndex` /// `c.index(after: c.index(before: i)) == i`. public protocol BidirectionalCollection: Collection where SubSequence: BidirectionalCollection, Indices: BidirectionalCollection { // FIXME: Only needed for associated type inference. override associatedtype Element override associatedtype Index override associatedtype SubSequence override associatedtype Indices /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index value immediately before `i`. func index(before i: Index) -> Index /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. func formIndex(before i: inout Index) /// Returns the position immediately after the given index. /// /// The successor of an index must be well defined. For an index `i` into a /// collection `c`, calling `c.index(after: i)` returns the same index every /// time. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. override func index(after i: Index) -> Index /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. override func formIndex(after i: inout Index) /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute /// value of `distance`. @_nonoverride func index(_ i: Index, offsetBy distance: Int) -> Index /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, a limit that is less than `i` has no effect. /// Likewise, if `distance < 0`, a limit that is greater than `i` has no /// effect. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute /// value of `distance`. @_nonoverride func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? /// Returns the distance between two indices. /// /// Unless the collection conforms to the `BidirectionalCollection` protocol, /// `start` must be less than or equal to `end`. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. The result can be /// negative only if the collection conforms to the /// `BidirectionalCollection` protocol. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the /// resulting distance. @_nonoverride func distance(from start: Index, to end: Index) -> Int /// The indices that are valid for subscripting the collection, in ascending /// order. /// /// A collection's `indices` property can hold a strong reference to the /// collection itself, causing the collection to be non-uniquely referenced. /// If you mutate the collection while iterating over its indices, a strong /// reference can cause an unexpected copy of the collection. To avoid the /// unexpected copy, use the `index(after:)` method starting with /// `startIndex` to produce indices instead. /// /// var c = MyFancyCollection([10, 20, 30, 40, 50]) /// var i = c.startIndex /// while i != c.endIndex { /// c[i] /= 5 /// i = c.index(after: i) /// } /// // c == MyFancyCollection([2, 4, 6, 8, 10]) override var indices: Indices { get } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) override subscript(bounds: Range<Index>) -> SubSequence { get } // FIXME: Only needed for associated type inference. @_borrowed override subscript(position: Index) -> Element { get } override var startIndex: Index { get } override var endIndex: Index { get } } /// Default implementation for bidirectional collections. extension BidirectionalCollection { @inlinable // protocol-only @inline(__always) public func formIndex(before i: inout Index) { i = index(before: i) } @inlinable // protocol-only public func index(_ i: Index, offsetBy distance: Int) -> Index { return _index(i, offsetBy: distance) } @inlinable // protocol-only internal func _index(_ i: Index, offsetBy distance: Int) -> Index { if distance >= 0 { return _advanceForward(i, by: distance) } var i = i for _ in stride(from: 0, to: distance, by: -1) { formIndex(before: &i) } return i } @inlinable // protocol-only public func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { return _index(i, offsetBy: distance, limitedBy: limit) } @inlinable // protocol-only internal func _index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { if distance >= 0 { return _advanceForward(i, by: distance, limitedBy: limit) } var i = i for _ in stride(from: 0, to: distance, by: -1) { if i == limit { return nil } formIndex(before: &i) } return i } @inlinable // protocol-only public func distance(from start: Index, to end: Index) -> Int { return _distance(from: start, to: end) } @inlinable // protocol-only internal func _distance(from start: Index, to end: Index) -> Int { var start = start var count = 0 if start < end { while start != end { count += 1 formIndex(after: &start) } } else if start > end { while start != end { count -= 1 formIndex(before: &start) } } return count } } extension BidirectionalCollection where SubSequence == Self { /// Removes and returns the last element of the collection. /// /// You can use `popLast()` to remove the last element of a collection that /// might be empty. The `removeLast()` method must be used only on a /// nonempty collection. /// /// - Returns: The last element of the collection if the collection has one /// or more elements; otherwise, `nil`. /// /// - Complexity: O(1) @inlinable // protocol-only public mutating func popLast() -> Element? { guard !isEmpty else { return nil } let element = last! self = self[startIndex..<index(before: endIndex)] return element } /// Removes and returns the last element of the collection. /// /// The collection must not be empty. To remove the last element of a /// collection that might be empty, use the `popLast()` method instead. /// /// - Returns: The last element of the collection. /// /// - Complexity: O(1) @inlinable // protocol-only @discardableResult public mutating func removeLast() -> Element { let element = last! self = self[startIndex..<index(before: endIndex)] return element } /// Removes the given number of elements from the end of the collection. /// /// - Parameter k: The number of elements to remove. `k` must be greater /// than or equal to zero, and must be less than or equal to the number of /// elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of /// elements to remove. @inlinable // protocol-only public mutating func removeLast(_ k: Int) { if k == 0 { return } _precondition(k >= 0, "Number of elements to remove should be non-negative") guard let end = index(endIndex, offsetBy: -k, limitedBy: startIndex) else { _preconditionFailure( "Can't remove more items from a collection than it contains") } self = self[startIndex..<end] } } extension BidirectionalCollection { /// Returns a subsequence containing all but the specified number of final /// elements. /// /// If the number of elements to drop exceeds the number of elements in the /// collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter k: The number of elements to drop off the end of the /// collection. `k` must be greater than or equal to zero. /// - Returns: A subsequence that leaves off `k` elements from the end. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of /// elements to drop. @inlinable // protocol-only public __consuming func dropLast(_ k: Int) -> SubSequence { _precondition( k >= 0, "Can't drop a negative number of elements from a collection") let end = index( endIndex, offsetBy: -k, limitedBy: startIndex) ?? startIndex return self[startIndex..<end] } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the collection. /// /// If the maximum length exceeds the number of elements in the collection, /// the result contains the entire collection. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of the collection with at /// most `maxLength` elements. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is equal to /// `maxLength`. @inlinable // protocol-only public __consuming func suffix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a suffix of negative length from a collection") let start = index( endIndex, offsetBy: -maxLength, limitedBy: startIndex) ?? startIndex return self[start..<endIndex] } }
apache-2.0
62898e94636946d08d3ba227d4e25540
36.419664
80
0.637529
4.195752
false
false
false
false
zyhndesign/DesignCourse
DesignCourse/DesignCourse/views/TopicsTableViewCell.swift
1
5780
// // TopicsTableViewCell.swift // DesignCourse // // Created by lotusprize on 15/10/10. // Copyright © 2015年 geekTeam. All rights reserved. // import UIKit import Haneke class TopicsTableViewCell: UIView { var timeTextLayer:CATextLayer! var titleTextLayer:CATextLayer! var authorTextLayer:CATextLayer! var abstractTextLayer:CATextLayer! var imageLayer1:CALayer! var imageLayer2:CALayer! var imageLayer3:CALayer! var imageLayer4:CALayer! var iconLayer:CALayer! var shareTextLayer:CATextLayer! var topicsModel:TopicsModel! let cache = Shared.imageCache init() { print("init topics table view cell...") super.init(frame:CGRect.zero) } override init(frame: CGRect) { super.init(frame: frame) } func initTopicsModel(topicsModel:TopicsModel){ self.topicsModel = topicsModel } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override func drawRect(rect: CGRect) { let retinaScreen:Bool = (UIScreen.mainScreen().currentMode?.size.width == 768) print(retinaScreen) timeTextLayer = CATextLayer() timeTextLayer.frame = CGRectMake(20.0, 20.0, 200, 15) timeTextLayer.fontSize = 14.0 timeTextLayer.foregroundColor = UIColor(red: 42.0/255.0, green: 58.0/255.0, blue: 97.0/255.0, alpha: 1.0).CGColor self.layer.addSublayer(timeTextLayer) titleTextLayer = CATextLayer() titleTextLayer.frame = CGRectMake(20.0, 49.0, 520, 36) titleTextLayer.fontSize = 30.0 titleTextLayer.foregroundColor = UIColor(red: 42.0/255.0, green: 58.0/255.0, blue: 97.0/255.0, alpha: 1.0).CGColor self.layer.addSublayer(titleTextLayer) authorTextLayer = CATextLayer() authorTextLayer.frame = CGRectMake(20.0, 92.0, 520, 36) authorTextLayer.fontSize = 18.0 authorTextLayer.foregroundColor = UIColor(red: 247/255.0, green: 182/255.0, blue: 0, alpha: 1.0).CGColor self.layer.addSublayer(authorTextLayer) abstractTextLayer = CATextLayer() abstractTextLayer.frame = CGRectMake(20, 128, 520, 193) abstractTextLayer.fontSize = 14.0 abstractTextLayer.alignmentMode = kCAAlignmentLeft abstractTextLayer.foregroundColor = UIColor(red: 122/255.0, green: 124/255.0, blue: 127/255.0, alpha: 1.0).CGColor if (retinaScreen) { timeTextLayer.contentsScale = 1.0 titleTextLayer.contentsScale = 1.0 authorTextLayer.contentsScale = 1.0 abstractTextLayer.contentsScale = 1.0 } else { timeTextLayer.contentsScale = 2.0 titleTextLayer.contentsScale = 2.0 authorTextLayer.contentsScale = 2.0 abstractTextLayer.contentsScale = 2.0 } abstractTextLayer.wrapped = true self.layer.addSublayer(abstractTextLayer) imageLayer1 = CALayer() imageLayer1.frame = CGRectMake(594, 0, 193, 193) self.layer.addSublayer(imageLayer1) imageLayer2 = CALayer() imageLayer2.frame = CGRectMake(797, 0, 193, 193) self.layer.addSublayer(imageLayer2) imageLayer3 = CALayer() imageLayer3.frame = CGRectMake(594, 193, 193, 193) self.layer.addSublayer(imageLayer3) imageLayer4 = CALayer() imageLayer4.frame = CGRectMake(797, 193, 193, 193) self.layer.addSublayer(imageLayer4) iconLayer = CALayer() iconLayer.frame = CGRectMake(20, 340, 18, 15) iconLayer.contents = UIImage(named: "worksIcon")?.CGImage self.layer.addSublayer(iconLayer) shareTextLayer = CATextLayer() shareTextLayer.frame = CGRectMake(40, 340, 100, 15) shareTextLayer.fontSize = 14.0 shareTextLayer.foregroundColor = UIColor(red: 122/255.0, green: 124/255.0, blue: 127/255.0, alpha: 1.0).CGColor self.layer.addSublayer(shareTextLayer) timeTextLayer.string = topicsModel.timeTextValue titleTextLayer.string = topicsModel.titleTextValue authorTextLayer.string = topicsModel.authorTextValue abstractTextLayer.string = topicsModel.abstractTextValue shareTextLayer.string = topicsModel.shareTextValue if let image1URL = topicsModel.image1Url{ let imageURL = NSURL(string: image1URL)! let fetcher = NetworkFetcher<UIImage>(URL: imageURL) cache.fetch(fetcher: fetcher).onSuccess { image in self.imageLayer1.contents = image.CGImage } } if let image2URL = topicsModel.image2Url{ let imageURL = NSURL(string: image2URL)! let fetcher = NetworkFetcher<UIImage>(URL: imageURL) cache.fetch(fetcher: fetcher).onSuccess { image in self.imageLayer2.contents = image.CGImage } } if let image3URL = topicsModel.image3Url{ let imageURL = NSURL(string: image3URL)! let fetcher = NetworkFetcher<UIImage>(URL: imageURL) cache.fetch(fetcher: fetcher).onSuccess { image in self.imageLayer3.contents = image.CGImage } } if let image4URL = topicsModel.image4Url{ let imageURL = NSURL(string: image4URL)! let fetcher = NetworkFetcher<UIImage>(URL: imageURL) cache.fetch(fetcher: fetcher).onSuccess { image in self.imageLayer4.contents = image.CGImage } } } }
apache-2.0
1ac8fec607538d737d3d32d666eff087
34.22561
122
0.618833
4.49572
false
false
false
false
hyperoslo/AsyncWall
Source/Nodes/Defaults/ActionBarNode.swift
1
2354
import UIKit import AsyncDisplayKit public class ActionBarNode: PostComponentNode { // MARK: - Configuration public var dividerHeight: CGFloat = 1 public override var height: CGFloat { return 40 } // MARK: - Nodes public lazy var likeControlNode: ControlNode = { var title = NSAttributedString( string: NSLocalizedString("Like", comment: ""), attributes: [ NSFontAttributeName: UIFont.boldSystemFontOfSize(14), NSForegroundColorAttributeName: UIColor.lightGrayColor() ]) let node = ControlNode(title: title) node.userInteractionEnabled = true return node }() public lazy var commentControlNode: ControlNode = { var title = NSAttributedString( string: NSLocalizedString("Comment", comment: ""), attributes: [ NSFontAttributeName: UIFont.boldSystemFontOfSize(14), NSForegroundColorAttributeName: UIColor.lightGrayColor() ]) let node = ControlNode(title: title) node.userInteractionEnabled = true return node }() public lazy var divider: ASDisplayNode = { let divider = ASDisplayNode() divider!.backgroundColor = .lightGrayColor() return divider }() public override var actionNodes: [TappedNode] { return [(node: likeControlNode, element: .LikeButton), (node: commentControlNode, element: .CommentButton)] } // MARK: - ConfigurableNode public override func configureNode() { for node in [divider, likeControlNode, commentControlNode] { addSubnode(node) } } // MARK: - Layout override public func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize { return CGSizeMake(width, height) } override public func layout() { var x: CGFloat = 0 let sideSize = CGSize(width: width / 2, height: height) divider.frame = CGRect( x: 0, y: 0, width: width, height: dividerHeight) if !likeControlNode.hidden { likeControlNode.frame = CGRect( origin: likeControlNode.size.centerInSize(sideSize), size: likeControlNode.size) x += sideSize.width } if !commentControlNode.hidden { var origin = commentControlNode.size.centerInSize(sideSize) origin.x += x commentControlNode.frame = CGRect( origin: origin, size: commentControlNode.size) } } }
mit
40d5b33752573d1cbae19f1b7747e210
23.520833
81
0.669924
4.642998
false
false
false
false
cuzv/ExtensionKit
Sources/Extension/UIView+Extension.swift
1
34031
// // UIView+Extension.swift // Copyright (c) 2015-2016 Red Rain (http://mochxiao.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 UIKit // MARK: - AssociationKey private struct AssociationKey { fileprivate static var gestureRecognizerWrapper: String = "com.mochxiao.uiview.gestureRecognizerWrapper" fileprivate static var activityIndicatorView: String = "com.mochxiao.uiview.activityIndicatorView" fileprivate static var arcIndicatorLayer: String = "com.mochxiao.uiview.arcIndicatorLayer" fileprivate static var isRoundingCornersExists: String = "com.mochxiao.uiview.isRoundingCornersExists" /// ActionTrampoline fileprivate static var singleTapGestureRecognizer: String = "com.mochxiao.uiview.singleTapGestureRecognizer" fileprivate static var doubleTapGestureRecognizer: String = "com.mochxiao.uiview.doubleTapGestureRecognizer" fileprivate static var longPressGestureRecognizer: String = "com.mochxiao.uiview.longPressGestureRecognizer" fileprivate static var touchExtendInsets: String = "touchExtendInsets" } // MARK: - UIGestureRecognizer // MARK: The `ClosureDecorator` implement private extension UIGestureRecognizer { var gestureRecognizerWrapper: ClosureDecorator<(UIView, UIGestureRecognizer)> { get { return associatedObject(forKey: &AssociationKey.gestureRecognizerWrapper) as! ClosureDecorator<(UIView, UIGestureRecognizer)> } set { associate(retainObject: newValue, forKey: &AssociationKey.gestureRecognizerWrapper) } } } public extension UIView { /// Single tap action closure func. /// **Note**: You should invoke `longPressAction:` or `doubleTapsAction` first if you need. public func tapAction(_ action: @escaping ((UIView, UIGestureRecognizer?) -> ())) { isUserInteractionEnabled = true let tapGesureRecognizer = UITapGestureRecognizer( target: self, action: #selector(UIView.handleGestureRecognizerAction(_:)) ) checkRequireGestureRecognizerToFailForSingleTapGesureRecognizer(tapGesureRecognizer) addGestureRecognizer(tapGesureRecognizer) tapGesureRecognizer.gestureRecognizerWrapper = ClosureDecorator(action) } /// Dobule tap action closure func. /// **Note**: You should invoke `longPressAction:` first if you need. public func doubleTapsAction(_ action: @escaping (UIView, UIGestureRecognizer?) -> ()) { isUserInteractionEnabled = true let doubleTapGesureRecognizer = UITapGestureRecognizer( target: self, action: #selector(UIView.handleGestureRecognizerAction(_:)) ) doubleTapGesureRecognizer.numberOfTapsRequired = 2 checkRequireGestureRecognizerToFailForDoubleTapGesureRecognizer(doubleTapGesureRecognizer) addGestureRecognizer(doubleTapGesureRecognizer) doubleTapGesureRecognizer.gestureRecognizerWrapper = ClosureDecorator(action) } /// Long press action closure func. public func longPressAction(_ action: @escaping (UIView, UIGestureRecognizer?) -> ()) { isUserInteractionEnabled = true let longPressGesureRecognizer = UILongPressGestureRecognizer( target: self, action: #selector(UIView.handleGestureRecognizerAction(_:)) ) addGestureRecognizer(longPressGesureRecognizer) longPressGesureRecognizer.gestureRecognizerWrapper = ClosureDecorator(action) } @objc internal func handleGestureRecognizerAction(_ sender: UIGestureRecognizer) { if (sender.state == .ended) { sender.gestureRecognizerWrapper.invoke((self, sender)) } } } private extension UIView { func checkRequireGestureRecognizerToFailForSingleTapGesureRecognizer(_ tapGesureRecognizer: UITapGestureRecognizer) { if let gestureRecognizers = gestureRecognizers { for gestureRecognizer in gestureRecognizers { if let tapGestureRecognizer = gestureRecognizer as? UITapGestureRecognizer, tapGestureRecognizer.numberOfTapsRequired > 1 { tapGesureRecognizer.require(toFail: gestureRecognizer) } else if gestureRecognizer is UILongPressGestureRecognizer { tapGesureRecognizer.require(toFail: gestureRecognizer) } } } } func checkRequireGestureRecognizerToFailForDoubleTapGesureRecognizer(_ doubleTapGesureRecognizer: UITapGestureRecognizer) { if let gesturesRecognizers = gestureRecognizers { for gesturesRecognizer in gesturesRecognizers { if gesturesRecognizer is UILongPressGestureRecognizer { doubleTapGesureRecognizer.require(toFail: gesturesRecognizer) } } } } } // MARK: The `ActionTrampoline` implement @objc public protocol UIGestureRecognizerFunctionProtocol {} extension UIView: UIGestureRecognizerFunctionProtocol {} public extension UIGestureRecognizerFunctionProtocol where Self: UIView { /// Single tap action closure func. /// **Note**: You should invoke `longPressAction:` or `tripleTapsAction` first if you need. public func tapAction(_ action: @escaping ((Self) -> ())) { isUserInteractionEnabled = true let trampoline = ActionTrampoline(action: action) let tapGestureRecognizer = UITapGestureRecognizer( target: trampoline, action: trampoline.selector ) checkRequireGestureRecognizerToFailForSingleTapGesureRecognizer(tapGestureRecognizer) addGestureRecognizer(tapGestureRecognizer) associate(retainObject: trampoline, forKey: &AssociationKey.singleTapGestureRecognizer) } /// Dobule taps action closure func. /// **Note**: You should invoke `longPressAction:` or `tripleTapsAction` first if you need. public func doubleTapsAction(_ action: @escaping (Self) -> ()) { isUserInteractionEnabled = true let trampoline = ActionTrampoline(action: action) let doubleTapGesureRecognizer = UITapGestureRecognizer( target: trampoline, action: trampoline.selector ) doubleTapGesureRecognizer.numberOfTapsRequired = 2 checkRequireGestureRecognizerToFailForDoubleTapGesureRecognizer(doubleTapGesureRecognizer) addGestureRecognizer(doubleTapGesureRecognizer) associate(retainObject: trampoline, forKey: &AssociationKey.doubleTapGestureRecognizer) } /// Triple taps action closure func. /// **Note**: You should invoke `longPressAction:` or `tripleTapsAction` first if you need. public func tripleTapsAction(_ action: @escaping (Self) -> ()) { isUserInteractionEnabled = true let trampoline = ActionTrampoline(action: action) let doubleTapGesureRecognizer = UITapGestureRecognizer( target: trampoline, action: trampoline.selector ) doubleTapGesureRecognizer.numberOfTapsRequired = 3 checkRequireGestureRecognizerToFailForDoubleTapGesureRecognizer(doubleTapGesureRecognizer) addGestureRecognizer(doubleTapGesureRecognizer) associate(retainObject: trampoline, forKey: &AssociationKey.doubleTapGestureRecognizer) } /// Multiple tap action closure func. /// **Note**: You should invoke `longPressAction:` or `tripleTapsAction` first if you need. public func multipleTaps(numberOfTapsRequired taps: Int, action: @escaping (Self) -> ()) { isUserInteractionEnabled = true let trampoline = ActionTrampoline(action: action) let doubleTapGesureRecognizer = UITapGestureRecognizer( target: trampoline, action: trampoline.selector ) doubleTapGesureRecognizer.numberOfTapsRequired = taps checkRequireGestureRecognizerToFailForDoubleTapGesureRecognizer(doubleTapGesureRecognizer) addGestureRecognizer(doubleTapGesureRecognizer) associate(retainObject: trampoline, forKey: &AssociationKey.doubleTapGestureRecognizer) } /// Long press action closure func. public func longPressAction(_ action: @escaping (Self) -> ()) { isUserInteractionEnabled = true let trampoline = ActionTrampoline(action: action) let longPressGesureRecognizer = UILongPressGestureRecognizer( target: trampoline, action: trampoline.selector ) addGestureRecognizer(longPressGesureRecognizer) associate(retainObject: trampoline, forKey: &AssociationKey.longPressGestureRecognizer) } } // MARK: - Responder public extension UIView { public var responderViewController: UIViewController? { return responder(ofClass: UIViewController.self) as? UIViewController } } // MARK: - Frame & Struct public extension UIView { public var origin: CGPoint { get { return frame.origin } set { frame = CGRect(x: newValue.x, y: newValue.y, width: width, height: height) } } public var size: CGSize { get { return frame.size } set { frame = CGRect(x: minX, y: minY, width: newValue.width, height: newValue.height) } } public var minX: CGFloat { get { return frame.origin.x } set { frame = CGRect(x: newValue, y: minY, width: width, height: height) } } public var left: CGFloat { get { return frame.origin.x } set { frame = CGRect(x: newValue, y: minY, width: width, height: height) } } public var midX: CGFloat { get { return frame.midX } set { frame = CGRect(x: newValue - width * 0.5, y: minY, width: width, height: height) } } public var centerX: CGFloat { get { return frame.midX } set { frame = CGRect(x: newValue - width * 0.5, y: minY, width: width, height: height) } } public var maxX: CGFloat { get { return minX + width } set { frame = CGRect(x: newValue - width, y: minY, width: width, height: height) } } public var right: CGFloat { get { return minX + width } set { frame = CGRect(x: newValue - width, y: minY, width: width, height: height) } } public var minY: CGFloat { get { return frame.origin.y } set { frame = CGRect(x: minX, y: newValue, width: width, height: height) } } public var top: CGFloat { get { return frame.origin.y } set { frame = CGRect(x: minX, y: newValue, width: width, height: height) } } public var midY: CGFloat { get { return frame.midY } set { frame = CGRect(x: minX, y: newValue - height * 0.5, width: width, height: height) } } public var centerY: CGFloat { get { return frame.midY } set { frame = CGRect(x: minX, y: newValue - height * 0.5, width: width, height: height) } } public var maxY: CGFloat { get { return minY + height } set { frame = CGRect(x: minX, y: newValue - height, width: width, height: height) } } public var bottom: CGFloat { get { return minY + height } set { frame = CGRect(x: minX, y: newValue - height, width: width, height: height) } } public var width: CGFloat { get { return bounds.width } set { frame = CGRect(x: minX, y: minY, width: newValue, height: height) } } public var height: CGFloat { get { return bounds.height } set { frame = CGRect(x: minX, y: minY, width: width, height: newValue) } } } // MARK: - Border public extension UIView { public var borderWith: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } public var borderColor: UIColor? { get { if let CGColor = layer.borderColor { return UIColor(cgColor: CGColor) } else { return nil } } set { layer.borderColor = newValue?.cgColor } } /// Setup border width & color. public func setBorder( width: CGFloat = 1.0 / UIScreen.main.scale, color: UIColor = UIColor.separator) { layer.borderWidth = width layer.borderColor = color.cgColor } /// Add dash border line view using CAShapeLayer. /// **Note**: Before you invoke this method, ensure `self` already have correct frame. /// Because using CAShapeLayer, can not remove it, make sure add only once. public func addDashBorderline( for rectEdge: UIRectEdge = .all, width: CGFloat = 1.0 / UIScreen.main.scale, color: UIColor = UIColor.separator, multiplier: CGFloat = 1, constant: CGFloat = 0, lineDashPattern: [CGFloat] = [5, 5]) { func makeLineLayer( width: CGFloat, color: UIColor, lineDashPattern: [CGFloat], startPoint: CGPoint, endPoint: CGPoint) -> CAShapeLayer { let lineLayer = CAShapeLayer() lineLayer.lineDashPattern = lineDashPattern as [NSNumber]? lineLayer.strokeColor = color.cgColor lineLayer.fillColor = UIColor.clear.cgColor lineLayer.lineJoin = kCALineJoinRound lineLayer.lineWidth = width let path = CGMutablePath() path.move(to: CGPoint(x: startPoint.x, y: startPoint.y)) path.addLine(to: CGPoint(x: endPoint.x, y: endPoint.y)) lineLayer.path = path return lineLayer } let w = bounds.size.width let h = bounds.size.height let startX = 0.5 * w * (1.0 - multiplier) + 0.5 * constant let endX = 0.5 * w * (1.0 + multiplier) - 0.5 * constant let startY = 0.5 * h * (1.0 - multiplier) + 0.5 * constant let endY = 0.5 * h * (1.0 + multiplier) - 0.5 * constant if rectEdge.contains(.top) { let lineLayer = makeLineLayer( width: width, color: color, lineDashPattern: lineDashPattern, startPoint: CGPoint(x: startX, y: 0), endPoint: CGPoint(x: endX, y: 0) ) layer.addSublayer(lineLayer) } if rectEdge.contains(.left) { let lineLayer = makeLineLayer( width: width, color: color, lineDashPattern: lineDashPattern, startPoint: CGPoint(x: 0, y: startY), endPoint: CGPoint(x: 0, y: endY) ) layer.addSublayer(lineLayer) } if rectEdge.contains(.bottom) { let lineLayer = makeLineLayer( width: width, color: color, lineDashPattern: lineDashPattern, startPoint: CGPoint(x: startX, y: h), endPoint: CGPoint(x: endX, y: h) ) layer.addSublayer(lineLayer) } if rectEdge.contains(.right) { let lineLayer = makeLineLayer( width: width, color: color, lineDashPattern: lineDashPattern, startPoint: CGPoint(x: w, y: startY), endPoint: CGPoint(x: w, y: endY) ) layer.addSublayer(lineLayer) } } fileprivate class _BorderLineView: UIView { fileprivate var edge: UIRectEdge fileprivate init(edge: UIRectEdge) { self.edge = edge super.init(frame: CGRect.zero) } required fileprivate init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } /// Add border line view using Autolayout. public func addBorderline( for rectEdge: UIRectEdge = .all, width: CGFloat = 1.0 / UIScreen.main.scale, color: UIColor = UIColor.separator, multiplier: CGFloat = 1.0, constant: CGFloat = 0) { func addLineViewConstraints( edge: NSLayoutAttribute, center: NSLayoutAttribute, size: NSLayoutAttribute, visualFormat: String, color: UIColor, multiplier: CGFloat, rectEdge: UIRectEdge) { let lineView = _BorderLineView(edge: rectEdge) lineView.backgroundColor = color lineView.translatesAutoresizingMaskIntoConstraints = false addSubview(lineView) let edgeConstraint = NSLayoutConstraint( item: lineView, attribute: edge, relatedBy: .equal, toItem: self, attribute: edge, multiplier: 1, constant: 0 ) let centerConstraint = NSLayoutConstraint( item: lineView, attribute: center, relatedBy: .equal, toItem: self, attribute: center, multiplier: 1, constant: 0 ) let sizeConstraint = NSLayoutConstraint( item: lineView, attribute: size, relatedBy: .equal, toItem: self, attribute: size, multiplier: multiplier, constant: constant ) addConstraints([edgeConstraint, centerConstraint, sizeConstraint]) let constraints = NSLayoutConstraint.constraints( withVisualFormat: visualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["lineView": lineView] ) addConstraints(constraints) } if rectEdge == UIRectEdge() { return } for view in subviews { if let view = view as? _BorderLineView , rectEdge.contains(view.edge) { return } } if rectEdge.contains(.top) { addLineViewConstraints( edge: .top, center: .centerX, size: .width, visualFormat: "V:[lineView(\(width))]", color: color, multiplier: multiplier, rectEdge: .top ) } if rectEdge.contains(.left) { addLineViewConstraints( edge: .left, center: .centerY, size: .height, visualFormat: "[lineView(\(width))]", color: color, multiplier: multiplier, rectEdge: .left ) } if rectEdge.contains(.bottom) { addLineViewConstraints( edge: .bottom, center: .centerX, size: .width, visualFormat: "V:[lineView(\(width))]", color: color, multiplier: multiplier, rectEdge: .bottom ) } if rectEdge.contains(.right) { addLineViewConstraints( edge: .right, center: .centerY, size: .height, visualFormat: "[lineView(\(width))]", color: color, multiplier: multiplier, rectEdge: .right ) } } /// Remove added border line view. public func removeBorderline(for rectEdge: UIRectEdge = .all) { if rectEdge == UIRectEdge() { return } for view in subviews { if let view = view as? _BorderLineView , rectEdge.contains(view.edge) { view.removeFromSuperview() } } } } // MARK: - Corner public extension UIView { public var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.masksToBounds = newValue > 0 layer.cornerRadius = newValue } } public internal(set) var isRoundingCornersExists: Bool { get { if let value = associatedObject(forKey: &AssociationKey.isRoundingCornersExists) as? Bool { return value } return false } set { associate(assignObject: newValue, forKey: &AssociationKey.isRoundingCornersExists) } } /// Add rounding corners radius. /// **Note**: Before you invoke this method, ensure `self` already have correct frame. public func addRoundingCorners( for corners: UIRectCorner = .allCorners, radius: CGFloat = 3, fillColor: UIColor? = nil, strokeColor: UIColor? = nil, strokeLineWidth: CGFloat = 0) { if frame.size.equalTo(CGSize.zero) { logging("Could not set rounding corners on zero size view.") return } DispatchQueue.global().async { let backImage = UIImage.make( color: fillColor ?? self.backgroundColor ?? UIColor.white, size: self.frame.size, roundingCorners: corners, radius: radius, strokeColor: strokeColor ?? self.backgroundColor ?? UIColor.clear, strokeLineWidth: strokeLineWidth ) DispatchQueue.main.async { self.backgroundColor = UIColor.clear self.layer.contents = backImage?.cgImage self.isRoundingCornersExists = true } } } /// This will remove all added rounding corners on self public func removeRoundingCorners() { layer.contents = nil isRoundingCornersExists = false } } // MARK: - Blur public extension UIView { @available(iOS 8.0, *) public class func blurEffect(style: UIBlurEffectStyle = .extraLight) -> UIView { let blurView = UIVisualEffectView(frame: CGRect.zero) blurView.effect = UIBlurEffect(style: style) return blurView } @available(iOS 8.0, *) public func addBlurEffectView(style: UIBlurEffectStyle = .extraLight, useAutolayout: Bool = true) -> UIView { let blurView = UIView.blurEffect(style: style) blurView.frame = bounds addSubview(blurView) if useAutolayout { blurView.translatesAutoresizingMaskIntoConstraints = false addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "|[blurView]|", options: .directionLeadingToTrailing, metrics: nil, views: ["blurView": blurView] )) addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "V:|[blurView]|", options: .directionLeadingToTrailing, metrics: nil, views: ["blurView": blurView] )) } return blurView } @available(iOS 6.0, *) public class func speclEffect(style: UIBarStyle = .default) -> UIView { let speclEffectView = UIToolbar(frame: CGRect.zero) speclEffectView.barStyle = style speclEffectView.isTranslucent = true return speclEffectView } @available(iOS 6.0, *) public func addSpeclEffectView(style: UIBarStyle = .default, useAutolayout: Bool = true) -> UIView { let speclEffectView = UIView.speclEffect(style: style) speclEffectView.frame = bounds if useAutolayout { speclEffectView.translatesAutoresizingMaskIntoConstraints = false addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "|[speclEffectView]|", options: .directionLeadingToTrailing, metrics: nil, views: ["speclEffectView": speclEffectView] )) addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "V:|[speclEffectView]|", options: .directionLeadingToTrailing, metrics: nil, views: ["speclEffectView": speclEffectView] )) } return speclEffectView } } // MARK: - UIActivityIndicatorView public extension UIView { fileprivate var activityIndicatorView: UIActivityIndicatorView? { get { return associatedObject(forKey: &AssociationKey.activityIndicatorView) as? UIActivityIndicatorView } set { associate(assignObject: newValue, forKey: &AssociationKey.activityIndicatorView) } } fileprivate func correspondCenter(dy: CGFloat) -> CGPoint { var newCenter = CGPoint(x: bounds.size.width * 0.5, y: bounds.size.height * 0.5) newCenter.y += dy return newCenter } /// Add activity indicator animation. public func startActivityIndicatorAnimation(indicatorColor color: UIColor = UIColor.lightGray, dy: CGFloat = 0) { if isActivityIndicatorAnimating { return } if let activityIndicatorView = self.activityIndicatorView { activityIndicatorView.color = color activityIndicatorView.center = correspondCenter(dy: dy) activityIndicatorView.isHidden = false activityIndicatorView.startAnimating() return } let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .white) activityIndicatorView.color = color activityIndicatorView.center = correspondCenter(dy: dy) activityIndicatorView.isUserInteractionEnabled = false activityIndicatorView.clipsToBounds = true addSubview(activityIndicatorView) activityIndicatorView.startAnimating() self.activityIndicatorView = activityIndicatorView } public func stopActivityIndicatorAnimation() { activityIndicatorView?.stopAnimating() activityIndicatorView?.isHidden = true } public var isActivityIndicatorAnimating: Bool { if let activityIndicatorView = activityIndicatorView { return activityIndicatorView.isAnimating } else { return false } } } // MARK: - bgColor public extension UIView { public var bgColor: UIColor? { if let bgColor = backgroundColor { return bgColor } if let superview = superview { return superview.bgColor } return nil } } // MARK: - Arc Animation public extension UIView { fileprivate var arcIndicatorLayer: CAShapeLayer! { get { return associatedObject(forKey: &AssociationKey.arcIndicatorLayer) as? CAShapeLayer } set { associate(assignObject: newValue, forKey: &AssociationKey.arcIndicatorLayer) } } fileprivate var stokeAnimationKey: String { return "stokeAnimation" } fileprivate func makeArcIndicatorLayer(lineWidth: CGFloat = 2, lineColor: UIColor = UIColor.lightGray) -> CAShapeLayer { let half = min(bounds.midX, bounds.midY) let path = UIBezierPath() path.addArc( withCenter: CGPoint(x: bounds.midX, y: bounds.midY), radius: half, startAngle: CGFloat(-90).radian, endAngle: CGFloat(270).radian, clockwise: true ) let arcIndicatorLayer = CAShapeLayer() arcIndicatorLayer.path = path.cgPath arcIndicatorLayer.fillColor = UIColor.clear.cgColor arcIndicatorLayer.strokeColor = UIColor.lightGray.cgColor arcIndicatorLayer.lineWidth = 2; arcIndicatorLayer.frame = bounds return arcIndicatorLayer } fileprivate func makeStrokeAnimation(duration: CFTimeInterval) -> CABasicAnimation { let animation = CABasicAnimation(keyPath: "strokeEnd") animation.duration = duration animation.fromValue = 0 animation.toValue = 1 animation.fillMode = kCAFillModeForwards animation.isRemovedOnCompletion = true return animation } public func addArcIndicatorLayerAnimation(duration: CFTimeInterval = 3, lineWidth: CGFloat = 2, lineColor: UIColor = UIColor.lightGray) { if let arcIndicatorLayer = self.arcIndicatorLayer { arcIndicatorLayer.removeAnimation(forKey: stokeAnimationKey) arcIndicatorLayer.isHidden = false let stokeAnimation = makeStrokeAnimation(duration: duration) arcIndicatorLayer.add(stokeAnimation, forKey: stokeAnimationKey) return } let arcIndicatorLayer = makeArcIndicatorLayer(lineWidth: lineWidth, lineColor: lineColor) let stokeAnimation = makeStrokeAnimation(duration: duration) arcIndicatorLayer.add(stokeAnimation, forKey: stokeAnimationKey) layer.addSublayer(arcIndicatorLayer) self.arcIndicatorLayer = arcIndicatorLayer } public func removeArcIndicatorLayerAnimation() { arcIndicatorLayer?.removeAnimation(forKey: stokeAnimationKey) arcIndicatorLayer?.isHidden = true } public var isArcIndicatorLayerAnimating: Bool { if let arcIndicatorLayer = arcIndicatorLayer { return !arcIndicatorLayer.isHidden } else { return false } } } // MARK: - Shake animation public extension UIView { fileprivate var shakeAnimationKey: String { return "shakeAnimation" } public func shake(horizontal: Bool = true) { layer.removeAnimation(forKey: shakeAnimationKey) let animation = CAKeyframeAnimation() animation.keyPath = horizontal ? "position.x" : "position.y" animation.values = [0, 10, -10, 10, 0] animation.keyTimes = [ NSNumber(value: 0), NSNumber(value: 1.0 / 6.0), NSNumber(value: 3.0 / 6.0), NSNumber(value: 5.0 / 6.0), NSNumber(value: 1), ] animation.isAdditive = true layer.add(animation, forKey: shakeAnimationKey) } } // MARK: - Snapshot public extension UIView { public var snapshot: UIImage? { UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0) if let content = UIGraphicsGetCurrentContext() { layer.render(in: content) } else { return nil } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } // MARK: - ExtendTouchRect public extension UIView { public var touchExtendInsets: UIEdgeInsets { get { if let value = associatedObject(forKey: &AssociationKey.touchExtendInsets) as? NSValue { return value.uiEdgeInsetsValue } return UIEdgeInsets.zero } set { associate(retainObject: NSValue(uiEdgeInsets: newValue), forKey: &AssociationKey.touchExtendInsets) } } @objc dynamic func _ek_point(inside point: CGPoint, with event: UIEvent?) -> Bool { if let control = self as? UIControl, !control.isEnabled || isHidden || touchExtendInsets == UIEdgeInsets.zero { return _ek_point(inside: point, with: event) } let extendInsets = UIEdgeInsetsMake( -touchExtendInsets.top, -touchExtendInsets.left, -touchExtendInsets.bottom, -touchExtendInsets.right ) var hitFrame = UIEdgeInsetsInsetRect(bounds, extendInsets) hitFrame.size.width = max(hitFrame.size.width, 0) hitFrame.size.height = max(hitFrame.size.height, 0) return hitFrame.contains(point) } } // MARK: - Layer Image public extension UIView { public var layerImage: UIImage? { get { if let cg = layer.contents { return UIImage(cgImage: cg as! CGImage) } else { return nil } } set { if let image = newValue { let imageView = self let iw = image.size.width let ih = image.size.height let vw = bounds.width let vh = bounds.height let scale = (ih / iw) / (vh / vw) if !scale.isNaN && scale > 1 { // 高图只保留顶部 imageView.contentMode = .scaleToFill; imageView.layer.contentsRect = CGRect(x: 0, y: 0, width: 1, height: (iw / ih) * (vh / vw)) } else { // 宽图把左右两边裁掉 imageView.contentMode = .scaleAspectFill imageView.layer.contentsRect = CGRect(x: 0, y: 0, width: 1, height: 1) } imageView.layer.contents = image.cgImage } else { layer.contents = nil } } } }
mit
89e143d7e7ee809d2fd16c8fdd2863a4
36.035948
141
0.611577
5.218573
false
false
false
false
chenxtdo/UPImageMacApp
UPImage/ImageService.swift
1
1808
// // ImageService.swift // U图床 // // Created by Pro.chen on 15/02/2017. // Copyright © 2017 chenxt. All rights reserved. // import Cocoa class ImageService: NSObject { static let shared = ImageService() public func uploadImg(_ pboard: NSPasteboard) { let files: NSArray? = pboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray var data : Data? statusItem.button?.image = NSImage(named: "loading-\(0)") statusItem.button?.image?.isTemplate = true if let files = files { guard let _ = NSImage(contentsOfFile: files.firstObject as! String) else { return } data = NSData(contentsOfFile: files.firstObject as! String) as Data? } else { guard let type = pboard.pasteboardItems?.first?.types.first else { return } // guard ["public.tiff","public.png"].contains(type as! String) else { // return // } data = (pboard.pasteboardItems?.first?.data(forType: type)) guard let _ = NSImage(data: data!) else { return } } //进行格式转换 if data?.imageFormat == .unknown { let imageRep = NSBitmapImageRep(data: data!) data = imageRep?.representation(using: .png, properties: [NSBitmapImageRep.PropertyKey.compressionMethod: ""]) // data = (imageRep?.representation(using: .PNG, properties: ["":""]))! } if AppCache.shared.appConfig.useDefServer{ SMMSService.shared.uploadImage(data!) }else{ QNService.shared.QiniuSDKUpload(data) } // } }
mit
0b02dbf78351d1de7318e7c07233bcf2
32.166667
134
0.559464
4.545685
false
false
false
false
kickstarter/ios-oss
KsApi/models/Project.swift
1
14407
import Foundation import Prelude import ReactiveSwift public struct Project { public var availableCardTypes: [String]? public var blurb: String public var category: Category public var country: Country public var creator: User public var extendedProjectProperties: ExtendedProjectProperties? public var memberData: MemberData public var dates: Dates public var displayPrelaunch: Bool? public var id: Int public var location: Location public var name: String public var personalization: Personalization public var photo: Photo public var prelaunchActivated: Bool? public var rewardData: RewardData public var slug: String public var staffPick: Bool public var state: State public var stats: Stats public var tags: [String]? public var urls: UrlsEnvelope public var video: Video? public struct Category { public var analyticsName: String? public var id: Int public var name: String public var parentAnalyticsName: String? public var parentId: Int? public var parentName: String? public var rootId: Int { return self.parentId ?? self.id } } public struct UrlsEnvelope { public var web: WebEnvelope public struct WebEnvelope { public var project: String public var updates: String? } } public struct Video { public var id: Int public var high: String public var hls: String? } public enum State: String, CaseIterable, Decodable { case canceled case failed case live case purged case started case submitted case successful case suspended } public struct Stats { public var backersCount: Int public var commentsCount: Int? public var convertedPledgedAmount: Float? /// The currency code of the project ex. USD public var currency: String /// The currency code of the User's preferred currency ex. SEK public var currentCurrency: String? /// The currency conversion rate between the User's preferred currency /// and the Project's currency public var currentCurrencyRate: Float? public var goal: Int public var pledged: Int public var staticUsdRate: Float public var updatesCount: Int? public var usdExchangeRate: Float? /// Percent funded as measured from `0.0` to `1.0`. See `percentFunded` for a value from `0` to `100`. public var fundingProgress: Float { return self.goal == 0 ? 0.0 : Float(self.pledged) / Float(self.goal) } /// Percent funded as measured from `0` to `100`. See `fundingProgress` for a value between `0.0` /// and `1.0`. public var percentFunded: Int { return Int(floor(self.fundingProgress * 100.0)) } /// Pledged amount converted to USD. public var pledgedUsd: Float { return floor(Float(self.pledged) * self.staticUsdRate) } /// Total amount currently pledged to the project, converted to USD, irrespective of the users selected currency public var totalAmountPledgedUsdCurrency: Float? { return self.usdExchangeRate.map { Float(self.pledged) * $0 } } /// Goal amount converted to USD. public var goalUsd: Float { return floor(Float(self.goal) * self.staticUsdRate) } /// Goal amount converted to current currency. public var goalCurrentCurrency: Float? { return self.currentCurrencyRate.map { floor(Float(self.goal) * $0) } } /// Goal amount, converted to USD, irrespective of the users selected currency public var goalUsdCurrency: Float { return Float(self.goal) * (self.usdExchangeRate ?? 0) } /// Country determined by current currency. public var currentCountry: Project.Country? { guard let currentCurrency = self.currentCurrency else { return nil } return Project.Country(currencyCode: currentCurrency) } /// Omit US currency code public var omitUSCurrencyCode: Bool { let currentCurrency = self.currentCurrency ?? Project.Country.us.currencyCode return currentCurrency == Project.Country.us.currencyCode } /// Project pledge & goal values need conversion public var needsConversion: Bool { let currentCurrency = self.currentCurrency ?? Project.Country.us.currencyCode return self.currency != currentCurrency } public var goalMet: Bool { return self.pledged >= self.goal } } public struct MemberData { public var lastUpdatePublishedAt: TimeInterval? public var permissions: [Permission] public var unreadMessagesCount: Int? public var unseenActivityCount: Int? public enum Permission: String { case editProject = "edit_project" case editFaq = "edit_faq" case post case comment case viewPledges = "view_pledges" case fulfillment case unknown } } public struct Dates { public var deadline: TimeInterval public var featuredAt: TimeInterval? public var finalCollectionDate: TimeInterval? public var launchedAt: TimeInterval public var stateChangedAt: TimeInterval /** Returns project duration in Days */ public func duration(using calendar: Calendar = .current) -> Int? { let deadlineDate = Date(timeIntervalSince1970: self.deadline) let launchedAtDate = Date(timeIntervalSince1970: self.launchedAt) return calendar.dateComponents([.day], from: launchedAtDate, to: deadlineDate).day } public func hoursRemaining(from date: Date = Date(), using calendar: Calendar = .current) -> Int? { let deadlineDate = Date(timeIntervalSince1970: self.deadline) guard let hoursRemaining = calendar.dateComponents([.hour], from: date, to: deadlineDate).hour else { return nil } return max(0, hoursRemaining) } } public struct Personalization { public var backing: Backing? public var friends: [User]? public var isBacking: Bool? public var isStarred: Bool? } public struct Photo { public var full: String public var med: String public var size1024x768: String? public var small: String } public struct RewardData { public var addOns: [Reward]? public var rewards: [Reward] } public var hasAddOns: Bool { return self.addOns?.isEmpty == false } public var addOns: [Reward]? { return self.rewardData.addOns } public var rewards: [Reward] { return self.rewardData.rewards } public func endsIn48Hours(today: Date = Date()) -> Bool { let twoDays: TimeInterval = 60.0 * 60.0 * 48.0 return self.dates.deadline - today.timeIntervalSince1970 <= twoDays } public func isFeaturedToday(today: Date = Date(), calendar: Calendar = .current) -> Bool { guard let featuredAt = self.dates.featuredAt else { return false } return self.isDateToday(date: featuredAt, today: today, calendar: calendar) } private func isDateToday(date: TimeInterval, today: Date, calendar: Calendar) -> Bool { let startOfToday = calendar.startOfDay(for: today) return abs(startOfToday.timeIntervalSince1970 - date) < 60.0 * 60.0 * 24.0 } } extension Project: Equatable {} public func == (lhs: Project, rhs: Project) -> Bool { return lhs.id == rhs.id } extension Project: CustomDebugStringConvertible { public var debugDescription: String { return "Project(id: \(self.id), name: \"\(self.name)\")" } } extension Project: Decodable { enum CodingKeys: String, CodingKey { case availableCardTypes = "available_card_types" case blurb case category case creator case displayPrelaunch = "display_prelaunch" case id case location case name case photo case prelaunchActivated = "prelaunch_activated" case slug case staffPick = "staff_pick" case state case tags case urls case video } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.availableCardTypes = try values.decodeIfPresent([String].self, forKey: .availableCardTypes) self.blurb = try values.decode(String.self, forKey: .blurb) self.category = try values.decode(Category.self, forKey: .category) self.country = try Project.Country(from: decoder) self.creator = try values.decode(User.self, forKey: .creator) self.memberData = try Project.MemberData(from: decoder) self.dates = try Project.Dates(from: decoder) self.displayPrelaunch = try values.decodeIfPresent(Bool.self, forKey: .displayPrelaunch) self.extendedProjectProperties = nil self.id = try values.decode(Int.self, forKey: .id) self.location = (try? values.decodeIfPresent(Location.self, forKey: .location)) ?? Location.none self.name = try values.decode(String.self, forKey: .name) self.personalization = try Project.Personalization(from: decoder) self.photo = try values.decode(Photo.self, forKey: .photo) self.prelaunchActivated = try values.decodeIfPresent(Bool.self, forKey: .prelaunchActivated) self.rewardData = try Project.RewardData(from: decoder) self.slug = try values.decode(String.self, forKey: .slug) self.staffPick = try values.decode(Bool.self, forKey: .staffPick) self.state = try values.decode(State.self, forKey: .state) self.stats = try Project.Stats(from: decoder) self.tags = try values.decodeIfPresent([String].self, forKey: .tags) self.urls = try values.decode(UrlsEnvelope.self, forKey: .urls) self.video = try values.decodeIfPresent(Video.self, forKey: .video) } } extension Project.UrlsEnvelope: Decodable { enum CodingKeys: String, CodingKey { case web } } extension Project.UrlsEnvelope.WebEnvelope: Decodable { enum CodingKeys: String, CodingKey { case project case updates } } extension Project.Stats: Decodable { enum CodingKeys: String, CodingKey { case backersCount = "backers_count" case commentsCount = "comments_count" case convertedPledgedAmount = "converted_pledged_amount" case currency case currentCurrency = "current_currency" case currentCurrencyRate = "fx_rate" case goal case pledged case staticUsdRate = "static_usd_rate" case updatesCount = "updates_count" case usdExchangeRate = "usd_exchange_rate" } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.backersCount = try values.decode(Int.self, forKey: .backersCount) self.commentsCount = try values.decodeIfPresent(Int.self, forKey: .commentsCount) self.convertedPledgedAmount = try values.decodeIfPresent(Float.self, forKey: .convertedPledgedAmount) self.currency = try values.decode(String.self, forKey: .currency) self.currentCurrency = try values.decodeIfPresent(String.self, forKey: .currentCurrency) self.currentCurrencyRate = try values.decodeIfPresent(Float.self, forKey: .currentCurrencyRate) self.goal = try values.decode(Int.self, forKey: .goal) let value = try values.decode(Double.self, forKey: .pledged) self.pledged = Int(value) self.staticUsdRate = try values.decodeIfPresent(Float.self, forKey: .staticUsdRate) ?? 1.0 self.updatesCount = try values.decodeIfPresent(Int.self, forKey: .updatesCount) self.usdExchangeRate = try values.decodeIfPresent(Float.self, forKey: .usdExchangeRate) } } extension Project.MemberData: Decodable { enum CodingKeys: String, CodingKey { case lastUpdatePublishedAt = "last_update_published_at" case permissions case unreadMessagesCount = "unread_messages_count" case unseenActivityCount = "unseen_activity_count" } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.lastUpdatePublishedAt = try values.decodeIfPresent(TimeInterval.self, forKey: .lastUpdatePublishedAt) self .permissions = removeUnknowns(try values.decodeIfPresent([Permission].self, forKey: .permissions) ?? []) self.unreadMessagesCount = try values.decodeIfPresent(Int.self, forKey: .unreadMessagesCount) self.unseenActivityCount = try values.decodeIfPresent(Int.self, forKey: .unseenActivityCount) } } extension Project.Dates: Decodable { enum CodingKeys: String, CodingKey { case deadline case featuredAt = "featured_at" case finalCollectionDate = "final_collection_date" case launchedAt = "launched_at" case stateChangedAt = "state_changed_at" } } extension Project.Personalization: Decodable { enum CodingKeys: String, CodingKey { case backing case friends case isBacking = "is_backing" case isStarred = "is_starred" } } extension Project.RewardData: Decodable { enum CodingKeys: String, CodingKey { case addOns = "add_ons" case rewards } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.addOns = try values.decodeIfPresent([Reward].self, forKey: .addOns) self.rewards = try values.decodeIfPresent([Reward].self, forKey: .rewards) ?? [] } } extension Project.Category: Decodable { enum CodingKeys: String, CodingKey { case analyticsName = "analytics_name" case id case name case parentId = "parent_id" case parentName = "parent_name" } } extension Project.Photo: Decodable { enum CodingKeys: String, CodingKey { case full case med case size1024x768 = "1024x768" case size1024x576 = "1024x576" case small } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.full = try values.decode(String.self, forKey: .full) self.med = try values.decode(String.self, forKey: .med) self.size1024x768 = try values .decodeIfPresent(String.self, forKey: .size1024x768) ?? (try values.decodeIfPresent(String.self, forKey: .size1024x576)) self.small = try values.decode(String.self, forKey: .small) } } extension Project.MemberData.Permission: Decodable { public init(from decoder: Decoder) throws { self = try Project.MemberData .Permission(rawValue: decoder.singleValueContainer().decode(RawValue.self)) ?? .unknown } } private func removeUnknowns(_ xs: [Project.MemberData.Permission]) -> [Project.MemberData.Permission] { return xs.filter { $0 != .unknown } } extension Project: GraphIDBridging { public static var modelName: String { return "Project" } } extension Project.Video: Decodable {}
apache-2.0
85c3fc822113aa5ac63b757ed8461385
31.521445
116
0.708128
4.161467
false
false
false
false
pecuniabanking/pecunia-client
Source/ExSwift/Dictionary.swift
1
9852
// // Dictionary.swift // ExSwift // // Created by pNre on 04/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation import Swift internal extension Dictionary { /** Difference of self and the input dictionaries. Two dictionaries are considered equal if they contain the same [key: value] pairs. - parameter dictionaries: Dictionaries to subtract - returns: Difference of self and the input dictionaries */ func difference <V: Equatable> (_ dictionaries: [Key: V]...) -> [Key: V] { var result = [Key: V]() each { if let item = $1 as? V { result[$0] = item } } // Difference for dictionary in dictionaries { for (key, value) in dictionary { if result.has(key) && result[key] == value { result.removeValue(forKey: key) } } } return result } /** Union of self and the input dictionaries. - parameter dictionaries: Dictionaries to join - returns: Union of self and the input dictionaries */ func union (_ dictionaries: Dictionary...) -> Dictionary { var result = self dictionaries.each { (dictionary) -> Void in dictionary.each { (key, value) -> Void in _ = result.updateValue(value, forKey: key) } } return result } /** Intersection of self and the input dictionaries. Two dictionaries are considered equal if they contain the same [key: value] copules. - parameter values: Dictionaries to intersect - returns: Dictionary of [key: value] couples contained in all the dictionaries and self */ func intersection <K, V> (_ dictionaries: [K: V]...) -> [K: V] where K: Equatable, V: Equatable { // Casts self from [Key: Value] to [K: V] let filtered = mapFilter { (item, value) -> (K, V)? in if (item is K) && (value is V) { return (item as! K, value as! V) } return nil } // Intersection return filtered.filter({ (key: K, value: V) -> Bool in // check for [key: value] in all the dictionaries dictionaries.all { $0.has(key) && $0[key] == value } }) } /** Checks if a key exists in the dictionary. - parameter key: Key to check - returns: true if the key exists */ func has (_ key: Key) -> Bool { return index(forKey: key) != nil } /** Creates an Array with values generated by running each [key: value] of self through the mapFunction. - parameter mapFunction: - returns: Mapped array */ func toArray <V> (_ map: (Key, Value) -> V) -> [V] { var mapped = [V]() each { mapped.append(map($0, $1)) } return mapped } /** Creates a Dictionary with the same keys as self and values generated by running each [key: value] of self through the mapFunction. - parameter mapFunction: - returns: Mapped dictionary */ func mapValues <V> (_ map: (Key, Value) -> V) -> [Key: V] { var mapped = [Key: V]() each { mapped[$0] = map($0, $1) } return mapped } /** Creates a Dictionary with the same keys as self and values generated by running each [key: value] of self through the mapFunction discarding nil return values. - parameter mapFunction: - returns: Mapped dictionary */ func mapFilterValues <V> (_ map: (Key, Value) -> V?) -> [Key: V] { var mapped = [Key: V]() each { if let value = map($0, $1) { mapped[$0] = value } } return mapped } /** Creates a Dictionary with keys and values generated by running each [key: value] of self through the mapFunction discarding nil return values. - parameter mapFunction: - returns: Mapped dictionary */ func mapFilter <K, V> (_ map: (Key, Value) -> (K, V)?) -> [K: V] { var mapped = [K: V]() each { if let value = map($0, $1) { mapped[value.0] = value.1 } } return mapped } /** Creates a Dictionary with keys and values generated by running each [key: value] of self through the mapFunction. - parameter mapFunction: - returns: Mapped dictionary */ func map <K, V> (_ map: (Key, Value) -> (K, V)) -> [K: V] { var mapped = [K: V]() self.each({ let (_key, _value) = map($0, $1) mapped[_key] = _value }) return mapped } /** Loops trough each [key: value] pair in self. - parameter eachFunction: Function to inovke on each loop */ func each (_ each: (Key, Value) -> ()) { for (key, value) in self { each(key, value) } } /** Creates a dictionary composed of keys generated from the results of running each element of self through groupingFunction. The corresponding value of each key is an array of the elements responsible for generating the key. - parameter groupingFunction: - returns: Grouped dictionary */ func groupBy <T> (_ group: (Key, Value) -> T) -> [T: [Value]] { var result = [T: [Value]]() for (key, value) in self { let groupKey = group(key, value) // If element has already been added to dictionary, append to it. If not, create one. if result.has(groupKey) { result[groupKey]! += [value] } else { result[groupKey] = [value] } } return result } /** Similar to groupBy. Doesn't return a list of values, but the number of values for each group. - parameter groupingFunction: Function called to define the grouping key - returns: Grouped dictionary */ func countBy <T> (_ group: (Key, Value) -> (T)) -> [T: Int] { var result = [T: Int]() for (key, value) in self { let groupKey = group(key, value) // If element has already been added to dictionary, append to it. If not, create one. if result.has(groupKey) { result[groupKey]! += 1 } else { result[groupKey] = 1 } } return result } /** Checks if test evaluates true for all the elements in self. - parameter test: Function to call for each element - returns: true if test returns true for all the elements in self */ func all (_ test: (Key, Value) -> (Bool)) -> Bool { for (key, value) in self { if !test(key, value) { return false } } return true } /** Checks if test evaluates true for any element of self. - parameter test: Function to call for each element - returns: true if test returns true for any element of self */ func any (_ test: (Key, Value) -> (Bool)) -> Bool { for (key, value) in self { if test(key, value) { return true } } return false } /** Returns the number of elements which meet the condition - parameter test: Function to call for each element - returns: the number of elements meeting the condition */ func countWhere (_ test: (Key, Value) -> (Bool)) -> Int { var result = 0 for (key, value) in self { if test(key, value) { result += 1 } } return result } /** Returns a copy of self, filtered to only have values for the whitelisted keys. - parameter keys: Whitelisted keys - returns: Filtered dictionary */ func pick (_ keys: [Key]) -> Dictionary { return filter { (key: Key, _) -> Bool in return keys.contains(key) } } /** Returns a copy of self, filtered to only have values for the whitelisted keys. - parameter keys: Whitelisted keys - returns: Filtered dictionary */ func pick (_ keys: Key...) -> Dictionary { return pick(keys) } /** Returns a copy of self, filtered to only have values for the whitelisted keys. - parameter keys: Keys to get - returns: Dictionary with the given keys */ func at (_ keys: Key...) -> Dictionary { return pick(keys) } /** Removes a (key, value) pair from self and returns it as tuple. If the dictionary is empty returns nil. - returns: (key, value) tuple */ mutating func shift () -> (Key, Value)? { if let key = keys.first { return (key, removeValue(forKey: key)!) } return nil } } /** Difference operator */ public func - <K, V: Equatable> (first: [K: V], second: [K: V]) -> [K: V] { return first.difference(second) } /** Intersection operator */ public func & <K, V: Equatable> (first: [K: V], second: [K: V]) -> [K: V] { return first.intersection(second) } /** Union operator */ public func | <K: Hashable, V> (first: [K: V], second: [K: V]) -> [K: V] { return first.union(second) }
gpl-2.0
f9c2864449ef1e3b2af74d5f5310cfaa
24.391753
101
0.517458
4.459937
false
false
false
false
Aioria1314/WeiBo
WeiBo/WeiBo/ZXCNavigationController.swift
1
2198
// // ZXCNavigationController.swift // WeiBo // // Created by Aioria on 2017/3/26. // Copyright © 2017年 Aioria. All rights reserved. // import UIKit class ZXCNavigationController: UINavigationController, UIGestureRecognizerDelegate { override func viewDidLoad() { super.viewDidLoad() self.interactivePopGestureRecognizer?.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func pushViewController(_ viewController: UIViewController, animated: Bool) { if viewControllers.count > 0 { viewController.hidesBottomBarWhenPushed = true if viewControllers.count == 1 { let title = self.viewControllers.first?.title viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title!, imgName: "navigationbar_back_withtext", target: self, action: #selector(leftAction)) } else { viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(leftAction)) } viewController.navigationItem.title = "第\(viewControllers.count+1)页" } super.pushViewController(viewController, animated: animated) } @objc private func leftAction() -> Void { self.popViewController(animated: true) } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if viewControllers.count == 1 { return false } 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. } */ }
mit
70fdd792e304b56ac26afc9dd7ceca9e
27.776316
181
0.615455
5.832
false
false
false
false
apple/swift-package-manager
Sources/SPMTestSupport/MockArchiver.swift
2
2698
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Basics import TSCBasic public class MockArchiver: Archiver { public typealias ExtractionHandler = (MockArchiver, AbsolutePath, AbsolutePath, (Result<Void, Error>) -> Void) throws -> Void public typealias ValidationHandler = (MockArchiver, AbsolutePath, (Result<Bool, Error>) -> Void) throws -> Void public struct Extraction: Equatable { public let archivePath: AbsolutePath public let destinationPath: AbsolutePath public init(archivePath: AbsolutePath, destinationPath: AbsolutePath) { self.archivePath = archivePath self.destinationPath = destinationPath } } public let supportedExtensions: Set<String> = ["zip"] public let extractions = ThreadSafeArrayStore<Extraction>() public let extractionHandler: ExtractionHandler? public let validationHandler: ValidationHandler? public convenience init(handler: ExtractionHandler? = nil) { self.init(extractionHandler: handler, validationHandler: nil) } public init(extractionHandler: ExtractionHandler? = nil, validationHandler: ValidationHandler? = nil) { self.extractionHandler = extractionHandler self.validationHandler = validationHandler } public func extract( from archivePath: AbsolutePath, to destinationPath: AbsolutePath, completion: @escaping (Result<Void, Error>) -> Void ) { do { if let handler = self.extractionHandler { try handler(self, archivePath, destinationPath, completion) } else { self.extractions.append(Extraction(archivePath: archivePath, destinationPath: destinationPath)) completion(.success(())) } } catch { completion(.failure(error)) } } public func validate(path: AbsolutePath, completion: @escaping (Result<Bool, Error>) -> Void) { do { if let handler = self.validationHandler { try handler(self, path, completion) } else { completion(.success(true)) } } catch { completion(.failure(error)) } } }
apache-2.0
2a0aea16355e9ba2a9df86f76ce4963c
36.472222
129
0.617865
5.406814
false
false
false
false
Webtrekk/webtrekk-ios-sdk
Source/Internal/CryptoSwift/Array+Extension.swift
1
4714
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, // and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // extension Array { public init(reserveCapacity: Int) { self = [Element]() self.reserveCapacity(reserveCapacity) } var slice: ArraySlice<Element> { return self[self.startIndex ..< self.endIndex] } } extension Array where Element == UInt8 { public init(hex: String) { self.init(reserveCapacity: hex.unicodeScalars.lazy.underestimatedCount) var buffer: UInt8? var skip = hex.hasPrefix("0x") ? 2 : 0 for char in hex.unicodeScalars.lazy { guard skip == 0 else { skip -= 1 continue } guard char.value >= 48 && char.value <= 102 else { removeAll() return } let v: UInt8 let c: UInt8 = UInt8(char.value) switch c { case let c where c <= 57: v = c - 48 case let c where c >= 65 && c <= 70: v = c - 55 case let c where c >= 97: v = c - 87 default: removeAll() return } if let b = buffer { append(b << 4 | v) buffer = nil } else { buffer = v } } if let b = buffer { append(b) } } public func toHexString() -> String { return `lazy`.reduce("") { var s = String($1, radix: 16) if s.count == 1 { s = "0" + s } return $0 + s } } } extension Array where Element == UInt8 { /// split in chunks with given chunk size @available(*, deprecated) public func chunks(size chunksize: Int) -> [[Element]] { var words = [[Element]]() words.reserveCapacity(count / chunksize) for idx in stride(from: chunksize, through: count, by: chunksize) { words.append(Array(self[idx - chunksize ..< idx])) // slow for large table } let remainder = suffix(count % chunksize) if !remainder.isEmpty { words.append(Array(remainder)) } return words } public func md5() -> [Element] { return Digest.md5(self) } // public func sha1() -> [Element] { // return Digest.sha1(self) // } // // public func sha224() -> [Element] { // return Digest.sha224(self) // } public func sha256() -> [Element] { return Digest.sha256(self) } // public func sha384() -> [Element] { // return Digest.sha384(self) // } // // public func sha512() -> [Element] { // return Digest.sha512(self) // } // // public func sha2(_ variant: SHA2.Variant) -> [Element] { // return Digest.sha2(self, variant: variant) // } // // public func sha3(_ variant: SHA3.Variant) -> [Element] { // return Digest.sha3(self, variant: variant) // } // // public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { // return Checksum.crc32(self, seed: seed, reflect: reflect) // } // // public func crc32c(seed: UInt32? = nil, reflect: Bool = true) -> UInt32 { // return Checksum.crc32c(self, seed: seed, reflect: reflect) // } // // public func crc16(seed: UInt16? = nil) -> UInt16 { // return Checksum.crc16(self, seed: seed) // } // // public func encrypt(cipher: Cipher) throws -> [Element] { // return try cipher.encrypt(slice) // } // // public func decrypt(cipher: Cipher) throws -> [Element] { // return try cipher.decrypt(slice) // } // // public func authenticate<A: Authenticator>(with authenticator: A) throws -> [Element] { // return try authenticator.authenticate(self) // } }
mit
c8b0c21d5ab2c9eabc0f28b344cfa8c8
30.42
124
0.558031
3.997455
false
false
false
false
superk589/CGSSGuide
DereGuide/Settings/View/DonationCell.swift
2
1661
// // DonationCell.swift // DereGuide // // Created by zzk on 2017/1/4. // Copyright © 2017 zzk. All rights reserved. // import UIKit import SnapKit class DonationCell: UICollectionViewCell { let borderView = UIView() let descLabel = UILabel() let amountLabel = UILabel() var borderColor: CGColor? { set { borderView.layer.borderColor = newValue } get { return borderView.layer.borderColor } } override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(borderView) borderView.snp.makeConstraints { (make) in make.edges.equalToSuperview().inset(UIEdgeInsets(top: 10, left: 1, bottom: 10, right: 1)) } borderView.layer.borderWidth = 1 / Screen.scale borderView.layer.cornerRadius = 10 borderView.layer.masksToBounds = true contentView.addSubview(amountLabel) amountLabel.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.top.equalTo(20) } amountLabel.font = .systemFont(ofSize: 16) contentView.addSubview(descLabel) descLabel.snp.makeConstraints { (make) in make.bottom.equalTo(-20) make.centerX.equalToSuperview() } descLabel.font = .systemFont(ofSize: 14) } func setup(amount: String, desc: String) { amountLabel.text = amount descLabel.text = desc } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
4db21855495e25b13a6d15d226683ede
25.349206
101
0.595181
4.70255
false
false
false
false
rajeejones/SavingPennies
Pods/IBAnimatable/IBAnimatable/CoverAnimator.swift
5
3018
// // Created by Tom Baranes on 16/07/16. // Copyright © 2016 Jake Lin. All rights reserved. // import UIKit public class CoverAnimator: NSObject, AnimatedPresenting { // MARK: - AnimatedPresenting public var transitionDuration: Duration = defaultTransitionDuration // MARK: - private fileprivate var direction: TransitionAnimationType.Direction public init(from direction: TransitionAnimationType.Direction, transitionDuration: Duration) { self.direction = direction self.transitionDuration = transitionDuration super.init() } } // MARK: - Animator extension CoverAnimator: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return retrieveTransitionDuration(transitionContext: transitionContext) } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let (fromView, toView, tempContainerView) = retrieveViews(transitionContext: transitionContext) let isPresenting = self.isPresenting(transitionContext: transitionContext) guard let containerView = tempContainerView, let animatingView = isPresenting ? toView : fromView else { transitionContext.completeTransition(true) return } let finalFrame: CGRect if isPresenting { finalFrame = getFinalFrame(from: direction, initialFrame: animatingView.frame, containerFrame: containerView.frame) containerView.addSubview(animatingView) } else { // Animate back to origin when dismiss the modal let oppositeDirection = direction.opposite finalFrame = getFinalFrame(from: oppositeDirection, initialFrame: animatingView.frame, containerFrame: containerView.frame) } animateCover(animatingView: animatingView, finalFrame: finalFrame) { if !isPresenting { fromView?.removeFromSuperview() } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } } // MARK: - Helper private extension CoverAnimator { func getFinalFrame(from direction: TransitionAnimationType.Direction, initialFrame: CGRect, containerFrame: CGRect) -> CGRect { var initialFrame = initialFrame switch direction { case .right: initialFrame.origin.x = 0 - initialFrame.size.width case .left: initialFrame.origin.x = containerFrame.size.width + initialFrame.size.width case .top: initialFrame.origin.y = containerFrame.size.height + initialFrame.size.height case .bottom: initialFrame.origin.y = 0 - initialFrame.size.height default: fatalError() } return initialFrame } } // MARK: - Animation private extension CoverAnimator { func animateCover(animatingView: UIView, finalFrame: CGRect, completion: @escaping AnimatableCompletion) { UIView.animate(withDuration: transitionDuration, animations: { animatingView.frame = finalFrame }, completion: { _ in completion() }) } }
gpl-3.0
fa26b29df5cfa7dcb657056da8a09f58
31.095745
129
0.744448
5.320988
false
false
false
false
AboutObjectsTraining/swift-comp-reston-2017-02
demos/Coolness/Coolness/CoolViewController.swift
1
1979
import UIKit extension CoolViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } class CoolViewController: UIViewController { var textField: UITextField? var contentView: CoolView? override func loadView() { view = UIView() let (accessoryRect, contentRect) = UIScreen.main.bounds.divided(atDistance: 90, from: .minYEdge) let accessoryView = UIView(frame: accessoryRect) contentView = CoolView(frame: contentRect) guard let contentView = contentView else { return } view.addSubview(accessoryView) view.addSubview(contentView) contentView.clipsToBounds = true configureControls(accessoryView: accessoryView) view.backgroundColor = UIColor.brown accessoryView.backgroundColor = UIColor(white: 1.0, alpha: 0.7) contentView.backgroundColor = UIColor(white: 1.0, alpha: 0.5) } func addCoolView() { let newCell = CoolViewCell() newCell.text = textField?.text newCell.sizeToFit() contentView?.addSubview(newCell) } func configureControls(accessoryView: UIView) { textField = UITextField(frame: CGRect(x: 20, y: 40, width: 240, height: 30)) textField?.borderStyle = .roundedRect textField?.placeholder = "Enter some text" textField?.delegate = self if let textField = textField { accessoryView.addSubview(textField) } let button = UIButton(type: .system) button.setTitle("Add", for: .normal) button.sizeToFit() button.frame = button.frame.offsetBy(dx: 270, dy: 40) button.addTarget(self, action: #selector(addCoolView), for: UIControlEvents.touchUpInside) accessoryView.addSubview(button) } }
mit
cdfb395e34eac35b4ce4bb6122316e66
30.412698
104
0.631127
5.061381
false
false
false
false
superman-coder/pakr
pakr/pakr/Extensions/UIImage+Resize.swift
1
1359
// // UIImage+Resize.swift // pakr // // Created by Huynh Quang Thao on 4/22/16. // Copyright © 2016 Pakr. All rights reserved. // import Foundation import UIKit extension UIImage { func resize(scale:CGFloat)-> UIImage { let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: size.width*scale, height: size.height*scale))) imageView.contentMode = UIViewContentMode.ScaleAspectFit imageView.image = self UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale) imageView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } func resizeToWidth(width:CGFloat)-> UIImage { let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height))))) imageView.contentMode = UIViewContentMode.ScaleAspectFit imageView.image = self UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale) imageView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } }
apache-2.0
cc581be15311e4d3a654028c8f32169d
38.970588
162
0.710604
5.01107
false
false
false
false
YuAo/LogDispatcher.Swift
LogDispatcher.swift
1
988
// // LogDispatcher.swift // // // Created by YuAo on 8/23/14. // // public func println<T>(object: Dictionary<String,T>) -> Bool { var processed = false for logProcessingModule in LogDispatcher.logProcessingModules { for (key, value) in object { if key == logProcessingModule.logKey { if logProcessingModule.processLog(value) { processed = true } } } } if !processed { let result: Void = println(object) } return processed } public protocol LogProcessingModuleType { var logKey: String { get } func processLog<T>(content: T) -> Bool /* Bool -> Processed */ } public struct LogDispatcher { public private(set) static var logProcessingModules = [LogProcessingModuleType]() public static func registerLogProcessingModule(logProcessingModule: LogProcessingModuleType) { logProcessingModules.append(logProcessingModule) } }
mit
6213d6cc383e5e11aba853e17c72fffd
25.026316
98
0.632591
4.258621
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Intro/IntroViewController.swift
1
18774
/* 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 SnapKit import Shared struct IntroUX { static let Width = 375 static let Height = 667 static let MinimumFontScale: CGFloat = 0.5 static let PagerCenterOffsetFromScrollViewBottom = UIScreen.main.bounds.width <= 320 ? 20 : 30 static let StartBrowsingButtonColor = UIColor.Photon.Blue40 static let StartBrowsingButtonHeight = 56 static let SignInButtonColor = UIColor.Photon.Blue40 static let SignInButtonHeight = 60 static let PageControlHeight = 40 static let SignInButtonWidth = 290 static let CardTextWidth = UIScreen.main.bounds.width <= 320 ? 240 : 280 static let FadeDuration = 0.25 } protocol IntroViewControllerDelegate: AnyObject { func introViewControllerDidFinish(_ introViewController: IntroViewController, requestToLogin: Bool) } class IntroViewController: UIViewController { weak var delegate: IntroViewControllerDelegate? // We need to hang on to views so we can animate and change constraints as we scroll var cardViews = [CardView]() var cards = IntroCard.defaultCards() lazy fileprivate var startBrowsingButton: UIButton = { let button = UIButton() button.backgroundColor = UIColor.clear button.setTitle(Strings.StartBrowsingButtonTitle, for: UIControl.State()) button.setTitleColor(IntroUX.StartBrowsingButtonColor, for: UIControl.State()) button.addTarget(self, action: #selector(IntroViewController.startBrowsing), for: UIControl.Event.touchUpInside) button.accessibilityIdentifier = "IntroViewController.startBrowsingButton" button.isHidden = true return button }() lazy var pageControl: UIPageControl = { let pc = UIPageControl() pc.pageIndicatorTintColor = UIColor.black.withAlphaComponent(0.3) pc.currentPageIndicatorTintColor = UIColor.black pc.accessibilityIdentifier = "IntroViewController.pageControl" pc.addTarget(self, action: #selector(IntroViewController.changePage), for: UIControl.Event.valueChanged) return pc }() lazy fileprivate var scrollView: UIScrollView = { let sc = UIScrollView() sc.backgroundColor = UIColor.clear sc.accessibilityLabel = NSLocalizedString("Intro Tour Carousel", comment: "Accessibility label for the introduction tour carousel") sc.delegate = self sc.bounces = false sc.isPagingEnabled = true sc.showsHorizontalScrollIndicator = false sc.accessibilityIdentifier = "IntroViewController.scrollView" return sc }() var horizontalPadding: Int { return self.view.frame.width <= 320 ? 20 : 50 } var verticalPadding: CGFloat { return self.view.frame.width <= 320 ? 10 : 38 } lazy fileprivate var imageViewContainer: UIStackView = { let sv = UIStackView() sv.axis = .horizontal sv.distribution = .fillEqually return sv }() // Because a stackview cannot have a background color fileprivate var imagesBackgroundView = UIView() override func viewDidLoad() { super.viewDidLoad() syncViaLP() assert(cards.count > 1, "Intro is empty. At least 2 cards are required") view.backgroundColor = UIColor.Photon.White100 // Add Views view.addSubview(pageControl) view.addSubview(scrollView) view.addSubview(startBrowsingButton) scrollView.addSubview(imagesBackgroundView) scrollView.addSubview(imageViewContainer) // Setup constraints imagesBackgroundView.snp.makeConstraints { make in make.edges.equalTo(imageViewContainer) } imageViewContainer.snp.makeConstraints { make in make.top.equalTo(self.view) make.height.equalTo(self.view.snp.width) } startBrowsingButton.snp.makeConstraints { make in make.left.right.equalTo(self.view) make.bottom.equalTo(self.view.safeArea.bottom) make.height.equalTo(IntroUX.StartBrowsingButtonHeight) } scrollView.snp.makeConstraints { make in make.left.right.top.equalTo(self.view) make.bottom.equalTo(pageControl.snp.top) } pageControl.snp.makeConstraints { make in make.centerX.equalTo(self.scrollView) make.centerY.equalTo(self.startBrowsingButton.snp.top).offset(-IntroUX.PagerCenterOffsetFromScrollViewBottom) } createSlides() pageControl.addTarget(self, action: #selector(changePage), for: .valueChanged) } func syncViaLP() { let startTime = Date.now() LeanPlumClient.shared.introScreenVars?.onValueChanged({ [weak self] in guard let newIntro = LeanPlumClient.shared.introScreenVars?.object(forKey: nil) as? [[String: Any]] else { return } let decoder = JSONDecoder() let newCards = newIntro.compactMap { (obj) -> IntroCard? in guard let object = try? JSONSerialization.data(withJSONObject: obj, options: []) else { return nil } let card = try? decoder.decode(IntroCard.self, from: object) // Make sure the selector actually goes somewhere. Otherwise dont show that slide if let selectorString = card?.buttonSelector, let wself = self { return wself.responds(to: NSSelectorFromString(selectorString)) ? card : nil } else { return card } } guard newCards != IntroCard.defaultCards(), newCards.count > 1 else { return } // We need to still be on the first page otherwise the content will change underneath the user's finger // We also need to let LP know this happened so we can track when a A/B test was not run guard self?.pageControl.currentPage == 0 else { let totalTime = Date.now() - startTime LeanPlumClient.shared.track(event: .onboardingTestLoadedTooSlow, withParameters: ["Total time": "\(totalTime) ms"]) return } self?.cards = newCards self?.createSlides() self?.viewDidLayoutSubviews() }) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scrollView.contentSize = imageViewContainer.frame.size } func createSlides() { // Make sure the scrollView has been setup before setting up the slides guard scrollView.superview != nil else { return } // Wipe any existing slides imageViewContainer.subviews.forEach { $0.removeFromSuperview() } cardViews.forEach { $0.removeFromSuperview() } cardViews = cards.compactMap { addIntro(card: $0) } pageControl.numberOfPages = cardViews.count setupDynamicFonts() if let firstCard = cardViews.first { setActive(firstCard, forPage: 0) } imageViewContainer.layoutSubviews() scrollView.contentSize = imageViewContainer.frame.size // This should never happen but just in case make sure there is a way out if cardViews.count == 1 { startBrowsingButton.isHidden = false } } func addIntro(card: IntroCard) -> CardView? { guard let image = UIImage(named: card.imageName) else { return nil } let imageView = UIImageView(image: image) imageViewContainer.addArrangedSubview(imageView) imageView.snp.makeConstraints { make in make.height.equalTo(imageViewContainer.snp.height) make.width.equalTo(imageViewContainer.snp.height) } let cardView = CardView(verticleSpacing: verticalPadding) cardView.configureWith(card: card) if let selectorString = card.buttonSelector, self.responds(to: NSSelectorFromString(selectorString)) { cardView.button.addTarget(self, action: NSSelectorFromString(selectorString), for: .touchUpInside) cardView.button.snp.makeConstraints { make in make.width.equalTo(IntroUX.CardTextWidth) make.height.equalTo(IntroUX.SignInButtonHeight) } } self.view.addSubview(cardView) cardView.snp.makeConstraints { make in make.top.equalTo(self.imageViewContainer.snp.bottom).offset(verticalPadding) make.bottom.equalTo(self.startBrowsingButton.snp.top) make.left.right.equalTo(self.view).inset(horizontalPadding) } return cardView } @objc func startBrowsing() { delegate?.introViewControllerDidFinish(self, requestToLogin: false) LeanPlumClient.shared.track(event: .dismissedOnboarding, withParameters: ["dismissedOnSlide": String(pageControl.currentPage)]) } @objc func login() { delegate?.introViewControllerDidFinish(self, requestToLogin: true) LeanPlumClient.shared.track(event: .dismissedOnboardingShowLogin, withParameters: ["dismissedOnSlide": String(pageControl.currentPage)]) } @objc func changePage() { let swipeCoordinate = CGFloat(pageControl.currentPage) * scrollView.frame.size.width scrollView.setContentOffset(CGPoint(x: swipeCoordinate, y: 0), animated: true) } fileprivate func setActive(_ introView: UIView, forPage page: Int) { guard introView.alpha != 1 else { return } UIView.animate(withDuration: IntroUX.FadeDuration, animations: { self.cardViews.forEach { $0.alpha = 0.0 } introView.alpha = 1.0 self.pageControl.currentPage = page }, completion: nil) } } // UIViewController setup extension IntroViewController { override var prefersStatusBarHidden: Bool { return true } override var shouldAutorotate: Bool { return false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { // This actually does the right thing on iPad where the modally // presented version happily rotates with the iPad orientation. return .portrait } } // Dynamic Font Helper extension IntroViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(dynamicFontChanged), name: .DynamicFontChanged, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: .DynamicFontChanged, object: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } @objc func dynamicFontChanged(_ notification: Notification) { guard notification.name == .DynamicFontChanged else { return } setupDynamicFonts() } fileprivate func setupDynamicFonts() { startBrowsingButton.titleLabel?.font = UIFont(name: "FiraSans-Regular", size: DynamicFontHelper.defaultHelper.IntroStandardFontSize) cardViews.forEach { cardView in cardView.titleLabel.font = UIFont(name: "FiraSans-Medium", size: DynamicFontHelper.defaultHelper.IntroBigFontSize) cardView.textLabel.font = UIFont(name: "FiraSans-UltraLight", size: DynamicFontHelper.defaultHelper.IntroStandardFontSize) } } } extension IntroViewController: UIScrollViewDelegate { func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { // Need to add this method so that when forcibly dragging, instead of letting deceleration happen, should also calculate what card it's on. // This especially affects sliding to the last or first cards. if !decelerate { scrollViewDidEndDecelerating(scrollView) } } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { // Need to add this method so that tapping the pageControl will also change the card texts. // scrollViewDidEndDecelerating waits until the end of the animation to calculate what card it's on. scrollViewDidEndDecelerating(scrollView) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let page = Int(scrollView.contentOffset.x / scrollView.frame.size.width) if let cardView = cardViews[safe: page] { setActive(cardView, forPage: page) } if page != 0 { startBrowsingButton.isHidden = false } } func scrollViewDidScroll(_ scrollView: UIScrollView) { let maximumHorizontalOffset = scrollView.frame.width let currentHorizontalOffset = scrollView.contentOffset.x var percentageOfScroll = currentHorizontalOffset / maximumHorizontalOffset percentageOfScroll = percentageOfScroll > 1.0 ? 1.0 : percentageOfScroll let whiteComponent = UIColor.Photon.White100.components let grayComponent = UIColor.Photon.Grey20.components let newRed = (1.0 - percentageOfScroll) * whiteComponent.red + percentageOfScroll * grayComponent.red let newGreen = (1.0 - percentageOfScroll) * whiteComponent.green + percentageOfScroll * grayComponent.green let newBlue = (1.0 - percentageOfScroll) * whiteComponent.blue + percentageOfScroll * grayComponent.blue imagesBackgroundView.backgroundColor = UIColor(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0) } } // A cardView repersents the text for each page of the intro. It does not include the image. class CardView: UIView { lazy var stackView: UIStackView = { let stackView = UIStackView() stackView.axis = .vertical stackView.alignment = .center return stackView }() lazy var titleLabel: UILabel = { let titleLabel = UILabel() titleLabel.numberOfLines = 2 titleLabel.adjustsFontSizeToFitWidth = true titleLabel.minimumScaleFactor = IntroUX.MinimumFontScale titleLabel.textAlignment = .center titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical) return titleLabel }() lazy var textLabel: UILabel = { let textLabel = UILabel() textLabel.numberOfLines = 5 textLabel.adjustsFontSizeToFitWidth = true textLabel.minimumScaleFactor = IntroUX.MinimumFontScale textLabel.textAlignment = .center textLabel.lineBreakMode = .byTruncatingTail textLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical) return textLabel }() lazy var button: UIButton = { let button = UIButton() button.backgroundColor = IntroUX.SignInButtonColor button.setTitle(Strings.SignInButtonTitle, for: []) button.setTitleColor(.white, for: []) button.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: .vertical) button.clipsToBounds = true button.accessibilityIdentifier = "turnOnSync.button" return button }() override init(frame: CGRect) { super.init(frame: frame) } init(verticleSpacing: CGFloat) { super.init(frame: .zero) stackView.spacing = verticleSpacing stackView.addArrangedSubview(titleLabel) stackView.addArrangedSubview(textLabel) addSubview(stackView) stackView.snp.makeConstraints { make in make.leading.trailing.top.equalTo(self) make.bottom.lessThanOrEqualTo(self).offset(-IntroUX.PageControlHeight) } alpha = 0 } func configureWith(card: IntroCard) { titleLabel.text = card.title textLabel.text = card.text if let buttonText = card.buttonText, card.buttonSelector != nil { button.setTitle(buttonText, for: .normal) addSubview(button) button.snp.makeConstraints { make in make.bottom.centerX.equalTo(self) } // When there is a button reduce the spacing to make more room for text stackView.spacing = stackView.spacing / 2 } } // Allows the scrollView to scroll while the CardView is in front override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { if let buttonSV = button.superview { return convert(button.frame, from: buttonSV).contains(point) } return false } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } struct IntroCard: Codable { let title: String let text: String let buttonText: String? let buttonSelector: String? // Selector is a string that is synthisized into a Selector via NSSelectorFromString (for LeanPlum's sake) let imageName: String init(title: String, text: String, imageName: String, buttonText: String? = nil, buttonSelector: String? = nil) { self.title = title self.text = text self.imageName = imageName self.buttonText = buttonText self.buttonSelector = buttonSelector } static func defaultCards() -> [IntroCard] { let welcome = IntroCard(title: Strings.CardTitleWelcome, text: Strings.CardTextWelcome, imageName: "tour-Welcome") let sync = IntroCard(title: Strings.CardTitleSync, text: Strings.CardTextSync, imageName: "tour-Sync", buttonText: Strings.SignInButtonTitle, buttonSelector: #selector(IntroViewController.login).description) return [welcome, sync] } /* Codable doesnt allow quick conversion to a dictonary */ func asDictonary() -> [String: Any]? { guard let data = try? JSONEncoder().encode(self) else { return nil } return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] } } } extension IntroCard: Equatable {} func == (lhs: IntroCard, rhs: IntroCard) -> Bool { return lhs.buttonText == rhs.buttonText && lhs.buttonSelector == rhs.buttonSelector && lhs.imageName == rhs.imageName && lhs.text == rhs.text && lhs.title == rhs.title } extension UIColor { var components: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) return (r, g, b, a) } }
mpl-2.0
d66a7943ae91b1ce9fe883d603925a17
39.287554
215
0.667998
4.969296
false
false
false
false
konkab/Respinner
RespinnerDemo/RespinnerDemo/Respinner.swift
3
4568
// // Respinner.swift // // The MIT License (MIT) // // Copyright (c) 2015 Konstantin Kabanov // // 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 class Respinner: UIControl { var animationDuration = 2.0 var scrollViewDefaultContentInset = UIEdgeInsetsZero private var spinningView: UIView! private var height: CGFloat! private (set) var refreshing: Bool = false private var previousYOffset = CGFloat(0.0) convenience init(spinningView: UIView) { self.init(spinningView: spinningView, height: 60.0) } init(spinningView: UIView, height: CGFloat) { super.init() self.spinningView = spinningView self.height = height autoresizingMask = .FlexibleWidth backgroundColor = UIColor.clearColor() addSubview(spinningView) } private override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToSuperview() { super.didMoveToSuperview() if let scrollView = self.superview as? UIScrollView { frame = CGRect(x: 0.0, y: -height, width: scrollView.frame.size.width, height: height) scrollView.addObserver(self, forKeyPath: "contentOffset", options: .Initial, context: nil) } } override func layoutSubviews() { super.layoutSubviews() spinningView.center = CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0) } override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { let scrollView = self.superview as UIScrollView if object as? UIScrollView == scrollView { if keyPath == "contentOffset" { var yOffsetWithoutInsets = scrollView.contentOffset.y + scrollViewDefaultContentInset.top if yOffsetWithoutInsets < -frame.size.height { if !scrollView.dragging && !refreshing { beginRefreshing() sendActionsForControlEvents(.ValueChanged) } else if !refreshing { spinningView.transform = CGAffineTransformMakeRotation(-(yOffsetWithoutInsets / frame.size.height) * 2.0 * CGFloat(M_PI)) } } else if !refreshing { spinningView.transform = CGAffineTransformMakeRotation(-(yOffsetWithoutInsets / frame.size.height) * 2.0 * CGFloat(M_PI)) } previousYOffset = scrollView.contentOffset.y } } } func beginRefreshing() { refreshing = true let animation = CABasicAnimation() animation.keyPath = "transform.rotation.z" animation.duration = animationDuration animation.removedOnCompletion = false animation.fillMode = kCAFillModeForwards animation.repeatCount = Float.infinity animation.additive = true animation.fromValue = CGFloat(0.0) animation.toValue = CGFloat(2.0 * M_PI) spinningView.layer.addAnimation(animation, forKey: "rotate") let scrollView = self.superview as UIScrollView scrollView.contentOffset.y = previousYOffset UIView.animateWithDuration(0.3, delay: 0.0, options: .AllowUserInteraction, animations: { () -> Void in scrollView.contentInset.top += self.frame.size.height scrollView.contentOffset.y = -scrollView.contentInset.top }, completion: nil) } func endRefreshing() { refreshing = false spinningView.layer.removeAnimationForKey("rotate") let scrollView = self.superview as UIScrollView UIView.animateWithDuration(0.3, delay: 0.0, options: .AllowUserInteraction, animations: { () -> Void in scrollView.contentInset = self.scrollViewDefaultContentInset }, completion: nil) } }
mit
13d2e754eeebfd93b30ecc5c7247b2ee
33.345865
153
0.73796
4.100539
false
false
false
false
wscqs/QSWB
DSWeibo/DSWeibo/Classes/Home/PhotoBrowser/PhotoBrowserCell.swift
1
5199
// // PhotoBrowserCell.swift // DSWeibo // // Created by xiaomage on 15/9/14. // Copyright © 2015年 小码哥. All rights reserved. // import UIKit import SDWebImage protocol PhotoBrowserCellDelegate : NSObjectProtocol { func photoBrowserCellDidClose(cell: PhotoBrowserCell) } class PhotoBrowserCell: UICollectionViewCell { weak var photoBrowserCellDelegate : PhotoBrowserCellDelegate? var imageURL: NSURL? { didSet{ // 1.重置属性 reset() // 2.显示菊花 activity.startAnimating() // 3.设置图片 iconView.sd_setImageWithURL(imageURL) { (image, _, _, _) -> Void in // 4.隐藏菊花 self.activity.stopAnimating() // 5.调整图片的尺寸和位置 self.setImageViewPostion() } } } /** 重置scrollview和imageview的属性 */ private func reset() { // 重置scrollview scrollview.contentInset = UIEdgeInsetsZero scrollview.contentOffset = CGPointZero scrollview.contentSize = CGSizeZero // 重置imageview iconView.transform = CGAffineTransformIdentity } /** 调整图片显示的位置 */ private func setImageViewPostion() { // 1.拿到按照宽高比计算之后的图片大小 let size = self.displaySize(iconView.image!) // 2.判断图片的高度, 是否大于屏幕的高度 if size.height < UIScreen.mainScreen().bounds.height { // 2.2小于 短图 --> 设置边距, 让图片居中显示 iconView.frame = CGRect(origin: CGPointZero, size: size) // 处理居中显示 let y = (UIScreen.mainScreen().bounds.height - size.height) * 0.5 self.scrollview.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0) }else { // 2.1大于 长图 --> y = 0, 设置scrollview的滚动范围为图片的大小 iconView.frame = CGRect(origin: CGPointZero, size: size) scrollview.contentSize = size } } /** 按照图片的宽高比计算图片显示的大小 */ private func displaySize(image: UIImage) -> CGSize { // 1.拿到图片的宽高比 let scale = image.size.height / image.size.width // 2.根据宽高比计算高度 let width = UIScreen.mainScreen().bounds.width let height = width * scale return CGSize(width: width, height: height) } override init(frame: CGRect) { super.init(frame: frame) // 1.初始化UI setupUI() } private func setupUI() { // 1.添加子控件 contentView.addSubview(scrollview) scrollview.addSubview(iconView) contentView.addSubview(activity) // 2.布局子控件 scrollview.frame = UIScreen.mainScreen().bounds activity.center = contentView.center // 3.处理缩放 scrollview.delegate = self scrollview.maximumZoomScale = 2.0 scrollview.minimumZoomScale = 0.5 // 4.监听图片的点击 let tap = UITapGestureRecognizer(target: self, action: "close") iconView.addGestureRecognizer(tap) iconView.userInteractionEnabled = true } /** 关闭浏览器 */ func close() { print("close") photoBrowserCellDelegate?.photoBrowserCellDidClose(self) } // MARK: - 懒加载 private lazy var scrollview: UIScrollView = UIScrollView() lazy var iconView: UIImageView = UIImageView() private lazy var activity: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PhotoBrowserCell: UIScrollViewDelegate { // 告诉系统需要缩放哪个控件 func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return iconView } // 重新调整配图的位置 // view: 被缩放的视图 func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) { print("scrollViewDidEndZooming") // 注意: 缩放的本质是修改transfrom, 而修改transfrom不会影响到bounds, 只有frame会受到影响 // print(view?.bounds) // print(view?.frame) var offsetX = (UIScreen.mainScreen().bounds.width - view!.frame.width) * 0.5 var offsetY = (UIScreen.mainScreen().bounds.height - view!.frame.height) * 0.5 // print("offsetX = \(offsetX), offsetY = \(offsetY)") offsetX = offsetX < 0 ? 0 : offsetX offsetY = offsetY < 0 ? 0 : offsetY scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: offsetY, right: offsetX) } }
mit
8b95089ee00c0cd614c963d0b4bed1c1
27.287425
146
0.58171
4.742972
false
false
false
false
Isahkaren/ND-OnTheMap
OnTheMap/Controllers/MapViewController.swift
1
5515
// // MapViewController.swift // OnTheMap // // Created by Isabela Karen de Oliveira Gomes on 14/01/16. // Copyright © 2017 Isabela Karen de Oliveira Gomes. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController { // MARK: - Properties @IBOutlet var mapMain: MKMapView! var locationMananger = CLLocationManager() fileprivate let pinReuseId = "pinStudentLocation" fileprivate let segueLocation = "sgLocation" // MARK: - Life Circle override func viewDidLoad() { super.viewDidLoad() mapMain.delegate = self locations() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) locations() } //MARK: - Actions @IBAction func btnRefresh_Clicked(_ sender: UIBarButtonItem) { locations() } @IBAction func btnLogout_Clicked(_ sender: UIBarButtonItem) { logout() } @IBAction func btnAddPin_Clicked(_ sender: UIBarButtonItem) { self.performSegue(withIdentifier: self.segueLocation, sender: nil) } //MARK: - Services func logout() { UdacityServices.logout(onSuccess: { (serviceResponse) in DispatchQueue.main.async { Login.shared.clearLoggedUserData() self.tabBarController?.dismiss(animated: true, completion: nil) } }, onFailure: { (serviceResponse) in self.displayError(title: "Sorry!", message: "Logout went wrong") }, onCompletion: { }) } func locations() { UdacityServices.locationStudents(onSuccess: { (serviceResponse) in guard let locationsDict = JsonUtils.deserialize(data: serviceResponse.data!) else { return } print(locationsDict) ShareLocations.share.locations = StudentLocation.mapLocations(dictionary: locationsDict) self.setupPins(locations: ShareLocations.share.locations) }, onFailure: { (serviceResponse) in self.displayError(title: "Sorry", message: "An error occurred") }, onCompletion: { }) } func setupPins(locations: [StudentLocation]) { var annotations = [MKPointAnnotation]() for location in locations { guard let firstName = location.firstName else { continue } guard let lat = location.latitude else { continue } guard let long = location.longitude else { continue } guard let lastName = location.lastName else { continue } guard let mediaURL = location.mediaURL else { continue } let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long) let annotation = MKPointAnnotation() annotation.coordinate = coordinate annotation.title = "\(firstName) \(lastName)" annotation.subtitle = mediaURL annotations.append(annotation) } DispatchQueue.main.async { self.mapMain.addAnnotations(annotations) } } func displayError(title: String, message: String) { let alert = UIAlertController(title: title, message:message , preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.destructive) { (action) in alert.dismiss(animated: true, completion: nil) } alert.addAction(okAction) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } } // MARK: - Map extension MapViewController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: pinReuseId) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: pinReuseId) pinView!.canShowCallout = true pinView!.pinTintColor = .red pinView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) } else { pinView!.annotation = annotation } if (pinView?.annotation?.title!!.contains("Isabela"))! { print("hey") } return pinView } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if control == view.rightCalloutAccessoryView { let app = UIApplication.shared if let toOpen = view.annotation?.subtitle, let urlString = toOpen, let url = URL(string: urlString), app.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { self.displayError(title: "Error", message: "An error occurred!") } } } }
mit
aa2f744ee7b538a2c3e7e3c78c9b28da
28.967391
134
0.565107
5.678682
false
false
false
false
TaikiFnit/Fnit-Calculator
Fnit-Calculator/ViewController.swift
1
5628
// // ViewController.swift // Fnit-Calculator // // Created by NOWALL on 2016/11/06. // Copyright © 2016年 NOWALL. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var harfResultLabel: UILabel! @IBOutlet weak var resultLabel: UILabel! var leftOperand:String? = "" var rightOperand:String? = "" var centerOperator:String = "" var is_end:Bool = false /* 演算子が押されたときの処理 */ @IBAction func tappedOperator(_ sender: UIButton) { // 左辺の値がまだ確定していなかったら、 if leftOperand! == "" { // 左辺の値を確定し、 leftOperand = resultLabel.text! // 次の値を受け付ける rightOperand = "" resultLabel.text = "" } // すでに確定している場合で、operatorもsetしてあったら else if (centerOperator != "") { /* print("do calc") // ラベルに表示されている値を右辺として変数に代入 rightOperand = resultLabel.text // 計算させる関数 calculate() // calculate()を実行した結果がresultLabelに表示されるので、それをさらにleftOperandに登録して,後に演算子を登録 leftOperand = resultLabel.text // 数値の受付 resultLabel.text = "" */ } // pushされた演算子を変数に格納 if let ope: String = sender.currentTitle { centerOperator = ope } is_end = false refresh() } /* 数字が押されたときの処理 */ @IBAction func tappedNum(_ sender: UIButton) { if is_end == true { resultLabel.text = "" harfResultLabel.text = "" } // 押された値がしっかり取得できていれば、それを表示させる if let num: String = sender.currentTitle { // 0がもともと表示されてる場合は、それを消す if (resultLabel.text == "0") { resultLabel.text = "" } // labelに押された値を表示 resultLabel.text = resultLabel.text! + num } is_end = false refresh() } // ドットが押されたときの処理 @IBAction func tappedDot(_ sender: UIButton) { if !hasDot(origString: resultLabel.text!) { resultLabel.text = resultLabel.text! + "." is_end = false refresh() } } // =が押されたときの処理 @IBAction func tappedEqual(_ sender: UIButton) { if is_end == false { // ラベルに表示されている値を右辺として変数に代入 rightOperand = resultLabel.text // 途中経過を表示 harfResultLabel.text = leftOperand! + " " + centerOperator + " " + rightOperand! // 計算させる関数 calculate() // 計算の終了 is_end = true } refresh() } // クリアボタンが押されたときの処理 @IBAction func tappedClear(_ sender: UIButton) { leftOperand = "" rightOperand = "" centerOperator = "" resultLabel.text = "0" harfResultLabel.text = "0" refresh() is_end = false } /* delete buttonが押されたときの処理 */ @IBAction func tappedDel(_ sender: UIButton) { let targetNum:String = resultLabel.text! let index = targetNum.index(targetNum.endIndex, offsetBy: -1) // 1文字削除する resultLabel.text = targetNum.substring(to: index) if resultLabel.text == "" { resultLabel.text = "0" } is_end = false refresh() } func calculate() { if(leftOperand! != "" && centerOperator != "" && rightOperand! != "") { // calc! var result:Double = 0.0 let left:Double = atof(leftOperand) as Double let right:Double = atof(rightOperand) as Double switch centerOperator { case "+": result = left + right break case "-": result = left - right break case "*": result = left * right break case "/": result = left / right default: break } resultLabel.text = String(result) leftOperand = "" rightOperand = "" centerOperator = "" } } func refresh() { harfResultLabel.text = leftOperand! + " " + centerOperator + " " + rightOperand! } func hasDot(origString:String)->Bool{ for i in origString.characters.indices[origString.startIndex..<origString.endIndex] { if (origString[i] == ".") { return true } } return false } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
a33ae6680da54c550db94694e485dcc4
24.994792
93
0.485875
4.362762
false
false
false
false
nmdias/FeedKit
Sources/FeedKit/Models/Namespaces/Media/MediaNamespace.swift
2
10628
// // MediaNamespace.swift // // Copyright (c) 2016 - 2018 Nuno Manuel Dias // // 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 /// Media RSS is a new RSS module that supplements the <enclosure> /// capabilities of RSS 2.0. RSS enclosures are already being used to /// syndicate audio files and images. Media RSS extends enclosures to /// handle other media types, such as short films or TV, as well as /// provide additional metadata with the media. Media RSS enables /// content publishers and bloggers to syndicate multimedia content /// such as TV and video clips, movies, images and audio. public class MediaNamespace { /// The <media:group> element is a sub-element of <item>. It allows grouping /// of <media:content> elements that are effectively the same content, /// yet different representations. For instance: the same song recorded /// in both the WAV and MP3 format. It's an optional element that must /// only be used for this purpose. public var mediaGroup: MediaGroup? /// <media:content> is a sub-element of either <item> or <media:group>. /// Media objects that are not the same content should not be included /// in the same <media:group> element. The sequence of these items implies /// the order of presentation. While many of the attributes appear to be /// audio/video specific, this element can be used to publish any type of /// media. It contains 14 attributes, most of which are optional. public var mediaContents: [MediaContent]? /// This allows the permissible audience to be declared. If this element is not /// included, it assumes that no restrictions are necessary. It has one /// optional attribute. public var mediaRating: MediaRating? /// The title of the particular media object. It has one optional attribute. public var mediaTitle: MediaTitle? /// Short description describing the media object typically a sentence in /// length. It has one optional attribute. public var mediaDescription: MediaDescription? /// Highly relevant keywords describing the media object with typically a /// maximum of 10 words. The keywords and phrases should be comma-delimited. public var mediaKeywords: [String]? /// Allows particular images to be used as representative images for the /// media object. If multiple thumbnails are included, and time coding is not /// at play, it is assumed that the images are in order of importance. It has /// one required attribute and three optional attributes. public var mediaThumbnails: [MediaThumbnail]? /// Allows a taxonomy to be set that gives an indication of the type of media /// content, and its particular contents. It has two optional attributes. public var mediaCategory: MediaCategory? /// This is the hash of the binary media file. It can appear multiple times as /// long as each instance is a different algo. It has one optional attribute. public var mediaHash: MediaHash? /// Allows the media object to be accessed through a web browser media player /// console. This element is required only if a direct media url attribute is /// not specified in the <media:content> element. It has one required attribute /// and two optional attributes. public var mediaPlayer: MediaPlayer? /// Notable entity and the contribution to the creation of the media object. /// Current entities can include people, companies, locations, etc. Specific /// entities can have multiple roles, and several entities can have the same /// role. These should appear as distinct <media:credit> elements. It has two /// optional attributes. public var mediaCredits: [MediaCredit]? /// Copyright information for the media object. It has one optional attribute. public var mediaCopyright: MediaCopyright? /// Allows the inclusion of a text transcript, closed captioning or lyrics of /// the media content. Many of these elements are permitted to provide a time /// series of text. In such cases, it is encouraged, but not required, that the /// elements be grouped by language and appear in time sequence order based on /// the start time. Elements can have overlapping start and end times. It has /// four optional attributes. public var mediaText: MediaText? /// Allows restrictions to be placed on the aggregator rendering the media in /// the feed. Currently, restrictions are based on distributor (URI), country /// codes and sharing of a media object. This element is purely informational /// and no obligation can be assumed or implied. Only one <media:restriction> /// element of the same type can be applied to a media object -- all others /// will be ignored. Entities in this element should be space-separated. /// To allow the producer to explicitly declare his/her intentions, two /// literals are reserved: "all", "none". These literals can only be used once. /// This element has one required attribute and one optional attribute (with /// strict requirements for its exclusion). public var mediaRestriction: MediaRestriction? /// This element stands for the community related content. This allows /// inclusion of the user perception about a media object in the form of view /// count, ratings and tags. public var mediaCommunity: MediaCommunity? /// Allows inclusion of all the comments a media object has received. public var mediaComments: [String]? /// Sometimes player-specific embed code is needed for a player to play any /// video. <media:embed> allows inclusion of such information in the form of /// key-value pairs. public var mediaEmbed: MediaEmbed? /// Allows inclusion of a list of all media responses a media object has /// received. public var mediaResponses: [String]? /// Allows inclusion of all the URLs pointing to a media object. public var mediaBackLinks: [String]? /// Optional tag to specify the status of a media object -- whether it's still /// active or it has been blocked/deleted. public var mediaStatus: MediaStatus? /// Optional tag to include pricing information about a media object. If this /// tag is not present, the media object is supposed to be free. One media /// object can have multiple instances of this tag for including different /// pricing structures. The presence of this tag would mean that media object /// is not free. public var mediaPrices: [MediaPrice]? /// Optional link to specify the machine-readable license associated with the /// content. public var mediaLicense: MediaLicence? /// Optional link to specify the machine-readable license associated with the /// content. public var mediaSubTitle: MediaSubTitle? /// Optional element for P2P link. public var mediaPeerLink: MediaPeerLink? /// Optional element to specify geographical information about various /// locations captured in the content of a media object. The format conforms /// to geoRSS. public var mediaLocation: MediaLocation? /// Optional element to specify the rights information of a media object. public var mediaRights: MediaRights? /// Optional element to specify various scenes within a media object. It can /// have multiple child <media:scene> elements, where each <media:scene> /// element contains information about a particular scene. <media:scene> has /// the optional sub-elements <sceneTitle>, <sceneDescription>, /// <sceneStartTime> and <sceneEndTime>, which contains title, description, /// start and end time of a particular scene in the media, respectively. public var mediaScenes: [MediaScene]? public init() { } } // MARK: - Equatable extension MediaNamespace: Equatable { public static func ==(lhs: MediaNamespace, rhs: MediaNamespace) -> Bool { return lhs.mediaGroup == rhs.mediaGroup && lhs.mediaContents == rhs.mediaContents && lhs.mediaRating == rhs.mediaRating && lhs.mediaTitle == rhs.mediaTitle && lhs.mediaDescription == rhs.mediaDescription && lhs.mediaKeywords == rhs.mediaKeywords && lhs.mediaThumbnails == rhs.mediaThumbnails && lhs.mediaCategory == rhs.mediaCategory && lhs.mediaHash == rhs.mediaHash && lhs.mediaPlayer == rhs.mediaPlayer && lhs.mediaCredits == rhs.mediaCredits && lhs.mediaCopyright == rhs.mediaCopyright && lhs.mediaText == rhs.mediaText && lhs.mediaRestriction == rhs.mediaRestriction && lhs.mediaCommunity == rhs.mediaCommunity && lhs.mediaComments == rhs.mediaComments && lhs.mediaEmbed == rhs.mediaEmbed && lhs.mediaResponses == rhs.mediaResponses && lhs.mediaBackLinks == rhs.mediaBackLinks && lhs.mediaStatus == rhs.mediaStatus && lhs.mediaPrices == rhs.mediaPrices && lhs.mediaLicense == rhs.mediaLicense && lhs.mediaSubTitle == rhs.mediaSubTitle && lhs.mediaPeerLink == rhs.mediaPeerLink && lhs.mediaLocation == rhs.mediaLocation && lhs.mediaRights == rhs.mediaRights && lhs.mediaScenes == rhs.mediaScenes } }
mit
20fe085605fa84b46eb9ce5f2655fcbd
48.203704
84
0.692887
4.837506
false
false
false
false
Alex-ZHOU/XYQSwift
XYQSwiftTests/Learn-from-Imooc/Play-with-Swift-2/05-Strings/03-String.playground/Contents.swift
1
1852
// // 5-3 Swift 2.0字符串之String.Index 和 Range // 03-String.playground // // Created by AlexZHOU on 21/05/2017. // Copyright © 2016年 AlexZHOU. All rights reserved. // import UIKit var str = "Hello, Swift String" print(str) // startIndex let startIndex = str.startIndex str[startIndex] // advancedBy // 在swift3.0中,advancedBy函数被取消。 //swift2: str[startIndex.advancedBy(5)] // 如果想通过一个已有的String.Index通过距离找到其他的String.Index,需要使用String.index(_:offsetBy:)方法 str[str.index(startIndex, offsetBy: 5)] //swift2: let spaceIndex = startIndex.advancedBy(6) //swuft3.0 let spaceIndex = str.index(startIndex, offsetBy: 6) spaceIndex str[spaceIndex] // predecessor 和 succesor // 在swift3中,predecessor 和 succesor方法均被取消 // swift2: str[spaceIndex.predecessor()] // swift2: str[spaceIndex.successor()] // 如果想寻找一个String.Index的前驱和后继,需要使用String.index(before:)和String.index(after:)方法 str[str.index(before: spaceIndex)] str[str.index(after: spaceIndex)] // endIndex let endIndex = str.endIndex str[str.index(before: endIndex)] // Range str[startIndex..<spaceIndex] let range = startIndex..<str.index(before: spaceIndex) // 在Swift3中,API的命名原则被大幅度调整。大多数函数的名字发生了改变。不过使用方法基本相同。 //swift2: str.replaceRange(range, with: "Hi") str.replaceSubrange(range, with: "Hi") //swift2: str.appendContentsOf("!!!") str.append("!!!") //swift2: str.insert("?", atIndex: str.endIndex) str.insert("?", at: str.endIndex) //swift2: str.removeAtIndex( str.endIndex.predecessor() ) str.remove(at: str.index(before: endIndex)) str //swift2: str.removeRange( str.endIndex.advancedBy(-2)..<str.endIndex ) str.removeSubrange(str.index(endIndex, offsetBy: -2)..<str.endIndex)
apache-2.0
0e4935916e72fb6599a32234c2b2351e
26.576271
78
0.743085
3.007394
false
false
false
false
ashfurrow/eidolon
Kiosk/App/Models/Bid.swift
2
475
import Foundation import SwiftyJSON final class Bid: NSObject, JSONAbleType { let id: String let amountCents: Currency init(id: String, amountCents: Currency) { self.id = id self.amountCents = amountCents } static func fromJSON(_ json:[String: Any]) -> Bid { let json = JSON(json) let id = json["id"].stringValue let amount = json["amount_cents"].uInt64 return Bid(id: id, amountCents: amount!) } }
mit
39567166aae8d28003a97e5c52219020
22.75
55
0.618947
4.059829
false
false
false
false
jopamer/swift
test/decl/var/lazy_properties.swift
1
5674
// RUN: %target-typecheck-verify-swift -parse-as-library -swift-version 4 lazy func lazy_func() {} // expected-error {{'lazy' may only be used on 'var' declarations}} {{1-6=}} lazy var b = 42 // expected-error {{'lazy' must not be used on an already-lazy global}} {{1-6=}} struct S { lazy static var lazy_global = 42 // expected-error {{'lazy' must not be used on an already-lazy global}} {{3-8=}} } protocol SomeProtocol { lazy var x : Int // expected-error {{'lazy' isn't allowed on a protocol requirement}} {{3-8=}} // expected-error@-1 {{property in protocol must have explicit { get } or { get set } specifier}} // expected-error@-2 {{lazy properties must have an initializer}} lazy var y : Int { get } // expected-error {{'lazy' isn't allowed on a protocol requirement}} {{3-8=}} // expected-error@-1 {{'lazy' must not be used on a computed property}} // expected-error@-2 {{lazy properties must have an initializer}} } class TestClass { lazy var a = 42 lazy var a1 : Int = 42 lazy let b = 42 // expected-error {{'lazy' cannot be used on a let}} {{3-8=}} lazy var c : Int { return 42 } // expected-error {{'lazy' must not be used on a computed property}} {{3-8=}} // expected-error@-1 {{lazy properties must have an initializer}} lazy var d : Int // expected-error {{lazy properties must have an initializer}} {{3-8=}} lazy var (e, f) = (1,2) // expected-error {{'lazy' cannot destructure an initializer}} {{3-8=}} lazy var g = { 0 }() // single-expr closure lazy var h : Int = { 0 }() // single-expr closure lazy var i = { () -> Int in return 0 }()+1 // multi-stmt closure lazy var j : Int = { return 0 }()+1 // multi-stmt closure lazy var k : Int = { () -> Int in return 0 }()+1 // multi-stmt closure lazy var l : Int = 42 { // expected-error {{lazy properties must not have observers}} {{3-8=}} didSet { } } init() { lazy var localvar = 42 // expected-error {{lazy is only valid for members of a struct or class}} {{5-10=}} localvar += 1 _ = localvar } } struct StructTest { lazy var p1 : Int = 42 mutating func f1() -> Int { return p1 } // expected-note @+1 {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} func f2() -> Int { return p1 // expected-error {{cannot use mutating getter on immutable value: 'self' is immutable}} } static func testStructInits() { let a = StructTest() // default init let b = StructTest(p1: 42) // Override the lazily init'd value. _ = a; _ = b } } // <rdar://problem/16889110> capture lists in lazy member properties cannot use self class CaptureListInLazyProperty { lazy var closure1 = { [weak self] in return self!.i } lazy var closure2: () -> Int = { [weak self] in return self!.i } var i = 42 } // Crash when initializer expression is type-checked both to infer the // property type and also as part of the getter class WeShouldNotReTypeCheckStatements { lazy var firstCase = { _ = nil // expected-error{{'nil' requires a contextual type}} _ = () } lazy var secondCase = { _ = () _ = () } } protocol MyProtocol { func f() -> Int } struct MyStruct : MyProtocol { func f() -> Int { return 0 } } struct Outer { static let p: MyProtocol = MyStruct() struct Inner { lazy var x = p.f() lazy var y = {_ = 3}() // expected-warning@-1 {{variable 'y' inferred to have type '()', which may be unexpected}} // expected-note@-2 {{add an explicit type annotation to silence this warning}} } } // https://bugs.swift.org/browse/SR-2616 struct Construction { init(x: Int, y: Int? = 42) { } } class Constructor { lazy var myQ = Construction(x: 3) } // Problems with self references class BaseClass { var baseInstanceProp = 42 static var baseStaticProp = 42 } class ReferenceSelfInLazyProperty : BaseClass { lazy var refs = (i, f()) lazy var trefs: (Int, Int) = (i, f()) lazy var qrefs = (self.i, self.f()) lazy var qtrefs: (Int, Int) = (self.i, self.f()) lazy var crefs = { (i, f()) }() lazy var ctrefs: (Int, Int) = { (i, f()) }() lazy var cqrefs = { (self.i, self.f()) }() lazy var cqtrefs: (Int, Int) = { (self.i, self.f()) }() lazy var mrefs = { () -> (Int, Int) in return (i, f()) }() lazy var mtrefs: (Int, Int) = { return (i, f()) }() lazy var mqrefs = { () -> (Int, Int) in (self.i, self.f()) }() lazy var mqtrefs: (Int, Int) = { return (self.i, self.f()) }() lazy var lcqrefs = { [unowned self] in (self.i, self.f()) }() lazy var lcqtrefs: (Int, Int) = { [unowned self] in (self.i, self.f()) }() lazy var lmrefs = { [unowned self] () -> (Int, Int) in return (i, f()) }() lazy var lmtrefs: (Int, Int) = { [unowned self] in return (i, f()) }() lazy var lmqrefs = { [unowned self] () -> (Int, Int) in (self.i, self.f()) }() lazy var lmqtrefs: (Int, Int) = { [unowned self] in return (self.i, self.f()) }() var i = 42 func f() -> Int { return 0 } lazy var refBaseClassProp = baseInstanceProp } class ReferenceStaticInLazyProperty { lazy var refs1 = i // expected-error@-1 {{static member 'i' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}} lazy var refs2 = f() // expected-error@-1 {{static member 'f' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}} lazy var trefs1: Int = i // expected-error@-1 {{static member 'i' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}} lazy var trefs2: Int = f() // expected-error@-1 {{static member 'f' cannot be used on instance of type 'ReferenceStaticInLazyProperty'}} static var i = 42 static func f() -> Int { return 0 } }
apache-2.0
ae0226734e5ad211a6ae18391aebe1d6
30.005464
115
0.620726
3.422195
false
false
false
false
steven7/ParkingApp
MapboxNavigation/Directions.swift
1
769
import Foundation import Mapbox import MapboxDirections import UIKit extension RouteOptions { class func preferredOptions(from origin: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D, heading: CLLocationDirection? = nil, profileIdentifier: MBDirectionsProfileIdentifier) -> RouteOptions { let options = RouteOptions(coordinates: [origin, destination]) options.includesSteps = true options.routeShapeResolution = .full options.profileIdentifier = profileIdentifier if let heading = heading, heading >= 0, let firstWaypoint = options.waypoints.first { firstWaypoint.heading = heading firstWaypoint.headingAccuracy = 90 } return options } }
isc
fd55a63c2b5f69ec759b234fdbce211a
35.619048
213
0.703511
5.453901
false
false
false
false
allbto/ios-angular-waythere
ios/WayThere/Pods/SwiftyJSON/Source/SwiftyJSON.swift
57
35722
// 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. :param: data The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary :param: opt The JSON serialization reading options. `.AllowFragments` by default. :param: 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) { if let object: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: opt, error: error) { self.init(object) } else { self.init(NSNull()) } } /** Creates a JSON using the object. :param: 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 } /** Creates a JSON from a [JSON] :param: jsonArray A Swift array of JSON objects :returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.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 : Swift.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() -> GeneratorOf <(String, JSON)> { switch self.type { case .Array: let array_ = object as! [AnyObject] var generate_ = array_.generate() var index_: Int = 0 return GeneratorOf<(String, JSON)> { 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 GeneratorOf<(String, JSON)> { if let (key_: String, value_: AnyObject) = generate_.next() { return (key_, JSON(value_)) } else { return nil } } default: return GeneratorOf<(String, JSON)> { 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: 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: String) -> JSON { get { var returnJSON = JSON.nullJSON if self.type == .Dictionary { let dictionary_ = self.object as! [String : AnyObject] if let object_: AnyObject = dictionary_[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: 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. :param: 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 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. :param: 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(0), error: NSErrorPointer = nil) -> NSData? { return NSJSONSerialization.dataWithJSONObject(self.object, options: opt, error:error) } public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { switch self.type { case .Array, .Dictionary: if let data = self.rawData(options: opt) { return NSString(data: data, encoding: encoding) as? String } else { 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: Printable, DebugPrintable { 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 map(self.object as! [AnyObject]){ 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 @availability(*, unavailable, renamed="JSON") public typealias JSONValue = JSON extension JSON { @availability(*, unavailable, message="use 'init(_ object:AnyObject)' instead") public init(object: AnyObject) { self = JSON(object) } @availability(*, unavailable, renamed="dictionaryObject") public var dictionaryObjects: [String : AnyObject]? { get { return self.dictionaryObject } } @availability(*, unavailable, renamed="arrayObject") public var arrayObjects: [AnyObject]? { get { return self.arrayObject } } @availability(*, unavailable, renamed="int8") public var char: Int8? { get { return self.number?.charValue } } @availability(*, unavailable, renamed="int8Value") public var charValue: Int8 { get { return self.numberValue.charValue } } @availability(*, unavailable, renamed="uInt8") public var unsignedChar: UInt8? { get{ return self.number?.unsignedCharValue } } @availability(*, unavailable, renamed="uInt8Value") public var unsignedCharValue: UInt8 { get{ return self.numberValue.unsignedCharValue } } @availability(*, unavailable, renamed="int16") public var short: Int16? { get{ return self.number?.shortValue } } @availability(*, unavailable, renamed="int16Value") public var shortValue: Int16 { get{ return self.numberValue.shortValue } } @availability(*, unavailable, renamed="uInt16") public var unsignedShort: UInt16? { get{ return self.number?.unsignedShortValue } } @availability(*, unavailable, renamed="uInt16Value") public var unsignedShortValue: UInt16 { get{ return self.numberValue.unsignedShortValue } } @availability(*, unavailable, renamed="int") public var long: Int? { get{ return self.number?.longValue } } @availability(*, unavailable, renamed="intValue") public var longValue: Int { get{ return self.numberValue.longValue } } @availability(*, unavailable, renamed="uInt") public var unsignedLong: UInt? { get{ return self.number?.unsignedLongValue } } @availability(*, unavailable, renamed="uIntValue") public var unsignedLongValue: UInt { get{ return self.numberValue.unsignedLongValue } } @availability(*, unavailable, renamed="int64") public var longLong: Int64? { get{ return self.number?.longLongValue } } @availability(*, unavailable, renamed="int64Value") public var longLongValue: Int64 { get{ return self.numberValue.longLongValue } } @availability(*, unavailable, renamed="uInt64") public var unsignedLongLong: UInt64? { get{ return self.number?.unsignedLongLongValue } } @availability(*, unavailable, renamed="uInt64Value") public var unsignedLongLongValue: UInt64 { get{ return self.numberValue.unsignedLongLongValue } } @availability(*, unavailable, renamed="int") public var integer: Int? { get { return self.number?.integerValue } } @availability(*, unavailable, renamed="intValue") public var integerValue: Int { get { return self.numberValue.integerValue } } @availability(*, unavailable, renamed="uInt") public var unsignedInteger: Int? { get { return self.number?.unsignedIntegerValue } } @availability(*, unavailable, renamed="uIntValue") public var unsignedIntegerValue: Int { get { return self.numberValue.unsignedIntegerValue } } }
mit
711c3940fa7411a22c2bdf4792bad896
25.519673
259
0.528022
4.717644
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/ObjectMapper/Sources/Mapper.swift
11
15792
// // Mapper.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-09. // // The MIT License (MIT) // // Copyright (c) 2014-2018 Tristan Himmelman // // 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 public enum MappingType { case fromJSON case toJSON } /// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects public final class Mapper<N: BaseMappable> { public var context: MapContext? public var shouldIncludeNilValues = false /// If this is set to true, toJSON output will include null values for any variables that are not set. public init(context: MapContext? = nil, shouldIncludeNilValues: Bool = false){ self.context = context self.shouldIncludeNilValues = shouldIncludeNilValues } // MARK: Mapping functions that map to an existing object toObject /// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is public func map(JSONObject: Any?, toObject object: N) -> N { if let JSON = JSONObject as? [String: Any] { return map(JSON: JSON, toObject: object) } return object } /// Map a JSON string onto an existing object public func map(JSONString: String, toObject object: N) -> N { if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) { return map(JSON: JSON, toObject: object) } return object } /// Maps a JSON dictionary to an existing object that conforms to Mappable. /// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject public func map(JSON: [String: Any], toObject object: N) -> N { var mutableObject = object let map = Map(mappingType: .fromJSON, JSON: JSON, toObject: true, context: context, shouldIncludeNilValues: shouldIncludeNilValues) mutableObject.mapping(map: map) return mutableObject } //MARK: Mapping functions that create an object /// Map a JSON string to an object that conforms to Mappable public func map(JSONString: String) -> N? { if let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) { return map(JSON: JSON) } return nil } /// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil. public func map(JSONObject: Any?) -> N? { if let JSON = JSONObject as? [String: Any] { return map(JSON: JSON) } return nil } /// Maps a JSON dictionary to an object that conforms to Mappable public func map(JSON: [String: Any]) -> N? { let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues) if let klass = N.self as? StaticMappable.Type { // Check if object is StaticMappable if var object = klass.objectForMapping(map: map) as? N { object.mapping(map: map) return object } } else if let klass = N.self as? Mappable.Type { // Check if object is Mappable if var object = klass.init(map: map) as? N { object.mapping(map: map) return object } } else if let klass = N.self as? ImmutableMappable.Type { // Check if object is ImmutableMappable do { if var object = try klass.init(map: map) as? N { object.mapping(map: map) return object } } catch let error { #if DEBUG let exception: NSException if let mapError = error as? MapError { exception = NSException(name: .init(rawValue: "MapError"), reason: mapError.description, userInfo: nil) } else { exception = NSException(name: .init(rawValue: "ImmutableMappableError"), reason: error.localizedDescription, userInfo: nil) } exception.raise() #endif } } else { // Ensure BaseMappable is not implemented directly assert(false, "BaseMappable should not be implemented directly. Please implement Mappable, StaticMappable or ImmutableMappable") } return nil } // MARK: Mapping functions for Arrays and Dictionaries /// Maps a JSON array to an object that conforms to Mappable public func mapArray(JSONString: String) -> [N]? { let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) if let objectArray = mapArray(JSONObject: parsedJSON) { return objectArray } // failed to parse JSON into array form // try to parse it into a dictionary and then wrap it in an array if let object = map(JSONObject: parsedJSON) { return [object] } return nil } /// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil. public func mapArray(JSONObject: Any?) -> [N]? { if let JSONArray = JSONObject as? [[String: Any]] { return mapArray(JSONArray: JSONArray) } return nil } /// Maps an array of JSON dictionary to an array of Mappable objects public func mapArray(JSONArray: [[String: Any]]) -> [N] { // map every element in JSON array to type N #if swift(>=4.1) let result = JSONArray.compactMap(map) #else let result = JSONArray.flatMap(map) #endif return result } /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. public func mapDictionary(JSONString: String) -> [String: N]? { let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) return mapDictionary(JSONObject: parsedJSON) } /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. public func mapDictionary(JSONObject: Any?) -> [String: N]? { if let JSON = JSONObject as? [String: [String: Any]] { return mapDictionary(JSON: JSON) } return nil } /// Maps a JSON dictionary of dictionaries to a dictionary of Mappable objects public func mapDictionary(JSON: [String: [String: Any]]) -> [String: N]? { // map every value in dictionary to type N let result = JSON.filterMap(map) if !result.isEmpty { return result } return nil } /// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil. public func mapDictionary(JSONObject: Any?, toDictionary dictionary: [String: N]) -> [String: N] { if let JSON = JSONObject as? [String : [String : Any]] { return mapDictionary(JSON: JSON, toDictionary: dictionary) } return dictionary } /// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappable objects public func mapDictionary(JSON: [String: [String: Any]], toDictionary dictionary: [String: N]) -> [String: N] { var mutableDictionary = dictionary for (key, value) in JSON { if let object = dictionary[key] { _ = map(JSON: value, toObject: object) } else { mutableDictionary[key] = map(JSON: value) } } return mutableDictionary } /// Maps a JSON object to a dictionary of arrays of Mappable objects public func mapDictionaryOfArrays(JSONObject: Any?) -> [String: [N]]? { if let JSON = JSONObject as? [String: [[String: Any]]] { return mapDictionaryOfArrays(JSON: JSON) } return nil } ///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) -> [String: [N]]? { // map every value in dictionary to type N let result = JSON.filterMap { mapArray(JSONArray: $0) } if !result.isEmpty { return result } return nil } /// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects public func mapArrayOfArrays(JSONObject: Any?) -> [[N]]? { if let JSONArray = JSONObject as? [[[String: Any]]] { let objectArray = JSONArray.map { innerJSONArray in return mapArray(JSONArray: innerJSONArray) } if !objectArray.isEmpty { return objectArray } } return nil } // MARK: Utility functions for converting strings to JSON objects /// Convert a JSON String into a Dictionary<String, Any> using NSJSONSerialization public static func parseJSONStringIntoDictionary(JSONString: String) -> [String: Any]? { let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) return parsedJSON as? [String: Any] } /// Convert a JSON String into an Object using NSJSONSerialization public static func parseJSONString(JSONString: String) -> Any? { let data = JSONString.data(using: String.Encoding.utf8, allowLossyConversion: true) if let data = data { let parsedJSON: Any? do { parsedJSON = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) } catch let error { print(error) parsedJSON = nil } return parsedJSON } return nil } } extension Mapper { // MARK: Functions that create model from JSON file /// JSON file to Mappable object /// - parameter JSONfile: Filename /// - Returns: Mappable object public func map(JSONfile: String) -> N? { if let path = Bundle.main.path(forResource: JSONfile, ofType: nil) { do { let JSONString = try String(contentsOfFile: path) do { return self.map(JSONString: JSONString) } } catch { return nil } } return nil } /// JSON file to Mappable object array /// - parameter JSONfile: Filename /// - Returns: Mappable object array public func mapArray(JSONfile: String) -> [N]? { if let path = Bundle.main.path(forResource: JSONfile, ofType: nil) { do { let JSONString = try String(contentsOfFile: path) do { return self.mapArray(JSONString: JSONString) } } catch { return nil } } return nil } } extension Mapper { // MARK: Functions that create JSON from objects ///Maps an object that conforms to Mappable to a JSON dictionary <String, Any> public func toJSON(_ object: N) -> [String: Any] { var mutableObject = object let map = Map(mappingType: .toJSON, JSON: [:], context: context, shouldIncludeNilValues: shouldIncludeNilValues) mutableObject.mapping(map: map) return map.JSON } ///Maps an array of Objects to an array of JSON dictionaries [[String: Any]] public func toJSONArray(_ array: [N]) -> [[String: Any]] { return array.map { // convert every element in array to JSON dictionary equivalent self.toJSON($0) } } ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. public func toJSONDictionary(_ dictionary: [String: N]) -> [String: [String: Any]] { return dictionary.map { (arg: (key: String, value: N)) in // convert every value in dictionary to its JSON dictionary equivalent return (arg.key, self.toJSON(arg.value)) } } ///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries. public func toJSONDictionaryOfArrays(_ dictionary: [String: [N]]) -> [String: [[String: Any]]] { return dictionary.map { (arg: (key: String, value: [N])) in // convert every value (array) in dictionary to its JSON dictionary equivalent return (arg.key, self.toJSONArray(arg.value)) } } /// Maps an Object to a JSON string with option of pretty formatting public func toJSONString(_ object: N, prettyPrint: Bool = false) -> String? { let JSONDict = toJSON(object) return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) } /// Maps an array of Objects to a JSON string with option of pretty formatting public func toJSONString(_ array: [N], prettyPrint: Bool = false) -> String? { let JSONDict = toJSONArray(array) return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) } /// Converts an Object to a JSON string with option of pretty formatting public static func toJSONString(_ JSONObject: Any, prettyPrint: Bool) -> String? { let options: JSONSerialization.WritingOptions = prettyPrint ? .prettyPrinted : [] if let JSON = Mapper.toJSONData(JSONObject, options: options) { return String(data: JSON, encoding: String.Encoding.utf8) } return nil } /// Converts an Object to JSON data with options public static func toJSONData(_ JSONObject: Any, options: JSONSerialization.WritingOptions) -> Data? { if JSONSerialization.isValidJSONObject(JSONObject) { let JSONData: Data? do { JSONData = try JSONSerialization.data(withJSONObject: JSONObject, options: options) } catch let error { print(error) JSONData = nil } return JSONData } return nil } } extension Mapper where N: Hashable { /// Maps a JSON array to an object that conforms to Mappable public func mapSet(JSONString: String) -> Set<N>? { let parsedJSON: Any? = Mapper.parseJSONString(JSONString: JSONString) if let objectArray = mapArray(JSONObject: parsedJSON) { return Set(objectArray) } // failed to parse JSON into array form // try to parse it into a dictionary and then wrap it in an array if let object = map(JSONObject: parsedJSON) { return Set([object]) } return nil } /// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil. public func mapSet(JSONObject: Any?) -> Set<N>? { if let JSONArray = JSONObject as? [[String: Any]] { return mapSet(JSONArray: JSONArray) } return nil } /// Maps an Set of JSON dictionary to an array of Mappable objects public func mapSet(JSONArray: [[String: Any]]) -> Set<N> { // map every element in JSON array to type N #if swift(>=4.1) return Set(JSONArray.compactMap(map)) #else return Set(JSONArray.flatMap(map)) #endif } ///Maps a Set of Objects to a Set of JSON dictionaries [[String : Any]] public func toJSONSet(_ set: Set<N>) -> [[String: Any]] { return set.map { // convert every element in set to JSON dictionary equivalent self.toJSON($0) } } /// Maps a set of Objects to a JSON string with option of pretty formatting public func toJSONString(_ set: Set<N>, prettyPrint: Bool = false) -> String? { let JSONDict = toJSONSet(set) return Mapper.toJSONString(JSONDict as Any, prettyPrint: prettyPrint) } } extension Dictionary { internal func map<K, V>(_ f: (Element) throws -> (K, V)) rethrows -> [K: V] { var mapped = [K: V]() for element in self { let newElement = try f(element) mapped[newElement.0] = newElement.1 } return mapped } internal func map<K, V>(_ f: (Element) throws -> (K, [V])) rethrows -> [K: [V]] { var mapped = [K: [V]]() for element in self { let newElement = try f(element) mapped[newElement.0] = newElement.1 } return mapped } internal func filterMap<U>(_ f: (Value) throws -> U?) rethrows -> [Key: U] { var mapped = [Key: U]() for (key, value) in self { if let newValue = try f(value) { mapped[key] = newValue } } return mapped } }
mit
e1a7abf599f5d0c1765acf3a1cb9a44a
31.162933
145
0.694656
3.827436
false
false
false
false
HarukaMa/iina
iina/ShortcutAvailableTextField.swift
1
1656
// // ShortcutAvailableTextField.swift // iina // // Created by lhc on 26/12/2016. // Copyright © 2016 lhc. All rights reserved. // http://stackoverflow.com/questions/970707 // import Cocoa class ShortcutAvailableTextField: NSTextField { private let commandKey = NSEventModifierFlags.command.rawValue private let commandShiftKey = NSEventModifierFlags.command.rawValue | NSEventModifierFlags.shift.rawValue override func performKeyEquivalent(with event: NSEvent) -> Bool { if event.type == NSEventType.keyDown { if (event.modifierFlags.rawValue & NSEventModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey { switch event.charactersIgnoringModifiers! { case "x": if NSApp.sendAction(#selector(NSText.cut(_:)), to:nil, from:self) { return true } case "c": if NSApp.sendAction(#selector(NSText.copy(_:)), to:nil, from:self) { return true } case "v": if NSApp.sendAction(#selector(NSText.paste(_:)), to:nil, from:self) { return true } case "z": if NSApp.sendAction(Selector(("undo:")), to:nil, from:self) { return true } case "a": if NSApp.sendAction(#selector(NSResponder.selectAll(_:)), to:nil, from:self) { return true } default: break } } else if (event.modifierFlags.rawValue & NSEventModifierFlags.deviceIndependentFlagsMask.rawValue) == commandShiftKey { if event.charactersIgnoringModifiers == "Z" { if NSApp.sendAction(Selector(("redo:")), to:nil, from:self) { return true } } } } return super.performKeyEquivalent(with: event) } }
gpl-3.0
f700760d7d7c9d73337388fd4f1cf015
35.777778
124
0.662236
4.321149
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Classes/Player/NormalPlayer/Controller/ZHNnormalPlayerViewController.swift
1
18328
// // ZHNnormalPlayerViewController.swift // zhnbilibili // // Created by zhn on 16/12/12. // Copyright © 2016年 zhn. All rights reserved. // import UIKit /// 一些常量 let knavibarheight: CGFloat = 64 let kinputDanmuHeight: CGFloat = 40 fileprivate let kslideMenuViewHeight: CGFloat = 30 class ZHNnormalPlayerViewController: ZHNPlayerBaseViewController { // MARK - 属性 /// 数据的模型 var itemModel: YSItemDetailModel? /// 判断是否需要滑动的效果 var watced = false /// viewmodel var playItemVM: ZHNnormalPlayerViewModel = ZHNnormalPlayerViewModel() /// 滑动切换播放时间的提示view var noticeView: ZHNforwardBackforwardNoticeView? /// 输入框是否正在展示 var isinputShowing = false /// (是否需要直接pop掉控制器,如果player被shutdown的情况下需要pop掉) var isNeedDisapper = false // MARK: - 懒加载控件 lazy var contentScrollView: UIScrollView = {[weak self] in let contentScrollView = UIScrollView() contentScrollView.contentSize = CGSize(width: kScreenWidth*2, height:1) contentScrollView.isPagingEnabled = true contentScrollView.bounces = false contentScrollView.showsHorizontalScrollIndicator = false contentScrollView.panGestureRecognizer.require(toFail: (self?.navigationController?.interactivePopGestureRecognizer)!) return contentScrollView }() lazy var detailController: ZHNnormalPlayerDetailTableViewController = { let detailController = ZHNnormalPlayerDetailTableViewController() detailController.delegate = self return detailController }() lazy var commondController: ZHNnormalPlayerCommondTableViewController = {[weak self] in let commondController = ZHNnormalPlayerCommondTableViewController() if let aid = self?.itemModel?.param{ commondController.aid = aid } return commondController }() lazy var slideMenuContainer: UIView = { let slideMenuContainer = UIView() slideMenuContainer.backgroundColor = UIColor.white return slideMenuContainer }() lazy var blurView: playerBlurView = { let blurView = playerBlurView() // 1. 背景的图片 blurView.blurImageString = self.itemModel?.cover // 2. 返回按钮的事件 blurView.backButtonAction = {[weak self] in _ = self?.navigationController?.popViewController(animated: true) } // 3. 屏幕的点击事件 blurView.tapAction = {[weak self] in self?.pLoadPlay() YSNotificationHelper.shutDownOldPlayer() } return blurView }() lazy var slideMenuView: SlideMenu = { [unowned self] in // 1.frame let width:CGFloat = 220 let height:CGFloat = 30 let x = (self.view.ysWidth - width)/2 let y = kslideMenuViewHeight - 26 let rect = CGRect(x: x, y: y, width: width, height: height) // 2.平常的颜色 let normalColor = SlideMenu.SlideMenuTitleColor(red: 198, green: 198, blue: 198) // 3.显示的颜色 let hightLightColor = SlideMenu.SlideMenuTitleColor(red: 252, green: 132, blue: 164) // 4.生成slidemenu let menu = SlideMenu(frame: rect, titles: [" 简介 "," 评论 "], padding: 15, normalColor: normalColor, highlightColor: hightLightColor, font: 16, sliderColor: kNavBarColor, scrollView: self.contentScrollView, isHorizon: true, rowHeight: 30) return menu }() lazy var loadingMaskView: normalPlayerLoadingMaskView = { let loadingMaskView = normalPlayerLoadingMaskView() loadingMaskView.backButtonAction = {[weak self] in _ = self?.navigationController?.popViewController(animated: true) } return loadingMaskView }() // MARK: - life cycle override func viewDidLoad() { // 1. 初始化ui setupUI() // 2. 监听滑动 observeTableViewScroll() // 3. 调用父类方法 super.viewDidLoad() // 4. 是否是普通播放器(默认是直播播放器) self.isNormalPlayer = true // 5. 需要先将播放器隐藏 liveContainerView.isHidden = true // 6. 加载数据 requestData(aid: (itemModel?.param)!,finishAction: {}) // 7. 加载通知 addNotification() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.clearAllNotice() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if isNeedDisapper { _ = navigationController?.popViewController(animated: false) } } deinit { removeAllobserve() } // MARK - 重写父类方法 override func firstLoadSuccess(notification: Notification) { super.firstLoadSuccess(notification: notification) // 传递一个player给弹幕view,这样弹幕的现实能够和播放的进度匹配 DispatchQueue.main.async { self.danmuView.player = self.player } } } //====================================================================== // MARK:- 私有方法 //====================================================================== extension ZHNnormalPlayerViewController { fileprivate func setupUI() { self.addChildViewController(detailController) self.addChildViewController(commondController) view.addSubview(contentScrollView) view.addSubview(slideMenuContainer) contentScrollView.addSubview(detailController.view) contentScrollView.addSubview(commondController.view) slideMenuContainer.addSubview(slideMenuView) view.addSubview(blurView) view.addSubview(loadingMaskView) contentScrollView.frame = CGRect(x: 0, y: knormalPlayerHeight+kslideMenuViewHeight, width: kScreenWidth, height: kScreenHeight - knavibarheight-kslideMenuViewHeight) detailController.view.frame = CGRect(x: 0, y: -20, width: kScreenWidth, height: contentScrollView.ysHeight) commondController.view.frame = CGRect(x: kScreenWidth, y: -20, width: kScreenWidth, height: contentScrollView.ysHeight) slideMenuContainer.frame = CGRect(x: 0, y: knormalPlayerHeight, width: kScreenWidth, height: kslideMenuViewHeight) blurView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: knormalPlayerHeight) loadingMaskView.frame = view.bounds } fileprivate func addNotification() { NotificationCenter.default.addObserver(self, selector: #selector(swipeToChangingPlayTime(notification:)), name: kSwipeScreenToChangePlayTimeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(swipeEnd(notification:)), name: kSwipeScreenEndNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(swipeStart(notification:)), name: kSwipeScrrenBeginNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(shutDownPlayer), name: kPlayingPlayerNeedToShutDownNotification, object: nil) } fileprivate func observeTableViewScroll() { detailController.tableView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil) commondController.tableView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil) } fileprivate func removeAllobserve() { detailController.tableView.removeObserver(self, forKeyPath: "contentOffset",context: nil) commondController.tableView.removeObserver(self, forKeyPath: "contentOffset",context: nil) NotificationCenter.default.removeObserver(self) } fileprivate func addInputView() { let inputView = UIView() inputView.backgroundColor = UIColor.black isinputShowing = true view.insertSubview(inputView, belowSubview: liveContainerView) inputView.snp.makeConstraints { (make) in make.left.right.equalTo(view) make.bottom.equalTo(slideMenuContainer.snp.top) make.height.equalTo(kinputDanmuHeight) } let iconImageView = UIImageView() iconImageView.image = UIImage(named: "misc_avatarDefault") iconImageView.layer.cornerRadius = 12 iconImageView.clipsToBounds = true inputView.addSubview(iconImageView) iconImageView.snp.makeConstraints { (make) in make.left.equalTo(inputView).offset(20) make.centerY.equalTo(inputView) make.size.equalTo(CGSize(width: 24, height: 24)) } let noticeLabel = UILabel() noticeLabel.text = "输入弹幕" noticeLabel.backgroundColor = UIColor.darkGray noticeLabel.textColor = UIColor.lightGray noticeLabel.textAlignment = .center noticeLabel.layer.cornerRadius = 13 noticeLabel.font = UIFont.systemFont(ofSize: 13) noticeLabel.clipsToBounds = true inputView.addSubview(noticeLabel) noticeLabel.snp.makeConstraints { (make) in make.centerY.equalTo(inputView) make.height.equalTo(26) make.left.equalTo(iconImageView.snp.right).offset(40) make.right.equalTo(inputView.snp.right).offset(-40) } } fileprivate func pLoadPlay() { // <<1. 视频上的处理 blurView.isHidden = true self.liveContainerView.isHidden = false if let playerurl = self.playItemVM.playerUrl { self.liveString = playerurl } self.loadPlayer() self.watced = true // <<2. 简介评论的处理 self.slideMenuContainer.ysY = knormalPlayerHeight + kinputDanmuHeight self.contentScrollView.ysY = knormalPlayerHeight + kinputDanmuHeight + kslideMenuViewHeight self.detailController.view.ysHeight = kScreenHeight - kinputDanmuHeight - kslideMenuViewHeight - knormalPlayerHeight self.commondController.view.ysHeight = kScreenHeight - kinputDanmuHeight - kslideMenuViewHeight - knormalPlayerHeight self.detailController.tableView.contentInset = UIEdgeInsets.zero self.commondController.tableView.contentInset = UIEdgeInsets.zero self.detailController.watched = watced self.addInputView() } fileprivate func requestData(aid: Int,finishAction:@escaping (()->Void)) { self.danmuView.endRender() self.danmuView.startRender() playItemVM.requestData(aid: aid, finishCallBack: { [weak self] in DispatchQueue.main.async { self?.titleString = self?.playItemVM.detailModel?.title self?.loadingMaskView.removeFromSuperview() self?.danmuView.danmuModelArray = self?.playItemVM.danmuModelArray self?.detailController.detailModel = self?.playItemVM.detailModel self?.blurView.titleLabel.text = "AV\((self?.itemModel?.param)!)" self?.clearAllNotice() if let urlStr = self?.playItemVM.detailModel?.pic { let url = URL(string: urlStr) self?.blurView.backImageView.sd_setImage(with: url) self?.blurView.backImageView.sd_setImage(with: url, completed: { (image, error, type, url) in self?.blurView.percent = 0.999 }) } self?.detailController.tableView.scrollToRow(at: IndexPath(item: 0, section: 0), at: .bottom, animated: true) finishAction() } }) { } } } //====================================================================== // MARK:- kvo 和 通知 //====================================================================== extension ZHNnormalPlayerViewController { override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // 1. 滑动 if keyPath == "contentOffset" { if watced {return} // <1. 拿到滑动的offset guard let NSoffset = change?[NSKeyValueChangeKey.newKey] else {return} guard let CGoffset = (NSoffset as AnyObject).cgPointValue else {return} // <2. 计算值(考虑边界的值) var delta = knormalPlayerHeight - CGoffset.y * 0.5 if delta < knavibarheight { delta = knavibarheight }else if delta > knormalPlayerHeight { delta = knormalPlayerHeight } // <3. 滑动控件 //<<1. blur 不会因为增加了输入view而改变 blurView.percent = (delta - knavibarheight)/(knormalPlayerHeight-knavibarheight) blurView.ysHeight = delta //<<2. slidemenu 和地下的view会随着改变 if isinputShowing { delta = delta + kinputDanmuHeight } slideMenuContainer.ysY = delta contentScrollView.ysY = delta+kslideMenuViewHeight } } @objc fileprivate func swipeStart(notification: Notification) { // 1.生成提示的view let noticeView = ZHNforwardBackforwardNoticeView.instanceView() noticeView.isHidden = true liveContainerView.addSubview(noticeView) noticeView.snp.makeConstraints { (make) in make.center.equalTo(liveContainerView) make.size.equalTo(CGSize(width: 150, height: 110)) } self.noticeView = noticeView // 2.赋值一个当前的播放时间 if let currentPlayBackTime = player?.currentPlaybackTime { self.noticeView?.currentPlayTime = currentPlayBackTime } } @objc fileprivate func swipeEnd(notification: Notification) { guard let needGoTime = noticeView?.needGoingPlayTime else {return} if noticeView?.isHidden == false { player?.currentPlaybackTime = needGoTime } noticeView?.removeFromSuperview() } @objc fileprivate func swipeToChangingPlayTime(notification: Notification) { noticeView?.isHidden = false guard let trans = notification.userInfo?[ktransKey] as? Float else {return} if let duration = player?.duration { noticeView?.maxPlayTime = duration } noticeView?.translate = trans } @objc fileprivate func shutDownPlayer() { if navigationController?.visibleViewController != self { if isinputShowing { player?.shutdown() isNeedDisapper = true } } } } //====================================================================== // MARK:- 各点击事件的响应方法 //====================================================================== extension ZHNnormalPlayerViewController: ZHNnormalPlayerDetailTableViewControllerDelegate { func ZHNnormalPlayerDetailTableViewControllerSelectedNewPlay(aid: Int) { // 切换播放器 if watced {// 在播放状态下的切换 self.noticeOnlyText("视频切换中") self.detailController.tableView.scrollToRow(at: IndexPath(item: 0, section: 0), at: .bottom, animated: true) // 2.加载数据 requestData(aid: aid,finishAction: { DispatchQueue.main.async { // 1.清空之前的播放的状态 self.player?.shutdown() self.player = nil } // <1. view的一些初始化 self.watced = false self.detailController.view.frame = CGRect(x: 0, y: -20, width: kScreenWidth, height: kScreenHeight - kinputDanmuHeight - kslideMenuViewHeight - knavibarheight) self.commondController.view.frame = CGRect(x: kScreenWidth, y: -20, width: kScreenWidth, height: kScreenHeight - kinputDanmuHeight - kslideMenuViewHeight - knavibarheight) self.detailController.detailModel = self.playItemVM.detailModel self.blurView.isHidden = false self.liveContainerView.isHidden = true if let urlStr = self.playItemVM.detailModel?.pic { let url = URL(string: urlStr) self.blurView.backImageView.sd_setImage(with: url, completed: { (image, error, type, url) in self.blurView.percent = 0.999 }) } self.playLoadingMenuView.isHidden = false // 切换评论 self.commondController.aid = aid }) }else {// 不在播放状态下的切换 self.noticeOnlyText("加载数据中") requestData(aid: aid, finishAction: { // 切换评论 self.commondController.aid = aid }) } } func ZHNnormalPlayerDetailTableViewControllerSelectedPage(cid: Int,index: Int) { self.noticeOnlyText("剧集切换中") // 清空之前的播放状态player的关闭要在主线程进行 self.player?.shutdown() self.player = nil self.danmuView.endRender() self.danmuView.startRender() self.detailController.tableView.scrollToRow(at: IndexPath(item: 0, section: 0), at: .bottom, animated: true) playItemVM.requestPagePlayUrl(page: index, cid: cid) { [weak self] in self?.clearAllNotice() if (self?.watced)! {// 在播放状态下的切换 // 先加载弹幕 self?.danmuView.danmuModelArray = self?.playItemVM.danmuModelArray // 在加载player if let playerurl = self?.playItemVM.playerUrl { self?.liveString = playerurl } self?.playLoadingMenuView.isHidden = false self?.loadPlayer() }else {// 不在播放状态下的切换 self?.pLoadPlay() } } } }
mit
eca555126e853a0d27a0168a807d2e02
40.883055
257
0.621346
4.8119
false
false
false
false
tadija/AEAccordion
Example/AEAccordionExample/SampleTableViewController.swift
1
1797
/** * https://github.com/tadija/AEAccordion * Copyright (c) Marko Tadić 2015-2018 * Licensed under the MIT license. See LICENSE file. */ import AEAccordion final class SampleTableViewController: AccordionTableViewController { // MARK: Properties private let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() registerCell() expandFirstCell() } // MARK: Helpers func registerCell() { let cellNib = UINib(nibName: SampleTableViewCell.reuseIdentifier, bundle: nil) tableView.register(cellNib, forCellReuseIdentifier: SampleTableViewCell.reuseIdentifier) } func expandFirstCell() { let firstCellIndexPath = IndexPath(row: 0, section: 0) expandedIndexPaths.append(firstCellIndexPath) } // MARK: UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return days.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SampleTableViewCell.reuseIdentifier, for: indexPath) if let cell = cell as? SampleTableViewCell { cell.day.text = days[indexPath.row] cell.weatherIcon.image = UIImage(named: "0\(indexPath.row + 1)") } return cell } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return expandedIndexPaths.contains(indexPath) ? 200.0 : 50.0 } }
mit
cdaf47cafda3f11001236496079efbdd
29.440678
117
0.654232
5.002786
false
false
false
false
TieShanWang/KKAutoScrollView
KKAutoScrollView/KKAutoScrollView/KKAutoScrollPageControl.swift
1
2205
// // KKAutoScrollPageControl.swift // KKAutoScrollView // // Created by 王铁山 on 2018/5/22. // Copyright © 2018年 king. All rights reserved. // import UIKit /// page control 父类 open class KKAutoScrollPageControl: UIView { open var currentPage: Int = 0 { didSet { self.didSetCurrentPage() } } open var numberOfPages: Int = 0 { didSet { self.didSetNumOfPages() } } open var pageIndicatorTintColor: UIColor = UIColor.white { didSet { self.didSetPageIndicatorTintColor() } } open var currentPageIndicatorTintColor: UIColor = UIColor.gray { didSet { self.didCurrentPageIndicatorTintColor() } } open func didSetCurrentPage() { } open func didSetNumOfPages() { } open func didSetPageIndicatorTintColor() { } open func didCurrentPageIndicatorTintColor() { } open func size(forNumberOfPages pageCount: Int) -> CGSize { fatalError("message must override this method") } } /// pagecontrol 默认使用的类 open class KKAutoScrollDefaultPageControl: KKAutoScrollPageControl { var pageControl: UIPageControl = UIPageControl() open override func didSetCurrentPage() { self.pageControl.currentPage = currentPage } open override func didSetNumOfPages() { self.pageControl.numberOfPages = numberOfPages } open override func didSetPageIndicatorTintColor() { self.pageControl.pageIndicatorTintColor = pageIndicatorTintColor } open override func didCurrentPageIndicatorTintColor() { self.pageControl.currentPageIndicatorTintColor = currentPageIndicatorTintColor } open override func size(forNumberOfPages pageCount: Int) -> CGSize { return self.pageControl.size(forNumberOfPages: pageCount) } open override func layoutSubviews() { super.layoutSubviews() if self.pageControl.superview == nil { self.addSubview(pageControl) } self.pageControl.frame = self.bounds } }
mit
3949a07a9b5531c0ba44a6f655fe0083
22.956044
86
0.631193
5.27845
false
false
false
false
hustlzp/iOS-Base
genstrings.swift
2
4825
#!/usr/bin/swift import Foundation class GenStrings { var str = "Hello, playground" let fileManager = FileManager.default let acceptedFileExtensions = ["swift"] let excludedFolderNames = ["Carthage"] let excludedFileNames = ["genstrings.swift"] var regularExpresions = [String:NSRegularExpression]() let localizedRegex = "(?<=\")([^\"]*)(?=\".(localized|localizedFormat))|(?<=(Localized|NSLocalizedString)\\(\")([^\"]*?)(?=\")" enum GenstringsError: Error { case Error } // Performs the genstrings functionality func perform(path: String? = nil) { let directoryPath = path ?? fileManager.currentDirectoryPath let rootPath = URL(fileURLWithPath:directoryPath) let allFiles = fetchFilesInFolder(rootPath: rootPath) // We use a set to avoid duplicates var localizableStrings = Set<String>() for filePath in allFiles { let stringsInFile = localizableStringsInFile(filePath: filePath) localizableStrings = localizableStrings.union(stringsInFile) } // We sort the strings let sortedStrings = localizableStrings.sorted(by: { $0 < $1 }) var processedStrings = String() for string in sortedStrings { processedStrings.append("\"\(string)\" = \"\(string)\"; \n") } print(processedStrings) } // Applies regex to a file at filePath. func localizableStringsInFile(filePath: URL) -> Set<String> { do { let fileContentsData = try Data(contentsOf: filePath) guard let fileContentsString = NSString(data: fileContentsData, encoding: String.Encoding.utf8.rawValue) else { return Set<String>() } let localizedStringsArray = try regexMatches(pattern: localizedRegex, string: fileContentsString as String).map({fileContentsString.substring(with: $0.range)}) return Set(localizedStringsArray) } catch {} return Set<String>() } //MARK: Regex func regexWithPattern(pattern: String) throws -> NSRegularExpression { var safeRegex = regularExpresions if let regex = safeRegex[pattern] { return regex } else { do { let currentPattern: NSRegularExpression currentPattern = try NSRegularExpression(pattern: pattern, options:NSRegularExpression.Options.caseInsensitive) safeRegex.updateValue(currentPattern, forKey: pattern) regularExpresions = safeRegex return currentPattern } catch { throw GenstringsError.Error } } } func regexMatches(pattern: String, string: String) throws -> [NSTextCheckingResult] { do { let internalString = string let currentPattern = try regexWithPattern(pattern: pattern) // NSRegularExpression accepts Swift strings but works with NSString under the hood. Safer to bridge to NSString for taking range. let nsString = internalString as NSString let stringRange = NSMakeRange(0, nsString.length) let matches = currentPattern.matches(in: internalString, options: [], range: stringRange) return matches } catch { throw GenstringsError.Error } } //MARK: File manager func fetchFilesInFolder(rootPath: URL) -> [URL] { var files = [URL]() do { let directoryContents = try fileManager.contentsOfDirectory(at: rootPath as URL, includingPropertiesForKeys: [], options: .skipsHiddenFiles) for urlPath in directoryContents { let stringPath = urlPath.path let lastPathComponent = urlPath.lastPathComponent let pathExtension = urlPath.pathExtension var isDir : ObjCBool = false if fileManager.fileExists(atPath: stringPath, isDirectory:&isDir) { if isDir.boolValue { if !excludedFolderNames.contains(lastPathComponent) { let dirFiles = fetchFilesInFolder(rootPath: urlPath) files.append(contentsOf: dirFiles) } } else { if acceptedFileExtensions.contains(pathExtension) && !excludedFileNames.contains(lastPathComponent) { files.append(urlPath) } } } } } catch {} return files } } let genStrings = GenStrings() if CommandLine.arguments.count > 1 { let path = CommandLine.arguments[1] genStrings.perform(path: path) } else { genStrings.perform() }
mit
a433bdc5ad291949c570ca9b4c4eea7b
37.608
171
0.601658
5.227519
false
false
false
false
shaps80/SwiftLayout
Pod/Classes/Constraint.swift
1
7999
/* Copyright © 2015 Shaps Mohsenin. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY FRANCESCO PETRUNGARO `AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL FRANCESCO PETRUNGARO OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if os(iOS) import UIKit public typealias LayoutPriority = UILayoutPriority public typealias LayoutAttribute = NSLayoutAttribute public typealias LayoutRelation = NSLayoutRelation #else import AppKit public typealias LayoutPriority = NSLayoutConstraint.Priority public typealias LayoutAttribute = NSLayoutConstraint.Attribute public typealias LayoutRelation = NSLayoutConstraint.Relation #endif public let LayoutPriorityRequired: LayoutPriority = LayoutPriority(rawValue: 1000) // A required constraint. Do not exceed this. public let LayoutPriorityDefaultHigh: LayoutPriority = LayoutPriority(rawValue: 750) // This is the priority level with which a button resists compressing its content. public let LayoutPriorityDefaultLow: LayoutPriority = LayoutPriority(rawValue: 250) // This is the priority level at which a button hugs its contents horizontally. /** * The classes included in this file extend NSLayoutConstraints, provide Swift implementations and cross-platform support for iOS, OSX, Watch and Apple TV */ /** * Defines various constraint traits (bitmask) that define the type of constraints applied to a view. */ public struct ConstraintsTraitMask: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// No constraints applied public static var None: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 0) } /// A top margin constraint is applied public static var topMargin: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 0) } /// A left margin constraint is applied public static var leftMargin: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 1) } /// A right margin constraint is applied public static var rightMargin: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 2) } /// A bottom margin constraint is applied public static var bottomMargin: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 3) } /// A horitzontal alignment constraint is applied public static var horizontalAlignment: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 4) } /// A vertical aligntment constraint is applied public static var verticalAlignment: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 5) } /// A horizontal sizing constraint is applied public static var horizontalSizing: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 6) } /// A vertical sizing constraint is applied public static var verticalSizing: ConstraintsTraitMask { return ConstraintsTraitMask(rawValue: 1 << 7) } /// Horizontal margin constraints are applied (Left and Right) public static var horizontalMargins: ConstraintsTraitMask { return [leftMargin, rightMargin] } /// Vertical margin constraints are applied (Top and Right) public static var verticalMargins: ConstraintsTraitMask { return [topMargin, bottomMargin] } } // MARK: - This extends UI/NS View to provide additional constraints support extension View { /// Returns all constraints relevant to this view public var viewConstraints: [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() for constraint in self.constraints { constraints.append(constraint) } if let superviewConstraints = self.superview?.constraints { for constraint in superviewConstraints { if constraint.firstItem as? View != self && constraint.secondItem as? View != self { continue } constraints.append(constraint) } } return constraints } } /** Defines an abstract representation of a constraint */ public protocol ConstraintDefinition { var priority: LayoutPriority { get } var constant: CGFloat { get set } var multiplier: CGFloat { get } var relation: LayoutRelation { get } var firstAttribute: LayoutAttribute { get } var secondAttribute: LayoutAttribute { get } var trait: ConstraintsTraitMask { get } } /** We extend the existing NSLayoutConstraint, as well as our own implementation ConstraintDefinition */ extension NSLayoutConstraint: ConstraintDefinition { } /** This extension provides a Swift value-type representation of NSLayoutConstraint */ extension ConstraintDefinition { public var trait: ConstraintsTraitMask { let left = self.firstAttribute == .left || self.firstAttribute == .leading let right = self.firstAttribute == .right || self.firstAttribute == .trailing let top = self.firstAttribute == .top let bottom = self.firstAttribute == .bottom let width = self.firstAttribute == .width let height = self.firstAttribute == .height let centerX = self.firstAttribute == .centerX let centerY = self.firstAttribute == .centerY if width { return .horizontalSizing } if height { return .verticalSizing } if centerX { return .horizontalAlignment } if centerY { return .verticalAlignment } if left { return .leftMargin } if right { return .rightMargin } if top { return .topMargin } if bottom { return .bottomMargin } return .None } } /** * A Swift value-type implementation of NSLayoutConstraint */ public struct Constraint: ConstraintDefinition { public internal(set) var priority: LayoutPriority public var constant: CGFloat public internal(set) var multiplier: CGFloat public internal(set) var relation: LayoutRelation public internal(set) var firstAttribute: LayoutAttribute public internal(set) var secondAttribute: LayoutAttribute public unowned var firstView: View { didSet { precondition(firstView.superview != nil, "The first view MUST be inserted into a superview before constraints can be applied") } } public weak var secondView: View? fileprivate weak var _constraint: NSLayoutConstraint? public init(view: View) { self.firstView = view self.firstAttribute = .notAnAttribute self.secondAttribute = .notAnAttribute self.constant = 0 self.multiplier = 1 self.relation = .equal self.priority = LayoutPriority(rawValue: 250) view.translatesAutoresizingMaskIntoConstraints = false } public mutating func constraint() -> NSLayoutConstraint { if self._constraint == nil { self._constraint = NSLayoutConstraint( item: self.firstView, attribute: firstAttribute, relatedBy: self.relation, toItem: self.secondView, attribute: self.secondAttribute, multiplier: self.multiplier, constant: self.constant) } return self._constraint! } }
mit
2f285b73adbdb19d7b0dba699fce8d14
35.190045
167
0.74131
5.091025
false
false
false
false
quintonwall/leads-sdk
Example/leads-sdk/ViewController.swift
1
2015
// // Sample implemention of the leads button // // Created by Quinton Wall on 01/27/2016. // Copyright (c) 2016 Quinton Wall. All rights reserved. // import UIKit import leads_sdk class ViewController: UIViewController { @IBOutlet weak var myLeadButton: LeadsButton! override func viewDidLoad() { super.viewDidLoad() //add a theme: default, dark, or graphical //or simply exclude to set your own styling LeadsThemeManager.applyTheme(LeadsTheme.default, leadsbutton: myLeadButton) } @IBAction func leadTapped(_ sender: AnyObject) { var d :Dictionary = [String: String]() //populate the standard fields d[Leads.StandardFields.FIRST_NAME] = "Quinton" d[Leads.StandardFields.LAST_NAME] = "Wall" d[Leads.StandardFields.EMAIL] = "[email protected]" d[Leads.StandardFields.COMPANY] = "Salesforce" d[Leads.StandardFields.CITY] = "San Francisco" d[Leads.StandardFields.STATE] = "CA" //if you have custom fields, get your salesforce admin to //use the web-to-lead form generator to generate field ids, and //add them to the dictionary d["00NG000000CZxsC"] = "MyCustomValue" //add the fields to the button myLeadButton.formFields = d //finally, submit the leads to salesforce //make sure you set the org id either programatically with myLeadButton.setOrgId or //using the storyboard fields. do { try myLeadButton.sendLead() } catch Leads.LeadError.noOrgId { print("no ord id set!") } catch Leads.LeadError.commsFailure { //comms problem } catch { //unexpected error } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
6eee72193f0acfe0b37ebefbf40e1a26
26.986111
92
0.605459
4.448124
false
false
false
false
Coderian/SwiftedGPX
SwiftedGPX/Elements/Comment.swift
1
1617
// // Cmt.swift // SwiftedGPX // // Created by 佐々木 均 on 2016/02/16. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// GPX Comment /// /// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd) /// /// <xsd:element name="cmt" type="xsd:string" minOccurs="0"> /// <xsd:annotation> /// <xsd:documentation> /// GPS waypoint comment. Sent to GPS as comment. /// </xsd:documentation> /// </xsd:annotation> /// </xsd:element> public class Comment : SPXMLElement, HasXMLElementValue, HasXMLElementSimpleValue { public static var elementName: String = "cmt" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as WayPoint: v.value.cmt = self case let v as Route: v.value.cmt = self case let v as RoutePoint: v.value.cmt = self case let v as Track: v.value.cmt = self case let v as TrackPoint: v.value.cmt = self default: break } } } } public var value: String! public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{ self.value = contents self.parent = parent return parent } public required init(attributes:[String:String]){ super.init(attributes: attributes) } }
mit
4a111c6509c512d7337da86d7956e01a
30.857143
83
0.576282
3.759036
false
false
false
false
data-licious/ceddl4swift
ceddl4swift/Example/Airline.swift
1
5323
// // Airline.swift // ceddl4swift // // Created by Sachin Vas on 23/10/16. // Copyright © 2016 Sachin Vas. All rights reserved. // import Foundation /** * Generates the air travel booking website example from the CEDDL specification on page 30. */ public class Airline: NSObject { public func airlineExample() { // Core flight reservation related data can be used to populate and extend the // productInfo field as shown below: // digitalData.product[n].productInfo = { // productID: "734565538989889110", // description: "Business Class One-Way Ticket", // originAirportCode: "RDU", // originCity: "Raleigh", // originState: "North Carolina", // originCounty: "USA", // destinationAirportCode: "BOM", // destinationState: "Maharashtra", // destinationCountry: "India", // departureDate: new Date("December 15, 2013 14:20:00"), // arrivalDate: new Date("December 16, 2013 21:40:00"), // numberOfTravellers: 1 // }; // Setup the departureDate and arrivalDate. let calendar = Calendar(identifier: .gregorian) var departureDateComponent = DateComponents() departureDateComponent.year = 2013 departureDateComponent.month = 12 departureDateComponent.day = 15 departureDateComponent.hour = 14 departureDateComponent.minute = 20 departureDateComponent.second = 0 let departureDate = calendar.date(from: departureDateComponent) var arrivalDateComponent = DateComponents() arrivalDateComponent.year = 2013 arrivalDateComponent.month = 12 arrivalDateComponent.day = 16 arrivalDateComponent.hour = 21 arrivalDateComponent.minute = 40 arrivalDateComponent.second = 0 let arrivalDate = calendar.date(from: arrivalDateComponent) let product = ((((((((((Product().productInfo() .productID("734565538989889110") .description("Business Class One-Way Ticket") .custom("originAirportCode", value: "RDU" as AnyObject) as! ProductInfo<Product>) .custom("originCity", value: "Raleigh" as AnyObject) as! ProductInfo<Product>) .custom("originState", value: "North Carolina" as AnyObject) as! ProductInfo<Product>) .custom("originCounty", value: "USA" as AnyObject) as! ProductInfo<Product>) .custom("destinationAirportCode", value: "BOM" as AnyObject) as! ProductInfo<Product>) .custom("destinationState", value: "Maharashtra" as AnyObject) as! ProductInfo<Product>) .custom("destinationCountry", value: "India" as AnyObject) as! ProductInfo<Product>) .custom("departureDate", value: departureDate as AnyObject) as! ProductInfo<Product>) .custom("arrivalDate", value: arrivalDate as AnyObject) as! ProductInfo<Product>) .custom("numberOfTravellers", value: 1 as AnyObject) as! ProductInfo<Product>) .endProductInfo() // As a travel product is moved into the cart details such as price, fees, and currency can // be used to populate or extend the digitalData.cart.price object literal. Additional // fields such as a confirmation number might extend the digitalData.transaction // objects. // digitalData.cart.price = { // basePrice: 1000.00, // currency: "USD", // fees: 200, // taxRate: 0.08, // cartTotal: 1296.00 // }; let cart = (Cart().price() .basePrice(1000.00) .currency("USD") .custom("fees", value: 200 as AnyObject) as! Price<Cart>) .taxRate(0.08) .cartTotal(1296.00) .endPrice() // A "frequent flyer club" property could be added to the // digitalData.user[n].segment object to capture the customer’s loyalty // level: // // digitalData.user[n].segment = { // frequentFlyerClub: // }; let user = User().addSegment("frequentFlyerClub", value: "Silver Elite") let airlineDigitalData = DigitalData.create() .addProduct(product) .setCart(cart) .addUser(user) do { let airlineDigitalDataDict = airlineDigitalData.getMap() if let json = try Utility.loadJSONFromFile(type(of: self), name: "airline-example") as? Dictionary<String, AnyObject> { assert(airlineDigitalDataDict == json, "Digital Data is not equal to contents of file") } else { assert(false, "Unable to generate dictionary from file") } } catch let error { print(error) } } }
bsd-3-clause
2c3008b302bfb4938ed5dac39a63359b
43.333333
131
0.555639
4.724689
false
false
false
false
deltaDNA/ios-sdk
DeltaDNA/TrackingHelper.swift
1
1539
import AppTrackingTransparency import AdSupport internal protocol TrackingHelperProtocol { func isIdfaPresent () -> Bool func getTrackingAuthorizationStatus() -> NSString @available(iOS 14, *) func getTrackingStatus() -> ATTrackingManager.AuthorizationStatus @available(iOS 12, *) func checkNetworkType(path: NWPathProtocol) -> NetworkType } internal class TrackingHelper: TrackingHelperProtocol { private let asIdentifierManager: ASIdentifierManager init(asIdentifierManager: ASIdentifierManager = ASIdentifierManager.shared()) { self.asIdentifierManager = asIdentifierManager } @available(iOS 14, *) func getTrackingStatus() -> ATTrackingManager.AuthorizationStatus { return ATTrackingManager.trackingAuthorizationStatus } func isIdfaPresent() -> Bool { if #available(iOS 14, *) { return ATTrackingManager.trackingAuthorizationStatus == .authorized } else { return asIdentifierManager.isAdvertisingTrackingEnabled } } func getTrackingAuthorizationStatus() -> NSString { return asIdentifierManager.advertisingIdentifier.uuidString as NSString } @available(iOS 12, *) func checkNetworkType(path: NWPathProtocol) -> NetworkType { if path.status == .satisfied { return path.isExpensive ? .celullar : .wifi } return .unknown } } public enum NetworkType: String, CaseIterable { case unknown case celullar case wifi }
apache-2.0
1d90baea0db9f0fa91a5cdab1b2340fd
29.78
91
0.693957
4.964516
false
false
false
false
nkirby/Humber
_lib/HMGithub/_src/Data/DataController+User.swift
1
2111
// ======================================================= // HMGithub // Nathaniel Kirby // ======================================================= import Foundation import RealmSwift import HMCore // ======================================================= public protocol GithubUserDataProviding { func user(userID userID: String) -> GithubUserModel? func saveUser(response response: GithubUserResponse, write: Bool) func saveUsers(userResponses responses: [GithubUserResponse], write: Bool) } // ======================================================= extension DataController: GithubUserDataProviding { internal func userObj(userID userID: String) -> GithubUser? { let realm = self.realm() return realm.objects(GithubUser.self).filter("userID = %@", userID).first } public func user(userID userID: String) -> GithubUserModel? { if let obj = self.userObj(userID: userID) { return GithubUserModel(object: obj) } return nil } public func saveUser(response response: GithubUserResponse, write: Bool = true) { let block = { let user: GithubUser if let obj = self.userObj(userID: response.userID) { user = obj } else { user = GithubUser() user.userID = response.userID self.realm().add(user) } user.login = response.login user.url = response.url user.type = response.type user.siteAdmin = response.siteAdmin } if write { self.withRealmTransaction(block) } else { block() } } public func saveUsers(userResponses responses: [GithubUserResponse], write: Bool = true) { let block = { for response in responses { self.saveUser(response: response, write: false) } } if write { self.withRealmTransaction(block) } else { block() } } }
mit
6d154d96b24edef9b1bcdd0336561474
27.917808
94
0.500711
5.264339
false
false
false
false
ifeherva/HSTracker
HSTracker/Importers/Handlers/Hearthstonetopdecks.swift
1
1355
// // Hearthstonetopdecks.swift // HSTracker // // Created by Istvan Fehervari on 29/08/16. // Copyright © 2016 Istvan Fehervari. All rights reserved. // import Foundation import Kanna import RegexUtil struct HearthstoneTopDecks: HttpImporter { var siteName: String { return "Hearthstonetopdecks" } var handleUrl: RegexPattern { return "hearthstonetopdecks\\.com\\/decks" } var preferHttps: Bool { return true } func loadDeck(doc: HTMLDocument, url: String) -> (Deck, [Card])? { guard let nameNode = doc.at_xpath("//h1[contains(@class, 'entry-title')]"), let deckName = nameNode.text else { logger.error("Deck name not found") return nil } logger.verbose("Got deck name \(deckName)") let xpath = "//div[contains(@class, 'deck-import-code')]/input[@type='text']" guard let deckStringNode = doc.at_xpath(xpath), let deckString = deckStringNode["value"]?.trim(), let (playerClass, cardList) = DeckSerializer.deserializeDeckString(deckString: deckString) else { logger.error("Card list not found") return nil } let deck = Deck() deck.name = deckName deck.playerClass = playerClass return (deck, cardList) } }
mit
0cb72ee72b03ae3c5c922165fcaf95ac
26.632653
109
0.604136
4.053892
false
false
false
false
GreenvilleCocoa/ChristmasDelivery
ChristmasDelivery/Constants.swift
1
560
// // Constants.swift // ChristmasDelivery // // Created by Marcus Smith on 12/8/14. // Copyright (c) 2014 GreenvilleCocoaheads. All rights reserved. // import UIKit struct PhysicsCategory { static let Present: UInt32 = 1 << 0 static let Sleigh: UInt32 = 1 << 1 static let Santa: UInt32 = 1 << 2 static let Reindeer: UInt32 = 1 << 3 static let Chimney: UInt32 = 1 << 4 static let Hazard: UInt32 = 1 << 5 static let EdgeLoop: UInt32 = 1 << 6 } enum BuildingType { case House case HouseWithChimney case ClockTower }
mit
c0cc6d409842d2f1cd00c8810560509c
21.44
65
0.653571
3.393939
false
false
false
false
christophhagen/Signal-iOS
Signal/src/Models/AccountManager.swift
1
5730
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit import SignalServiceKit /** * Signal is actually two services - textSecure for messages and red phone (for calls). * AccountManager delegates to both. */ class AccountManager: NSObject { let TAG = "[AccountManager]" let textSecureAccountManager: TSAccountManager let networkManager: TSNetworkManager let preferences: OWSPreferences var pushManager: PushManager { // dependency injection hack since PushManager has *alot* of dependencies, and would induce a cycle. return PushManager.shared() } required init(textSecureAccountManager: TSAccountManager, preferences: OWSPreferences) { self.networkManager = textSecureAccountManager.networkManager self.textSecureAccountManager = textSecureAccountManager self.preferences = preferences super.init() SwiftSingletons.register(self) } // MARK: registration @objc func register(verificationCode: String) -> AnyPromise { return AnyPromise(register(verificationCode: verificationCode)) } func register(verificationCode: String) -> Promise<Void> { guard verificationCode.count > 0 else { let error = OWSErrorWithCodeDescription(.userError, NSLocalizedString("REGISTRATION_ERROR_BLANK_VERIFICATION_CODE", comment: "alert body during registration")) return Promise(error: error) } Logger.debug("\(self.TAG) registering with signal server") let registrationPromise: Promise<Void> = firstly { self.registerForTextSecure(verificationCode: verificationCode) }.then { self.syncPushTokens() }.recover { (error) -> Promise<Void> in switch error { case PushRegistrationError.pushNotSupported(let description): // This can happen with: // - simulators, none of which support receiving push notifications // - on iOS11 devices which have disabled "Allow Notifications" and disabled "Enable Background Refresh" in the system settings. Logger.info("\(self.TAG) Recovered push registration error. Registering for manual message fetcher because push not supported: \(description)") return self.registerForManualMessageFetching() default: throw error } }.then { self.completeRegistration() } registrationPromise.retainUntilComplete() return registrationPromise } private func registerForTextSecure(verificationCode: String) -> Promise<Void> { return Promise { fulfill, reject in self.textSecureAccountManager.verifyAccount(withCode:verificationCode, success:fulfill, failure:reject) } } private func syncPushTokens() -> Promise<Void> { Logger.info("\(self.TAG) in \(#function)") let job = SyncPushTokensJob(accountManager: self, preferences: self.preferences) job.uploadOnlyIfStale = false return job.run() } private func completeRegistration() { Logger.info("\(self.TAG) in \(#function)") self.textSecureAccountManager.didRegister() } // MARK: Message Delivery func updatePushTokens(pushToken: String, voipToken: String) -> Promise<Void> { return Promise { fulfill, reject in self.textSecureAccountManager.registerForPushNotifications(pushToken:pushToken, voipToken:voipToken, success:fulfill, failure:reject) } } func registerForManualMessageFetching() -> Promise<Void> { return Promise { fulfill, reject in self.textSecureAccountManager.registerForManualMessageFetching(success:fulfill, failure:reject) } } // MARK: Turn Server func getTurnServerInfo() -> Promise<TurnServerInfo> { return Promise { fulfill, reject in self.networkManager.makeRequest(TurnServerInfoRequest(), success: { (_: URLSessionDataTask, responseObject: Any?) in guard responseObject != nil else { return reject(OWSErrorMakeUnableToProcessServerResponseError()) } if let responseDictionary = responseObject as? [String: AnyObject] { if let turnServerInfo = TurnServerInfo(attributes:responseDictionary) { return fulfill(turnServerInfo) } Logger.error("\(self.TAG) unexpected server response:\(responseDictionary)") } return reject(OWSErrorMakeUnableToProcessServerResponseError()) }, failure: { (_: URLSessionDataTask, error: Error) in return reject(error) }) } } }
gpl-3.0
eeb04e532dd5e3427c819b87ed3db722
41.444444
159
0.555672
6.296703
false
false
false
false
pfvernon2/swiftlets
iOSX/iOS/UIImage+maskColor.swift
1
1607
// // UIImage+maskColor.swift // swiftlets // // Created by Frank Vernon on 1/3/16. // Copyright © 2016 Frank Vernon. All rights reserved. // import UIKit extension UIImage { func mask(withColor color:UIColor) -> UIImage? { let newRect:CGRect = CGRect(origin: CGPoint.zero, size: size) UIGraphicsBeginImageContextWithOptions(newRect.size, false, scale) let context:CGContext = UIGraphicsGetCurrentContext()! draw(in: newRect) context.setFillColor(color.cgColor) context.setBlendMode(.sourceAtop) context.fill(newRect) let result:UIImage? = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } func clipMask(withColor color:UIColor) -> UIImage? { guard let cgImage = self.cgImage else { return nil } let rect:CGRect = CGRect(origin: CGPoint.zero, size: size) UIGraphicsBeginImageContext(rect.size) defer { UIGraphicsEndImageContext() } let context:CGContext = UIGraphicsGetCurrentContext()! context.clip(to: rect, mask: cgImage) context.setFillColor(color.cgColor) context.fill(rect) let masked:UIImage? = UIGraphicsGetImageFromCurrentImageContext() guard let image = masked?.cgImage else { return nil } let flippedImage:UIImage = UIImage(cgImage: image, scale: 1.0, orientation: .downMirrored) return flippedImage } }
apache-2.0
172c01dae8ae8b651b1b9ad26bc5f48f
28.2
98
0.616438
5.214286
false
false
false
false
apple/swift
test/SILOptimizer/diagnostic_constant_propagation_int_arch64.swift
33
9272
// RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify // // REQUIRES: PTRSIZE=64 // // This file tests diagnostics for arithmetic and bitwise operations on `Int` // and `UInt` types for 64 bit architectures. // // FIXME: This test should be merged back into // diagnostic_constant_propagation.swift when we have fixed: // <rdar://problem/19434979> -verify does not respect #if // // FIXME: <rdar://problem/29937936> False negatives when using integer initializers // // FIXME: <rdar://problem/39193272> A false negative that happens only in REPL import StdlibUnittest func testArithmeticOverflow_Int_64bit() { do { // Literals. var _: Int = 0x7fff_ffff_ffff_ffff // OK var _: Int = 0x8000_0000_0000_0000 // expected-error {{integer literal '9223372036854775808' overflows when stored into 'Int'}} var _: Int = -0x8000_0000_0000_0000 // OK var _: Int = -0x8000_0000_0000_0001 // expected-error {{integer literal '-9223372036854775809' overflows when stored into 'Int'}} } do { // Negation. var _: Int = -(-0x7fff_ffff_ffff_ffff) // OK var _: Int = -(-0x8000_0000_0000_0000) // expected-error {{arithmetic operation '0 - -9223372036854775808' (on signed 64-bit integer type) results in an overflow}} // FIXME: Missing diagnostic in REPL: // <rdar://problem/39193272> Overflow in arithmetic negation is not detected // at compile time when running in REPL } do { // Addition. var _: Int = 0x7fff_ffff_ffff_fffe + 1 // OK var _: Int = 0x7fff_ffff_ffff_fffe + 2 // expected-error {{arithmetic operation '9223372036854775806 + 2' (on type 'Int') results in an overflow}} var _: Int = -0x7fff_ffff_ffff_ffff + (-1) // OK var _: Int = -0x7fff_ffff_ffff_ffff + (-2) // expected-error {{arithmetic operation '-9223372036854775807 + -2' (on type 'Int') results in an overflow}} } do { // Subtraction. var _: Int = 0x7fff_ffff_ffff_fffe - (-1) // OK var _: Int = 0x7fff_ffff_ffff_fffe - (-2) // expected-error {{arithmetic operation '9223372036854775806 - -2' (on type 'Int') results in an overflow}} var _: Int = -0x7fff_ffff_ffff_ffff - 1 // OK var _: Int = -0x7fff_ffff_ffff_ffff - 2 // expected-error {{arithmetic operation '-9223372036854775807 - 2' (on type 'Int') results in an overflow}} } do { // Multiplication. var _: Int = 0x7fff_ffff_ffff_fffe * 1 // OK var _: Int = 0x7fff_ffff_ffff_fffe * 2 // expected-error {{arithmetic operation '9223372036854775806 * 2' (on type 'Int') results in an overflow}} var _: Int = -0x7fff_ffff_ffff_ffff * 1 // OK var _: Int = -0x7fff_ffff_ffff_ffff * 2 // expected-error {{arithmetic operation '-9223372036854775807 * 2' (on type 'Int') results in an overflow}} } do { // Division. var _: Int = 0x7fff_ffff_ffff_fffe / 2 // OK var _: Int = 0x7fff_ffff_ffff_fffe / 0 // expected-error {{division by zero}} var _: Int = -0x7fff_ffff_ffff_ffff / 2 // OK var _: Int = -0x7fff_ffff_ffff_ffff / 0 // expected-error {{division by zero}} var _: Int = -0x8000_0000_0000_0000 / -1 // expected-error {{division '-9223372036854775808 / -1' results in an overflow}} } do { // Remainder. var _: Int = 0x7fff_ffff_ffff_fffe % 2 // OK var _: Int = 0x7fff_ffff_ffff_fffe % 0 // expected-error {{division by zero}} var _: Int = -0x7fff_ffff_ffff_ffff % 2 // OK var _: Int = -0x7fff_ffff_ffff_ffff % 0 // expected-error {{division by zero}} var _: Int = -0x8000_0000_0000_0000 % -1 // expected-error {{division '-9223372036854775808 % -1' results in an overflow}} } do { // Right shift. // Due to "smart shift" introduction, there can be no overflows errors // during shift operations var _: Int = 0 >> 0 var _: Int = 0 >> 1 var _: Int = 0 >> (-1) var _: Int = 123 >> 0 var _: Int = 123 >> 1 var _: Int = 123 >> (-1) var _: Int = (-1) >> 0 var _: Int = (-1) >> 1 var _: Int = 0x7fff_ffff_ffff_ffff >> 63 var _ :Int = 0x7fff_ffff_ffff_ffff >> 64 var _ :Int = 0x7fff_ffff_ffff_ffff >> 65 } do { // Left shift. // Due to "smart shift" introduction, there can be no overflows errors // during shift operations var _: Int = 0 << 0 var _: Int = 0 << 1 var _: Int = 0 << (-1) var _: Int = 123 << 0 var _: Int = 123 << 1 var _: Int = 123 << (-1) var _: Int = (-1) << 0 var _: Int = (-1) << 1 var _: Int = 0x7fff_ffff_ffff_ffff << 63 var _ :Int = 0x7fff_ffff_ffff_ffff << 64 var _ :Int = 0x7fff_ffff_ffff_ffff << 65 } do { var _ : Int = ~0 var _ : Int = (0x7fff_ffff_ffff_fff) | (0x4000_0000_0000_0000 << 1) var _ : Int = (0x7fff_ffff_ffff_ffff) | 0x8000_0000_0000_0000 // expected-error {{integer literal '9223372036854775808' overflows when stored into 'Int'}} } } func testArithmeticOverflow_UInt_64bit() { do { // Literals. var _: UInt = 0x7fff_ffff_ffff_ffff // OK var _: UInt = 0x8000_0000_0000_0000 var _: UInt = 0xffff_ffff_ffff_ffff var _: UInt = -1 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}} var _: UInt = -0xffff_ffff_ffff_ffff // expected-error {{negative integer '-18446744073709551615' overflows when stored into unsigned type 'UInt'}} } do { // Addition. var _: UInt = 0 + 0 // OK var _: UInt = 0xffff_ffff_ffff_ffff + 0 // OK var _: UInt = 0xffff_ffff_ffff_ffff + 1 // expected-error {{arithmetic operation '18446744073709551615 + 1' (on type 'UInt') results in an overflow}} var _: UInt = 0xffff_ffff_ffff_fffe + 1 // OK var _: UInt = 0xffff_ffff_ffff_fffe + 2 // expected-error {{arithmetic operation '18446744073709551614 + 2' (on type 'UInt') results in an overflow}} } do { // Subtraction. var _: UInt = 0xffff_ffff_ffff_fffe - 1 // OK var _: UInt = 0xffff_ffff_ffff_fffe - 0xffff_ffff_ffff_ffff // expected-error {{arithmetic operation '18446744073709551614 - 18446744073709551615' (on type 'UInt') results in an overflow}} var _: UInt = 0 - 0 // OK var _: UInt = 0 - 1 // expected-error {{arithmetic operation '0 - 1' (on type 'UInt') results in an overflow}} } do { // Multiplication. var _: UInt = 0xffff_ffff_ffff_ffff * 0 // OK var _: UInt = 0xffff_ffff_ffff_ffff * 1 // OK var _: UInt = 0xffff_ffff_ffff_ffff * 2 // expected-error {{arithmetic operation '18446744073709551615 * 2' (on type 'UInt') results in an overflow}} var _: UInt = 0xffff_ffff_ffff_ffff * 0xffff_ffff_ffff_ffff // expected-error {{arithmetic operation '18446744073709551615 * 18446744073709551615' (on type 'UInt') results in an overflow}} var _: UInt = 0x7fff_ffff_ffff_fffe * 0 // OK var _: UInt = 0x7fff_ffff_ffff_fffe * 1 // OK var _: UInt = 0x7fff_ffff_ffff_fffe * 2 // OK var _: UInt = 0x7fff_ffff_ffff_fffe * 3 // expected-error {{arithmetic operation '9223372036854775806 * 3' (on type 'UInt') results in an overflow}} } do { // Division. var _: UInt = 0x7fff_ffff_ffff_fffe / 2 // OK var _: UInt = 0x7fff_ffff_ffff_fffe / 0 // expected-error {{division by zero}} var _: UInt = 0xffff_ffff_ffff_ffff / 2 // OK var _: UInt = 0xffff_ffff_ffff_ffff / 0 // expected-error {{division by zero}} } do { // Remainder. var _: UInt = 0x7fff_ffff_ffff_fffe % 2 // OK var _: UInt = 0x7fff_ffff_ffff_fffe % 0 // expected-error {{division by zero}} var _: UInt = 0xffff_ffff_ffff_ffff % 2 // OK var _: UInt = 0xffff_ffff_ffff_ffff % 0 // expected-error {{division by zero}} } do { // Shift operations don't result in overflow errors but note that // one cannot use negative values while initializing of an unsigned value var _: UInt = 0 >> 0 var _: UInt = 0 >> 1 var _: UInt = 123 >> 0 var _: UInt = 123 >> 1 var _: UInt = (-1) >> 0 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}} var _: UInt = (-1) >> 1 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}} var _: UInt = 0x7fff_ffff_ffff_ffff >> 63 var _: UInt = 0x7fff_ffff_ffff_ffff >> 64 var _: UInt = 0x7fff_ffff_ffff_ffff >> 65 } do { // Shift operations don't result in overflow errors but note that // one cannot use negative values while initializing of an unsigned value var _: UInt = 0 << 0 var _: UInt = 0 << 1 var _: UInt = 123 << 0 var _: UInt = 123 << 1 var _: UInt = (-1) << 0 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}} var _: UInt = (-1) << 1 // expected-error {{negative integer '-1' overflows when stored into unsigned type 'UInt'}} var _: UInt = 0x7fff_ffff_ffff_ffff << 63 var _: UInt = 0x7fff_ffff_ffff_ffff << 64 var _: UInt = 0x7fff_ffff_ffff_ffff << 65 } do { // bitwise operations. No overflows can happen during these operations var _ : UInt = ~0 var _ : UInt = (0x7fff_ffff_ffff_ffff) | (0x4000_0000_0000_0000 << 1) var _ : UInt = (0x7fff_ffff) | 0x8000_0000_0000_0000 } } func testIntToFloatConversion() { // No warnings are emitted for conversion through explicit constructor calls. _blackHole(Double(9_007_199_254_740_993)) }
apache-2.0
3217c3c914485ba7bf3c3d0c5ca1de0e
37.31405
192
0.620039
3.379009
false
false
false
false
tangrams/tangram-es
platforms/ios/swift/TangramDemoSwift/ViewController.swift
1
1293
// // ViewController.swift // TangramDemoSwift // // Created by Matt Blair on 1/11/20. // Copyright © 2020 Matt Blair. All rights reserved. // import UIKit import TangramMap class ViewController: UIViewController, TGMapViewDelegate, TGRecognizerDelegate { override func viewDidLoad() { super.viewDidLoad() let mapView = self.view as! TGMapView mapView.mapViewDelegate = self mapView.gestureDelegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let apiKey = Bundle.main.infoDictionary?["NextzenApiKey"] as! String let sceneUpdates = [TGSceneUpdate(path: "global.sdk_api_key", value: apiKey)] let mapView = self.view as! TGMapView let sceneUrl = URL(string: "https://www.nextzen.org/carto/bubble-wrap-style/9/bubble-wrap-style.zip")! mapView.loadSceneAsync(from: sceneUrl, with: sceneUpdates) } func mapView(_ mapView: TGMapView, didLoadScene sceneID: Int32, withError sceneError: Error?) { print("MapView did complete loading") let newYork = CLLocationCoordinate2DMake(40.70532700869127, -74.00976419448854) mapView.cameraPosition = TGCameraPosition(center: newYork, zoom: 15, bearing: 0, pitch: 0) } }
mit
83c958ba526d2471dd9c4fdae8b609b4
28.363636
110
0.691176
4.024922
false
false
false
false
1457792186/JWSwift
SwiftWX/LGWeChatKit/LGChatKit/conversion/imagePick/LGAssetToolView.swift
1
4059
// // LGAssetToolView.swift // LGChatViewController // // Created by jamy on 10/23/15. // Copyright © 2015 jamy. All rights reserved. // import UIKit private let buttonWidth = 20 private let durationTime = 0.3 class LGAssetToolView: UIView { var preViewButton: UIButton! var totalButton: UIButton! var sendButton: UIButton! weak var parent: UIViewController! var selectCount = Int() { willSet { if newValue > 0 { totalButton.addAnimation(durationTime) totalButton.isHidden = false totalButton.setTitle("\(newValue)", for: UIControlState()) } else { totalButton.isHidden = true } } } var addSelectCount: Int? { willSet { selectCount += newValue! } } convenience init(leftTitle:String, leftSelector: Selector, rightSelector: Selector, parent: UIViewController) { self.init() self.parent = parent preViewButton = UIButton(type: .custom) preViewButton.titleLabel?.font = UIFont.systemFont(ofSize: 14.0) preViewButton.setTitle(leftTitle, for: UIControlState()) preViewButton.setTitleColor(UIColor.black, for: UIControlState()) preViewButton.addTarget(parent, action: leftSelector, for: .touchUpInside) totalButton = UIButton(type: .custom) totalButton.titleLabel?.font = UIFont.systemFont(ofSize: 14.0) totalButton.setBackgroundImage(UIImage.imageWithColor(UIColor.green), for: UIControlState()) totalButton.layer.cornerRadius = CGFloat(buttonWidth / 2) totalButton.layer.masksToBounds = true totalButton.isHidden = true sendButton = UIButton(type: .custom) sendButton.titleLabel?.font = UIFont.systemFont(ofSize: 14.0) sendButton.setTitle("发送", for: UIControlState()) sendButton.setTitleColor(UIColor.gray, for: UIControlState()) sendButton.addTarget(parent, action: rightSelector, for: .touchUpInside) backgroundColor = UIColor.groupTableViewBackground addSubview(preViewButton) addSubview(totalButton) addSubview(sendButton) preViewButton.translatesAutoresizingMaskIntoConstraints = false totalButton.translatesAutoresizingMaskIntoConstraints = false sendButton.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: preViewButton, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 5)) addConstraint(NSLayoutConstraint(item: preViewButton, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: sendButton, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: -5)) addConstraint(NSLayoutConstraint(item: sendButton, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: totalButton, attribute: .right, relatedBy: .equal, toItem: sendButton, attribute: .left, multiplier: 1, constant: -5)) addConstraint(NSLayoutConstraint(item: totalButton, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0)) totalButton.addConstraint(NSLayoutConstraint(item: totalButton, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: CGFloat(buttonWidth))) totalButton.addConstraint(NSLayoutConstraint(item: totalButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: CGFloat(buttonWidth))) } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
2aa7b132237f17736853b61c3a3ed963
44.044444
191
0.678096
4.866747
false
false
false
false
saasquatch/mobile-sdk-ios-sample
SampleApp/LoginViewController.swift
1
6541
/* Cloud icon by https://www.iconfinder.com/aha-soft is licensed under http://creativecommons.org/licenses/by/3.0/ */ import Foundation import UIKit import saasquatch import JWT class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet var loginButton: UIButton! @IBOutlet var emailField: UITextField! @IBOutlet var passwordField: UITextField! let user = User.sharedUser // Insert your tenant alias below // ie. let tenant = "test_alqzo6fwdqqw63v4bw" let tenant = "TENANT_ALIAS_HERE" // Insert your API key below /* ie. let raw_token = "TEST_j0aWxsvRedKkBo5Gv1l9ispXIfsos2CsdeeIL3" */ let raw_token = "ADD_JWT_HERE" override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(LoginViewController.dismissKeyboard), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) let tap = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.dismissKeyboard)) self.view.addGestureRecognizer(tap) loginButton.layer.cornerRadius = 5 loginButton.clipsToBounds = false emailField.delegate = self passwordField.delegate = self // Creating a test user let userInfo: [String: AnyObject] = createUser(firstName: "saasquatch", lastName: "ios", email: "[email protected]") Saasquatch.registerUserForTenant(user.tenant, withUserID: user.id, withAccountID: user.accountId, withToken: user.token, withUserInfo: userInfo as AnyObject, completionHandler: {(userInfo: AnyObject?, error: NSError?) in if error != nil { // Show an alert describing the error DispatchQueue.main.async(execute: { self.showErrorAlert("Registration Error", message: error!.localizedDescription) }) return } // Parse the returned context guard let shareLinks = userInfo!["shareLinks"] as? [String: AnyObject], let shareLink = shareLinks["shareLink"] as? String, let facebookShareLink = shareLinks["mobileFacebookShareLink"] as? String, let twitterShareLink = shareLinks["mobileTwitterShareLink"] as? String else { DispatchQueue.main.async(execute: { self.showErrorAlert("Registration Error", message: "Something went wrong in registration. Please try again.") }) return } // Give the user their share links let shareLinksDict: [String: String] = ["shareLink": shareLink, "facebook": facebookShareLink, "twitter": twitterShareLink] self.user.shareLinks = shareLinksDict }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func login(_ sender: UIButton!) { self.performSegue(withIdentifier: "signupsegue", sender: sender) } func showErrorAlert(_ title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } @objc func dismissKeyboard() { self.view.endEditing(true) } func textFieldDidBeginEditing(_ textField: UITextField) { animateTextField(true) } func textFieldDidEndEditing(_ textField: UITextField) { animateTextField(false) } func animateTextField(_ up: Bool) { let movementDistance = 160 let movementDuration = 0.3 let movement = (up ? -movementDistance : movementDistance) UIView.beginAnimations("anim", context: nil) UIView.setAnimationBeginsFromCurrentState(true) UIView.setAnimationDuration(movementDuration) self.view.frame = self.view.frame.offsetBy(dx: 0, dy: CGFloat(movement)) UIView.commitAnimations() } func createUser(firstName: String, lastName: String, email: String) -> [String: AnyObject] { let userId = String(arc4random()) let accountId = String(arc4random()) let locale = "en_US" let referralCode = "\(firstName.uppercased())\(lastName.uppercased())" let result: [String: AnyObject] = ["id": userId as AnyObject, "accountId": accountId as AnyObject, "email": email as AnyObject, "firstName": firstName as AnyObject, "lastName": lastName as AnyObject, "locale": locale as AnyObject, "referralCode": referralCode as AnyObject, "imageUrl": "" as AnyObject] let token = JWT.encode(.hs256(self.raw_token.data(using: .utf8)!)) { builder in builder["sub"] = userId + "_" + accountId builder["user"] = result } // Uncomment to create with Anonymous User. You must also remove the token section and raw token section above. /* let token: String? token = nil */ user.login(token: token, token_raw: self.raw_token, id: userId, accountId: accountId, firstName: firstName, lastName: lastName, email: email, referralCode: referralCode, tenant: self.tenant ,shareLinks: nil) return result } }
mit
699e83a5587e1c8e3331d56bbd322b90
38.642424
215
0.534781
5.717657
false
false
false
false
abelsanchezali/ViewBuilder
Source/Document/Core/DocumentBuilder.swift
1
3168
// // DocumentBuilder.swift // ViewBuilder // // Created by Abel Sanchez on 6/8/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import Foundation /** Class that serves as an entry point for instantiating documents. Could be extended to customize some aspects but also provideds a `shared` instance for convenience. ## Examples ``` // Have document path first let pathToDocument = ... // User generic load function to build instance let view: UIView? = DocumentBuilder.shared.load(pathToDocument, ofType: "xml") ``` */ open class DocumentBuilder: NSObject { // Shared instance public private(set) static var shared = DocumentBuilder() public private(set) var deserializer: DataDeserializerProtocol! public private(set) var documentCache: DocumentCacheProtocol! public override init() { super.init() deserializer = createDeserializer() documentCache = createDocumentCache() } /// Extension point that creates default build options to be used. open func defaultOptions() -> BuildOptions { return BuildOptions() } /// Extension point to create deserializer to be used. open func createDeserializer() -> DataDeserializerProtocol { return XMLDataDeserializer() } /// Extension point to create document cache to be used. open func createDocumentCache() -> DocumentCacheProtocol { return DefaultDocumentCache() } @nonobjc private func createDocumentKey(_ path: String, options: DocumentOptions) -> DocumentCacheKey { return DocumentCacheKey(path: path, namespaces: options.namespaces, includeParsingInfo: options.includeParsingInfo) } /** Loads a document from a given path. - Parameter path: Path to document. - Parameter options: Options that will be used in its loading. - Returns: A Document from given path. Those are cached and reused. */ public func loadDocument(_ path: String, options: DocumentOptions? = nil) -> DataDocument? { let options = options ?? defaultOptions().document options.defineDocumentPath(path: path) let key = createDocumentKey(path, options: options) if let document = documentCache.getDocumentWithKey(key) { return document } guard let dataNode = deserializer.loadData(from: path, options: options) else { return nil } let document = DataDocument(root: dataNode, builder: self, options: options) if let document = document { let _ = documentCache.saveDocumentWithKey(key, document: document) } return document } /** Creates a factory for a document. - Parameter document: Document to be used in factory. - Parameter options: Options that will be used within factory. - Returns: DocumentFactory associated with this document. */ public func createFactory(_ document: DataDocument, options: FactoryOptions? = nil) -> DocumentFactory { let options = options ?? defaultOptions().factory return DocumentFactory(document: document, options: options) } }
mit
60bbd3ec20b0987f942a6008c8654e44
30.356436
123
0.682665
4.879815
false
false
false
false
hugweb/HWPullToInfinity
HWPullToInfinity/HWPullToInfinity.swift
1
16644
// // HWPullToInfinity.swift // HypeUGC // // Created by Hugues Blocher on 21/01/16. // Copyright © 2016 Hype. All rights reserved. // import UIKit import QuartzCore import ObjectiveC // MARK: Pull to refresh scrollView extension extension UIScrollView { var pullRefreshColor: UIColor? { get { return self.refreshControlView.tintColor } set(newValue) { self.refreshControlView.tintColor = newValue } } private struct PullAssociatedKeys { static var refreshControlView: UIRefreshControl? static var pullRefreshHasBeenSetup : Bool = false static var pullRefreshHandler: (() -> Void)? } private class pullRefreshHandlerWrapper { var handler: (() -> Void) init(handler: (() -> Void)) { self.handler = handler } } private var pullRefreshHandler: (() -> Void)? { get { if let wrapper = objc_getAssociatedObject(self, &PullAssociatedKeys.pullRefreshHandler) as? pullRefreshHandlerWrapper { return wrapper.handler } return nil } set { objc_setAssociatedObject(self, &PullAssociatedKeys.pullRefreshHandler, pullRefreshHandlerWrapper(handler: newValue!), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var refreshControlView: UIRefreshControl { get { return objc_getAssociatedObject(self, &PullAssociatedKeys.refreshControlView) as! UIRefreshControl } set { objc_setAssociatedObject(self, &PullAssociatedKeys.refreshControlView, newValue as UIRefreshControl?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var pullRefreshHasBeenSetup: Bool { get { guard let number = objc_getAssociatedObject(self, &PullAssociatedKeys.pullRefreshHasBeenSetup) as? NSNumber else { return false } return number.boolValue } set(value) { objc_setAssociatedObject(self, &PullAssociatedKeys.pullRefreshHasBeenSetup, NSNumber(bool: value), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func addPullToRefreshWithActionHandler(actionHandler: () -> Void) { if !self.pullRefreshHasBeenSetup { let view: UIRefreshControl = UIRefreshControl() view.addTarget(self, action: "triggerPullToRefresh", forControlEvents: UIControlEvents.ValueChanged) view.layer.zPosition = self.layer.zPosition - 1 self.refreshControlView = view self.pullRefreshHandler = actionHandler self.addSubview(view) self.pullRefreshHasBeenSetup = true } } func addPullToRefreshWithTitleAndActionHandler(pullToRefreshTitle: NSAttributedString?, actionHandler: () -> Void) { if !self.pullRefreshHasBeenSetup { let view: UIRefreshControl = UIRefreshControl() if let title = pullToRefreshTitle { view.attributedTitle = title } view.addTarget(self, action: "triggerPullToRefresh", forControlEvents: UIControlEvents.ValueChanged) view.layer.zPosition = self.layer.zPosition - 1 self.refreshControlView = view self.pullRefreshHandler = actionHandler self.addSubview(view) self.pullRefreshHasBeenSetup = true } } func triggerPullToRefresh() { if let handler = self.pullRefreshHandler { handler() } } func stopPullToRefresh() { self.refreshControlView.endRefreshing() } } // MARK: Infinite Scroll enum HWPullToInfinityState { case Stopped case Triggered case Loading case All } let HWPullToInfinityViewHeight: CGFloat = 60 let HWPullToInfinityViewWidth: CGFloat = HWPullToInfinityViewHeight class HWPullToInfinityView: UIView { // MARK: Infinite properties var isHorizontal: Bool = false var enabled: Bool = false private var _infiniteRefreshColor : UIColor = UIColor.grayColor() var color : UIColor { get { return _infiniteRefreshColor } set(newColor) { _activityIndicatorView?.color = newColor } } private weak var scrollView: UIScrollView? private var infiniteScrollingHandler: (() -> Void)? private var viewForState: [AnyObject] = ["", "", "", ""] private var originalInset: CGFloat = 0.0 private var wasTriggeredByUser: Bool = false private var isObserving: Bool = false private var isSetup: Bool = false private var _activityIndicatorView : UIActivityIndicatorView? private var activityIndicatorView : UIActivityIndicatorView { get { if _activityIndicatorView == nil { _activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .White) _activityIndicatorView?.color = _infiniteRefreshColor _activityIndicatorView?.hidesWhenStopped = true self.addSubview(_activityIndicatorView!) } return _activityIndicatorView! } } private var _state: HWPullToInfinityState = .Stopped private var state: HWPullToInfinityState { get { return _state } set(newState) { if _state == newState { return } let previousState: HWPullToInfinityState = state _state = newState for otherView in self.viewForState { if otherView is UIView { otherView.removeFromSuperview() } } let customView: AnyObject = self.viewForState[newState.hashValue] if let custom = customView as? UIView { self.addSubview(custom) let viewBounds: CGRect = custom.bounds let x = CGFloat(roundf(Float((self.bounds.size.width - viewBounds.size.width) / 2))) let y = CGFloat(roundf(Float((self.bounds.size.height - viewBounds.size.height) / 2))) let origin: CGPoint = CGPointMake(x, y) custom.frame = CGRectMake(origin.x, origin.y, viewBounds.size.width, viewBounds.size.height) } else { let viewBounds: CGRect = self.activityIndicatorView.bounds let x = CGFloat(roundf(Float((self.bounds.size.width - viewBounds.size.width) / 2))) let y = CGFloat(roundf(Float((self.bounds.size.height - viewBounds.size.height) / 2))) let origin: CGPoint = CGPointMake(x, y) self.activityIndicatorView.frame = CGRectMake(origin.x, origin.y, viewBounds.size.width, viewBounds.size.height) switch newState { case .Stopped: self.activityIndicatorView.stopAnimating() case .Triggered: self.activityIndicatorView.startAnimating() case .Loading: self.activityIndicatorView.startAnimating() default: break } } if previousState == .Triggered && newState == .Loading && self.enabled { if let handler = self.infiniteScrollingHandler { handler() } } } } // MARK: Infinite initializer override init(frame: CGRect) { super.init(frame: frame) self.autoresizingMask = .FlexibleWidth self.enabled = true } convenience init () { self.init(frame:CGRectZero) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override func layoutSubviews() { self.activityIndicatorView.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2) } // MARK: Infinite scrollView func resetScrollViewContentInset() { var currentInsets: UIEdgeInsets = self.scrollView!.contentInset if self.isHorizontal { currentInsets.right = self.originalInset } else { currentInsets.bottom = self.originalInset } self.setScrollViewContentInset(currentInsets) } func setScrollViewContentInsetForInfiniteScrolling() { var currentInsets: UIEdgeInsets = self.scrollView!.contentInset if self.isHorizontal { currentInsets.right = self.originalInset + HWPullToInfinityViewWidth } else { currentInsets.bottom = self.originalInset + HWPullToInfinityViewHeight } self.setScrollViewContentInset(currentInsets) } func setScrollViewContentInset(contentInset: UIEdgeInsets) { UIView.animateWithDuration(0.3, delay: 0, options: [.AllowUserInteraction, .BeginFromCurrentState], animations: {() -> Void in self.scrollView!.contentInset = contentInset }, completion: { _ in }) } func scrollViewDidScroll(contentOffset: CGPoint) { if self.state != .Loading && self.enabled { if self.isHorizontal { let scrollViewContentWidth: CGFloat = self.scrollView!.contentSize.width let scrollOffsetThreshold: CGFloat = scrollViewContentWidth - self.scrollView!.bounds.size.width if !self.scrollView!.dragging && self.state == .Triggered { self.state = .Loading } else if contentOffset.x > scrollOffsetThreshold && self.state == .Stopped && self.scrollView!.dragging { self.state = .Triggered } else if contentOffset.x < scrollOffsetThreshold && self.state != .Stopped { self.state = .Stopped } } else { let scrollViewContentHeight: CGFloat = self.scrollView!.contentSize.height let scrollOffsetThreshold: CGFloat = scrollViewContentHeight - self.scrollView!.bounds.size.height if !self.scrollView!.dragging && self.state == .Triggered { self.state = .Loading } else if contentOffset.y > scrollOffsetThreshold && self.state == .Stopped && self.scrollView!.dragging { self.state = .Triggered } else if contentOffset.y < scrollOffsetThreshold && self.state != .Stopped { self.state = .Stopped } } } } // MARK: Infinite observing override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if (keyPath == "contentOffset") { let new = (change?[NSKeyValueChangeNewKey] as! NSValue).CGPointValue() self.scrollViewDidScroll(new) } else if (keyPath == "contentSize") { self.layoutSubviews() if self.isHorizontal { self.frame = CGRectMake(self.scrollView!.contentSize.width, 0, HWPullToInfinityViewWidth, self.scrollView!.contentSize.height) } else { self.frame = CGRectMake(0, self.scrollView!.contentSize.height, self.bounds.size.width, HWPullToInfinityViewHeight) } } } // MARK: Infinite setters func setCustomView(view: UIView, forState state: HWPullToInfinityState) { let viewPlaceholder: AnyObject = view if state == .All { self.viewForState[0...3] = [viewPlaceholder, viewPlaceholder, viewPlaceholder] } else { self.viewForState[state.hashValue] = viewPlaceholder } self.state = state } func setActivityIndicatorViewColor(color: UIColor) { self.activityIndicatorView.tintColor = color } func triggerRefresh() { self.state = .Triggered self.state = .Loading } func startAnimating() { self.state = .Loading } func stopAnimating() { self.state = .Stopped } } // MARK: Infinite scrollView extension extension UIScrollView { private struct InfiniteAssociatedKeys { static var infiniteScrollingView: HWPullToInfinityView? static var showsInfiniteScrolling : Bool = false static var infiniteScrollingHasBeenSetup : Bool = false } var infiniteScrollingHasBeenSetup: Bool { get { guard let number = objc_getAssociatedObject(self, &InfiniteAssociatedKeys.infiniteScrollingHasBeenSetup) as? NSNumber else { return false } return number.boolValue } set(value) { objc_setAssociatedObject(self,&InfiniteAssociatedKeys.infiniteScrollingHasBeenSetup,NSNumber(bool: value),objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var showsInfiniteScrolling : Bool { get { return !self.infiniteScrollingView.hidden } set(value) { self.infiniteScrollingView.hidden = !showsInfiniteScrolling if !value { if self.infiniteScrollingView.isObserving { self.removeObserver(self.infiniteScrollingView, forKeyPath: "contentOffset") self.removeObserver(self.infiniteScrollingView, forKeyPath: "contentSize") self.infiniteScrollingView.resetScrollViewContentInset() self.infiniteScrollingView.isObserving = false } } else { if !self.infiniteScrollingView.isObserving { self.addObserver(self.infiniteScrollingView, forKeyPath: "contentOffset", options: .New, context: nil) self.addObserver(self.infiniteScrollingView, forKeyPath: "contentSize", options: .New, context: nil) self.infiniteScrollingView.setScrollViewContentInsetForInfiniteScrolling() self.infiniteScrollingView.isObserving = true self.infiniteScrollingView.setNeedsLayout() if self.infiniteScrollingView.isHorizontal { self.infiniteScrollingView.frame = CGRectMake(self.contentSize.width, 0, HWPullToInfinityViewWidth, self.contentSize.height) } else { self.infiniteScrollingView.frame = CGRectMake(0, self.contentSize.height, self.infiniteScrollingView.bounds.size.width, HWPullToInfinityViewHeight) } } } } } var infiniteScrollingView: HWPullToInfinityView { get { return objc_getAssociatedObject(self, &InfiniteAssociatedKeys.infiniteScrollingView) as! HWPullToInfinityView } set { self.willChangeValueForKey("UIScrollViewInfiniteScrollingView") objc_setAssociatedObject(self, &InfiniteAssociatedKeys.infiniteScrollingView, newValue as HWPullToInfinityView?, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.didChangeValueForKey("UIScrollViewInfiniteScrollingView") } } func addInfiniteScrollingWithActionHandler(actionHandler: () -> Void) { if !self.infiniteScrollingHasBeenSetup { let view: HWPullToInfinityView = HWPullToInfinityView(frame: CGRectMake(0, self.contentSize.height, self.bounds.size.width, HWPullToInfinityViewHeight)) view.infiniteScrollingHandler = actionHandler view.scrollView = self self.addSubview(view) view.originalInset = self.contentInset.bottom self.infiniteScrollingView = view self.showsInfiniteScrolling = true self.infiniteScrollingHasBeenSetup = true } } func addHorizontalInfiniteScrollingWithActionHandler(actionHandler: () -> Void) { if !self.infiniteScrollingHasBeenSetup { let view: HWPullToInfinityView = HWPullToInfinityView(frame: CGRectMake(self.contentSize.width, 0, HWPullToInfinityViewWidth, self.contentSize.height)) view.infiniteScrollingHandler = actionHandler view.scrollView = self view.isHorizontal = true self.addSubview(view) view.originalInset = self.contentInset.right self.infiniteScrollingView = view self.showsInfiniteScrolling = true self.infiniteScrollingHasBeenSetup = true } } func triggerInfiniteScrolling() { self.infiniteScrollingView.state = .Triggered self.infiniteScrollingView.startAnimating() } }
mit
bad62281533321a4200895e196edb11c
39.103614
187
0.62675
5.327465
false
false
false
false
tkremenek/swift
validation-test/compiler_crashers_fixed/01085-swift-declcontext-lookupqualified.swift
65
774
// 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 // RUN: not %target-swift-frontend %s -typecheck struct B<T : A> { func f<g>() -> (g, g -> g) -> g { d j d.i = { } { g) { h } } protocol f { } class d: f{ class func i {} struct d<f : e,e where g.h == f.h> { } } protocol a { typeal= D>(e: A.B) { } } } override func d() -> String { func} func b((Any, c))(Any, AnyObject func g<T where T.E == F>(f: B<T>) { } struct c<S: Sequence, T where Optional<T> == S.Iterator.Element>
apache-2.0
64267253ae1b1b5eb75502dbc0abf340
22.454545
79
0.643411
2.835165
false
false
false
false
phatblat/Butler
Tests/ButlerTests/FreeStyleProjectSpec.swift
1
4622
// // FreeStyleProjectSpec.swift // Butler // // Created by Ben Chatelain on 6/2/17. // // @testable import Butler import Quick import Nimble import Foundation class FreeStyleProjectSpec: QuickSpec { override func spec() { describe("freestyle project job") { let jsonFile: NSString = "FreeStyleProject.json" var project: FreeStyleProject! = nil beforeEach { let bundle = Bundle(for: type(of: self)) let url = bundle.url(forResource: jsonFile.deletingPathExtension, withExtension: jsonFile.pathExtension, subdirectory: "JSON/Job")! let data = try! Data(contentsOf: url) let decoder = JSONDecoder() project = try! decoder.decode(FreeStyleProject.self, from: data) } it("has class") { expect(project._class) == JavaClass.freestyleProject } it("has a url") { expect(project.url) == URL(string: "http://mini.log-g.co/jenkins/job/whoami/") } it("is buildable") { expect(project.buildable) == true } it("is blue") { expect(project.color) == "blue" } it("is not concurrent") { expect(project.concurrentBuild) == false } it("has an empty description") { expect(project.description) == "" } it("has a name") { expect(project.name) == "whoami" } it("has a full name") { expect(project.fullName) == "whoami" } it("has a display name") { expect(project.displayName) == "whoami" } it("has a full display name") { expect(project.fullDisplayName) == "whoami" } it("has 2 builds") { expect(project.builds.count) == 2 } it("has a next build number") { expect(project.nextBuildNumber) == 3 } it("has no scm") { expect(project.scm["_class"]) == "hudson.scm.NullSCM" } it("has no properties") { expect(project.property) == [] } it("has no downstream projects") { expect(project.downstreamProjects) == [] } it("has no uptream projects") { expect(project.upstreamProjects) == [] } it("has a health report") { expect(project.healthReport).notTo(beNil()) let healthReport = project.healthReport.first! expect(healthReport.description) == "Build stability: No recent builds failed." expect(healthReport.score) == 100 } it("is not in the queue") { expect(project.inQueue) == false } it("has no queue item") { expect(project.queueItem).to(beNil()) } it("does not keep dependencies") { expect(project.keepDependencies) == false } it("has a last build") { expect(project.lastBuild.number) == 2 expect(project.lastBuild.url.absoluteString) == "http://mini.log-g.co/jenkins/job/whoami/2/" } it("has a last complete build") { expect(project.lastCompletedBuild.number) == 2 expect(project.lastCompletedBuild.url.absoluteString) == "http://mini.log-g.co/jenkins/job/whoami/2/" } it("has a last stable build") { expect(project.lastStableBuild.number) == 2 expect(project.lastStableBuild.url.absoluteString) == "http://mini.log-g.co/jenkins/job/whoami/2/" } it("has a last successful build") { expect(project.lastSuccessfulBuild.number) == 2 expect(project.lastSuccessfulBuild.url.absoluteString) == "http://mini.log-g.co/jenkins/job/whoami/2/" } it("does not have a last failed build") { expect(project.lastFailedBuild).to(beNil()) } it("does not have a last unstable build") { expect(project.lastUnstableBuild).to(beNil()) } it("does not have a last unsuccessful build") { expect(project.lastUnsuccessfulBuild).to(beNil()) } } } }
mit
4f744258044299fb384eaa1eb80d5a49
37.516667
118
0.499784
4.612774
false
false
false
false
wolfhous/haochang_swift
haochang_swift/haochang_swift/主文件-main/HCBasicVC.swift
1
1627
// // HCBasicVC.swift // haochang_swift // // Created by 壹号商圈 on 16/12/28. // Copyright © 2016年 com.houshuai. All rights reserved. // import UIKit class HCBasicVC: UIViewController { // MARK: 定义属性 var contentView : UIView? // MARK: 懒加载属性 fileprivate lazy var animImageView : UIImageView = { [unowned self] in let imageView = UIImageView(image: UIImage(named: "img_loading_1")) imageView.center = self.view.center imageView.animationImages = [UIImage(named : "img_loading_1")!, UIImage(named : "img_loading_2")!] imageView.animationDuration = 0.5 imageView.animationRepeatCount = LONG_MAX imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin] return imageView }() // MARK: 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() } } extension HCBasicVC { func setupUI() { // 1.隐藏内容的View contentView?.isHidden = true // 2.添加执行动画的UIImageView view.addSubview(animImageView) // 3.给animImageView执行动画 animImageView.startAnimating() // 4.设置view的背景颜色 view.backgroundColor = UIColor(r: 250, g: 250, b: 250) } func loadDataFinished() { // 1.停止动画 animImageView.stopAnimating() // 2.隐藏animImageView animImageView.isHidden = true // 3.显示内容的View contentView?.isHidden = false } }
mit
7afb2634c4c6d25d17f3268698c32353
22.030303
106
0.590789
4.418605
false
false
false
false
danger/danger-swift
Sources/DangerShellExecutor/ShellExecutor.swift
1
5066
import Foundation public enum SpawnError: Error { case commandFailed(command: String, exitCode: Int32, stdout: String, stderr: String) } public protocol ShellExecuting { @discardableResult func execute(_ command: String, arguments: [String], environmentVariables: [String: String], outputFile: String?) -> String @discardableResult func spawn(_ command: String, arguments: [String], environmentVariables: [String: String], outputFile: String?) throws -> String } extension ShellExecuting { @discardableResult public func execute(_ command: String, arguments: [String]) -> String { execute(command, arguments: arguments, environmentVariables: [:], outputFile: nil) } @discardableResult func execute(_ command: String, arguments: [String], environmentVariables: [String: String]) -> String { execute(command, arguments: arguments, environmentVariables: environmentVariables, outputFile: nil) } @discardableResult public func spawn(_ command: String, arguments: [String]) throws -> String { try spawn(command, arguments: arguments, environmentVariables: [:], outputFile: nil) } @discardableResult func spawn(_ command: String, arguments: [String], environmentVariables: [String: String]) throws -> String { try spawn(command, arguments: arguments, environmentVariables: environmentVariables, outputFile: nil) } } public struct ShellExecutor: ShellExecuting { public init() {} public func execute(_ command: String, arguments: [String], environmentVariables: [String: String], outputFile: String?) -> String { let task = makeTask(for: command, with: arguments, environmentVariables: environmentVariables, outputFile: outputFile) let pipe = Pipe() task.standardOutput = pipe task.launch() task.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() return String(data: data, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines) } // Similar to above, but can throw, and throws with most of // what you'd probably need in a scripting environment public func spawn(_ command: String, arguments: [String], environmentVariables: [String: String], outputFile: String?) throws -> String { let task = makeTask(for: command, with: arguments, environmentVariables: environmentVariables, outputFile: outputFile) let stdout = Pipe() task.standardOutput = stdout let stderr = Pipe() task.standardError = stderr task.launch() task.waitUntilExit() // Pull out the STDOUT as a string because we'll need that regardless let stdoutData = stdout.fileHandleForReading.readDataToEndOfFile() let stdoutString = String(data: stdoutData, encoding: .utf8)! // 0 is no problems in unix land if task.terminationStatus == 0 { return stdoutString.trimmingCharacters(in: .whitespacesAndNewlines) } // OK, so it failed, raise a new error with all the useful metadata let stderrData = stderr.fileHandleForReading.readDataToEndOfFile() let stderrString = String(data: stderrData, encoding: .utf8)! throw SpawnError.commandFailed(command: command, exitCode: task.terminationStatus, stdout: stdoutString, stderr: stderrString) } private func makeTask(for command: String, with arguments: [String], environmentVariables: [String: String], outputFile: String?) -> Process { let scriptOutputFile: String if let outputFile = outputFile { scriptOutputFile = " > \(outputFile)" } else { scriptOutputFile = "" } let script = "\(command) \(arguments.joined(separator: " "))" + scriptOutputFile let task = Process() task.launchPath = "/bin/sh" task.arguments = ["-c", script] task.environment = mergeEnvs(localEnv: environmentVariables, processEnv: ProcessInfo.processInfo.environment) task.currentDirectoryPath = FileManager.default.currentDirectoryPath return task } private func mergeEnvs(localEnv: [String: String], processEnv: [String: String]) -> [String: String] { localEnv.merging(processEnv, uniquingKeysWith: { _, envString -> String in envString }) } }
mit
e52ecfb47aa464a1f0dc92dc8f439bf3
36.80597
117
0.589222
5.660335
false
false
false
false
gbuenoandrade/e-urbano
e-urbano/History.swift
1
1204
// // History.swift // e-urbano // // Created by Guilherme Andrade on 7/5/15. // Copyright (c) 2015 Laboratório de Estudos Urbanos da Unicamp. All rights reserved. // import Foundation import Parse class History: PFObject { @NSManaged var title: String? @NSManaged var authorName: String? @NSManaged var imageFile: PFFile? @NSManaged var textContent: String? @NSManaged var latitude: NSNumber? @NSManaged var longitude: NSNumber? @NSManaged var printableAddress: String? @NSManaged var authorUsername: String? func getImageSynchronously() -> UIImage? { if let data = imageFile?.getData() { return UIImage(data: data) } return nil } func createImageFileFromImage(image: UIImage!) { let data = UIImagePNGRepresentation(image) self.imageFile = PFFile(data: data) } override init() { super.init() } override class func query() -> PFQuery? { let query = PFQuery(className: History.parseClassName()) return query } } extension History: PFSubclassing { class func parseClassName() -> String { return "History" } override class func initialize() { var onceToken: dispatch_once_t = 0 dispatch_once(&onceToken) { self.registerSubclass() } } }
mit
5db143f7b907d9316b62c67af0e39a9e
20.122807
86
0.710723
3.507289
false
false
false
false
atl009/WordPress-iOS
WordPress/Classes/Extensions/PHAsset+Exporters.swift
1
14800
import Foundation import Photos import MobileCoreServices import AVFoundation extension PHAsset: ExportableAsset { internal func exportToURL(_ url: URL, targetUTI: String, maximumResolution: CGSize, stripGeoLocation: Bool, synchronous: Bool, successHandler: @escaping SuccessHandler, errorHandler: @escaping ErrorHandler) { switch self.mediaType { case .image: exportImageToURL(url, targetUTI: targetUTI, maximumResolution: maximumResolution, stripGeoLocation: stripGeoLocation, synchronous: synchronous, successHandler: successHandler, errorHandler: errorHandler) case .video: exportVideoToURL(url, targetUTI: targetUTI, maximumResolution: maximumResolution, stripGeoLocation: stripGeoLocation, successHandler: successHandler, errorHandler: errorHandler) default: errorHandler(errorForCode(.unsupportedAssetType, failureReason: NSLocalizedString("This media type is not supported on WordPress.", comment: "Error reason to display when exporting an unknow asset type from the device library"))) } } internal func exportImageToURL(_ url: URL, targetUTI: String, maximumResolution: CGSize, stripGeoLocation: Bool, synchronous: Bool, successHandler: @escaping SuccessHandler, errorHandler: @escaping ErrorHandler) { let pixelSize = CGSize(width: pixelWidth, height: pixelHeight) let requestedSize = maximumResolution.clamp(min: CGSize.zero, max: pixelSize) exportImageWithSize(requestedSize, synchronous: synchronous) { (image, info) in guard let image = image else { if let error = info?[PHImageErrorKey] as? NSError { errorHandler(error) } else { errorHandler(self.errorForCode(.failedToExport, failureReason: NSLocalizedString("Unknown asset export error", comment: "Error reason to display when the export of a image from device library fails") )) } return } self.requestMetadataWithCompletionBlock({ (metadata) -> () in do { var attributesToRemove = [String]() if stripGeoLocation { attributesToRemove.append(kCGImagePropertyGPSDictionary as String) } var exportMetadata = self.removeAttributes(attributesToRemove, fromMetadata: metadata) exportMetadata = self.matchMetadata(exportMetadata, image: image) try image.writeToURL(url, type: targetUTI, compressionQuality: 0.9, metadata: exportMetadata) successHandler(image.size) } catch let error as NSError { errorHandler(error) } }, failureBlock: { (error) -> () in errorHandler(error) }) } } func exportMaximumSizeImage(_ completion: @escaping (UIImage?, [AnyHashable: Any]?) -> Void) { let targetSize = CGSize(width: pixelWidth, height: pixelHeight) exportImageWithSize(targetSize, synchronous: false, completion: completion) } func exportImageWithSize(_ targetSize: CGSize, synchronous: Bool, completion: @escaping (UIImage?, [AnyHashable: Any]?) -> Void) { let options = PHImageRequestOptions() options.version = .current options.deliveryMode = .highQualityFormat options.resizeMode = .exact options.isSynchronous = synchronous options.isNetworkAccessAllowed = true let manager = PHImageManager.default() manager.requestImage(for: self, targetSize: targetSize, contentMode: .aspectFit, options: options) { (image, info) in completion(image, info) } } func exportOriginalImage(_ toURL: URL, successHandler: @escaping SuccessHandler, errorHandler: @escaping ErrorHandler) { let pixelSize = CGSize(width: pixelWidth, height: pixelHeight) let options = PHAssetResourceRequestOptions() options.isNetworkAccessAllowed = true let manager = PHAssetResourceManager.default() let resources = PHAssetResource.assetResources(for: self) let filteredResources = resources.filter { (resource) -> Bool in return resource.type == .photo } if let resource = filteredResources.first { manager.writeData(for: resource, toFile: toURL, options: options) { (error) in if let error = error { errorHandler(error as NSError) return } successHandler(pixelSize) } } else { errorHandler(self.errorForCode(.failedToExport, failureReason: NSLocalizedString("Unknown asset export error", comment: "Error reason to display when the export of a image from device library fails") )) } } func removeAttributes(_ attributes: [String], fromMetadata: [String: AnyObject]) -> [String: AnyObject] { var resultingMetadata = fromMetadata for attribute in attributes { resultingMetadata.removeValue(forKey: attribute) if attribute == kCGImagePropertyOrientation as String { if let tiffMetadata = resultingMetadata[kCGImagePropertyTIFFDictionary as String] as? [String: AnyObject] { var newTiffMetadata = tiffMetadata newTiffMetadata.removeValue(forKey: kCGImagePropertyTIFFOrientation as String) resultingMetadata[kCGImagePropertyTIFFDictionary as String] = newTiffMetadata as AnyObject? } } } return resultingMetadata } /// Makes sure the metadata of the image is matching the attributes in the Image. /// /// - Parameters: /// - metadata: The original metadata of the image. /// - image: The current image. /// /// - Returns: A new metadata object where the values match the values on the UIImage /// func matchMetadata(_ metadata: [String: AnyObject], image: UIImage) -> [String: AnyObject] { var resultingMetadata = metadata let correctOrientation = image.metadataOrientation resultingMetadata[kCGImagePropertyOrientation as String] = Int(correctOrientation.rawValue) as AnyObject? if var tiffMetadata = resultingMetadata[kCGImagePropertyTIFFDictionary as String] as? [String: AnyObject] { tiffMetadata[kCGImagePropertyTIFFOrientation as String] = Int(correctOrientation.rawValue) as AnyObject? resultingMetadata[kCGImagePropertyTIFFDictionary as String] = tiffMetadata as AnyObject? } return resultingMetadata } func exportVideoToURL(_ url: URL, targetUTI: String, maximumResolution: CGSize, stripGeoLocation: Bool, successHandler: @escaping SuccessHandler, errorHandler: @escaping ErrorHandler) { let options = PHVideoRequestOptions() options.isNetworkAccessAllowed = true PHImageManager.default().requestExportSession(forVideo: self, options: options, exportPreset: MediaSettings().maxVideoSizeSetting.videoPreset) { (exportSession, info) -> Void in guard let exportSession = exportSession else { if let error = info?[PHImageErrorKey] as? NSError { errorHandler(error) } else { errorHandler(self.errorForCode(.failedToExport, failureReason: NSLocalizedString("Unknown asset export error", comment: "Error reason to display when the export of a image from device library fails") )) } return } exportSession.outputFileType = targetUTI exportSession.shouldOptimizeForNetworkUse = true if stripGeoLocation { exportSession.metadataItemFilter = AVMetadataItemFilter.forSharing() } exportSession.outputURL = url exportSession.exportAsynchronously(completionHandler: { () -> Void in guard exportSession.status == .completed else { if let error = exportSession.error { errorHandler(error as NSError) } return } successHandler(CGSize(width: self.pixelWidth, height: self.pixelHeight)) }) } } func exportThumbnailToURL(_ url: URL, targetSize: CGSize, synchronous: Bool, successHandler: @escaping SuccessHandler, errorHandler: @escaping ErrorHandler) { let options = PHImageRequestOptions() options.version = .current options.deliveryMode = .highQualityFormat options.resizeMode = .fast options.isSynchronous = synchronous options.isNetworkAccessAllowed = true var requestedSize = targetSize if requestedSize == CGSize.zero { requestedSize = PHImageManagerMaximumSize } PHImageManager.default().requestImage(for: self, targetSize: requestedSize, contentMode: .aspectFit, options: options) { (image, info) -> Void in guard let image = image else { if let error = info?[PHImageErrorKey] as? NSError { errorHandler(error) } else { errorHandler(self.errorForCode(.failedToExport, failureReason: NSLocalizedString("Unknown asset export error", comment: "Error reason to display when the export of a image from device library fails") )) } return } do { try image.writeToURL(url, type: self.defaultThumbnailUTI, compressionQuality: 0.9, metadata: nil) successHandler(image.size) } catch let error as NSError { errorHandler(error) } } } var defaultThumbnailUTI: String { get { return kUTTypeJPEG as String } } var assetMediaType: MediaType { get { if self.mediaType == .image { return .image } else if self.mediaType == .video { /** HACK: Sergio Estevao (2015-11-09): We ignore allowsFileTypes for videos in WP.com because we have an exception on the server for mobile that allows video uploads event if videopress is not enabled. */ return .video } return .document } } // MARK: - Error Handling enum ErrorCode: Int { case unsupportedAssetType = 1 case failedToExport = 2 case failedToExportMetadata = 3 } fileprivate func errorForCode(_ errorCode: ErrorCode, failureReason: String) -> NSError { let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason] let error = NSError(domain: "PHAsset+ExporterExtensions", code: errorCode.rawValue, userInfo: userInfo) return error } func requestMetadataWithCompletionBlock(_ completionBlock: @escaping (_ metadata: [String: AnyObject]) ->(), failureBlock: @escaping (_ error: NSError) -> ()) { let editOptions = PHContentEditingInputRequestOptions() editOptions.isNetworkAccessAllowed = true self.requestContentEditingInput(with: editOptions) { (contentEditingInput, info) -> Void in guard let contentEditingInput = contentEditingInput, let fullSizeImageURL = contentEditingInput.fullSizeImageURL, let image = CIImage(contentsOf: fullSizeImageURL) else { completionBlock([String: AnyObject]()) if let error = info[PHImageErrorKey] as? NSError { failureBlock(error) } else { failureBlock(self.errorForCode(.failedToExportMetadata, failureReason: NSLocalizedString("Unable to export metadata", comment: "Error reason to display when the export of a image from device library fails") )) } return } completionBlock(image.properties as [String: AnyObject]) } } func originalUTI() -> String? { let resources = PHAssetResource.assetResources(for: self) var types: [PHAssetResourceType.RawValue] = [] if mediaType == PHAssetMediaType.image { types = [PHAssetResourceType.photo.rawValue] } else if mediaType == PHAssetMediaType.video { types = [PHAssetResourceType.video.rawValue] } for resource in resources { if types.contains(resource.type.rawValue) { return resource.uniformTypeIdentifier } } return nil } func originalFilename() -> String? { let resources = PHAssetResource.assetResources(for: self) var types: [PHAssetResourceType.RawValue] = [] if mediaType == PHAssetMediaType.image { types = [PHAssetResourceType.photo.rawValue] } else if mediaType == PHAssetMediaType.video { types = [PHAssetResourceType.video.rawValue] } for resource in resources { if types.contains(resource.type.rawValue) { return resource.originalFilename } } return nil } } extension String { static func StringFromCFType(_ cfValue: Unmanaged<CFString>?) -> String? { let value = Unmanaged.fromOpaque(cfValue!.toOpaque()).takeUnretainedValue() as CFString if CFGetTypeID(value) == CFStringGetTypeID() { return value as String } else { return nil } } }
gpl-2.0
266a931973729128481a66748961423f
42.529412
183
0.584257
5.941389
false
false
false
false
ngallo/SwiftTaskLibrary
SwiftTaskLibrary/CancellationTokenSource.swift
1
1391
// // CancellationTokenSource.swift // SwiftTaskLibrary // // Created by Nicola Gallo on 03/07/2016. // Copyright © 2016 Nicola Gallo. All rights reserved. // import Foundation public final class CancellationToken { //#MARK: Fields fileprivate var _canceled = false //#MARK: Constructors & Destructors fileprivate init() { id = UUID().uuidString } //#MARK: Properties public let id:String /// Gets whether cancellation has been requested for this token. public var isCancellationRequested:Bool { return _canceled == true } //#MARK: Methods fileprivate func cancel() { _canceled = true } /// Throws a TaskError.Canceled if this token has had cancellation requested. public func throwIfCancellationRequested() throws { if _canceled == true { throw TaskError.canceled } } } public final class CancellationTokenSource { //#MARK: Constructors & Destructors public init() { token = CancellationToken() } //#MARK: Properties /// Gets whether cancellation has been requested for this CancellationTokenSource. public let token:CancellationToken //#MARK: Methods /// Communicates a request for cancellation. public func cancel() { token.cancel() } }
mit
b51eb446b125140f004daca6fe2a7161
19.746269
86
0.623022
5.148148
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/minimum-height-trees.swift
2
4266
/** * https://leetcode.com/problems/minimum-height-trees/ * * */ // Date: Tue Jun 9 10:01:29 PDT 2020 class Solution { /// TLE /// - Complexity: /// - Time: O(n*n*e), n is the number of nodes and e is number of edges. So, possibly O(n^4). /// - Space: O(e) /// func findMinHeightTrees(_ n: Int, _ edges: [[Int]]) -> [Int] { var graph: [[Int]] = Array(repeating: [], count: n) for edge in edges { graph[edge[0]].append(edge[1]) graph[edge[1]].append(edge[0]) } var roots: [Int] = [] var minHeight = n for root in 0 ..< n { var queue = [root] var height = 0 var visited: Set<Int> = [root] while queue.isEmpty == false { var n = queue.count height += 1 while n > 0 { n -= 1 let node = queue.removeFirst() for dst in graph[node] { if visited.contains(dst) == false { queue.append(dst) visited.insert(dst) } } } } // print("Root: \(root) - \(height)") if height < minHeight { roots = [root] minHeight = height } else if height == minHeight { roots.append(root) minHeight = height } } return roots } } /** * https://leetcode.com/problems/minimum-height-trees/ * * */ // Date: Wed Nov 4 10:16:50 PST 2020 class Solution { /// TLE solution, O(n^2 + n * E) /// - Complexity: /// - Time: O(n * (V + E)), v = n, e = edges.count. /// - Space: func findMinHeightTrees(_ n: Int, _ edges: [[Int]]) -> [Int] { var graph: [[Int]] = Array(repeating: [], count: n) for edge in edges { graph[edge[0]].append(edge[1]) graph[edge[1]].append(edge[0]) } var roots: [Int] = [] var minHeight = n for root in 0 ..< n { var queue: [Int] = [root] var visited: Set<Int> = [root] var height = 0 while queue.isEmpty == false { var layerCount = queue.count height += 1 while layerCount > 0 { layerCount -= 1 let node = queue.removeFirst() for neighbor in graph[node] { if visited.contains(neighbor) == false { visited.insert(neighbor) queue.append(neighbor) } } } } if height < minHeight { minHeight = height roots = [root] } else if height == minHeight { roots.append(root) } } return roots } }/** * https://leetcode.com/problems/minimum-height-trees/ * * */ // Date: Wed Nov 4 10:19:41 PST 2020 class Solution { /// Toplogical solution. /// - Complexity: /// - Time: O(V + E), V = n, e = edges.count /// - Space: func findMinHeightTrees(_ n: Int, _ edges: [[Int]]) -> [Int] { var graph: [Set<Int>] = Array(repeating: [], count: n) for edge in edges { graph[edge[0]].insert(edge[1]) graph[edge[1]].insert(edge[0]) } var leaves: Set<Int> = [] for leaf in 0 ..< n { if graph[leaf].count <= 1 { leaves.insert(leaf) } } var nextLayer: Set<Int> = [] repeat { nextLayer = [] for leaf in leaves { for neighbor in graph[leaf] { graph[neighbor].remove(leaf) if graph[neighbor].count == 1 { nextLayer.insert(neighbor) } } } if nextLayer.isEmpty == false { leaves = nextLayer } } while !nextLayer.isEmpty return Array(leaves) } }
mit
4842623c722138390e9c72cb7a7953cb
29.262411
101
0.416315
4.322188
false
false
false
false
IvanKalaica/GitHubSearch
GitHubSearch/GitHubSearch/View/ViewController/UserViewController.swift
1
2552
// // UserViewController.swift // GitHubSearch // // Created by Ivan Kalaica on 21/09/2017. // Copyright © 2017 Kalaica. All rights reserved. // import UIKit import RxSwift import RxCocoa import Eureka class UserViewController: FormViewController { private let disposeBag = DisposeBag() init(viewModel: UserViewModel) { super.init(nibName: nil, bundle: nil) let section = Section() { $0.header = HeaderFooterView<EurekaLogoView>(.class) } section.tag = Tags.section self.form +++ section <<< LabelRow(Tags.name) <<< LabelRow(Tags.createdAt) <<< LabelRow(Tags.company) <<< LabelRow(Tags.email) +++ Section() <<< ButtonRow() { $0.title = NSLocalizedString("User details", comment: "User details button title") } .onCellSelection { cell, row in viewModel.userDidSelect.on(.next())} viewModel.username.drive(onNext: { [weak self] in self?.title = $0 }).addDisposableTo(self.disposeBag) viewModel.name.drive(onNext: { [weak self] in self?.set($0, forTag: Tags.name) }).addDisposableTo(self.disposeBag) viewModel.createdAt.drive(onNext: { [weak self] in self?.set($0, forTag: Tags.createdAt) }).addDisposableTo(self.disposeBag) viewModel.company.drive(onNext: { [weak self] in self?.set($0, forTag: Tags.company) }).addDisposableTo(self.disposeBag) viewModel.email.drive(onNext: { [weak self] in self?.set($0, forTag: Tags.email) }).addDisposableTo(self.disposeBag) viewModel.avatarUrl.drive(onNext: { [weak self] (avatarUrl: String) in guard let sSelf = self, let section = sSelf.form.sectionBy(tag: Tags.section), let view: EurekaLogoView = section.header?.viewForSection(section, type: .header) as? EurekaLogoView else { return } view.imageView.load(url: avatarUrl) }).addDisposableTo(self.disposeBag) viewModel.presentUser.drive(onNext: { (url: String) in guard let url = URL(string: url) else { return } UIApplication.shared.open(url, options: [:], completionHandler: nil) }).disposed(by: self.disposeBag) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } fileprivate struct Tags { static let name = "name" static let createdAt = "createdAt" static let company = "company" static let email = "email" static let section = "section" }
mit
88a77907baa3dd02f26c7a442b1bab42
42.237288
132
0.639749
4.237542
false
false
false
false
zakkhoyt/ColorPicKit
ColorPicKit/Classes/HSBWheelView.swift
1
801
// // HSBWheelView.swift // ColorPicKitExample // // Created by Zakk Hoyt on 10/8/16. // Copyright © 2016 Zakk Hoyt. All rights reserved. // import UIKit class HSBWheelView: WheelView { override func rgbaFor(point: CGPoint) -> RGBA { let center = CGPoint(x: radius, y: radius) let angle = atan2(point.x - center.x, point.y - center.y) + CGFloat.pi let dist = pointDistance(point, CGPoint(x: center.x, y: center.y)) var hue = angle / (CGFloat.pi * 2.0) hue = min(hue, 1.0 - 0.0000001) hue = max(hue, 0.0) var sat = dist / radius sat = min(sat, 1.0) sat = max(sat, 0.0) let rgba = UIColor.hsbaToRGBA(hsba: HSBA(hue: hue, saturation: sat, brightness: brightness)) return rgba } }
mit
dee20895c5d00bce67440e7e803f08a3
26.586207
100
0.5825
3.333333
false
false
false
false
wireapp/wire-ios-sync-engine
Source/SessionManager/SessionManager+Authentication.swift
1
1461
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 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 // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // public extension SessionManager { static let previousSystemBootTimeContainer = "PreviousSystemBootTime" static var previousSystemBootTime: Date? { get { guard let data = ZMKeychain.data(forAccount: previousSystemBootTimeContainer), let string = String(data: data, encoding: .utf8), let timeInterval = TimeInterval(string) else { return nil } return Date(timeIntervalSince1970: timeInterval) } set { guard let newValue = newValue, let data = "\(newValue.timeIntervalSince1970)".data(using: .utf8) else { return } ZMKeychain.setData(data, forAccount: previousSystemBootTimeContainer) } } }
gpl-3.0
b13cdc1a8d1e334c1f615cd4a9834eb7
36.461538
97
0.674196
4.638095
false
false
false
false
SmallPlanetSwift/Saturn
Source/SaturnObject.swift
1
2523
// // SaturnObject.swift // Saturn // // Created by Quinn McHenry on 11/14/15. // Copyright © 2015 Small Planet. All rights reserved. // public protocol SaturnObject { func loadIntoParent(parent: AnyObject) mutating func setAttribute(attribute: String, forProperty property: String) mutating func setAttributes(attributes:[String:String]?) func objectsWithId(id: String) -> [AnyObject] } extension SaturnObject { public static func readFromFile(path: String?, intoParent parent: AnyObject? = nil) -> SaturnObject? { guard let path = path else { return nil } do { let string = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding) return readFromString(string, intoParent: parent) } catch let error as NSError { print("error writing to url \(path)") print(error.localizedDescription) } return nil } public static func readFromString(string: String?, intoParent parent: AnyObject? = nil) -> SaturnObject? { guard let string = string, xmlData = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) else { return nil } let xmlDoc = try? AEXMLDocument(xmlData: xmlData, processNamespaces: false) return parseElement(xmlDoc?.root, intoParent: parent) } public static func parseElement(element: AEXMLElement?, intoParent parent: AnyObject? = nil) -> SaturnObject? { guard let element = element, entityClass = classFromElement(element) else { return nil } let entity = entityClass.init() entity.setAttributes(element.attributes as? [String:String]) if let parent = parent { entity.loadIntoParent(parent) } element.children.forEach { child in parseElement(child, intoParent: entity) } return entity } private static func classFromElement(element: AEXMLElement) -> NSObject.Type? { return (NSClassFromString(element.name) as? NSObject.Type) ?? (NSClassFromString("Saturn.\(element.name)") as? NSObject.Type) } } // styles handled by reading an xml file with style definitions and storing the attribute dictionaries in a ditionary keyed by the styleId // config dictionary read from plist, handled in parseElement, replacing keys with values before setAttributes struct Saturn { static private var styles: [String : [String:String]]? static private var config: [String : AnyObject]? }
mit
c1b885c99954ce12cdc750ba8d05cecb
39.031746
140
0.680809
4.644567
false
false
false
false
adrfer/swift
test/Interpreter/generic_casts.swift
14
4247
// RUN: %target-run-simple-swift | FileCheck %s // RUN: %target-build-swift -O %s -o %t/a.out.optimized // RUN: %target-run %t/a.out.optimized | FileCheck %s // REQUIRES: executable_test // FIXME: rdar://problem/19648117 Needs splitting objc parts out // XFAIL: linux import Foundation func allToInt<T>(x: T) -> Int { return x as! Int } func allToIntOrZero<T>(x: T) -> Int { if x is Int { return x as! Int } return 0 } func anyToInt(x: protocol<>) -> Int { return x as! Int } func anyToIntOrZero(x: protocol<>) -> Int { if x is Int { return x as! Int } return 0 } protocol Class : class {} class C : Class { func print() { Swift.print("C!") } } class D : C { override func print() { Swift.print("D!") } } class E : C { override func print() { Swift.print("E!") } } class X : Class { } func allToC<T>(x: T) -> C { return x as! C } func allToCOrE<T>(x: T) -> C { if x is C { return x as! C } return E() } func anyToC(x: protocol<>) -> C { return x as! C } func anyToCOrE(x: protocol<>) -> C { if x is C { return x as! C } return E() } func allClassesToC<T : Class>(x: T) -> C { return x as! C } func allClassesToCOrE<T : Class>(x: T) -> C { if x is C { return x as! C } return E() } func anyClassToC(x: protocol<Class>) -> C { return x as! C } func anyClassToCOrE(x: protocol<Class>) -> C { if x is C { return x as! C } return E() } func allToAll<T, U>(t: T, _: U.Type) -> Bool { return t is U } func allMetasToAllMetas<T, U>(_: T.Type, _: U.Type) -> Bool { return T.self is U.Type } print(allToInt(22)) // CHECK: 22 print(anyToInt(44)) // CHECK: 44 allToC(C()).print() // CHECK: C! allToC(D()).print() // CHECK: D! anyToC(C()).print() // CHECK: C! anyToC(D()).print() // CHECK: D! allClassesToC(C()).print() // CHECK: C! allClassesToC(D()).print() // CHECK: D! anyClassToC(C()).print() // CHECK: C! anyClassToC(D()).print() // CHECK: D! print(allToIntOrZero(55)) // CHECK: 55 print(allToIntOrZero("fifty-five")) // CHECK: 0 print(anyToIntOrZero(88)) // CHECK: 88 print(anyToIntOrZero("eighty-eight")) // CHECK: 0 allToCOrE(C()).print() // CHECK: C! allToCOrE(D()).print() // CHECK: D! allToCOrE(143).print() // CHECK: E! allToCOrE(X()).print() // CHECK: E! anyToCOrE(C()).print() // CHECK: C! anyToCOrE(D()).print() // CHECK: D! anyToCOrE(143).print() // CHECK: E! anyToCOrE(X()).print() // CHECK: E! allClassesToCOrE(C()).print() // CHECK: C! allClassesToCOrE(D()).print() // CHECK: D! allClassesToCOrE(X()).print() // CHECK: E! anyClassToCOrE(C()).print() // CHECK: C! anyClassToCOrE(D()).print() // CHECK: D! anyClassToCOrE(X()).print() // CHECK: E! // CHECK-LABEL: type comparisons: print("type comparisons:\n") print(allMetasToAllMetas(Int.self, Int.self)) // CHECK: true print(allMetasToAllMetas(Int.self, Float.self)) // CHECK: false print(allMetasToAllMetas(C.self, C.self)) // CHECK: true print(allMetasToAllMetas(D.self, C.self)) // CHECK: true print(allMetasToAllMetas(C.self, D.self)) // CHECK: false print(C.self is D.Type) // CHECK: false print((D.self as C.Type) is D.Type) // CHECK: true let t: Any.Type = (1 as Any).dynamicType print(t is Int.Type) // CHECK: true print(t is Float.Type) // CHECK: false print(t is C.Type) // CHECK: false let u: Any.Type = (D() as Any).dynamicType print(u is C.Type) // CHECK: true print(u is D.Type) // CHECK: true print(u is E.Type) // CHECK: false print(u is Int.Type) // CHECK: false // FIXME: Can't spell AnyObject.Protocol // CHECK-LABEL: AnyObject casts: print("AnyObject casts:") print(allToAll(C(), AnyObject.self)) // CHECK-NEXT: true print(allToAll(C().dynamicType, AnyObject.self)) // CHECK-NEXT: true // Bridging print(allToAll(0, AnyObject.self)) // CHECK-NEXT: true struct NotBridged { var x: Int } print(allToAll(NotBridged(x: 0), AnyObject.self)) // CHECK-NEXT: false // // rdar://problem/19482567 // func swiftOptimizesThisFunctionIncorrectly() -> Bool { let anArray = [] as NSArray if let whyThisIsNeverExecutedIfCalledFromFunctionAndNotFromMethod = anArray as? [NSObject] { return true } return false } let result = swiftOptimizesThisFunctionIncorrectly() print("Bridge cast result: \(result)") // CHECK-NEXT: Bridge cast result: true
apache-2.0
cbb3b88323140f47af7de33dfb014027
22.726257
96
0.639981
2.978261
false
false
false
false