repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
keith/radars
refs/heads/main
LazyCollectionEvaluatedMultipleTimes/LazyCollectionEvaluatedMultipleTimes.swift
mit
1
func g(string: String) -> String { let result = string == "b" ? "hi" : "" print("Called with '\(string)' returning '\(result)'") return result } public extension CollectionType { public func find(includedElement: Generator.Element -> Bool) -> Generator.Element? { if let index = self.indexOf(includedElement) { return self[index] } return nil } } func f(fields: [String]) { _ = fields.lazy .map { g($0) } .find { !$0.isEmpty } } f(["a", "b", "c"])
df1b469ab205fe4638ddeb9fe5f10bea
21.913043
88
0.552182
false
false
false
false
jngd/advanced-ios10-training
refs/heads/master
T9E01/T9E01/RecipeListViewController.swift
apache-2.0
1
/** * Copyright (c) 2016 Juan Garcia * * 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 RecipeListViewController: UIViewController { var cells: NSArray? override func viewDidLoad() { super.viewDidLoad() let path = Bundle.main.bundlePath as NSString let finalPath = path.appendingPathComponent("recetas.plist") cells = NSArray(contentsOfFile: finalPath) } } extension RecipeListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (cells?.count)! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Recipe", for: indexPath) as! RecipeListCell let recipeName = ((self.cells![indexPath.row] as AnyObject?)!.object(forKey: "nombre") as? String)! let recipeImageName = ((self.cells![indexPath.row] as AnyObject?)!.object(forKey: "imagen") as? String)! let recipeImage: UIImage = UIImage(named: recipeImageName)! let recipeDescription = ((self.cells![indexPath.row] as AnyObject?)!.object(forKey: "descripcion") as? String)! cell.recipeName?.text = recipeName cell.recipeImage?.image = recipeImage cell.recipeDescription = recipeDescription return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == "ViewRecipeDetail" else { fatalError("Segue identifier not found") } guard let cell = sender as! RecipeListCell? else { fatalError("Recipe list cell cannot be cast") } guard let recipeViewController = segue.destination as? RecipeViewController else { return } recipeViewController.recipeImageURL = cell.recipeImage.image?.accessibilityIdentifier recipeViewController.recipeNameText = cell.recipeName.text recipeViewController.recipeDescriptionText = cell.recipeDescription } } extension RecipeListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } }
c94ea25776374a5cd6be3655847d84cd
35.452381
113
0.767146
false
false
false
false
kpham13/SkaterBrad
refs/heads/master
SkaterBrad/NewGameMenu.swift
bsd-2-clause
1
// // NewGrameNode.swift // SkaterBrad // // Copyright (c) 2014 Mother Functions. All rights reserved. // import UIKit import SpriteKit enum SoundButtonSwitch { case On case Off } class NewGameNode: SKNode { var titleLabel: SKLabelNode! var directionLabel: SKLabelNode! var playButton: SKSpriteNode! var soundOnButton: SKSpriteNode! var soundOffButton: SKSpriteNode! var gameCenterButton: SKSpriteNode! //xx init(scene: SKScene, playSound: Bool) { super.init() self.titleLabel = SKLabelNode(text: "Skater Brad") self.titleLabel.fontName = "SkaterDudes" self.titleLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.8) self.titleLabel.zPosition = 5 self.directionLabel = SKLabelNode(text: "Swipe up to jump") self.directionLabel.fontName = "SkaterDudes" self.directionLabel.zPosition = 5 // New Game Button self.playButton = SKSpriteNode(imageNamed: "playNow.png") self.playButton.name = "PlayNow" self.playButton.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMidY(scene.frame)) self.playButton.zPosition = 10 self.playButton.xScale = 0.6 self.playButton.yScale = 0.6 self.addChild(self.playButton) // Sound On Button self.soundOnButton = SKSpriteNode(imageNamed: "SoundOn") self.soundOnButton.position = CGPoint(x: CGRectGetMaxX(scene.frame) - self.soundOnButton.frame.width / 2, y: CGRectGetMaxY(scene.frame) - self.soundOnButton.frame.height / 2) self.soundOnButton?.name = "SoundOn" self.soundOnButton.xScale = 0.40 self.soundOnButton.yScale = 0.40 self.soundOnButton.zPosition = 2.0 // Sound Off Button self.soundOffButton = SKSpriteNode(imageNamed: "SoundOff") self.soundOffButton.position = CGPoint(x: CGRectGetMaxX(scene.frame) - self.soundOffButton.frame.width, y: CGRectGetMaxY(scene.frame) - self.soundOffButton.frame.height / 2) self.soundOffButton?.name = "SoundOff" self.soundOffButton.xScale = 0.40 self.soundOffButton.yScale = 0.40 self.soundOffButton.zPosition = 2.0 if playSound == true { self.addChild(self.soundOnButton) } else { self.addChild(self.soundOffButton) } // Game Center Button [KP] //15 self.gameCenterButton = SKSpriteNode(imageNamed: "GameCenter") self.gameCenterButton?.name = "GameCenterButton" self.gameCenterButton?.zPosition = 10 self.gameCenterButton.xScale = 0.8 self.gameCenterButton.yScale = 0.8 self.gameCenterButton?.anchorPoint = CGPointMake(0, 0) if scene.frame.size.height == 568 { self.titleLabel.fontSize = 40 self.directionLabel.fontSize = 18 self.directionLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.13) self.gameCenterButton.position = CGPointMake(CGRectGetMaxX(scene.frame) * (-0.04), CGRectGetMaxY(scene.frame) * (-0.03)) } else if scene.frame.size.height == 667 { self.titleLabel.fontSize = 45 self.directionLabel.fontSize = 20 self.directionLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.11) self.gameCenterButton.position = CGPointMake(CGRectGetMaxX(scene.frame) * (-0.01), CGRectGetMaxY(scene.frame) * (-0.025)) } else if scene.frame.size.height == 736 { println(scene.frame.size.height) self.titleLabel.fontSize = 50 self.directionLabel.fontSize = 22 self.directionLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.11) self.gameCenterButton.xScale = 1.0 self.gameCenterButton.yScale = 1.0 self.gameCenterButton.position = CGPointMake(CGRectGetMaxX(scene.frame) * 0.02, CGRectGetMaxY(scene.frame) * (-0.015)) } else { self.titleLabel.fontSize = 40 self.titleLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.78) self.directionLabel.fontSize = 18 self.directionLabel.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMaxY(scene.frame) * 0.15) self.gameCenterButton.xScale = 0.7 self.gameCenterButton.yScale = 0.7 self.gameCenterButton.position = CGPointMake(CGRectGetMaxX(scene.frame) * (-0.03), CGRectGetMaxY(scene.frame) * (-0.03)) } self.addChild(self.titleLabel) self.addChild(self.directionLabel) self.addChild(self.gameCenterButton) } func turnSoundOnOff(switchButton : SoundButtonSwitch) { if switchButton == SoundButtonSwitch.On { println("SoundButtonSwitch.On") self.soundOffButton.removeFromParent() self.addChild(self.soundOnButton) } else { println("SoundButtonSwitch.Off") self.soundOnButton.removeFromParent() self.addChild(self.soundOffButton) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
57357672db4bd47c4d79b8e9f75c13f2
42.282258
182
0.651137
false
false
false
false
JGiola/swift
refs/heads/main
test/PrintAsObjC/empty.swift
apache-2.0
2
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) %s -typecheck -emit-objc-header-path %t/empty.h // RUN: %FileCheck %s < %t/empty.h // RUN: %check-in-clang -std=c99 %t/empty.h // RUN: %check-in-clang -std=c11 %t/empty.h // RUN: %check-cxx-header-in-clang -x objective-c++-header -std=c++11 -D_LIBCPP_CSTDLIB %t/empty.h // RUN: %check-cxx-header-in-clang -x objective-c++-header -std=c++14 -D_LIBCPP_CSTDLIB %t/empty.h // RUN: %check-in-clang -std=c99 -fno-modules -Qunused-arguments %t/empty.h // RUN: not %check-in-clang -I %S/Inputs/clang-headers %t/empty.h 2>&1 | %FileCheck %s --check-prefix=CUSTOM-OBJC-PROLOGUE // Make sure we can handle two bridging headers. rdar://problem/22702104 // RUN: %check-in-clang -include %t/empty.h -std=c99 -fno-modules -Qunused-arguments %t/empty.h // REQUIRES: objc_interop // CHECK-NOT: @import Swift; // CHECK-LABEL: #if !defined(__has_feature) // CHECK-NEXT: # define __has_feature(x) 0 // CHECK-NEXT: #endif // CHECK-LABEL: #include <Foundation/Foundation.h> // CHECK: #include <stdint.h> // CHECK: #include <stddef.h> // CHECK: #include <stdbool.h> // CHECK: # define SWIFT_METATYPE(X) // CHECK: # define SWIFT_CLASS // CHECK: # define SWIFT_CLASS_NAMED // CHECK: # define SWIFT_PROTOCOL // CHECK: # define SWIFT_PROTOCOL_NAMED // CHECK: # define SWIFT_EXTENSION(M) // CHECK: # define OBJC_DESIGNATED_INITIALIZER // CHECK-LABEL: #if __has_feature(modules) // CHECK-NEXT: #if __has_warning // CHECK-NEXT: #pragma clang diagnostic // CHECK-NEXT: #endif // CHECK-NEXT: #endif // CHECK-NOT: {{[@;{}]}} // CUSTOM-OBJC-PROLOGUE: swift/objc-prologue.h:1:2: error: "Prologue included"
2a0715af82ba80e160126c05a7fa0922
35.391304
122
0.681004
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/WordPressTest/ViewRelated/Post/Controllers/PostListViewControllerTests.swift
gpl-2.0
1
import UIKit import XCTest import Nimble @testable import WordPress class PostListViewControllerTests: XCTestCase { private var context: NSManagedObjectContext! override func setUp() { context = TestContextManager().mainContext super.setUp() } override func tearDown() { context = nil TestContextManager.overrideSharedInstance(nil) super.tearDown() } func testShowsGhostableTableView() { let blog = BlogBuilder(context).build() let postListViewController = PostListViewController.controllerWithBlog(blog) let _ = postListViewController.view postListViewController.startGhost() expect(postListViewController.ghostableTableView.isHidden).to(beFalse()) } func testHidesGhostableTableView() { let blog = BlogBuilder(context).build() let postListViewController = PostListViewController.controllerWithBlog(blog) let _ = postListViewController.view postListViewController.stopGhost() expect(postListViewController.ghostableTableView.isHidden).to(beTrue()) } func testShowTenMockedItemsInGhostableTableView() { let blog = BlogBuilder(context).build() let postListViewController = PostListViewController.controllerWithBlog(blog) let _ = postListViewController.view postListViewController.startGhost() expect(postListViewController.ghostableTableView.numberOfRows(inSection: 0)).to(equal(50)) } func testItCanHandleNewPostUpdatesEvenIfTheGhostViewIsStillVisible() { // This test simulates and proves that the app will no longer crash on these conditions: // // 1. The app is built using Xcode 11 and running on iOS 13.1 // 2. The user has no cached data on the device // 3. The user navigates to the Post List → Drafts // 4. The user taps on the plus (+) button which adds a post in the Drafts list // // Please see https://git.io/JeK3y for more information about this crash. // // This test fails when executed on 00c88b9b // Given let blog = BlogBuilder(context).build() try! context.save() let postListViewController = PostListViewController.controllerWithBlog(blog) let _ = postListViewController.view let draftsIndex = postListViewController.filterTabBar.items.firstIndex(where: { $0.title == i18n("Drafts") }) ?? 1 postListViewController.updateFilter(index: draftsIndex) postListViewController.startGhost() // When: Simulate a post being created // Then: This should not cause a crash expect { _ = PostBuilder(self.context, blog: blog).with(status: .draft).build() try! self.context.save() }.notTo(raiseException()) } }
0a861d4e757f5d41d8c67a06e8be4970
32.916667
122
0.679888
false
true
false
false
blkbrds/intern09_final_project_tung_bien
refs/heads/master
MyApp/Model/API/Core/ApiManager.swift
mit
1
// // ApiManager.swift // MyApp // // Created by DaoNV on 4/10/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // import Foundation import Alamofire typealias JSObject = [String: Any] typealias JSArray = [JSObject] typealias Completion = (Result<Any>) -> Void let api = ApiManager() final class ApiManager { let session = Session() var defaultHTTPHeaders: [String: String] { var headers: [String: String] = [:] headers["Content-Type"] = "application/json" if let token = Session.shared.getToken() { headers["Authorization"] = "Bearer \(token)" } return headers } }
8e155e95becd7404b366f58fdd8df990
20.225806
62
0.629179
false
false
false
false
biohazardlover/NintendoEverything
refs/heads/master
Pods/SwiftSoup/Sources/DocumentType.swift
mit
4
// // DocumentType.swift // SwifSoup // // Created by Nabil Chatbi on 29/09/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation /** * A {@code <!DOCTYPE>} node. */ public class DocumentType: Node { static let PUBLIC_KEY: String = "PUBLIC" static let SYSTEM_KEY: String = "SYSTEM"; private static let NAME: String = "name" private static let PUB_SYS_KEY: String = "pubSysKey"; // PUBLIC or SYSTEM private static let PUBLIC_ID: String = "publicId" private static let SYSTEM_ID: String = "systemId" // todo: quirk mode from publicId and systemId /** * Create a new doctype element. * @param name the doctype's name * @param publicId the doctype's public ID * @param systemId the doctype's system ID * @param baseUri the doctype's base URI */ public init(_ name: String, _ publicId: String, _ systemId: String, _ baseUri: String) { super.init(baseUri) do { try attr(DocumentType.NAME, name); try attr(DocumentType.PUBLIC_ID, publicId); if (has(DocumentType.PUBLIC_ID)) { try attr(DocumentType.PUB_SYS_KEY, DocumentType.PUBLIC_KEY); } try attr(DocumentType.SYSTEM_ID, systemId); } catch {} } /** * Create a new doctype element. * @param name the doctype's name * @param publicId the doctype's public ID * @param systemId the doctype's system ID * @param baseUri the doctype's base URI */ public init(_ name: String, _ pubSysKey: String?, _ publicId: String, _ systemId: String, _ baseUri: String) { super.init(baseUri) do { try attr(DocumentType.NAME, name) if(pubSysKey != nil){ try attr(DocumentType.PUB_SYS_KEY, pubSysKey!) } try attr(DocumentType.PUBLIC_ID, publicId); try attr(DocumentType.SYSTEM_ID, systemId); } catch {} } public override func nodeName() -> String { return "#doctype" } override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) { if (out.syntax() == OutputSettings.Syntax.html && !has(DocumentType.PUBLIC_ID) && !has(DocumentType.SYSTEM_ID)) { // looks like a html5 doctype, go lowercase for aesthetics accum.append("<!doctype") } else { accum.append("<!DOCTYPE") } if (has(DocumentType.NAME)) { do { accum.append(" ").append(try attr(DocumentType.NAME)) } catch {} } if (has(DocumentType.PUB_SYS_KEY)){ do { try accum.append(" ").append(attr(DocumentType.PUB_SYS_KEY)) } catch {} } if (has(DocumentType.PUBLIC_ID)) { do { try accum.append(" \"").append(attr(DocumentType.PUBLIC_ID)).append("\""); } catch {} } if (has(DocumentType.SYSTEM_ID)) { do { accum.append(" \"").append(try attr(DocumentType.SYSTEM_ID)).append("\"") } catch {} } accum.append(">") } override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) { } private func has(_ attribute: String) -> Bool { do { return !StringUtil.isBlank(try attr(attribute)) } catch {return false} } public override func copy(with zone: NSZone? = nil) -> Any { let clone = DocumentType(attributes!.get(key: DocumentType.NAME), attributes!.get(key: DocumentType.PUBLIC_ID), attributes!.get(key: DocumentType.SYSTEM_ID), baseUri!) return copy(clone: clone) } public override func copy(parent: Node?) -> Node { let clone = DocumentType(attributes!.get(key: DocumentType.NAME), attributes!.get(key: DocumentType.PUBLIC_ID), attributes!.get(key: DocumentType.SYSTEM_ID), baseUri!) return copy(clone: clone, parent: parent) } public override func copy(clone: Node, parent: Node?) -> Node { return super.copy(clone: clone, parent: parent) } }
83e5e11e954f94deb55e0af66c809bd3
31.368421
121
0.563995
false
false
false
false
babedev/Food-Swift
refs/heads/master
Food-Swift-iOS/FoodSwift/FoodSwift/PhotoConfirmViewController.swift
unlicense
1
// // PhotoConfirmViewController.swift // FoodSwift // // Created by NiM on 3/4/2560 BE. // Copyright © 2560 tryswift. All rights reserved. // import UIKit import MapKit import SVProgressHUD class PhotoConfirmViewController: UIViewController { var image:UIImage? var userID = ""; var location:CLLocationCoordinate2D? var placeName = ""; @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.imageView.image = self.image; if let place = FoodLocation.defaultManager.currentPlace?.name { self.placeName = place; } self.title = self.placeName; var region = MKCoordinateRegion(); region.center = self.location ?? self.mapView.region.center; var span = MKCoordinateSpan(); span.latitudeDelta = 0.0015; span.longitudeDelta = 0.0015; region.span = span; self.mapView.setRegion(region, animated: true); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func sendPhoto() { if let selectedImage = self.image { print("Start upload"); SVProgressHUD.show(); FoodPhoto.uploadImage(image: selectedImage, completion: { (url, error) in SVProgressHUD.dismiss(); print("Finish upload"); if let photoURL = url { print("Got url \(photoURL)"); FoodPhoto.addNewPost( imageURL: photoURL, location: self.location ?? CLLocationCoordinate2DMake(0.0, 0.0), placeName: self.placeName, userID: self.userID, completion: { Void in self.dismiss(animated: true, completion: nil); } ); } else { print("Finish upload with error - \(error)"); } }) } } /* // 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. } */ }
9d7a6a8e6482e971ed1bc720e66b593c
29.604651
106
0.56269
false
false
false
false
ra1028/OwnKit
refs/heads/master
OwnKit/Util/Transition/PushBackTransitionAnimator.swift
mit
1
// // PushBackTransitionAnimator.swift // OwnKit // // Created by Ryo Aoyama on 1/13/16. // Copyright © 2016 Ryo Aoyama. All rights reserved. // import UIKit public final class PushBackTransitionAnimator: TransitionAnimator { public var pushBackScale = 0.95.f private let backgroundView: UIView = { let v = UIView() v.backgroundColor = UIColor.blackColor().alphaColor(0.7) return v }() public init(pushBackScale: CGFloat = 0.95) { super.init() duration = 0.6 self.pushBackScale = pushBackScale } public override func animatePresentingTransition(transitionContext: UIViewControllerContextTransitioning, from: UIViewController?, to: UIViewController?) { super.animatePresentingTransition(transitionContext, from: from, to: to) guard let fromView = from?.view, toView = to?.view, containerView = transitionContext.containerView() else { return } backgroundView.frame = containerView.bounds containerView.addSubview(backgroundView) containerView.addSubview(toView) toView.layer.transform = .translation(x: toView.width) UIView.animate( duration, springDamping: 1, initialVelocity: 0, animations: { self.backgroundView.alpha = 0 self.backgroundView.alpha = 1 fromView.layer.transform = .scale(x: self.pushBackScale, y: self.pushBackScale) toView.layer.transform = .identity }, completion: { _ in transitionContext.completeTransition(true) } ) } public override func animateDismissingTransition(transitionContext: UIViewControllerContextTransitioning, from: UIViewController?, to: UIViewController?) { super.animateDismissingTransition(transitionContext, from: from, to: to) guard let fromView = from?.view, toView = to?.view, containerView = transitionContext.containerView()else { return } containerView.insertSubview(toView, atIndex: 0) UIView.animate( duration, springDamping: 1, initialVelocity: 0, animations: { self.backgroundView.alpha = 1 self.backgroundView.alpha = 0 fromView.layer.transform = .translation(x: fromView.width) toView.layer.transform = .identity }, completion: { _ in fromView.removeFromSuperview() transitionContext.completeTransition(true) } ) } }
a13d7822131f9f1c63ea82cd0274e556
33
159
0.597167
false
false
false
false
mownier/Umalahokan
refs/heads/master
Umalahokan/Source/Transition/MessageWriterTransitioning.swift
mit
1
// // MessageWriterTransitioning.swift // Umalahokan // // Created by Mounir Ybanez on 15/02/2017. // Copyright © 2017 Ner. All rights reserved. // import UIKit class MessageWriterTransitioning: NSObject, UIViewControllerTransitioningDelegate { var composerButtonFrame: CGRect = .zero func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { let transition = MessageWriterTransition(style: .presentation) transition.composerButtonFrame = composerButtonFrame return transition } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { let transition = AlphaTransition(style: .dismissal) return transition } } class MessageWriterTransition: NSObject, UIViewControllerAnimatedTransitioning { enum Style { case presentation, dismissal } private(set) var style: Style = .presentation var duration: TimeInterval = 5.5 var composerButtonFrame: CGRect = .zero init(style: Style) { super.init() self.style = style } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using context: UIViewControllerContextTransitioning) { // Setting up context let presentedKey: UITransitionContextViewKey = style == .presentation ? .to : .from let presented = context.view(forKey: presentedKey) as! MessageWriterView let container = context.containerView let whiteColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) switch style { case .presentation: presented.header.closeButton.alpha = 0 presented.header.titleLabel.alpha = 0 presented.header.inputBackground.alpha = 0 presented.header.inputLabel.alpha = 0 presented.header.inputTextField.alpha = 0 presented.sendView.alpha = 0 presented.backgroundColor = whiteColor.withAlphaComponent(0) presented.tableView.backgroundColor = UIColor.clear presented.header.backgroundColor = UIColor.clear presented.header.backgroundView.frame = composerButtonFrame presented.header.backgroundView.layer.cornerRadius = composerButtonFrame.width / 2 presented.header.backgroundView.layer.masksToBounds = true container.addSubview(presented) presentationAnimation(presented, context: context) case .dismissal: break } } func presentationAnimation(_ presented: MessageWriterView, context: UIViewControllerContextTransitioning) { let whiteColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) let color = whiteColor.withAlphaComponent(1) let duration: TimeInterval = 1.25 UIView.animateKeyframes(withDuration: duration, delay: 0, options: .calculationModeLinear, animations: { var keyframeDuration: TimeInterval = 0.25 var delay: TimeInterval = 0 var relativeStartTime: TimeInterval = 0 + (delay / duration) var relativeDuration: TimeInterval = keyframeDuration / duration var totalKeyframeDuration = keyframeDuration + delay UIView.addKeyframe(withRelativeStartTime: relativeStartTime, relativeDuration: relativeDuration, animations: { presented.backgroundColor = color presented.header.backgroundView.frame.origin.y = 0 presented.header.backgroundView.frame.origin.x = (presented.header.frame.width - presented.header.backgroundView.frame.width) / 2 }) keyframeDuration = 0.25 delay = 0 relativeStartTime = relativeDuration + (delay / duration) relativeDuration += (keyframeDuration / duration) totalKeyframeDuration += (keyframeDuration + delay) UIView.addKeyframe(withRelativeStartTime: relativeStartTime, relativeDuration: relativeDuration, animations: { presented.header.backgroundView.transform = CGAffineTransform(scaleX: 10, y: 10) }) keyframeDuration = 0.25 delay = 0 relativeStartTime = relativeDuration + (delay / duration) relativeDuration += (keyframeDuration / duration) totalKeyframeDuration += (keyframeDuration + delay) UIView.addKeyframe(withRelativeStartTime: relativeStartTime, relativeDuration: relativeDuration, animations: { presented.header.closeButton.alpha = 1 presented.header.titleLabel.alpha = 1 }) keyframeDuration = 0.25 delay = 0.25 relativeStartTime = relativeDuration + (delay / duration) relativeDuration += (keyframeDuration / duration) totalKeyframeDuration += (keyframeDuration + delay) UIView.addKeyframe(withRelativeStartTime: relativeStartTime, relativeDuration: relativeDuration, animations: { presented.header.inputBackground.alpha = 1 presented.header.inputLabel.alpha = 1 presented.header.inputTextField.alpha = 1 presented.sendView.alpha = 1 }) assert(totalKeyframeDuration == duration, "Total keyframe duration is not in sync.") }) { _ in context.completeTransition(!context.transitionWasCancelled) } perform(#selector(self.reloadTableView(_:)), with: presented, afterDelay: 0.50) perform(#selector(self.clipToBounds(_:)), with: presented, afterDelay: 0.49) } @objc func reloadTableView(_ presented: MessageWriterView) { presented.isValidToReload = true presented.tableView.reloadData() presented.header.inputTextField.becomeFirstResponder() } @objc func clipToBounds(_ presented: MessageWriterView) { presented.header.clipsToBounds = true } }
04e78851ec90f38fe91258e0e37c83fa
40.603896
170
0.644607
false
false
false
false
tardieu/swift
refs/heads/master
test/Parse/matching_patterns.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-source-import import imported_enums // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int,Int,Int), y: (Int,Int,Int)) -> Bool { return true } var x:Int func square(_ x: Int) -> Int { return x*x } struct A<B> { struct C<D> { } } switch x { // Expressions as patterns. case 0: () case 1 + 2: () case square(9): () // 'var' and 'let' patterns. case var a: a = 1 case let a: a = 1 // expected-error {{cannot assign}} case var var a: // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}} a += 1 case var let a: // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}} print(a, terminator: "") case var (var b): // expected-error {{'var' cannot appear nested inside another 'var'}} b += 1 // 'Any' pattern. case _: () // patterns are resolved in expression-only positions are errors. case 1 + (_): // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} () } switch (x,x) { case (var a, var a): // expected-error {{definition conflicts with previous value}} expected-note {{previous definition of 'a' is here}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} fallthrough case _: () } var e : Any = 0 switch e { // 'is' pattern. case is Int, is A<Int>, is A<Int>.C<Int>, is (Int, Int), is (a: Int, b: Int): () } // Enum patterns. enum Foo { case A, B, C } func == <T>(_: Voluntary<T>, _: Voluntary<T>) -> Bool { return true } enum Voluntary<T> : Equatable { case Naught case Mere(T) case Twain(T, T) func enumMethod(_ other: Voluntary<T>, foo: Foo) { switch self { case other: () case .Naught, .Naught(), .Naught(_, _): // expected-error{{tuple pattern has the wrong length for tuple type '()'}} () case .Mere, .Mere(), // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}} .Mere(_), .Mere(_, _): // expected-error{{tuple pattern cannot match values of the non-tuple type 'T'}} () case .Twain(), // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}} .Twain(_), .Twain(_, _), .Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(T, T)'}} () } switch foo { case .Naught: // expected-error{{enum case 'Naught' not found in type 'Foo'}} () case .A, .B, .C: () } } } var n : Voluntary<Int> = .Naught switch n { case Foo.A: // expected-error{{enum case 'A' is not a member of type 'Voluntary<Int>'}} () case Voluntary<Int>.Naught, Voluntary<Int>.Naught(), Voluntary<Int>.Naught(_, _), // expected-error{{tuple pattern has the wrong length for tuple type '()'}} Voluntary.Naught, .Naught: () case Voluntary<Int>.Mere, Voluntary<Int>.Mere(_), Voluntary<Int>.Mere(_, _), // expected-error{{tuple pattern cannot match values of the non-tuple type 'Int'}} Voluntary.Mere, Voluntary.Mere(_), .Mere, .Mere(_): () case .Twain, .Twain(_), .Twain(_, _), .Twain(_, _, _): // expected-error{{tuple pattern has the wrong length for tuple type '(Int, Int)'}} () } var notAnEnum = 0 switch notAnEnum { case .Foo: // expected-error{{enum case 'Foo' not found in type 'Int'}} () } struct ContainsEnum { enum Possible<T> { case Naught case Mere(T) case Twain(T, T) } func member(_ n: Possible<Int>) { switch n { case ContainsEnum.Possible<Int>.Naught, ContainsEnum.Possible.Naught, Possible<Int>.Naught, Possible.Naught, .Naught: () } } } func nonmemberAccessesMemberType(_ n: ContainsEnum.Possible<Int>) { switch n { case ContainsEnum.Possible<Int>.Naught, .Naught: () } } var m : ImportedEnum = .Simple switch m { case imported_enums.ImportedEnum.Simple, ImportedEnum.Simple, .Simple: () case imported_enums.ImportedEnum.Compound, imported_enums.ImportedEnum.Compound(_), ImportedEnum.Compound, ImportedEnum.Compound(_), .Compound, .Compound(_): () } // Check that single-element tuple payloads work sensibly in patterns. enum LabeledScalarPayload { case Payload(name: Int) } var lsp: LabeledScalarPayload = .Payload(name: 0) func acceptInt(_: Int) {} func acceptString(_: String) {} switch lsp { case .Payload(0): () case .Payload(name: 0): () case let .Payload(x): acceptInt(x) acceptString("\(x)") case let .Payload(name: x): acceptInt(x) acceptString("\(x)") case let .Payload((name: x)): acceptInt(x) acceptString("\(x)") case .Payload(let (name: x)): acceptInt(x) acceptString("\(x)") case .Payload(let (name: x)): acceptInt(x) acceptString("\(x)") case .Payload(let x): acceptInt(x) acceptString("\(x)") case .Payload((let x)): acceptInt(x) acceptString("\(x)") } // Property patterns. struct S { static var stat: Int = 0 var x, y : Int var comp : Int { return x + y } func nonProperty() {} } // Tuple patterns. var t = (1, 2, 3) prefix operator +++ infix operator +++ prefix func +++(x: (Int,Int,Int)) -> (Int,Int,Int) { return x } func +++(x: (Int,Int,Int), y: (Int,Int,Int)) -> (Int,Int,Int) { return (x.0+y.0, x.1+y.1, x.2+y.2) } switch t { case (_, var a, 3): a += 1 case var (_, b, 3): b += 1 case var (_, var c, 3): // expected-error{{'var' cannot appear nested inside another 'var'}} c += 1 case (1, 2, 3): () // patterns in expression-only positions are errors. case +++(_, var d, 3): // expected-error@-1{{'+++' is not a prefix unary operator}} () case (_, var e, 3) +++ (1, 2, 3): // expected-error@-1{{binary operator '+++' cannot be applied to operands of type '(_, <<error type>>, Int)' and '(Int, Int, Int)'}} // expected-note@-2{{expected an argument list of type '((Int, Int, Int), (Int, Int, Int))'}} // expected-error@-3{{'var' binding pattern cannot appear in an expression}} // expected-error@-4{{'var' binding pattern cannot appear in an expression}} () } // FIXME: We don't currently allow subpatterns for "isa" patterns that // require interesting conditional downcasts. class Base { } class Derived : Base { } switch [Derived(), Derived(), Base()] { case let ds as [Derived]: // expected-error{{downcast pattern value of type '[Derived]' cannot be used}} () default: () } // Optional patterns. let op1 : Int? let op2 : Int?? switch op1 { case nil: break case 1?: break case _?: break } switch op2 { case nil: break case _?: break case (1?)?: break case (_?)?: break } // <rdar://problem/20365753> Bogus diagnostic "refutable pattern match can fail" let (responseObject: Int?) = op1 // expected-error @-1 {{expected ',' separator}} {{25-25=,}} // expected-error @-2 {{expected pattern}}
5aed9a2fc5a0fdcbe1abb6f9acfe91a2
21.587859
322
0.610467
false
false
false
false
teambition/CardStyleTableView
refs/heads/master
CardStyleTableView/Constants.swift
mit
1
// // Constants.swift // CardStyleTableView // // Created by Xin Hong on 16/1/28. // Copyright © 2016年 Teambition. All rights reserved. // import UIKit internal struct AssociatedKeys { static var cardStyleTableViewStyleSource = "CardStyleTableViewStyleSource" static var cardStyleTableViewCellTableView = "CardStyleTableViewCellTableView" } internal struct TableViewSelectors { static let layoutSubviews = #selector(UITableView.layoutSubviews) static let swizzledLayoutSubviews = #selector(UITableView.cardStyle_tableViewSwizzledLayoutSubviews) } internal struct TableViewCellSelectors { static let layoutSubviews = #selector(UITableViewCell.layoutSubviews) static let didMoveToSuperview = #selector(UITableViewCell.didMoveToSuperview) static let swizzledLayoutSubviews = #selector(UITableViewCell.cardStyle_tableViewCellSwizzledLayoutSubviews) static let swizzledDidMoveToSuperview = #selector(UITableViewCell.cardStyle_tableViewCellSwizzledDidMoveToSuperview) }
7aac3fdfcea7b6cd94821f0ac250f990
37.615385
120
0.815737
false
false
false
false
larryhou/swift
refs/heads/master
AVProgramming/AVProgramming/PhotoAlbumViewController.swift
mit
1
// // ViewController.swift // AVProgramming // // Created by larryhou on 4/3/15. // Copyright (c) 2015 larryhou. All rights reserved. // import UIKit import AssetsLibrary import CoreGraphics let SEPARATOR_COLOR_WHITE: CGFloat = 0.9 class PhotoAlbumCell: UITableViewCell { @IBOutlet weak var posterImage: UIImageView! @IBOutlet weak var albumName: UILabel! @IBOutlet weak var albumAssetsCount: UILabel! @IBOutlet weak var albumID: UILabel! } class NavigationViewController: UINavigationController { override func shouldAutorotate() -> Bool { return topViewController.shouldAutorotate() } override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation { return topViewController.preferredInterfaceOrientationForPresentation() } } class PhotoAlubmViewController: UITableViewController, UITableViewDataSource { private var _groups: [NSURL]! private var _library: ALAssetsLibrary! override func viewDidLoad() { super.viewDidLoad() tableView.separatorColor = UIColor(white: SEPARATOR_COLOR_WHITE, alpha: 1.0) _groups = [] _library = ALAssetsLibrary() _library.enumerateGroupsWithTypes(ALAssetsGroupAlbum | ALAssetsGroupSavedPhotos, usingBlock: { (group:ALAssetsGroup!, _:UnsafeMutablePointer<ObjCBool>) in if group != nil { self._groups.append(group.valueForProperty(ALAssetsGroupPropertyURL) as! NSURL) dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } }, failureBlock: { (error: NSError!) in println(error) }) } // MARK: table view override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 90 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _groups.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let url = _groups[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("PhotoAlbumCell") as! PhotoAlbumCell _library.groupForURL(url, resultBlock: { (group:ALAssetsGroup!) in cell.albumName.text = (group.valueForProperty(ALAssetsGroupPropertyName) as! String) cell.albumID.text = (group.valueForProperty(ALAssetsGroupPropertyPersistentID) as! String) cell.albumAssetsCount.text = "\(group.numberOfAssets())" cell.posterImage.image = UIImage(CGImage: group.posterImage().takeUnretainedValue(), scale: UIScreen.mainScreen().scale, orientation: UIImageOrientation.Up) }, failureBlock: { (error: NSError!) in println((error, url.absoluteString)) }) return cell } // MARK: segue override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showAlbumPhotos" { let indexPath = tableView.indexPathForSelectedRow()! var dst = segue.destinationViewController as! PhotoViewController dst.url = _groups[indexPath.row] tableView.deselectRowAtIndexPath(indexPath, animated: false) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
d754a8912b8e8d8c6b741f04b11e5214
29.524272
159
0.75986
false
false
false
false
eraydiler/password-locker
refs/heads/master
PasswordLockerSwift/Supporting Files/AppDelegate.swift
mit
1
// // AppDelegate.swift // PasswordLockerSwift // // Created by Eray on 19/01/15. // Copyright (c) 2015 Eray. All rights reserved. // import UIKit import CoreData import MagicalRecord let kPasswordLockerUserDefaultsHasInitialized = "kPasswordLockerUserDefaultsHasInitialized" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { MagicalRecord.setupCoreDataStack() let managedObjectContext = NSManagedObjectContext.mr_default() let isAppInitializedWithData = UserDefaults.standard.bool(forKey: kPasswordLockerUserDefaultsHasInitialized) if (isAppInitializedWithData == false) { DataFactory.deleteAllObjects(managedObjectContext, entityDescription: "Category") DataFactory.deleteAllObjects(managedObjectContext, entityDescription: "Type") DataFactory.deleteAllObjects(managedObjectContext, entityDescription: "Row") DataFactory.setupInitialData(managedObjectContext) UserDefaults.standard.set(true, forKey: kPasswordLockerUserDefaultsHasInitialized) print("Initial Data inserted") } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { guard let splashController = self.window?.rootViewController else { return } guard let aController = splashController.presentedViewController else { return } guard let tabBarController = aController.presentedViewController else { return } tabBarController.dismiss(animated: false) } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. MagicalRecord.cleanUp() } }
7c60c37081827cf0dd154c6e02057784
39.473684
285
0.726268
false
false
false
false
KieranHarper/KJHUIKit
refs/heads/master
Sources/CrossfadingLabel.swift
mit
1
// // CrossfadingLabel.swift // KJHUIKit // // Created by Kieran Harper on 1/7/17. // Copyright © 2017 Kieran Harper. All rights reserved. // import UIKit /// Simple crossfading UILabel subclass. @objc open class CrossfadingLabel: UILabel { /// The duration to perform the crossfade over. @objc open var crossfadeDuration: TimeInterval = 0.25 /// Master switch to disable crossfade, which is useful in situations where the code setting the text isn't aware of some other condition, or when you'd like to temporarily make it instant but can't store the current duration and apply it later. @objc open var disableCrossfade = false /// Set the text, with or without crossfading. @objc open func setText(_ text: String?, crossfading: Bool, completion: ((Bool) -> Void)? = nil) { if crossfading, !disableCrossfade, crossfadeDuration > 0.0 { UIView.transition(with: self, duration: crossfadeDuration, options: .transitionCrossDissolve, animations: { super.text = text }, completion: completion) } else { super.text = text } } /// Set the attributed text, with or without crossfading. @objc open func setAttributedText(_ attributedText: NSAttributedString?, crossfading: Bool, completion: ((Bool) -> Void)? = nil) { if crossfading, !disableCrossfade, crossfadeDuration > 0.0 { UIView.transition(with: self, duration: crossfadeDuration, options: .transitionCrossDissolve, animations: { super.attributedText = attributedText }, completion: completion) } else { super.attributedText = attributedText } } }
9b60dccea1a2e4833d63f884ffd2dd9b
40.804878
249
0.663361
false
false
false
false
toohotz/IQKeyboardManager
refs/heads/master
Demo/Swift_Demo/ViewController/ScrollViewController.swift
mit
1
// // ScrollViewController.swift // IQKeyboard // // Created by Iftekhar on 23/09/14. // Copyright (c) 2014 Iftekhar. All rights reserved. // import Foundation import UIKit class ScrollViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UITextViewDelegate, UIPopoverPresentationControllerDelegate { @IBOutlet private var scrollViewDemo : UIScrollView! @IBOutlet private var simpleTableView : UITableView! @IBOutlet private var scrollViewOfTableViews : UIScrollView! @IBOutlet private var tableViewInsideScrollView : UITableView! @IBOutlet private var scrollViewInsideScrollView : UIScrollView! @IBOutlet private var topTextField : UITextField! @IBOutlet private var bottomTextField : UITextField! @IBOutlet private var topTextView : UITextView! @IBOutlet private var bottomTextView : UITextView! override func viewDidLoad() { super.viewDidLoad() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "\(indexPath.section) \(indexPath.row)" var cell = tableView.dequeueReusableCellWithIdentifier(identifier) if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier) cell?.selectionStyle = UITableViewCellSelectionStyle.None cell?.backgroundColor = UIColor.clearColor() let textField = UITextField(frame: CGRectInset(cell!.contentView.bounds, 5, 5)) textField.autoresizingMask = [UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleWidth] textField.placeholder = identifier textField.borderStyle = UITextBorderStyle.RoundedRect cell?.contentView.addSubview(textField) } return cell! } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { if identifier == "SettingsNavigationController" { let controller = segue.destinationViewController controller.modalPresentationStyle = .Popover controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem let heightWidth = max(CGRectGetWidth(UIScreen.mainScreen().bounds), CGRectGetHeight(UIScreen.mainScreen().bounds)); controller.preferredContentSize = CGSizeMake(heightWidth, heightWidth) controller.popoverPresentationController?.delegate = self } } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } func prepareForPopoverPresentation(popoverPresentationController: UIPopoverPresentationController) { self.view.endEditing(true) } override func shouldAutorotate() -> Bool { return true } }
dcbb41e4fc0369c524b30b58f97a2daa
37.360465
172
0.685965
false
false
false
false
Ivacker/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01217-swift-typechecker-resolveidentifiertype.swift
apache-2.0
13
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing private class B<C> { let enum S<T> : P { func f<T>() -> T -> T { return { x in x 1 { b[c][c] = 1 } } class A { class func a() -> String { let d: String = { return self.a() }() } struct d<f : e, g: e where g.h == f.h> { } } class C<D> { init <A: A where A.B == D>(e: A.B) { } } } struct D : C { func g<T where T.E == F>(f: B<T>) { } protocol A { } struct B<T : A> {
93d74804770b00ad0b58e3a98b7f4bdc
16.117647
87
0.582474
false
true
false
false
fnky/drawling-components
refs/heads/master
DrawlingComponents/Components/RBScrollView.swift
gpl-2.0
1
// // RBScrollView.swift // DrawlingComponents // // Created by Christian Petersen // Copyright (c) 2015 Reversebox. All rights reserved. // import Foundation import UIKit class RBScrollView : UIScrollView { // All subviews should conform to this ScrollView's height // with a aspect ratio. //let gradient: CAGradientLayer? = nil /*private func calculateContentSize(views: [AnyObject]) -> CGSize { var size: CGSize = CGSizeMake(0, 0) var counter: Int = 0 for view in views { let x: CGFloat = view.bounds.origin.x let y: CGFloat = view.bounds.origin.y let w: CGFloat = view.bounds.size.width let h: CGFloat = view.bounds.size.height size.width += w counter++ } println("view) \(size)") return CGSizeMake(size.width, self.frame.size.height) }*/ private func calculateContentSize(views: [AnyObject]) -> CGSize { let lo = views.last as UIView let oy = lo.frame.origin.x let ht = lo.frame.size.width var s = CGSizeMake(oy + ht, self.frame.size.height) println(s) return s } override func layoutIfNeeded() { } override func layoutSubviews() { } override func addSubview(view: UIView) { // when adding subview, the given view's size // set itselfs contentSize accordingly super.addSubview(view) self.contentSize = calculateContentSize(self.subviews) } override func layoutSublayersOfLayer(layer: CALayer!) { let gradient: CAGradientLayer = CAGradientLayer(layer: layer) gradient.frame = self.bounds gradient.colors = [UIColor(white: 1, alpha: 1).CGColor, UIColor(white: 1, alpha: 0).CGColor] gradient.locations = [0.8, 1.0] gradient.startPoint = CGPointMake(0, 0.5) gradient.endPoint = CGPointMake(1, 0.5) layer.mask = gradient } override func drawRect(rect: CGRect) { } }
0b0dfe0ec7e107abbcfc84c08dd837fa
23.525641
96
0.650628
false
false
false
false
trd-jameshwart/FamilySNIOS
refs/heads/master
FamilySns/ViewController.swift
mit
1
// // ViewController.swift // FamilySns // // Created by Jameshwart Lopez on 12/8/15. // Copyright © 2015 Minato. All rights reserved. // import UIKit class ViewController: UIViewController,UIPopoverPresentationControllerDelegate{ @IBOutlet weak var tableView: UITableView! @IBOutlet weak var usernameLabel: UILabel! @IBAction func showAlertWasTapped(sender: AnyObject) { let alertController = UIAlertController(title: "Appcoda", message: "Message in alert dialog", preferredStyle: UIAlertControllerStyle.ActionSheet) let deleteAction = UIAlertAction(title: "Delete", style: UIAlertActionStyle.Destructive, handler: {(alert :UIAlertAction!) in print("Delete button tapped") }) alertController.addAction(deleteAction) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {(alert :UIAlertAction!) in print("OK button tapped") }) alertController.addAction(okAction) alertController.popoverPresentationController?.sourceView = view alertController.popoverPresentationController?.sourceRect = sender.frame presentViewController(alertController, animated: true, completion: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "popoverSegue"{ // dispatch_async(dispatch_get_main_queue(), { // let popoverViewController = segue.destinationViewController // popoverViewController.modalPresentationStyle = UIModalPresentationStyle.Popover // popoverViewController.popoverPresentationController!.delegate = self // }) let vc = PostModal() vc.modalPresentationStyle = .Popover presentViewController(vc, animated: true, completion: nil) vc.popoverPresentationController?.sourceView = view; // vc.popoverPresentationController?.sourceRect = } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return UIModalPresentationStyle.None } override func viewWillAppear(animated: Bool) { } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //[self setModalPresentationStyle:UIModalPresentationCurrentContext]; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { //self.performSegueWithIdentifier("goto_login", sender: self) } @IBAction func profileTapped(sender: AnyObject) { self.performSegueWithIdentifier("goto_profile", sender: nil) } @IBAction func logoutTapped(sender: UIButton) { self.performSegueWithIdentifier("goto_login", sender: self) } // // func tableView(tableview: UITableView, numberOfRowsInSection section:Int)-> Int{ // // } // // func tableview(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell{ // // } // // func tableView(tableView: UITableView, didSelectRowAtIndexPaht indexPath:NSIndexPath){ // // } }
bbe7a72c032e8b21acef0f1ec83e4dcd
31.718447
153
0.691691
false
false
false
false
AlexanderNey/Futuristics
refs/heads/alpha
Tests/FunctionCompositionTests.swift
mit
1
// // FunctionCompositionTests.swift // Futuristics // // Created by Alexander Ney on 05/08/2015. // Copyright © 2015 Alexander Ney. All rights reserved. // import Foundation import XCTest import Futuristics class FunctionCopositionTests : XCTestCase { enum ConvertError: Error { case failedToConvertStringToNumber(String) } func stringToNumber(_ str: String) throws -> Int { if let number = Int(str) { return number } else { throw ConvertError.failedToConvertStringToNumber(str) } } func doubleNumber(_ number: Int) throws -> Int { return number * 2 } func testBasicFunctionComposition() { let composition = stringToNumber >>> doubleNumber do { let result = try composition("100") XCTAssertEqual(result, 200) } catch { XCTFail("function call not expected to throw") } } func testBasicFunctionCompositionThrowing() { let composition = stringToNumber >>> doubleNumber let throwExpectation = expectation(description: "throw expectation") do { _ = try composition("abc") XCTFail("function call expected to throw") } catch ConvertError.failedToConvertStringToNumber(let str) { if str == "abc" { throwExpectation.fulfill() } } catch { XCTFail("generic error not expected") } waitForExpectationsWithDefaultTimeout() } func testBasicFunctionCompositionInvocation() { do { let result = try "100" |> stringToNumber |> doubleNumber XCTAssertEqual(result, 200) } catch { XCTFail("function call not expected to throw") } } func testBasicFunctionCompositionInvocationThrowing() { let throwExpectation = expectation(description: "throw expectation") do { _ = try ( "abc" |> stringToNumber |> doubleNumber ) XCTFail("function call expected to throw") } catch ConvertError.failedToConvertStringToNumber(let str) { if str == "abc" { throwExpectation.fulfill() } } catch { XCTFail("generic error not expected") } waitForExpectationsWithDefaultTimeout() } }
dfdfabb2c24fbaf0597b1b31fd182440
26.561798
76
0.575214
false
true
false
false
CKalnasy/SwiftSerialize
refs/heads/master
SwiftSerialize/Serializer.swift
mit
1
import Foundation let kClassKey = "@type" public struct Serializer { public static func serialize(a: Any) -> NSData? { if let obj = serializeObject(a) { do { return try NSJSONSerialization.dataWithJSONObject(obj, options: NSJSONWritingOptions(rawValue: 0)) } catch { return nil } } return nil } private static func serializeObject(a: Any) -> AnyObject? { if isBaseType(a) { // floats need to have a decimal for some languages to recognize it as a float rather than an int if isFloatingPoint(a) { return Float(String(a)) // This adds a decimal and a zero } return (a as! AnyObject) } if isList(a) { if let array = a as? [Any] { return serializeArray(array) } else if let array = a as? NSArray { return serializeArray(array) } else if let map = a as? [String: Any] { return serializeMap(map) } else if let map = a as? [String: AnyObject] { // for some reason, this doesn't always match above return serializeMap(map) } else if let map = a as? NSDictionary { // ditto (seriously wtf apple, Swift is not production ready) return serializeMap(map) } else if let set = a as? NSSet { return serializeArray(set) } } let mirror = Mirror(reflecting: a) if mirror.children.count > 0 { var obj = [String: AnyObject](); for case let (label?, value) in mirror.children { obj[label] = serializeObject(value) } obj[kClassKey] = String(mirror.subjectType) return obj } return a as? AnyObject } private static func isFloatingPoint(a: Any) -> Bool { return a.dynamicType == Float.self || a.dynamicType == Double.self } public static func deserialize(jsonData: NSData) throws -> Any? { do { if let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) as? NSDictionary { return deserialize(json) } } catch { return nil } return nil } public static func deserialize(a: AnyObject) -> Any? { if isBaseType(a) { return a } if isClass(a) { if let a = a as? [String: AnyObject] { if a[kClassKey] as? String != nil { do { return try Initializer.initClass(a) } catch { return nil } } } } if isList(a) { if let array = a as? NSArray { var ret: [Any] = [] for element in array { if let element = deserialize(element) { ret.append(element) } } return ret } else if let map = a as? [String: AnyObject] { var ret: [String: Any] = [:] for (key, value) in map { if let value = deserialize(value) { ret[key] = value } } return ret } else if let set = a as? NSSet { var ret: [Any] = [] for s in set { if let s = deserialize(s) { ret.append(s) } } return ret } } return nil } } // MARK: private functions extension Serializer { private static func serializeArray(array: [Any]) -> [AnyObject] { var ret:[AnyObject] = [] for element in array { if let obj = serializeObject(element) { ret.append(obj) } } return ret } private static func serializeArray(array: NSArray) -> [AnyObject] { var ret:[AnyObject] = [] for element in array { if let obj = serializeObject(element) { ret.append(obj) } } return ret } private static func serializeArray(array: NSSet) -> [AnyObject] { var ret:[AnyObject] = [] for element in array { if let obj = serializeObject(element) { ret.append(obj) } } return ret } private static func serializeMap(map: [String: Any]) -> [String: AnyObject] { var ret: [String: AnyObject] = [:] for (key, value) in map { if let value = serializeObject(value) { ret[key] = value } } return ret } private static func serializeMap(map: [String: AnyObject]) -> [String: AnyObject] { var ret: [String: AnyObject] = [:] for (key, value) in map { if let value = serializeObject(value) { ret[key] = value } } return ret } private static func serializeMap(map: NSDictionary) -> [String: AnyObject] { var ret: [String: AnyObject] = [:] for (key, value) in map { if let key = key as? String { if let value = serializeObject(value) { ret[key] = value } } } return ret } private static func isList(a: Any) -> Bool { if let _ = a as? [Any] { return true } if let _ = a as? NSArray { return true } if let _ = a as? NSDictionary { return true } if let _ = a as? [String: Any] { return true } if let _ = a as? NSSet { return true } return false } private static func isClass(a: Any) -> Bool { if let map = a as? [String: AnyObject] { return map[kClassKey] != nil } return false } private static func isBaseType(a: Any) -> Bool { if let _ = a as? Int { return true } if let _ = a as? Float { return true } if let _ = a as? Double { return true } if let _ = a as? String { return true } if let _ = a as? Bool { return true } if let _ = a as? Int8 { return true } if let _ = a as? Int16 { return true } if let _ = a as? Int32 { return true } if let _ = a as? Int64 { return true } if let _ = a as? UInt { return true } if let _ = a as? UInt8 { return true } if let _ = a as? UInt16 { return true } if let _ = a as? UInt32 { return true } if let _ = a as? UInt64 { return true } if let _ = a as? Character { return true } return false } private static func isSerializeableType(a: Any) -> Bool { if let _ = a as? Int { return true } if let _ = a as? Float { return true } if let _ = a as? Double { return true } if let _ = a as? String { return true } if let _ = a as? Bool { return true } if let _ = a as? Int8 { return true } if let _ = a as? Int16 { return true } if let _ = a as? Int32 { return true } if let _ = a as? Int64 { return true } if let _ = a as? UInt { return true } if let _ = a as? UInt8 { return true } if let _ = a as? UInt16 { return true } if let _ = a as? UInt32 { return true } if let _ = a as? UInt64 { return true } if let _ = a as? Character { return true } if let _ = a as? NSObject { return true } if let _ = a as? NSNull { return true } if let _ = a as? NSNumber { return true } if let _ = a as? NSString { return true } if let _ = a as? NSURL { return true } if let _ = a as? NSDate { return true } if let _ = a as? NSData { return true } if let _ = a as? CGFloat { return true } if let _ = a as? UIImage { return true } return false } }
75659f9927d3c605529a2ef349785b90
28.116667
120
0.561105
false
false
false
false
Mai-Tai-D/maitaid001
refs/heads/master
Pods/SwiftCharts/SwiftCharts/Layers/ChartPointsLineLayer.swift
mit
2
// // ChartPointsLineLayer.swift // SwiftCharts // // Created by ischuetz on 25/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public enum LineJoin { case miter case round case bevel public var CALayerString: String { switch self { case .miter: return kCALineJoinMiter case .round: return kCALineCapRound case .bevel: return kCALineJoinBevel } } public var CGValue: CGLineJoin { switch self { case .miter: return .miter case .round: return .round case .bevel: return .bevel } } } public enum LineCap { case butt case round case square public var CALayerString: String { switch self { case .butt: return kCALineCapButt case .round: return kCALineCapRound case .square: return kCALineCapSquare } } public var CGValue: CGLineCap { switch self { case .butt: return .butt case .round: return .round case .square: return .square } } } public struct ScreenLine<T: ChartPoint> { public internal(set) var points: [CGPoint] public let color: UIColor public let lineWidth: CGFloat public let lineJoin: LineJoin public let lineCap: LineCap public let animDuration: Float public let animDelay: Float public let lineModel: ChartLineModel<T> public let dashPattern: [Double]? init(points: [CGPoint], color: UIColor, lineWidth: CGFloat, lineJoin: LineJoin, lineCap: LineCap, animDuration: Float, animDelay: Float, lineModel: ChartLineModel<T>, dashPattern: [Double]?) { self.points = points self.color = color self.lineWidth = lineWidth self.lineJoin = lineJoin self.lineCap = lineCap self.animDuration = animDuration self.animDelay = animDelay self.lineModel = lineModel self.dashPattern = dashPattern } } open class ChartPointsLineLayer<T: ChartPoint>: ChartPointsLayer<T> { open fileprivate(set) var lineModels: [ChartLineModel<T>] open fileprivate(set) var lineViews: [ChartLinesView] = [] open let pathGenerator: ChartLinesViewPathGenerator open fileprivate(set) var screenLines: [(screenLine: ScreenLine<T>, view: ChartLinesView)] = [] public let useView: Bool public let delayInit: Bool fileprivate var isInTransform = false public init(xAxis: ChartAxis, yAxis: ChartAxis, lineModels: [ChartLineModel<T>], pathGenerator: ChartLinesViewPathGenerator = StraightLinePathGenerator(), displayDelay: Float = 0, useView: Bool = true, delayInit: Bool = false) { self.lineModels = lineModels self.pathGenerator = pathGenerator self.useView = useView self.delayInit = delayInit let chartPoints: [T] = lineModels.flatMap{$0.chartPoints} super.init(xAxis: xAxis, yAxis: yAxis, chartPoints: chartPoints, displayDelay: displayDelay) } fileprivate func toScreenLine(lineModel: ChartLineModel<T>, chart: Chart) -> ScreenLine<T> { return ScreenLine( points: lineModel.chartPoints.map{chartPointScreenLoc($0)}, color: lineModel.lineColor, lineWidth: lineModel.lineWidth, lineJoin: lineModel.lineJoin, lineCap: lineModel.lineCap, animDuration: lineModel.animDuration, animDelay: lineModel.animDelay, lineModel: lineModel, dashPattern: lineModel.dashPattern ) } override open func display(chart: Chart) { if !delayInit { if useView { initScreenLines(chart) } } } open func initScreenLines(_ chart: Chart) { let screenLines = lineModels.map{toScreenLine(lineModel: $0, chart: chart)} for screenLine in screenLines { let lineView = generateLineView(screenLine, chart: chart) lineViews.append(lineView) lineView.isUserInteractionEnabled = false chart.addSubviewNoTransform(lineView) self.screenLines.append((screenLine, lineView)) } } open func generateLineView(_ screenLine: ScreenLine<T>, chart: Chart) -> ChartLinesView { return ChartLinesView( path: pathGenerator.generatePath(points: screenLine.points, lineWidth: screenLine.lineWidth), frame: chart.contentView.bounds, lineColor: screenLine.color, lineWidth: screenLine.lineWidth, lineJoin: screenLine.lineJoin, lineCap: screenLine.lineCap, animDuration: isInTransform ? 0 : screenLine.animDuration, animDelay: isInTransform ? 0 : screenLine.animDelay, dashPattern: screenLine.dashPattern ) } override open func chartDrawersContentViewDrawing(context: CGContext, chart: Chart, view: UIView) { if !useView { for lineModel in lineModels { let points = lineModel.chartPoints.map { modelLocToScreenLoc(x: $0.x.scalar, y: $0.y.scalar) } let path = pathGenerator.generatePath(points: points, lineWidth: lineModel.lineWidth) context.saveGState() context.addPath(path.cgPath) context.setLineWidth(lineModel.lineWidth) context.setLineJoin(lineModel.lineJoin.CGValue) context.setLineCap(lineModel.lineCap.CGValue) context.setLineDash(phase: 0, lengths: lineModel.dashPattern?.map { CGFloat($0) } ?? []) context.setStrokeColor(lineModel.lineColor.cgColor) context.strokePath() context.restoreGState() } } } open override func modelLocToScreenLoc(x: Double) -> CGFloat { return xAxis.screenLocForScalar(x) - (chart?.containerFrame.origin.x ?? 0) } open override func modelLocToScreenLoc(y: Double) -> CGFloat { return yAxis.screenLocForScalar(y) - (chart?.containerFrame.origin.y ?? 0) } open override func zoom(_ scaleX: CGFloat, scaleY: CGFloat, centerX: CGFloat, centerY: CGFloat) { if !useView { chart?.drawersContentView.setNeedsDisplay() } } open override func zoom(_ x: CGFloat, y: CGFloat, centerX: CGFloat, centerY: CGFloat) { if !useView { chart?.drawersContentView.setNeedsDisplay() } else { updateScreenLines() } } open override func pan(_ deltaX: CGFloat, deltaY: CGFloat) { if !useView { chart?.drawersContentView.setNeedsDisplay() } else { updateScreenLines() } } fileprivate func updateScreenLines() { guard let chart = chart else {return} isInTransform = true for i in 0..<screenLines.count { for j in 0..<screenLines[i].screenLine.points.count { let chartPoint = screenLines[i].screenLine.lineModel.chartPoints[j] screenLines[i].screenLine.points[j] = modelLocToScreenLoc(x: chartPoint.x.scalar, y: chartPoint.y.scalar) } screenLines[i].view.removeFromSuperview() screenLines[i].view = generateLineView(screenLines[i].screenLine, chart: chart) chart.addSubviewNoTransform(screenLines[i].view) } isInTransform = false } }
ce1499448361207d8019d8b0d49449bc
33.78341
232
0.622284
false
false
false
false
AsyncNinja/AsyncNinja
refs/heads/master
Sources/AsyncNinja/appleOS_URLSession.swift
mit
1
// // Copyright (c) 2016-2017 Anton Mironov // // 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. // #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) import Foundation /// Conformance URLSessionTask to Cancellable extension URLSessionTask: Cancellable { } /// URLSession improved with AsyncNinja public extension URLSession { /// Makes data task and returns Future of response func data( at url: URL, cancellationToken: CancellationToken? = nil ) -> Future<(Data?, URLResponse)> { return dataFuture(cancellationToken: cancellationToken) { dataTask(with: url, completionHandler: $0) } } /// Makes data task and returns Future of response func data( with request: URLRequest, cancellationToken: CancellationToken? = nil ) -> Future<(Data?, URLResponse)> { return dataFuture(cancellationToken: cancellationToken) { dataTask(with: request, completionHandler: $0) } } /// Makes upload task and returns Future of response func upload( with request: URLRequest, fromFile fileURL: URL, cancellationToken: CancellationToken? = nil ) -> Future<(Data?, URLResponse)> { return dataFuture(cancellationToken: cancellationToken) { uploadTask(with: request, fromFile: fileURL, completionHandler: $0) } } /// Makes upload task and returns Future of response func upload( with request: URLRequest, from bodyData: Data?, cancellationToken: CancellationToken? = nil ) -> Future<(Data?, URLResponse)> { return dataFuture(cancellationToken: cancellationToken) { uploadTask(with: request, from: bodyData, completionHandler: $0) } } /// Makes download task and returns Future of response func download( at sourceURL: URL, to destinationURL: URL, cancellationToken: CancellationToken? = nil ) -> Future<URL> { return downloadFuture(to: destinationURL, cancellationToken: cancellationToken) { downloadTask(with: sourceURL, completionHandler: $0) } } /// Makes download task and returns Future of response func download( with request: URLRequest, to destinationURL: URL, cancellationToken: CancellationToken? = nil ) -> Future<URL> { return downloadFuture(to: destinationURL, cancellationToken: cancellationToken) { downloadTask(with: request, completionHandler: $0) } } } fileprivate extension URLSession { /// a shortcut to url session callback typealias URLSessionCallback = (Data?, URLResponse?, Swift.Error?) -> Void /// a shortcut to url session task construction typealias MakeURLTask = (@escaping URLSessionCallback) -> URLSessionDataTask func dataFuture( cancellationToken: CancellationToken?, makeTask: MakeURLTask) -> Future<(Data?, URLResponse)> { let promise = Promise<(Data?, URLResponse)>() let task = makeTask { [weak promise] (data, response, error) in guard let promise = promise else { return } guard let error = error else { promise.succeed((data, response!), from: nil) return } if let cancellationRepresentable = error as? CancellationRepresentableError, cancellationRepresentable.representsCancellation { promise.cancel(from: nil) } else { promise.fail(error, from: nil) } } promise._asyncNinja_notifyFinalization { [weak task] in task?.cancel() } cancellationToken?.add(cancellable: task) cancellationToken?.add(cancellable: promise) task.resume() return promise } /// a shortcut to url session callback typealias DownloadTaskCallback = (URL?, URLResponse?, Swift.Error?) -> Void /// a shortcut to url session task construction typealias MakeDownloadTask = (@escaping DownloadTaskCallback) -> URLSessionDownloadTask func downloadFuture( to destinationURL: URL, cancellationToken: CancellationToken?, makeTask: MakeDownloadTask) -> Future<URL> { let promise = Promise<URL>() let task = makeTask { [weak promise] (temporaryURL, _, error) in guard let promise = promise else { return } if let error = error { if let cancellationRepresentable = error as? CancellationRepresentableError, cancellationRepresentable.representsCancellation { promise.cancel(from: nil) } else { promise.fail(error, from: nil) } } else if let temporaryURL = temporaryURL { do { try FileManager.default.moveItem(at: temporaryURL, to: destinationURL) promise.succeed(destinationURL) } catch { promise.fail(error) } return } else { promise.fail(NSError(domain: URLError.errorDomain, code: URLError.dataNotAllowed.rawValue)) } } promise._asyncNinja_notifyFinalization { [weak task] in task?.cancel() } cancellationToken?.add(cancellable: task) cancellationToken?.add(cancellable: promise) task.resume() return promise } } #endif
7e6eca0bd29548171b186d6f4df5f6a5
36.329341
101
0.671158
false
false
false
false
qvacua/vimr
refs/heads/master
Commons/Tests/CommonsTests/ArrayCommonsTest.swift
mit
1
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Nimble import XCTest @testable import Commons private class DummyToken: Comparable { static func == (left: DummyToken, right: DummyToken) -> Bool { left.value == right.value } static func < (left: DummyToken, right: DummyToken) -> Bool { left.value < right.value } let value: String init(_ value: String) { self.value = value } } class ArrayCommonsTest: XCTestCase { func testTuplesToDict() { let tuples = [ (1, "1"), (2, "2"), (3, "3"), ] expect(tuplesToDict(tuples)).to(equal( [ 1: "1", 2: "2", 3: "3", ] )) } func testToDict() { let array = [1, 2, 3] expect(array.toDict { "\($0)" }) .to(equal( [ 1: "1", 2: "2", 3: "3", ] )) } func testRemovingDuplicatesPreservingFromBeginning() { let array = [1, 2, 3, 4, 3, 3, 5, 3] expect(array.removingDuplicatesPreservingFromBeginning()).to(equal([1, 2, 3, 4, 5])) } func testSubstituting1() { let substitute = [ DummyToken("a0"), DummyToken("a1"), DummyToken("a2"), ] let array = [ DummyToken("b0"), DummyToken("b1"), DummyToken("a0"), DummyToken("a1"), DummyToken("b4"), DummyToken("a2"), ] let result = array.substituting(elements: substitute) expect(result[2]).to(beIdenticalTo(substitute[0])) expect(result[3]).to(beIdenticalTo(substitute[1])) expect(result[5]).to(beIdenticalTo(substitute[2])) expect(result).to(equal(array)) } func testSubstituting2() { let substitute = [ DummyToken("a0"), DummyToken("a1"), DummyToken("a2"), ] let array = [ DummyToken("a0"), DummyToken("b0"), DummyToken("a1"), DummyToken("b1"), DummyToken("a2"), DummyToken("b4"), ] let result = array.substituting(elements: substitute) expect(result[0]).to(beIdenticalTo(substitute[0])) expect(result[2]).to(beIdenticalTo(substitute[1])) expect(result[4]).to(beIdenticalTo(substitute[2])) expect(result).to(equal(array)) } func testSubstituting3() { let substitute = [ DummyToken("a0"), DummyToken("a1"), DummyToken("a2"), ] let array = [ DummyToken("b0"), DummyToken("b1"), DummyToken("b4"), DummyToken("a0"), DummyToken("a1"), DummyToken("a2"), ] let result = array.substituting(elements: substitute) expect(result[3]).to(beIdenticalTo(substitute[0])) expect(result[4]).to(beIdenticalTo(substitute[1])) expect(result[5]).to(beIdenticalTo(substitute[2])) expect(result).to(equal(array)) } func testSubstituting4() { let substitute = [ DummyToken("a0"), DummyToken("a1"), DummyToken("a2"), ] let array = [ DummyToken("a0"), DummyToken("a1"), DummyToken("a2"), DummyToken("b0"), DummyToken("b1"), DummyToken("b4"), ] let result = array.substituting(elements: substitute) expect(result[0]).to(beIdenticalTo(substitute[0])) expect(result[1]).to(beIdenticalTo(substitute[1])) expect(result[2]).to(beIdenticalTo(substitute[2])) expect(result).to(equal(array)) } func testSubstituting5() { let substitute = [ DummyToken("a0"), DummyToken("something else"), DummyToken("a1"), DummyToken("a2"), ] let array = [ DummyToken("a0"), DummyToken("b0"), DummyToken("a1"), DummyToken("b1"), DummyToken("a2"), DummyToken("b4"), ] let result = array.substituting(elements: substitute) expect(result[0]).to(beIdenticalTo(substitute[0])) expect(result[2]).to(beIdenticalTo(substitute[2])) expect(result[4]).to(beIdenticalTo(substitute[3])) expect(result).to(equal(array)) } }
01d45ccc09458cbb0840bcf9152ee9be
20.318919
88
0.575051
false
true
false
false
kvvzr/Twinkrun
refs/heads/master
Twinkrun/Models/TWRGame.swift
mit
2
// // TWRGame.swift // Twinkrun // // Created by Kawazure on 2014/10/09. // Copyright (c) 2014年 Twinkrun. All rights reserved. // import Foundation import UIKit import CoreBluetooth enum TWRGameState { case Idle case CountDown case Started } protocol TWRGameDelegate { func didUpdateCountDown(count: UInt) func didStartGame() func didUpdateScore(score: Int) func didFlash(color: UIColor) func didUpdateRole(color: UIColor, score: Int) func didEndGame() } class TWRGame: NSObject, CBCentralManagerDelegate, CBPeripheralManagerDelegate { var player: TWRPlayer var others: [TWRPlayer] let option: TWRGameOption var state = TWRGameState.Idle var transition: Array<(role: TWRRole, scores: [Int])>?, currentTransition: [Int]? var score: Int, addScore: Int, flashCount: UInt?, countDown: UInt? var startTime: NSDate? var scanTimer: NSTimer?, updateRoleTimer: NSTimer?, updateScoreTimer: NSTimer?, flashTimer: NSTimer?, gameTimer: NSTimer? unowned var centralManager: CBCentralManager unowned var peripheralManager: CBPeripheralManager var delegate: TWRGameDelegate? init(player: TWRPlayer, others: [TWRPlayer], central: CBCentralManager, peripheral: CBPeripheralManager) { self.player = player self.others = others self.option = TWROption.sharedInstance.gameOption self.centralManager = central self.peripheralManager = peripheral score = option.startScore addScore = 0 super.init() centralManager.delegate = self peripheralManager.delegate = self } func start() { transition = [] currentTransition = [] score = option.startScore flashCount = 0 countDown = option.countTime scanTimer = NSTimer(timeInterval: 1, target: self, selector: Selector("countDown:"), userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(scanTimer!, forMode: NSRunLoopCommonModes) countDown(nil) } func countDown(timer: NSTimer?) { state = TWRGameState.CountDown if countDown! == 0 { timer?.invalidate() state = TWRGameState.Started delegate?.didStartGame() startTime = NSDate() let current = UInt(NSDate().timeIntervalSinceDate(startTime!)) let currentRole = player.currentRole(current) delegate?.didUpdateRole(currentRole.color, score: score) updateRoleTimer = NSTimer(timeInterval: Double(currentRole.time), target: self, selector: Selector("updateRole:"), userInfo: nil, repeats: false) updateScoreTimer = NSTimer(timeInterval: Double(option.scanInterval), target: self, selector: Selector("updateScore:"), userInfo: nil, repeats: true) flashTimer = NSTimer(timeInterval: Double(option.flashStartTime(currentRole.time)), target: self, selector: Selector("flash:"), userInfo: nil, repeats: false) gameTimer = NSTimer(timeInterval: Double(option.gameTime()), target: self, selector: Selector("end:"), userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(flashTimer!, forMode: NSRunLoopCommonModes) NSRunLoop.mainRunLoop().addTimer(updateRoleTimer!, forMode: NSRunLoopCommonModes) NSRunLoop.mainRunLoop().addTimer(updateScoreTimer!, forMode: NSRunLoopCommonModes) NSRunLoop.mainRunLoop().addTimer(gameTimer!, forMode: NSRunLoopCommonModes) } else { delegate?.didUpdateCountDown(countDown!) --countDown! } } func updateRole(timer: NSTimer?) { let current = UInt(NSDate().timeIntervalSinceDate(startTime!)) let prevRole = player.previousRole(current) let currentRole = player.currentRole(current) if let prevRole = prevRole { transition! += [(role: prevRole, scores: currentTransition!)] } flashCount = 0 currentTransition = [] delegate?.didUpdateRole(currentRole.color, score: score) updateRoleTimer = NSTimer(timeInterval: Double(currentRole.time), target: self, selector: Selector("updateRole:"), userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(updateRoleTimer!, forMode: NSRunLoopCommonModes) flashTimer = NSTimer(timeInterval: Double(option.flashStartTime(currentRole.time)), target: self, selector: Selector("flash:"), userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(flashTimer!, forMode: NSRunLoopCommonModes) } func updateScore(timer: NSTimer) { currentTransition!.append(score) score += addScore addScore = 0 for player in others { player.countedScore = false } delegate?.didUpdateScore(score) } func flash(timer: NSTimer) { if (flashCount < option.flashCount) { let current = UInt(NSDate().timeIntervalSinceDate(startTime!)) let nextRole = player.nextRole(current) if (nextRole == nil) { return } delegate?.didFlash((flashCount! % 2 == 0 ? nextRole! : player.currentRole(current)).color) self.flashTimer = NSTimer(timeInterval: Double(option.flashInterval()), target: self, selector: Selector("flash:"), userInfo: nil, repeats: false) NSRunLoop.mainRunLoop().addTimer(flashTimer!, forMode: NSRunLoopCommonModes) } ++flashCount! } func end() { if let startTime = startTime { let current = UInt(NSDate().timeIntervalSinceDate(startTime)) let prevRole = player.previousRole(current)! transition! += [(role: prevRole, scores: currentTransition!)] currentTransition = [] } if let timer: NSTimer = scanTimer { timer.invalidate() } if let timer: NSTimer = updateRoleTimer { timer.invalidate() } if let timer: NSTimer = updateScoreTimer { timer.invalidate() } if let timer: NSTimer = flashTimer { timer.invalidate() } if let timer: NSTimer = gameTimer { timer.invalidate() } state = TWRGameState.Idle } func end(timer: NSTimer) { end() delegate?.didEndGame() } func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) { if let localName = advertisementData["kCBAdvDataLocalName"] as AnyObject? as? String { if let startTime = startTime { let current = UInt(NSDate().timeIntervalSinceDate(startTime)) let findPlayer = TWRPlayer(advertisementDataLocalName: localName, identifier: peripheral.identifier) let other = others.filter { $0 == findPlayer } if !other.isEmpty { other.first!.RSSI = RSSI.integerValue if other.first!.playWith && !other.first!.countedScore && RSSI.integerValue <= 0 { let point = min(pow(2, (RSSI.floatValue + 45) / 4), 3.0) addScore -= Int(point * player.currentRole(current).score) addScore += Int(point * other.first!.currentRole(current).score) other.first!.countedScore = true } } } } } func centralManagerDidUpdateState(central: CBCentralManager) { } func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { } }
5d7b5080780b8b64178691f2c9d9b962
35.697248
170
0.610326
false
false
false
false
PaulWoodIII/GRMustache.swift
refs/heads/master
MustacheTests/Public/TemplateRepositoryTests/TemplateRepositoryFileSystemTests/TemplateRepositoryURLTests.swift
mit
4
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest import Mustache class TemplateRepositoryURLTests: XCTestCase { func testTemplateRepositoryWithURL() { let testBundle = NSBundle(forClass: self.dynamicType) let URL = testBundle.URLForResource("TemplateRepositoryFileSystemTests_UTF8", withExtension: nil)! let repo = TemplateRepository(baseURL: URL) var template: Template? var error: NSError? var rendering: String? template = repo.template(named: "notFound", error: &error) XCTAssertNil(template) XCTAssertNotNil(error) template = repo.template(named: "file1") rendering = template?.render() XCTAssertEqual(rendering!, "é1.mustache\ndir/é1.mustache\ndir/dir/é1.mustache\ndir/dir/é2.mustache\n\n\ndir/é2.mustache\n\n\né2.mustache\n\n") template = repo.template(string: "{{>file1}}") rendering = template?.render() XCTAssertEqual(rendering!, "é1.mustache\ndir/é1.mustache\ndir/dir/é1.mustache\ndir/dir/é2.mustache\n\n\ndir/é2.mustache\n\n\né2.mustache\n\n") template = repo.template(string: "{{>dir/file1}}") rendering = template?.render() XCTAssertEqual(rendering!, "dir/é1.mustache\ndir/dir/é1.mustache\ndir/dir/é2.mustache\n\n\ndir/é2.mustache\n\n") template = repo.template(string: "{{>dir/dir/file1}}") rendering = template?.render() XCTAssertEqual(rendering!, "dir/dir/é1.mustache\ndir/dir/é2.mustache\n\n") } func testTemplateRepositoryWithURLTemplateExtensionEncoding() { let testBundle = NSBundle(forClass: self.dynamicType) var URL: NSURL var repo: TemplateRepository var template: Template var rendering: String URL = testBundle.URLForResource("TemplateRepositoryFileSystemTests_UTF8", withExtension: nil)! repo = TemplateRepository(baseURL: URL, templateExtension: "mustache", encoding: NSUTF8StringEncoding) template = repo.template(named: "file1")! rendering = template.render()! XCTAssertEqual(rendering, "é1.mustache\ndir/é1.mustache\ndir/dir/é1.mustache\ndir/dir/é2.mustache\n\n\ndir/é2.mustache\n\n\né2.mustache\n\n") URL = testBundle.URLForResource("TemplateRepositoryFileSystemTests_UTF8", withExtension: nil)! repo = TemplateRepository(baseURL: URL, templateExtension: "txt", encoding: NSUTF8StringEncoding) template = repo.template(named: "file1")! rendering = template.render()! XCTAssertEqual(rendering, "é1.txt\ndir/é1.txt\ndir/dir/é1.txt\ndir/dir/é2.txt\n\n\ndir/é2.txt\n\n\né2.txt\n\n") URL = testBundle.URLForResource("TemplateRepositoryFileSystemTests_UTF8", withExtension: nil)! repo = TemplateRepository(baseURL: URL, templateExtension: "", encoding: NSUTF8StringEncoding) template = repo.template(named: "file1")! rendering = template.render()! XCTAssertEqual(rendering, "é1\ndir/é1\ndir/dir/é1\ndir/dir/é2\n\n\ndir/é2\n\n\né2\n\n") URL = testBundle.URLForResource("TemplateRepositoryFileSystemTests_ISOLatin1", withExtension: nil)! repo = TemplateRepository(baseURL: URL, templateExtension: "mustache", encoding: NSISOLatin1StringEncoding) template = repo.template(named: "file1")! rendering = template.render()! XCTAssertEqual(rendering, "é1.mustache\ndir/é1.mustache\ndir/dir/é1.mustache\ndir/dir/é2.mustache\n\n\ndir/é2.mustache\n\n\né2.mustache\n\n") URL = testBundle.URLForResource("TemplateRepositoryFileSystemTests_ISOLatin1", withExtension: nil)! repo = TemplateRepository(baseURL: URL, templateExtension: "txt", encoding: NSISOLatin1StringEncoding) template = repo.template(named: "file1")! rendering = template.render()! XCTAssertEqual(rendering, "é1.txt\ndir/é1.txt\ndir/dir/é1.txt\ndir/dir/é2.txt\n\n\ndir/é2.txt\n\n\né2.txt\n\n") URL = testBundle.URLForResource("TemplateRepositoryFileSystemTests_ISOLatin1", withExtension: nil)! repo = TemplateRepository(baseURL: URL, templateExtension: "", encoding: NSISOLatin1StringEncoding) template = repo.template(named: "file1")! rendering = template.render()! XCTAssertEqual(rendering, "é1\ndir/é1\ndir/dir/é1\ndir/dir/é2\n\n\ndir/é2\n\n\né2\n\n") } func testAbsolutePartialName() { let testBundle = NSBundle(forClass: self.dynamicType) let URL = testBundle.URLForResource("TemplateRepositoryFileSystemTests", withExtension: nil)! let repo = TemplateRepository(baseURL: URL) let template = repo.template(named: "base")! let rendering = template.render()! XCTAssertEqual(rendering, "success") } func testPartialNameCanNotEscapeTemplateRepositoryRootURL() { let testBundle = NSBundle(forClass: self.dynamicType) let URL = testBundle.URLForResource("TemplateRepositoryFileSystemTests", withExtension: nil)! let repo = TemplateRepository(baseURL: URL.URLByAppendingPathComponent("partials")) let template = repo.template(named: "partial2")! let rendering = template.render()! XCTAssertEqual(rendering, "success") var error: NSError? let badTemplate = repo.template(named: "up", error: &error) XCTAssertNil(badTemplate) XCTAssertEqual(error!.domain, GRMustacheErrorDomain) XCTAssertEqual(error!.code, GRMustacheErrorCodeTemplateNotFound) } }
d6308cac616a91d7dbaa52db667dd2bd
51.992063
150
0.697469
false
true
false
false
CalQL8ed-K-OS/SwiftProceduralLevelGeneration
refs/heads/master
Procedural/Code/Scene.swift
mit
1
// // Scene.swift // Procedural // // Created by Xavi on 3/19/15. // Copyright (c) 2015 Xavi. All rights reserved. // import SpriteKit class Scene:SKScene { private let world = SKNode() private let hud = SKNode() private let dPad = Scene.createDpad() private let map = Map() private var player = Scene.createPlayer() private let playerShadow = Scene.createShadow() private let exit = Scene.createExit() private var isExistingLevel = false private static let playerSpeed:CGFloat = 100.0 private var lastUpdateTime = NSTimeInterval(0) override init(size:CGSize) { super.init(size: size) backgroundColor = SKColor(hue: 0.5, saturation: 0.5, brightness: 0.5, alpha: 1.0) setupNodes() setupPhysics() } override func update(currentTime: NSTimeInterval) { let timeDelta:NSTimeInterval = { let time = currentTime - lastUpdateTime return time > 1 ? time : 1.0 / 60.0 }() lastUpdateTime = currentTime updatePlayer(timeDelta) updateCamera() } override func didSimulatePhysics() { player.zRotation = 0.0 playerShadow.position = CGPoint(x: player.position.x, y: player.position.y - 7.0) } // Shoutout to Nate Cook for his // [NS_OPTIONS Bitmasker Generator for Swift](http://natecook.com/blog/2014/07/swift-options-bitmask-generator/) struct CollisionType : RawOptionSetType { typealias RawValue = UInt32 private var value: RawValue = 0 init(_ value: RawValue) { self.value = value } init(rawValue value: RawValue) { self.value = value } init(nilLiteral: ()) { self.value = 0 } static var allZeros: CollisionType { return self(0) } static func fromMask(raw: RawValue) -> CollisionType { return self(raw) } var rawValue: RawValue { return self.value } static var Player: CollisionType { return CollisionType(1 << 0) } static var Wall: CollisionType { return CollisionType(1 << 1) } static var Exit: CollisionType { return CollisionType(1 << 2) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: SKPhysicsContactDelegate extension Scene:SKPhysicsContactDelegate { func didBeginContact(contact: SKPhysicsContact) { let firstBody:SKPhysicsBody let secondBody:SKPhysicsBody if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } if CollisionType.fromMask( firstBody.categoryBitMask) == CollisionType.Player && CollisionType.fromMask(secondBody.categoryBitMask) == CollisionType.Exit { resolveExit() } } } // MARK: Private private extension Scene { // MARK: Setup func setupNodes() { player.position = map.spawnPosition exit.position = map.exitPosition world.addChild(map) world.addChild(exit) world.addChild(playerShadow) world.addChild(player) hud.addChild(dPad) self.addChild(world) self.addChild(hud) } func setupPhysics() { physicsWorld.gravity = CGVector(dx: 0, dy: 0) physicsWorld.contactDelegate = self } // MARK: Update cycle func updatePlayer(timeDelta:NSTimeInterval) { let playerVelocity = isExistingLevel ? CGPoint.zeroPoint : dPad.velocity // Position player.position = CGPoint(x: player.position.x + playerVelocity.x * CGFloat(timeDelta) * Scene.playerSpeed, y: player.position.y + playerVelocity.y * CGFloat(timeDelta) * Scene.playerSpeed) if playerVelocity.x != 0.0 { player.xScale = playerVelocity.x > 0.0 ? -1.0 : 1.0 } // Animation let anim:PlayerAnimation = playerVelocity.x != 0.0 ? .Walk : .Idle let key = anim.key let action = player.actionForKey(key) if let action = action { return } else { var action = SKAction.animateWithTextures(anim.frames, timePerFrame: 5.0/60.0, resize: true, restore: false) if anim == .Walk { let stepSound = SKAction.playSoundFileNamed("step.wav", waitForCompletion: false) action = SKAction.group([action, stepSound]) } player.runAction(action, withKey: key) } } func updateCamera() { world.position = CGPoint(x: -player.position.x + frame.midX, y: -player.position.y + frame.midY) } func resolveExit() { isExistingLevel = true playerShadow.removeFromParent() let move = SKAction.moveTo(map.exitPosition, duration: 0.5) let rotate = SKAction.rotateByAngle(CGFloat(M_PI * 2), duration: 0.5) let fade = SKAction.fadeAlphaTo(0.0, duration: 0.5) let scale = SKAction.scaleXTo(0.0, y: 0.0, duration: 0.5) let sound = SKAction.playSoundFileNamed("win.wav", waitForCompletion: false) let presentNextScene = SKAction.runBlock { self.view!.presentScene(Scene(size: self.size), transition: SKTransition.doorsCloseVerticalWithDuration(0.5)) } player.runAction(SKAction.sequence([SKAction.group([move, rotate, fade, scale, sound]), presentNextScene])) } // MARK: Inner types enum PlayerAnimation { case Idle, Walk var key:String { switch self { case Idle: return "anim_idle" case Walk: return "anim_walk" } } var frames:[SKTexture] { switch self { case Idle: return Scene.idleTextures case Walk: return Scene.walkTextures } } } // MARK: Sprite creation static var spriteAtlas:SKTextureAtlas = SKTextureAtlas(named: "sprites") class func createExit() -> SKSpriteNode { let exit = SKSpriteNode(texture: self.spriteAtlas.textureNamed("exit")) exit.physicsBody = { let size = CGSize(width: exit.texture!.size().width / 2.0, height: exit.texture!.size().height / 2.0) var body = SKPhysicsBody(rectangleOfSize: size) body.categoryBitMask = CollisionType.Exit.rawValue body.collisionBitMask = 0 return body }() return exit } class func createPlayer() -> SKSpriteNode { let player = SKSpriteNode(texture: self.spriteAtlas.textureNamed("idle_0")) player.physicsBody = { let body = SKPhysicsBody(rectangleOfSize: player.texture!.size()) body.categoryBitMask = CollisionType.Player.rawValue body.contactTestBitMask = CollisionType.Exit.rawValue body.collisionBitMask = CollisionType.Wall.rawValue body.allowsRotation = false return body }() return player } class func createDpad() -> DPad { let dpad = DPad(rect: CGRect(x: 0, y: 0, width: 64, height: 64)) dpad.position = CGPoint(x: 16, y: 16) dpad.numberOfDirections = 24 dpad.deadRadius = 8 return dpad } class func createShadow() -> SKSpriteNode { let shadow = SKSpriteNode(texture: self.spriteAtlas.textureNamed("shadow")) shadow.xScale = 0.6 shadow.yScale = 0.5 shadow.alpha = 0.4 return shadow } // MARK: Animation texture array creation static let idleTextures = Scene.createIdleAnimation() static let walkTextures = Scene.createWalkAnimation() class func createIdleAnimation() -> [SKTexture] { return [self.spriteAtlas.textureNamed("idle_0")] } class func createWalkAnimation() -> [SKTexture] { return [0, 1, 2].map { self.spriteAtlas.textureNamed("walk_\($0)") } } }
9e1777a98440407a5eb6946c5e5d2276
33.05668
120
0.588564
false
false
false
false
everald/JetPack
refs/heads/master
Sources/Extensions/UIKit/NSAttributedString+UIKit.swift
mit
1
import UIKit extension NSAttributedString { @nonobjc public func capitalLetterSpacing(in range: NSRange, forLineHeight lineHeight: CGFloat? = nil, usingFontLeading: Bool = true) -> CapitalLetterSpacing? { var smallestSpacingAboveCapitalLetters: CGFloat? var smallestSpacingBelowCapitalLetters: CGFloat? enumerateAttributes(in: range, options: .longestEffectiveRangeNotRequired) { attributes, _, _ in guard let font = attributes[.font] as? UIFont else { return } var effectiveLineHeight: CGFloat if let lineHeight = lineHeight { effectiveLineHeight = lineHeight - (usingFontLeading ? font.leading : 0) } else if let paragraphStyle = attributes[.paragraphStyle] as? NSParagraphStyle { effectiveLineHeight = paragraphStyle.effectiveLineHeight(for: font.lineHeight) } else { effectiveLineHeight = font.lineHeight } let spacingAboveCapitalLetters = (effectiveLineHeight - font.capHeight + font.descender).coerced(atLeast: 0) let spacingBelowCapitalLetters = -font.descender smallestSpacingAboveCapitalLetters = optionalMin(smallestSpacingAboveCapitalLetters, spacingAboveCapitalLetters) smallestSpacingBelowCapitalLetters = optionalMin(smallestSpacingBelowCapitalLetters, spacingBelowCapitalLetters) } if let smallestSpacingAboveCapitalLetters = smallestSpacingAboveCapitalLetters, let smallestSpacingBelowCapitalLetters = smallestSpacingBelowCapitalLetters { return CapitalLetterSpacing(above: smallestSpacingAboveCapitalLetters, below: smallestSpacingBelowCapitalLetters) } else { return nil } } public struct CapitalLetterSpacing { public var above: CGFloat public var below: CGFloat public init(above: CGFloat, below: CGFloat) { self.above = above self.below = below } } }
8717235fe4f15db60ed9be34c6e3ecf7
29.862069
152
0.77933
false
false
false
false
arkverse/SwiftRecord
refs/heads/master
Example-iOS/SwiftRecordExample/SwiftRecordExample/AppDelegate.swift
mit
1
// // AppDelegate.swift // SwiftRecordExample // // Created by Zaid on 5/8/15. // Copyright (c) 2015 ark. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.ark.SwiftRecordExample" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("SwiftRecordExample", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. var coordinator: NSPersistentStoreCoordinator? do { // Create the coordinator and store coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SwiftRecordExample.sqlite") try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch let error as NSError { coordinator = nil // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error.userInfo)") abort() } catch { var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = "There was an error creating or loading the application's saved data." var error = NSError(domain: "Initialization", code: 0, userInfo: dict) NSLog("Unresolved error \(error), \(error.userInfo)") } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { if moc.hasChanges { do { try moc.save() } catch let error as NSError { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error.userInfo)") abort() } } } } }
3e83ab79d31cbf7eba4dddce1f05f8bc
50.739496
290
0.70164
false
false
false
false
loudnate/Loop
refs/heads/master
LoopUI/Views/LoopCompletionHUDView.swift
apache-2.0
1
// // LoopCompletionHUDView.swift // Naterade // // Created by Nathan Racklyeft on 5/1/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import UIKit import LoopKitUI import LoopCore public final class LoopCompletionHUDView: BaseHUDView { @IBOutlet private weak var loopStateView: LoopStateView! override public var orderPriority: HUDViewOrderPriority { return 1 } private(set) var freshness = LoopCompletionFreshness.unknown { didSet { updateTintColor() } } override public func awakeFromNib() { super.awakeFromNib() updateDisplay(nil) } public var dosingEnabled = false { didSet { loopStateView.open = !dosingEnabled } } public var lastLoopCompleted: Date? { didSet { if lastLoopCompleted != oldValue { loopInProgress = false } } } public var loopInProgress = false { didSet { loopStateView.animated = loopInProgress if !loopInProgress { updateTimer = nil assertTimer() } } } public func assertTimer(_ active: Bool = true) { if active && window != nil, let date = lastLoopCompleted { initTimer(date) } else { updateTimer = nil } } override public func stateColorsDidUpdate() { super.stateColorsDidUpdate() updateTintColor() } private func updateTintColor() { let tintColor: UIColor? switch freshness { case .fresh: tintColor = stateColors?.normal case .aging: tintColor = stateColors?.warning case .stale: tintColor = stateColors?.error case .unknown: tintColor = stateColors?.unknown } self.tintColor = tintColor } private func initTimer(_ startDate: Date) { let updateInterval = TimeInterval(minutes: 1) let timer = Timer( fireAt: startDate.addingTimeInterval(2), interval: updateInterval, target: self, selector: #selector(updateDisplay(_:)), userInfo: nil, repeats: true ) updateTimer = timer RunLoop.main.add(timer, forMode: .default) } private var updateTimer: Timer? { willSet { if let timer = updateTimer { timer.invalidate() } } } private lazy var formatter: DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.allowedUnits = [.day, .hour, .minute] formatter.maximumUnitCount = 1 formatter.unitsStyle = .short return formatter }() @objc private func updateDisplay(_: Timer?) { if let date = lastLoopCompleted { let ago = abs(min(0, date.timeIntervalSinceNow)) freshness = LoopCompletionFreshness(age: ago) if let timeString = formatter.string(from: ago) { switch traitCollection.preferredContentSizeCategory { case UIContentSizeCategory.extraSmall, UIContentSizeCategory.small, UIContentSizeCategory.medium, UIContentSizeCategory.large: // Use a longer form only for smaller text sizes caption.text = String(format: LocalizedString("%@ ago", comment: "Format string describing the time interval since the last completion date. (1: The localized date components"), timeString) default: caption.text = timeString } accessibilityLabel = String(format: LocalizedString("Loop ran %@ ago", comment: "Accessbility format label describing the time interval since the last completion date. (1: The localized date components)"), timeString) } else { caption.text = "—" accessibilityLabel = nil } } else { caption.text = "—" accessibilityLabel = LocalizedString("Waiting for first run", comment: "Acessibility label describing completion HUD waiting for first run") } if dosingEnabled { accessibilityHint = LocalizedString("Closed loop", comment: "Accessibility hint describing completion HUD for a closed loop") } else { accessibilityHint = LocalizedString("Open loop", comment: "Accessbility hint describing completion HUD for an open loop") } } override public func didMoveToWindow() { super.didMoveToWindow() assertTimer() } }
8d740530f24e1caff92a67ee63c0d4db
28.333333
233
0.583544
false
false
false
false
jasperscholten/programmeerproject
refs/heads/master
JasperScholten-project/MainMenuVC.swift
apache-2.0
1
// // MainMenuVC.swift // JasperScholten-project // // Created by Jasper Scholten on 11-01-17. // Copyright © 2017 Jasper Scholten. All rights reserved. // // This ViewController handles the presentation of a main menu, which content depends on the type of user that has logged in; an admin will have more options. The main menu also serves as a hub, that sends specific data to other ViewControllers (mainly currentOrganisationID and currenOrganisation name). import UIKit import Firebase class MainMenuVC: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: - Constants and variables let userRef = FIRDatabase.database().reference(withPath: "Users") let uid = FIRAuth.auth()?.currentUser?.uid var admin = Bool() var currentOrganisation = String() var currentOrganisationID = String() var currentLocation = String() var currentName = String() var menuItems = [String]() // MARK: - Outlets @IBOutlet weak var menuTableView: UITableView! // MARK: - UIViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() userRef.child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in if snapshot.hasChildren() { let userData = User(snapshot: snapshot) if userData.uid == self.uid! { self.currentOrganisation = userData.organisationName! self.currentOrganisationID = userData.organisationID! self.currentLocation = userData.locationID! self.currentName = userData.name! if userData.admin! == true { self.menuItems = ["Beoordelen", "Resultaten", "Nieuws (admin)", "Stel lijst samen", "Medewerker verzoeken"] self.admin = true } else { self.menuItems = ["Beoordelingen", "Nieuws"] // Only allow admins to access settings menu. [1] self.navigationItem.rightBarButtonItem = nil } self.menuTableView.reloadData() self.resizeTable() } } }) } override func viewDidAppear(_ animated: Bool) { resizeTable() } // Resize table on device rotation. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { _ in self.resizeTable() }, completion: nil) } // MARK: - TableView Population func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = menuTableView.dequeueReusableCell(withIdentifier: "menuCell", for: indexPath) as! MainMenuCell cell.menuItem.text = menuItems[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: menuItems[indexPath.row], sender: self) menuTableView.deselectRow(at: indexPath, animated: true) } // MARK: - Segue data specific to current user to chosen menu option. override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let employeeResults = segue.destination as? ReviewResultsEmployeeVC { employeeResults.employee = currentName employeeResults.employeeID = uid! } else if let news = segue.destination as? NewsAdminVC { news.admin = admin news.location = currentLocation news.organisationID = currentOrganisationID } else if let requests = segue.destination as? RequestsVC { requests.organisationID = currentOrganisationID } else if let forms = segue.destination as? FormsListVC { forms.organisation = currentOrganisation forms.organisationID = currentOrganisationID } else if let employees = segue.destination as? ReviewEmployeeVC { employees.organisation = currentOrganisation employees.organisationID = currentOrganisationID } else if let results = segue.destination as? ReviewResultsVC { results.organisation = currentOrganisation results.organisationID = currentOrganisationID } else if let settings = segue.destination as? SettingsVC { settings.organisationName = currentOrganisation settings.organisationID = currentOrganisationID } } // MARK: - Actions @IBAction func signOut(_ sender: Any) { if (try? FIRAuth.auth()?.signOut()) != nil { self.dismiss(animated: true, completion: {}) } else { alertSingleOption(titleInput: "Fout bij uitloggen", messageInput: "Het is niet gelukt om je correct uit te loggen. Probeer het nog een keer.") } } @IBAction func showSettings(_ sender: Any) { performSegue(withIdentifier: "showSettings", sender: self) } // MARK: - Functions // Resize the rowheight of menu cells, such that they fill the screen and are of equal height. [2] func resizeTable() { let heightOfVisibleTableViewArea = view.bounds.height - topLayoutGuide.length - bottomLayoutGuide.length let numberOfRows = menuTableView.numberOfRows(inSection: 0) menuTableView.rowHeight = heightOfVisibleTableViewArea / CGFloat(numberOfRows) menuTableView.reloadData() } } // MARK: - References // 1. http://stackoverflow.com/questions/27887218/how-to-hide-a-bar-button-item-for-certain-users // 2. http://stackoverflow.com/questions/34161016/how-to-make-uitableview-to-fill-all-my-view
dc87acd8f7fe01c914089ca8405c8fb0
41.51049
305
0.637276
false
false
false
false
ZTfer/FlagKit
refs/heads/master
Sources/FlagKitDemo-iOS/FlagsListViewController.swift
mit
2
// // Copyright © 2017 Bowtie. All rights reserved. // import UIKit import FlagKit class FlagsListViewController: UITableViewController { var style: FlagStyle = .none { didSet { tableView.reloadData() } } let stylePicker: UISegmentedControl = { let items = FlagStyle.all.map({ $0.name }) let control = UISegmentedControl(items: items) control.selectedSegmentIndex = 0 return control }() let flags = Flag.all override func viewDidLoad() { super.viewDidLoad() navigationItem.titleView = stylePicker tableView.backgroundColor = UIColor(red: 0.91, green: 0.96, blue: 0.97, alpha: 1.0) tableView.separatorColor = UIColor.black.withAlphaComponent(0.1) tableView.register(FlagTableViewCell.self, forCellReuseIdentifier: FlagTableViewCell.identifier) stylePicker.addTarget(self, action: #selector(styleDidChange), for: .valueChanged) } // MARK: UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return flags.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: FlagTableViewCell.identifier, for: indexPath) let flag = flags[indexPath.row] cell.textLabel?.text = flag.localizedName cell.detailTextLabel?.text = flag.countryCode cell.imageView?.image = flag.image(style: style) return cell } // MARK: Private @objc private func styleDidChange() { style = FlagStyle(rawValue: stylePicker.selectedSegmentIndex)! } }
697013caf08ce7dbd850122ab80b9fd5
30.633333
110
0.651212
false
false
false
false
dsonara/DSImageCache
refs/heads/master
DSImageCache/Classes/Extensions/ImageView+DSImageCache.swift
mit
1
// // ImageView+DSImageCache.swift // DSImageCache // // Created by Dipak Sonara on 29/03/17. // Copyright © 2017 Dipak Sonara. All rights reserved. // import UIKit // MARK: - Extension methods. /** * Set image to use from web. */ extension DSImageCache where Base: ImageView { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `DSImageCacheOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult public func setImage(with resource: Resource?, placeholder: Image? = nil, options: DSImageCacheOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { guard let resource = resource else { base.image = placeholder setWebURL(nil) completionHandler?(nil, nil, .none, nil) return .empty } var options = options ?? DSImageCacheEmptyOptionsInfo if !options.keepCurrentImageWhileLoading { base.image = placeholder } let maybeIndicator = indicator maybeIndicator?.startAnimatingView() setWebURL(resource.downloadURL) if base.shouldPreloadAllGIF() { options.append(.preloadAllGIFData) } let task = DSImageCacheManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in guard resource.downloadURL == self.webURL else { return } if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.webURL else { return } self.setImageTask(nil) guard let image = image else { maybeIndicator?.stopAnimatingView() completionHandler?(nil, error, cacheType, imageURL) return } guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)), case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else { maybeIndicator?.stopAnimatingView() strongBase.image = image completionHandler?(image, error, cacheType, imageURL) return } UIView.transition(with: strongBase, duration: 0.0, options: [], animations: { maybeIndicator?.stopAnimatingView() }, completion: { _ in UIView.transition(with: strongBase, duration: transition.duration, options: [transition.animationOptions, .allowUserInteraction], animations: { // Set image property in the animation. transition.animations?(strongBase, image) }, completion: { finished in transition.completion?(finished) completionHandler?(image, error, cacheType, imageURL) }) }) } }) setImageTask(task) return task } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelDownloadTask() { imageTask?.cancel() } } // MARK: - Associated Object private var lastURLKey: Void? private var indicatorKey: Void? private var indicatorTypeKey: Void? private var imageTaskKey: Void? extension DSImageCache where Base: ImageView { /// Get the image URL binded to this image view. public var webURL: URL? { return objc_getAssociatedObject(base, &lastURLKey) as? URL } fileprivate func setWebURL(_ url: URL?) { objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } /// Holds which indicator type is going to be used. /// Default is .none, means no indicator will be shown. public var indicatorType: IndicatorType { get { let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box<IndicatorType?>)?.value return indicator ?? .none } set { switch newValue { case .none: indicator = nil case .activity: indicator = ActivityIndicator() case .image(let data): indicator = ImageIndicator(imageData: data) case .custom(let anIndicator): indicator = anIndicator } objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `indicatorType` is `.none`. public fileprivate(set) var indicator: Indicator? { get { return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value } set { // Remove previous if let previousIndicator = indicator { previousIndicator.view.removeFromSuperview() } // Add new if var newIndicator = newValue { newIndicator.view.frame = base.frame newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY) newIndicator.view.isHidden = true base.addSubview(newIndicator.view) } // Save in associated object objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var imageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask } fileprivate func setImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated. Only for back compatibility. /** * Set image to use from web. Deprecated. Use `ds` namespacing instead. */ extension ImageView { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `DSImageCacheOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.ds.setImage` instead.", renamed: "ds.setImage") @discardableResult public func ds_setImage(with resource: Resource?, placeholder: Image? = nil, options: DSImageCacheOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return ds.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.ds.cancelDownloadTask` instead.", renamed: "ds.cancelDownloadTask") public func ds_cancelDownloadTask() { ds.cancelDownloadTask() } /// Get the image URL binded to this image view. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.ds.webURL` instead.", renamed: "ds.webURL") public var ds_webURL: URL? { return ds.webURL } /// Holds which indicator type is going to be used. /// Default is .none, means no indicator will be shown. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.ds.indicatorType` instead.", renamed: "ds.indicatorType") public var ds_indicatorType: IndicatorType { get { return ds.indicatorType } set { ds.indicatorType = newValue } } @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.ds.indicator` instead.", renamed: "ds.indicator") /// Holds any type that conforms to the protocol `Indicator`. /// The protocol `Indicator` has a `view` property that will be shown when loading an image. /// It will be `nil` if `ds_indicatorType` is `.none`. public private(set) var ds_indicator: Indicator? { get { return ds.indicator } set { ds.indicator = newValue } } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "ds.imageTask") fileprivate var ds_imageTask: RetrieveImageTask? { return ds.imageTask } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "ds.setImageTask") fileprivate func ds_setImageTask(_ task: RetrieveImageTask?) { ds.setImageTask(task) } @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "ds.setWebURL") fileprivate func ds_setWebURL(_ url: URL) { ds.setWebURL(url) } } extension ImageView { func shouldPreloadAllGIF() -> Bool { return true } }
2a7d721a83455ebc9c6afcc2c7fa585f
44.247191
173
0.589769
false
false
false
false
DAloG/BlueCap
refs/heads/master
BlueCap/Peripheral/PeripheralManagerServiceCharacteristicsViewController.swift
mit
1
// // PeripheralManagerServiceCharacteristicsViewController.swift // BlueCap // // Created by Troy Stribling on 8/19/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit import BlueCapKit class PeripheralManagerServiceCharacteristicsViewController : UITableViewController { var service : MutableService? var peripheralManagerViewController : PeripheralManagerViewController? struct MainStoryboard { static let peripheralManagerServiceChracteristicCell = "PeripheralManagerServiceChracteristicCell" static let peripheralManagerServiceCharacteristicSegue = "PeripheralManagerServiceCharacteristic" } required init?(coder aDecoder:NSCoder) { super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let service = self.service { self.navigationItem.title = service.name } NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationItem.title = "" NSNotificationCenter.defaultCenter().removeObserver(self) } override func prepareForSegue(segue:UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == MainStoryboard.peripheralManagerServiceCharacteristicSegue { if let service = self.service { if let selectedIndex = self.tableView.indexPathForCell(sender as! UITableViewCell) { let viewController = segue.destinationViewController as! PeripheralManagerServiceCharacteristicViewController viewController.characteristic = service.characteristics[selectedIndex.row] if let peripheralManagerViewController = self.peripheralManagerViewController { viewController.peripheralManagerViewController = peripheralManagerViewController } } } } } func didResignActive() { Logger.debug() if let peripheralManagerViewController = self.peripheralManagerViewController { self.navigationController?.popToViewController(peripheralManagerViewController, animated:false) } } func didBecomeActive() { Logger.debug() } // UITableViewDataSource override func numberOfSectionsInTableView(tableView:UITableView) -> Int { return 1 } override func tableView(_:UITableView, numberOfRowsInSection section:Int) -> Int { if let service = self.service { return service.characteristics.count } else { return 0; } } override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralManagerServiceChracteristicCell, forIndexPath: indexPath) as! NameUUIDCell if let service = self.service { let characteristic = service.characteristics[indexPath.row] cell.nameLabel.text = characteristic.name cell.uuidLabel.text = characteristic.uuid.UUIDString } return cell } }
6c27924e6192a266c568d096a8b15162
37.797872
162
0.689608
false
false
false
false
russelhampton05/MenMew
refs/heads/master
App Prototypes/App_Prototype_A_001/RegisterViewController.swift
mit
1
// // RegisterViewController.swift // App_Prototype_Alpha_001 // // Created by Jon Calanio on 9/28/16. // Copyright © 2016 Jon Calanio. All rights reserved. // import UIKit import Firebase class RegisterViewController: UIViewController, UITextFieldDelegate { //IBOutlets @IBOutlet var registerLabel: UILabel! @IBOutlet var nameLabel: UILabel! @IBOutlet var emailLabel: UILabel! @IBOutlet var passwordLabel: UILabel! @IBOutlet var reenterLabel: UILabel! @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var confirmPasswordField: UITextField! @IBOutlet weak var confirmRegisterButton: UIButton! @IBOutlet var cancelButton: UIButton! @IBOutlet var nameLine: UIView! @IBOutlet var emailLine: UIView! @IBOutlet var passwordLine: UIView! @IBOutlet var reenterLine: UIView! override func viewDidLoad() { super.viewDidLoad() usernameField.delegate = self emailField.delegate = self passwordField.delegate = self confirmPasswordField.delegate = self confirmRegisterButton.isEnabled = false emailField.keyboardType = UIKeyboardType.emailAddress passwordField.isSecureTextEntry = true confirmPasswordField.isSecureTextEntry = true usernameField.autocorrectionType = UITextAutocorrectionType.no emailField.autocorrectionType = UITextAutocorrectionType.no passwordField.autocorrectionType = UITextAutocorrectionType.no confirmPasswordField.autocorrectionType = UITextAutocorrectionType.no loadTheme() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(_ textField: UITextField) -> Bool { let nextTag = textField.tag + 1 let nextResponder = textField.superview?.viewWithTag(nextTag) if nextResponder != nil { nextResponder?.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } func textFieldDidEndEditing(_ textField: UITextField) { if self.usernameField.text != "" && self.passwordField.text != "" && self.confirmPasswordField.text != "" { confirmRegisterButton.isEnabled = true } } @IBAction func registerButtonPressed(_ sender: AnyObject) { if !self.emailField.hasText || !self.usernameField.hasText || !self.passwordField.hasText { showPopup(message: "Please enter your name, email and password.", isRegister: false) } else if self.passwordField.text != self.confirmPasswordField.text { showPopup(message: "Password entries do not match.", isRegister: false) self.passwordField.text = "" self.confirmPasswordField.text = "" } else { FIRAuth.auth()?.createUser(withEmail: self.emailField.text!, password: self.passwordField.text!, completion: {(user, error) in if error == nil { //Create associated entry on Firebase let newUser = User(id: (user?.uid)!, email: (user?.email)!, name: self.usernameField.text!, ticket: nil, image: nil, theme: "Salmon", touchEnabled: true, notifications: true) UserManager.UpdateUser(user: newUser) currentUser = newUser self.emailField.text = "" self.passwordField.text = "" self.confirmPasswordField.text = "" self.showPopup(message: "Thank you for registering, " + self.usernameField.text! + "!", isRegister: true) self.usernameField.text = "" } else { self.showPopup(message: (error?.localizedDescription)!, isRegister: false) } }) } } @IBAction func cancelButtonPressed(_ sender: Any) { performSegue(withIdentifier: "UnwindToLoginSegue", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "QRScanSegue" { _ = segue.destination as! QRViewController } } func showPopup(message: String, isRegister: Bool) { let loginPopup = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Popup") as! PopupViewController if isRegister { loginPopup.register = true } self.addChildViewController(loginPopup) loginPopup.view.frame = self.view.frame self.view.addSubview(loginPopup.view) loginPopup.didMove(toParentViewController: self) loginPopup.addMessage(context: message) } func loadTheme() { currentTheme = Theme.init(type: "Salmon") UIView.animate(withDuration: 0.8, animations: { () -> Void in //Background and Tint self.view.backgroundColor = currentTheme!.primary! self.view.tintColor = currentTheme!.highlight! //Labels self.registerLabel.textColor = currentTheme!.highlight! self.emailLine.backgroundColor = currentTheme!.highlight! self.passwordLine.backgroundColor = currentTheme!.highlight! self.nameLine.backgroundColor = currentTheme!.highlight! self.reenterLine.backgroundColor = currentTheme!.highlight! self.nameLabel.textColor = currentTheme!.highlight! self.emailLabel.textColor = currentTheme!.highlight! self.passwordLabel.textColor = currentTheme!.highlight! self.reenterLabel.textColor = currentTheme!.highlight! //Fields self.usernameField.textColor = currentTheme!.highlight! self.usernameField.tintColor = currentTheme!.highlight! self.emailField.textColor = currentTheme!.highlight! self.emailField.tintColor = currentTheme!.highlight! self.passwordField.textColor = currentTheme!.highlight! self.passwordField.tintColor = currentTheme!.highlight! self.confirmPasswordField.textColor = currentTheme!.highlight! self.confirmPasswordField.tintColor = currentTheme!.highlight! //Buttons self.confirmRegisterButton.backgroundColor = currentTheme!.highlight! self.confirmRegisterButton.setTitleColor(currentTheme!.primary!, for: .normal) self.cancelButton.backgroundColor = currentTheme!.highlight! self.cancelButton.setTitleColor(currentTheme!.primary!, for: .normal) }) } }
eb036264db48d57420e5a226b07e0f4c
38.943503
194
0.625318
false
false
false
false
Sai628/NirZhihuDaily
refs/heads/master
zhihuDaily/Controllers/LaunchViewController.swift
mit
1
// // LaunchViewController.swift // zhihuDaily 2.0 // // Created by Nirvana on 10/1/15. // Copyright © 2015 NSNirvana. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class LaunchViewController: UIViewController, JSAnimatedImagesViewDataSource { @IBOutlet weak var animatedImagesView: JSAnimatedImagesView! @IBOutlet weak var text: UILabel! override func viewDidLoad() { super.viewDidLoad() //如果已有下载好的文字则使用 text.text = NSUserDefaults.standardUserDefaults().objectForKey(Keys.launchTextKey) as? String //下载下一次所需的启动页数据 Alamofire.request(.GET, "http://news-at.zhihu.com/api/4/start-image/1080*1776").responseJSON { response in guard response.response?.statusCode == 200 else { print("获取数据失败") return } //拿到text并保存 let text = JSON(response.result.value!)["text"].string! self.text.text = text NSUserDefaults.standardUserDefaults().setObject(text, forKey: Keys.launchTextKey) //拿到图像URL后取出图像并保存 let launchImageURL = JSON(response.result.value!)["img"].string! Alamofire.request(.GET, launchImageURL).responseData({ response in let imgData = response.result.value! NSUserDefaults.standardUserDefaults().setObject(imgData, forKey: Keys.launchImgKey) }) } //设置自己为JSAnimatedImagesView的数据源 animatedImagesView.dataSource = self //半透明遮罩层 let blurView = UIView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)) blurView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.45) animatedImagesView.addSubview(blurView) //渐变遮罩层 let gradientView = GradientView(frame: CGRectMake(0, self.view.frame.height / 3 * 2, self.view.frame.width, self.view.frame.height / 3 ), type: TRANSPARENT_GRADIENT_TYPE) animatedImagesView.addSubview(gradientView) //遮罩层透明度渐变 UIView.animateWithDuration(2.5) { () -> Void in blurView.backgroundColor = UIColor.clearColor() } } func animatedImagesNumberOfImages(animatedImagesView: JSAnimatedImagesView!) -> UInt { return 2 } func animatedImagesView(animatedImagesView: JSAnimatedImagesView!, imageAtIndex index: UInt) -> UIImage! { //如果已有下载好的图片则使用 if let data = NSUserDefaults.standardUserDefaults().objectForKey(Keys.launchImgKey) { return UIImage(data: data as! NSData) } return UIImage(named: "DemoLaunchImage") } /* // 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. } */ }
543c5a651c844680db01d29f78190832
35.494118
178
0.644101
false
false
false
false
e78l/swift-corelibs-foundation
refs/heads/master
TestFoundation/TestProcessInfo.swift
apache-2.0
2
// 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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // class TestProcessInfo : XCTestCase { static var allTests: [(String, (TestProcessInfo) -> () throws -> Void)] { return [ ("test_operatingSystemVersion", test_operatingSystemVersion ), ("test_processName", test_processName ), ("test_globallyUniqueString", test_globallyUniqueString ), ("test_environment", test_environment), ] } func test_operatingSystemVersion() { let processInfo = ProcessInfo.processInfo let versionString = processInfo.operatingSystemVersionString XCTAssertFalse(versionString.isEmpty) let version = processInfo.operatingSystemVersion XCTAssert(version.majorVersion != 0) #if os(Linux) || canImport(Darwin) let minVersion = OperatingSystemVersion(majorVersion: 1, minorVersion: 0, patchVersion: 0) XCTAssertTrue(processInfo.isOperatingSystemAtLeast(minVersion)) #endif } func test_processName() { // Assert that the original process name is "TestFoundation". This test // will fail if the test target ever gets renamed, so maybe it should // just test that the initial name is not empty or something? #if DARWIN_COMPATIBILITY_TESTS let targetName = "xctest" #else let targetName = "TestFoundation" #endif let processInfo = ProcessInfo.processInfo let originalProcessName = processInfo.processName XCTAssertEqual(originalProcessName, targetName, "\"\(originalProcessName)\" not equal to \"TestFoundation\"") // Try assigning a new process name. let newProcessName = "TestProcessName" processInfo.processName = newProcessName XCTAssertEqual(processInfo.processName, newProcessName, "\"\(processInfo.processName)\" not equal to \"\(newProcessName)\"") // Assign back to the original process name. processInfo.processName = originalProcessName XCTAssertEqual(processInfo.processName, originalProcessName, "\"\(processInfo.processName)\" not equal to \"\(originalProcessName)\"") } func test_globallyUniqueString() { let uuid = ProcessInfo.processInfo.globallyUniqueString let parts = uuid.components(separatedBy: "-") XCTAssertEqual(parts.count, 5) XCTAssertEqual(parts[0].utf16.count, 8) XCTAssertEqual(parts[1].utf16.count, 4) XCTAssertEqual(parts[2].utf16.count, 4) XCTAssertEqual(parts[3].utf16.count, 4) XCTAssertEqual(parts[4].utf16.count, 12) } func test_environment() { #if os(Windows) func setenv(_ key: String, _ value: String, _ overwrite: Int) -> Int32 { assert(overwrite == 1) return putenv("\(key)=\(value)") } #endif let preset = ProcessInfo.processInfo.environment["test"] setenv("test", "worked", 1) let postset = ProcessInfo.processInfo.environment["test"] XCTAssertNil(preset) XCTAssertEqual(postset, "worked") // Bad values that wont be stored XCTAssertEqual(setenv("", "", 1), -1) XCTAssertEqual(setenv("bad1=", "", 1), -1) XCTAssertEqual(setenv("bad2=", "1", 1) ,-1) XCTAssertEqual(setenv("bad3=", "=2", 1), -1) // Good values that will be, check splitting on '=' XCTAssertEqual(setenv("var1", "",1 ), 0) XCTAssertEqual(setenv("var2", "=", 1), 0) XCTAssertEqual(setenv("var3", "=x", 1), 0) XCTAssertEqual(setenv("var4", "x=", 1), 0) XCTAssertEqual(setenv("var5", "=x=", 1), 0) let env = ProcessInfo.processInfo.environment XCTAssertNil(env[""]) XCTAssertNil(env["bad1"]) XCTAssertNil(env["bad1="]) XCTAssertNil(env["bad2"]) XCTAssertNil(env["bad2="]) XCTAssertNil(env["bad3"]) XCTAssertNil(env["bad3="]) XCTAssertEqual(env["var1"], "") XCTAssertEqual(env["var2"], "=") XCTAssertEqual(env["var3"], "=x") XCTAssertEqual(env["var4"], "x=") XCTAssertEqual(env["var5"], "=x=") } }
327cdf32d8b7a0f16ba654454a2b5844
38.309735
142
0.6362
false
true
false
false
tarrgor/LctvSwift
refs/heads/master
Sources/LctvAuthViewController.swift
mit
1
// // LctvAuthViewController.swift // Pods // // // import UIKit import OAuthSwift public typealias CancelHandler = () -> () public final class LctvAuthViewController : OAuthWebViewController { var webView: UIWebView = UIWebView() var targetURL: NSURL = NSURL() var toolbar: UIToolbar = UIToolbar() var cancelItem: UIBarButtonItem? public var onCancel: CancelHandler? = nil public var toolbarTintColor: UIColor = UIColor.blackColor() { didSet { toolbar.barTintColor = toolbarTintColor } } public var cancelButtonColor: UIColor = UIColor.whiteColor() { didSet { cancelItem?.tintColor = cancelButtonColor } } public override func viewDidLoad() { super.viewDidLoad() // white status bar UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent webView.frame = self.view.bounds webView.scalesPageToFit = true webView.delegate = self webView.backgroundColor = UIColor.blackColor() view.addSubview(webView) let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.height toolbar.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 44 + statusBarHeight) toolbar.barTintColor = toolbarTintColor view.addSubview(toolbar) cancelItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(LctvAuthViewController.cancelButtonPressed(_:))) cancelItem!.tintColor = UIColor.whiteColor() toolbar.setItems([cancelItem!], animated: true) loadAddressUrl() } public override func handle(url: NSURL) { targetURL = url super.handle(url) loadAddressUrl() } func loadAddressUrl() { let req = NSURLRequest(URL: targetURL) webView.loadRequest(req) } func cancelButtonPressed(sender: UIBarButtonItem) { if let callback = onCancel { callback() } self.dismissWebViewController() } } extension LctvAuthViewController : UIWebViewDelegate { public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if let url = request.URL where (url.host == "localhost"){ self.dismissWebViewController() } return true } }
492af2a13e670916f4163c8fbb40715d
25.229885
143
0.707274
false
false
false
false
peteratseneca/dps923winter2015
refs/heads/master
Week_05/CanadaAdd/Classes/ProvinceEdit.swift
mit
1
// // ProvinceEdit.swift // Canada // // Created by Peter McIntyre on 2015-02-10. // Copyright (c) 2015 School of ICT, Seneca College. All rights reserved. // import UIKit class ProvinceEdit: UIViewController { // MARK: - Properties var delegate: EditItemDelegate? var model: Model! var detailItem: AnyObject? // MARK: - User interface @IBOutlet weak var provinceName: UITextField! @IBOutlet weak var premierName: UITextField! @IBOutlet weak var areaInKm: UITextField! @IBOutlet weak var dateCreated: UIDatePicker! // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() } // MARK: - User interface tasks // Cancel... // Call back to the delegate, do not send an object @IBAction func cancel(sender: UIBarButtonItem) { delegate?.editItemController(self, didEditItem: nil) } // Save... // Call back to the delegate, send a new object @IBAction func save(sender: UIBarButtonItem) { // In this version of the app, we are not doing any data validation // or app/business logic checks - we would add those in the future // Add a new object to the (managed object) context, and configure it let newItem = model.addNew("Province") as Province newItem.provinceName = provinceName.text newItem.premierName = premierName.text newItem.areaInKm = areaInKm.text.toInt()! newItem.dateCreated = dateCreated.date delegate?.editItemController(self, didEditItem: newItem) } } protocol EditItemDelegate { func editItemController(controller: AnyObject, didEditItem item: AnyObject?) }
6336fcd677bbc76fa98c4a981710a925
27.112903
80
0.652324
false
false
false
false
matthewcheok/JSONCodable
refs/heads/master
JSONCodableTests/PropertyItem.swift
mit
1
// // PropertyItem.swift // JSONCodable // // Created by Richard Fox on 6/19/16. // // import JSONCodable struct PropertyItem { let name: String let long: Double let lat: Double let rel: String let type: String } extension PropertyItem: JSONDecodable { init(object: JSONObject) throws { let decoder = JSONDecoder(object: object) rel = try decoder.decode("rel") type = try decoder.decode("class") name = try decoder.decode("properties.name") long = try decoder.decode("properties.location.coord.long") lat = try decoder.decode("properties.location.coord.lat") } } extension PropertyItem: JSONEncodable { func toJSON() throws -> Any { return try JSONEncoder.create { (encoder) -> Void in try encoder.encode(rel, key: "rel") try encoder.encode(type, key: "class") try encoder.encode(name, key: "properties.name") try encoder.encode(long, key: "properties.location.coord.long") try encoder.encode(lat, key: "properties.location.coord.lat") } } }
724ed36083fc74db45acb405d40d91db
26.725
75
0.629396
false
false
false
false
backslash112/DPEContainer
refs/heads/master
Example/DPEContainer/ViewController.swift
mit
1
// // ViewController.swift // DPEContainer // // Created by backslash112 on 09/18/2015. // Copyright (c) 2015 backslash112. All rights reserved. // import UIKit import DPEContainer class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let container = DPEContainer(frame: self.view.frame) container.backgroundColor = UIColor.lightGrayColor() let view1 = UIView(frame: CGRectMake(0, 0, 100, 100)) view1.backgroundColor = UIColor.redColor() container.addElement(view1) let view2 = UIView(frame: CGRectMake(0, 0, 50, 100)) view2.backgroundColor = UIColor.greenColor() container.addElement(view2) let view3 = UIView(frame: CGRectMake(0, 0, 150, 100)) view3.backgroundColor = UIColor.yellowColor() container.addElement(view3) let view4 = UIView(frame: CGRectMake(0, 0, 70, 100)) view4.backgroundColor = UIColor.blueColor() container.addElement(view4) let view5 = UIView(frame: CGRectMake(0, 0, 40, 100)) view5.backgroundColor = UIColor.yellowColor() container.addElement(view5) let view6 = UIView(frame: CGRectMake(0, 0, 80, 100)) view6.backgroundColor = UIColor.purpleColor() container.addElement(view6) let view7 = UIView(frame: CGRectMake(0, 0, 200, 100)) view7.backgroundColor = UIColor.orangeColor() container.addElement(view7) let view8 = UIView(frame: CGRectMake(0, 0, 90, 100)) view8.backgroundColor = UIColor.magentaColor() container.addElement(view8) //container.elements = [view1, view2, view3, view4, view5] self.view.addSubview(container) } }
fcb868bac08ec629839c64b6e5e1261f
32.438596
80
0.63064
false
false
false
false
Noobish1/KeyedMapper
refs/heads/master
Example/Pods/Quick/Sources/Quick/Example.swift
apache-2.0
7
import Foundation #if canImport(Darwin) @objcMembers public class _ExampleBase: NSObject {} #else public class _ExampleBase: NSObject {} #endif /** Examples, defined with the `it` function, use assertions to demonstrate how code should behave. These are like "tests" in XCTest. */ final public class Example: _ExampleBase { /** A boolean indicating whether the example is a shared example; i.e.: whether it is an example defined with `itBehavesLike`. */ public var isSharedExample = false /** The site at which the example is defined. This must be set correctly in order for Xcode to highlight the correct line in red when reporting a failure. */ public var callsite: Callsite weak internal var group: ExampleGroup? private let internalDescription: String private let closure: () -> Void private let flags: FilterFlags internal init(description: String, callsite: Callsite, flags: FilterFlags, closure: @escaping () -> Void) { self.internalDescription = description self.closure = closure self.callsite = callsite self.flags = flags } public override var description: String { return internalDescription } /** The example name. A name is a concatenation of the name of the example group the example belongs to, followed by the description of the example itself. The example name is used to generate a test method selector to be displayed in Xcode's test navigator. */ public var name: String { guard let groupName = group?.name else { return description } return "\(groupName), \(description)" } /** Executes the example closure, as well as all before and after closures defined in the its surrounding example groups. */ public func run() { let world = World.sharedWorld if world.numberOfExamplesRun == 0 { world.suiteHooks.executeBefores() } let exampleMetadata = ExampleMetadata(example: self, exampleIndex: world.numberOfExamplesRun) world.currentExampleMetadata = exampleMetadata defer { world.currentExampleMetadata = nil } world.exampleHooks.executeBefores(exampleMetadata) group!.phase = .beforesExecuting for before in group!.befores { before(exampleMetadata) } group!.phase = .beforesFinished closure() group!.phase = .aftersExecuting for after in group!.afters { after(exampleMetadata) } group!.phase = .aftersFinished world.exampleHooks.executeAfters(exampleMetadata) world.numberOfExamplesRun += 1 if !world.isRunningAdditionalSuites && world.numberOfExamplesRun >= world.cachedIncludedExampleCount { world.suiteHooks.executeAfters() } } /** Evaluates the filter flags set on this example and on the example groups this example belongs to. Flags set on the example are trumped by flags on the example group it belongs to. Flags on inner example groups are trumped by flags on outer example groups. */ internal var filterFlags: FilterFlags { var aggregateFlags = flags for (key, value) in group!.filterFlags { aggregateFlags[key] = value } return aggregateFlags } } extension Example { /** Returns a boolean indicating whether two Example objects are equal. If two examples are defined at the exact same callsite, they must be equal. */ @nonobjc public static func == (lhs: Example, rhs: Example) -> Bool { return lhs.callsite == rhs.callsite } }
7c625aac3ac4be155607feaf48375972
30.280992
111
0.652048
false
false
false
false
Sticky-Gerbil/furry-adventure
refs/heads/master
FurryAdventure/API/SpoonacularApiClient.swift
apache-2.0
1
//// //// SpoonacularApiClient.swift //// FurryAdventure //// //// Created by Edwin Young on 3/27/17. //// Copyright © 2017 Sticky Gerbils. All rights reserved. //// // //import UIKit //import AFNetworking // //class SpoonacularApiClient: RecipeApiClient, RecipeApiProtocol { // // static let shared = SpoonacularApiClient(baseUrlString: "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes", key: "SpoonacularKey", app: nil) // // override init(baseUrlString: String!, key: String!, app: String?) { // super.init(baseUrlString: baseUrlString, key: key, app: app) // // EP_RECIPES_SEARCH = "/findByIngredients" // EP_RECIPE_SEARCH = "/information" // } // // // API requests to Spoonacular API require HTTP headers instead of passing via query string; specifically // // X-Mashape-Key: ${SPOONACULAR_KEY} // // Accept: application/json // func findRecipes(by ingredients: [Ingredient]?) -> [Recipe]? { // // Modify request headers for API calls // let requestSerializer = AFNetworking.AFHTTPRequestSerializer() // requestSerializer.setValue(apiKey!, forHTTPHeaderField: "X-Mashape-Key") // requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept") // // // Set up API endpoint calls & query string params // var urlString = apiUrlString + EP_RECIPES_SEARCH + "?"; // var params = [ // "fillIngredients": "false", // "limitLicense": "false", // "number": "10", // "ranking": "2" // this is to minimize the number of missing ingredients // ] // // // API takes the ingredients as a list of comma separated values // if ingredients != nil && ingredients!.count >= 1 { // params["ingredients"] = ingredients![0].name // for i in 1..<ingredients!.count { // params["ingredients"] = params["ingredients"]! + "," + ingredients![i].name // } // } else { // return nil // } // // // Create & URL encode the ingredients values // var queryString = "" // for (key, value) in params { // queryString = queryString + "\(key)=\(value)&" // } // queryString = queryString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! // urlString = urlString + queryString // // // Call the API endpoint // let request = requestSerializer.request(withMethod: "GET", urlString: urlString, parameters: nil, error: nil) // let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main) // let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data: Data?, response: URLResponse?, error: Error?) in // if let data = data { // if let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary { // print(dataDictionary) // // // Can't even run this bit of code // // Maybe look into this? Would bypass AFNetworking.AFHTTPRequestSerializer entirely // // http://stackoverflow.com/a/37245658 // } // } // } // task.resume() // } // // func findRecipe(by id: String!) -> Recipe? { // let requestSerializer = AFNetworking.AFHTTPRequestSerializer() // requestSerializer.setValue(apiKey!, forHTTPHeaderField: "X-Mashape-Key") // requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept") // // // Set up API endpoint calls // var urlString = apiUrlString + "/" + id + EP_RECIPES_SEARCH; // // // Call the API endpoint // let request = requestSerializer.request(withMethod: "GET", urlString: urlString, parameters: nil, error: nil) // let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main) // let task: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data: Data?, response: URLResponse?, error: Error?) in // if let data = data { // if let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary { // print(dataDictionary) // // // Can't even run this bit of code // } // } // } // task.resume() // // return nil // } // // // //}
c5474b1a837144dec20377924c1194e6
37.834951
161
0.674
false
false
false
false
artyom-stv/TextInputKit
refs/heads/develop
TextInputKit/TextInputKit/Code/TextInputFormat/TextInputFormat+Filter.swift
mit
1
// // TextInputFormat+Filter.swift // TextInputKit // // Created by Artem Starosvetskiy on 24/11/2016. // Copyright © 2016 Artem Starosvetskiy. All rights reserved. // import Foundation public extension TextInputFormat { typealias FilterPredicate = TextInputFormatterType.FilterPredicate /// Creates a `TextInputFormat` which filters the output of the source formatter /// (the formatter of the callee format). /// /// - Parameters: /// - predicate: The predicate which is used to filter the output of the source formatter. /// - Returns: The created `TextInputFormat`. func filter(_ predicate: @escaping FilterPredicate) -> TextInputFormat<Value> { return TextInputFormat.from( serializer, formatter.filter(predicate)) } } public extension TextInputFormat { /// Creates a `TextInputFormat` with a formatter which rejects the output of the source formatter /// (the formatter of the callee format) if the output contains characters out of the `characterSet`. /// /// - Parameters: /// - characterSet: The character set which is used to filter the output of the source formatter. /// - Returns: The created `TextInputFormat`. func filter(by characterSet: CharacterSet) -> TextInputFormat<Value> { let invertedCharacterSet = characterSet.inverted return filter { string in return string.rangeOfCharacter(from: invertedCharacterSet) == nil } } /// Creates a `TextInputFormat` with a formatter which rejects the output of the source formatter /// (the formatter of the callee format) if the output exceeds the `maxCharactersCount` limit. /// /// - Parameters: /// - maxCharactersCount: The maximum characters count which is used to filter the output of the source formatter. /// - Returns: The created `TextInputFormat`. func filter(constrainingCharactersCount maxCharactersCount: Int) -> TextInputFormat<Value> { return filter { string in return (string.count <= maxCharactersCount) } } }
986e2cfed7290991de878824ec353586
34.516667
120
0.679962
false
false
false
false
zapdroid/RXWeather
refs/heads/master
Pods/RxSwift/RxSwift/Observables/Implementations/GroupBy.swift
mit
1
// // GroupBy.swift // RxSwift // // Created by Tomi Koskinen on 01/12/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // final class GroupedObservableImpl<Key, Element>: Observable<Element> { private var _subject: PublishSubject<Element> private var _refCount: RefCountDisposable init(key _: Key, subject: PublishSubject<Element>, refCount: RefCountDisposable) { _subject = subject _refCount = refCount } public override func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E { let release = _refCount.retain() let subscription = _subject.subscribe(observer) return Disposables.create(release, subscription) } } final class GroupBySink<Key: Hashable, Element, O: ObserverType> : Sink<O> , ObserverType where O.E == GroupedObservable<Key, Element> { typealias E = Element typealias ResultType = O.E typealias Parent = GroupBy<Key, Element> private let _parent: Parent private let _subscription = SingleAssignmentDisposable() private var _refCountDisposable: RefCountDisposable! private var _groupedSubjectTable: [Key: PublishSubject<Element>] init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent _groupedSubjectTable = [Key: PublishSubject<Element>]() super.init(observer: observer, cancel: cancel) } func run() -> Disposable { _refCountDisposable = RefCountDisposable(disposable: _subscription) _subscription.setDisposable(_parent._source.subscribe(self)) return _refCountDisposable } private func onGroupEvent(key: Key, value: Element) { if let writer = _groupedSubjectTable[key] { writer.on(.next(value)) } else { let writer = PublishSubject<Element>() _groupedSubjectTable[key] = writer let group = GroupedObservable( key: key, source: GroupedObservableImpl(key: key, subject: writer, refCount: _refCountDisposable) ) forwardOn(.next(group)) writer.on(.next(value)) } } final func on(_ event: Event<Element>) { switch event { case let .next(value): do { let groupKey = try _parent._selector(value) onGroupEvent(key: groupKey, value: value) } catch let e { error(e) return } case let .error(e): error(e) case .completed: forwardOnGroups(event: .completed) forwardOn(.completed) _subscription.dispose() dispose() } } final func error(_ error: Swift.Error) { forwardOnGroups(event: .error(error)) forwardOn(.error(error)) _subscription.dispose() dispose() } final func forwardOnGroups(event: Event<Element>) { for writer in _groupedSubjectTable.values { writer.on(event) } } } final class GroupBy<Key: Hashable, Element>: Producer<GroupedObservable<Key, Element>> { typealias KeySelector = (Element) throws -> Key fileprivate let _source: Observable<Element> fileprivate let _selector: KeySelector init(source: Observable<Element>, selector: @escaping KeySelector) { _source = source _selector = selector } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == GroupedObservable<Key, Element> { let sink = GroupBySink(parent: self, observer: observer, cancel: cancel) return (sink: sink, subscription: sink.run()) } }
3a8b35e0a908deef91dce339bd01dbca
30.880342
168
0.621448
false
false
false
false
EclipseSoundscapes/EclipseSoundscapes
refs/heads/master
Example/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift
apache-2.0
6
// // AsMaybe.swift // RxSwift // // Created by Krunoslav Zaher on 3/12/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // private final class AsMaybeSink<Observer: ObserverType> : Sink<Observer>, ObserverType { typealias Element = Observer.Element private var _element: Event<Element>? func on(_ event: Event<Element>) { switch event { case .next: if self._element != nil { self.forwardOn(.error(RxError.moreThanOneElement)) self.dispose() } self._element = event case .error: self.forwardOn(event) self.dispose() case .completed: if let element = self._element { self.forwardOn(element) } self.forwardOn(.completed) self.dispose() } } } final class AsMaybe<Element>: Producer<Element> { private let _source: Observable<Element> init(source: Observable<Element>) { self._source = source } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = AsMaybeSink(observer: observer, cancel: cancel) let subscription = self._source.subscribe(sink) return (sink: sink, subscription: subscription) } }
107ef3636b79cae6fd5c22f3eba8b4cb
28.291667
171
0.602418
false
false
false
false
humblehacker/BarFun
refs/heads/master
BarFun/FunViewController.swift
mit
1
// // FunViewController.swift // BarFun // // Created by David Whetstone on 1/11/16. // Copyright (c) 2016 humblehacker. All rights reserved. // import UIKit class FunViewController: UIViewController { override func viewDidLoad() { title = "BarFun" view.backgroundColor = UIColor.redColor() view.layer.borderColor = UIColor.blackColor().CGColor view.layer.borderWidth = 2.0 navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Present", style: .Plain, target: self, action: "present") navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Dismiss", style: .Plain, target: self, action: "dismiss") addCenterView() } func addCenterView() { let centerView = UIView() centerView.backgroundColor = UIColor.orangeColor() view.addSubview(centerView) centerView.snp_makeConstraints { make in make.edges.equalTo(self.view).inset(UIEdgeInsetsMake(10, 10, 10, 10)) } } func present() { let nc = UINavigationController(rootViewController: FunViewController()) presentViewController(nc, animated: true, completion: nil) } func dismiss() { dismissViewControllerAnimated(true, completion: nil) } }
494ad083ed2e3058b3c892e4a54e8c4b
25.16
125
0.648318
false
false
false
false
abunur/quran-ios
refs/heads/master
Quran/TranslationPageLayoutOperation.swift
gpl-3.0
2
// // TranslationPageLayoutOperation.swift // Quran // // Created by Mohamed Afifi on 4/1/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import PromiseKit import UIKit class TranslationPageLayoutOperation: AbstractPreloadingOperation<TranslationPageLayout> { let page: TranslationPage let width: CGFloat init(request: TranslationPageLayoutRequest) { self.page = request.page self.width = request.width - Layout.Translation.horizontalInset * 2 } override func main() { autoreleasepool { let verseLayouts = page.verses.map { verse -> TranslationVerseLayout in let arabicPrefixLayouts = verse.arabicPrefix.map { arabicLayoutFrom($0) } let arabicSuffixLayouts = verse.arabicSuffix.map { arabicLayoutFrom($0) } return TranslationVerseLayout(ayah: verse.ayah, arabicTextLayout: arabicLayoutFrom(verse.arabicText), translationLayouts: verse.translations.map { translationTextLayoutFrom($0) }, arabicPrefixLayouts: arabicPrefixLayouts, arabicSuffixLayouts: arabicSuffixLayouts) } let pageLayout = TranslationPageLayout(pageNumber: page.pageNumber, verseLayouts: verseLayouts) fulfill(pageLayout) } } private func arabicLayoutFrom(_ text: String) -> TranslationArabicTextLayout { let size = text.size(withFont: .translationArabicQuranText, constrainedToWidth: width) return TranslationArabicTextLayout(arabicText: text, size: size) } private func translationTextLayoutFrom(_ text: TranslationText) -> TranslationTextLayout { let translatorSize = text.translation.translationName.size(withFont: text.translation.preferredTranslatorNameFont, constrainedToWidth: width) if text.isLongText { return longTranslationTextLayoutFrom(text, translatorSize: translatorSize) } else { return shortTranslationTextLayoutFrom(text, translatorSize: translatorSize) } } private func shortTranslationTextLayoutFrom(_ text: TranslationText, translatorSize: CGSize) -> TranslationTextLayout { let size = text.attributedText.stringSize(constrainedToWidth: width) return TranslationTextLayout(text: text, size: size, longTextLayout: nil, translatorSize: translatorSize) } private func longTranslationTextLayoutFrom(_ text: TranslationText, translatorSize: CGSize) -> TranslationTextLayout { // create the main objects let layoutManager = NSLayoutManager() let textContainer = NSTextContainer(size: CGSize(width: width, height: .infinity)) textContainer.lineFragmentPadding = 0 let textStorage = NSTextStorage(attributedString: text.attributedText) // connect the objects together textStorage.addLayoutManager(layoutManager) layoutManager.addTextContainer(textContainer) // get number of glyphs let numberOfGlyphs = layoutManager.numberOfGlyphs let range = NSRange(location: 0, length: numberOfGlyphs) // get the size in screen let bounds = layoutManager.boundingRect(forGlyphRange: range, in: textContainer) let size = CGSize(width: width, height: ceil(bounds.height)) let textLayout = LongTranslationTextLayout(textContainer: textContainer, numberOfGlyphs: numberOfGlyphs) return TranslationTextLayout(text: text, size: size, longTextLayout: textLayout, translatorSize: translatorSize) } }
d68e18e9886bbe82ca53282227ed97cd
44.641304
149
0.699929
false
false
false
false
crspybits/SyncServerII
refs/heads/dev
Sources/Server/Database/Repositories.swift
mit
1
// // Repositories.swift // Server // // Created by Christopher Prince on 2/7/17. // // import Foundation struct Repositories { let db: Database lazy var user = UserRepository(db) lazy var masterVersion = MasterVersionRepository(db) lazy var fileIndex = FileIndexRepository(db) lazy var upload = UploadRepository(db) lazy var deviceUUID = DeviceUUIDRepository(db) lazy var sharing = SharingInvitationRepository(db) lazy var sharingGroup = SharingGroupRepository(db) lazy var sharingGroupUser = SharingGroupUserRepository(db) init(db: Database) { self.db = db } }
e012649567d82ff9de64f67f5adba3c6
23.230769
62
0.698413
false
false
false
false
spacedrabbit/100-days
refs/heads/master
masks.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit import CoreGraphics var str = "Hello, playground" func drawARect() -> UIView { let view: UIView = UIView(frame: CGRectMake(0.0, 0.0, 100.0, 200.0)) view.backgroundColor = UIColor.yellowColor() let interiorView: UIView = UIView(frame: CGRectInset(view.frame, 10.0, 10.0)) interiorView.backgroundColor = UIColor.redColor() view.addSubview(interiorView) let bezier: UIBezierPath = getSomeCurves() let mask: CAShapeLayer = makeTheMask(forPath: bezier) // interiorView.layer.addSublayer(mask) return view } func getSomeCurves() -> UIBezierPath { let transparentFrame: CGRect = CGRectMake(5.0, 5.0, 20.0, 50.0) let maskLayerPathBase: UIBezierPath = UIBezierPath(roundedRect: transparentFrame, cornerRadius: 5.0) let maskLayerPathDefined: UIBezierPath = UIBezierPath(roundedRect: CGRectInset(transparentFrame, 4.0, 4.0), cornerRadius: 4.0) maskLayerPathBase.appendPath(maskLayerPathDefined) return maskLayerPathBase } func makeTheMask(forPath path: UIBezierPath) -> CAShapeLayer { let transparentFrameLocation = path.bounds let maskLayer: CAShapeLayer = CAShapeLayer() maskLayer.bounds = transparentFrameLocation maskLayer.frame = transparentFrameLocation maskLayer.path = path.CGPath maskLayer.backgroundColor = UIColor.whiteColor().CGColor maskLayer.fillRule = kCAFillRuleEvenOdd return maskLayer } let rects: UIView = drawARect()
c125263b4c8f3ee67f3f525cbc22c453
28.36
128
0.756812
false
false
false
false
material-motion/material-motion-swift
refs/heads/develop
Pods/MaterialMotion/src/operators/gestures/scaled.swift
apache-2.0
2
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. 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 import UIKit extension MotionObservableConvertible where T: UIPinchGestureRecognizer { /** Multiplies the current scale by the initial scale and emits the result while the gesture recognizer is active. */ func scaled<O: MotionObservableConvertible>(from initialScale: O) -> MotionObservable<CGFloat> where O.T == CGFloat { var cachedInitialScale: CGFloat? var lastInitialScale: CGFloat? return MotionObservable { observer in let initialScaleSubscription = initialScale.subscribeToValue { lastInitialScale = $0 } let upstreamSubscription = self.subscribeAndForward(to: observer) { value in if value.state == .began || (value.state == .changed && cachedInitialScale == nil) { cachedInitialScale = lastInitialScale } else if value.state != .began && value.state != .changed { cachedInitialScale = nil } if let cachedInitialScale = cachedInitialScale { let scale = value.scale observer.next(cachedInitialScale * scale) } } return { upstreamSubscription.unsubscribe() initialScaleSubscription.unsubscribe() } } } }
207b83975ecdf6b99b32a1c58ff9bc3f
33.692308
119
0.714523
false
false
false
false
multinerd/Mia
refs/heads/master
Mia/Testing/Material/MaterialColorGroupWithAccents.swift
mit
1
// // MaterialColorGroupWithAccents.swift // Mia // // Created by Michael Hedaitulla on 8/2/18. // import Foundation open class MaterialColorGroupWithAccents: MaterialColorGroup { open let A100: MaterialColor open let A200: MaterialColor open let A400: MaterialColor open let A700: MaterialColor open var accents: [MaterialColor] { return [A100, A200, A400, A700] } open override var hashValue: Int { return super.hashValue + accents.reduce(0) { $0 + $1.hashValue } } open override var endIndex: Int { return colors.count + accents.count } open override subscript(i: Int) -> MaterialColor { return (colors + accents)[i] } internal init(name: String, _ P50: MaterialColor, _ P100: MaterialColor, _ P200: MaterialColor, _ P300: MaterialColor, _ P400: MaterialColor, _ P500: MaterialColor, _ P600: MaterialColor, _ P700: MaterialColor, _ P800: MaterialColor, _ P900: MaterialColor, _ A100: MaterialColor, _ A200: MaterialColor, _ A400: MaterialColor, _ A700: MaterialColor ) { self.A100 = A100 self.A200 = A200 self.A400 = A400 self.A700 = A700 super.init(name: name, P50, P100, P200, P300, P400, P500, P600, P700, P800, P900) } open override func colorForName(_ name: String) -> MaterialColor? { return (colors + accents).filter { $0.name == name}.first } } func ==(lhs: MaterialColorGroupWithAccents, rhs: MaterialColorGroupWithAccents) -> Bool { return (lhs as MaterialColorGroup) == (rhs as MaterialColorGroup) && lhs.accents == rhs.accents }
66f93fa354de1c22ce4e0020d0efbec3
29.174603
89
0.56181
false
false
false
false
ahayman/RxStream
refs/heads/master
RxStreamTests/StreamProcessorTests.swift
mit
1
// // StreamProcessorTests.swift // RxStream // // Created by Aaron Hayman on 4/21/17. // Copyright © 2017 Aaron Hayman. All rights reserved. // import XCTest @testable import Rx class StreamProcessorTests: XCTestCase { func testProcessorDoNothing() { let processor = StreamProcessor<Int>(stream: HotInput<Int>()) processor.process(next: .next(1), withKey: .share) XCTAssertTrue(true) } func testDownStreamProcessorStreamVariable() { let stream = HotInput<Int>() let processor = DownstreamProcessor<Int, Int>(stream: stream) { _, _ in } XCTAssertEqual(stream.id, (processor.stream as! Hot<Int>).id) } func testDownStreamProcessorWork() { var events = [Event<Int>]() let stream = HotInput<Int>() let processor = DownstreamProcessor<Int, Int>(stream: stream) { event, _ in events.append(event) } processor.process(next: .next(0), withKey: .share) XCTAssertEqual(events.count, 1) processor.process(next: .next(0), withKey: .share) XCTAssertEqual(events.count, 2) } }
f2e717ee8fa7f616de22162c9e3be661
24.047619
79
0.681559
false
true
false
false
kstaring/swift
refs/heads/upstream-master
test/expr/expressions.swift
apache-2.0
1
// RUN: %target-parse-verify-swift //===----------------------------------------------------------------------===// // Tests and samples. //===----------------------------------------------------------------------===// // Comment. With unicode characters: ¡ç®åz¥! func markUsed<T>(_: T) {} // Various function types. var func1 : () -> () // No input, no output. var func2 : (Int) -> Int var func3 : () -> () -> () // Takes nothing, returns a fn. var func3a : () -> (() -> ()) // same as func3 var func6 : (_ fn : (Int,Int) -> Int) -> () // Takes a fn, returns nothing. var func7 : () -> (Int,Int,Int) // Takes nothing, returns tuple. // Top-Level expressions. These are 'main' content. func1() _ = 4+7 var bind_test1 : () -> () = func1 var bind_test2 : Int = 4; func1 // expected-error {{expression resolves to an unused l-value}} (func1, func2) // expected-error {{expression resolves to an unused l-value}} func basictest() { // Simple integer variables. var x : Int var x2 = 4 // Simple Type inference. var x3 = 4+x*(4+x2)/97 // Basic Expressions. // Declaring a variable Void, aka (), is fine too. var v : Void var x4 : Bool = true var x5 : Bool = 4 // expected-error {{cannot convert value of type 'Int' to specified type 'Bool'}} //var x6 : Float = 4+5 var x7 = 4; 5 // expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}} // Test implicit conversion of integer literal to non-Int64 type. var x8 : Int8 = 4 x8 = x8 + 1 _ = x8 + 1 _ = 0 + x8 1.0 + x8 // expected-error{{binary operator '+' cannot be applied to operands of type 'Double' and 'Int8'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}} var x9 : Int16 = x8 + 1 // expected-error {{cannot convert value of type 'Int8' to specified type 'Int16'}} // Various tuple types. var tuple1 : () var tuple2 : (Int) var tuple3 : (Int, Int, ()) var tuple2a : (a : Int) // expected-error{{cannot create a single-element tuple with an element label}}{{18-22=}} var tuple3a : (a : Int, b : Int, c : ()) var tuple4 = (1, 2) // Tuple literal. var tuple5 = (1, 2, 3, 4) // Tuple literal. var tuple6 = (1 2) // expected-error {{expected ',' separator}} {{18-18=,}} // Brace expressions. var brace3 = { var brace2 = 42 // variable shadowing. _ = brace2+7 } // Function calls. var call1 : () = func1() var call2 = func2(1) var call3 : () = func3()() // Cannot call an integer. bind_test2() // expected-error {{cannot call value of non-function type 'Int'}}{{13-15=}} } // Infix operators and attribute lists. infix operator %% : MinPrecedence precedencegroup MinPrecedence { associativity: left lowerThan: AssignmentPrecedence } func %%(a: Int, b: Int) -> () {} var infixtest : () = 4 % 2 + 27 %% 123 // The 'func' keyword gives a nice simplification for function definitions. func funcdecl1(_ a: Int, _ y: Int) {} func funcdecl2() { return funcdecl1(4, 2) } func funcdecl3() -> Int { return 12 } func funcdecl4(_ a: ((Int) -> Int), b: Int) {} func signal(_ sig: Int, f: (Int) -> Void) -> (Int) -> Void {} // Doing fun things with named arguments. Basic stuff first. func funcdecl6(_ a: Int, b: Int) -> Int { return a+b } // Can dive into tuples, 'b' is a reference to a whole tuple, c and d are // fields in one. Cannot dive into functions or through aliases. func funcdecl7(_ a: Int, b: (c: Int, d: Int), third: (c: Int, d: Int)) -> Int { _ = a + b.0 + b.c + third.0 + third.1 b.foo // expected-error {{value of tuple type '(c: Int, d: Int)' has no member 'foo'}} } // Error recovery. func testfunc2 (_: (((), Int)) -> Int) -> Int {} func errorRecovery() { testfunc2({ $0 + 1 }) // expected-error {{binary operator '+' cannot be applied to operands of type '((), Int)' and 'Int'}} expected-note {{expected an argument list of type '(Int, Int)'}} enum union1 { case bar case baz } var a: Int = .hello // expected-error {{type 'Int' has no member 'hello'}} var b: union1 = .bar // ok var c: union1 = .xyz // expected-error {{type 'union1' has no member 'xyz'}} var d: (Int,Int,Int) = (1,2) // expected-error {{cannot convert value of type '(Int, Int)' to specified type '(Int, Int, Int)'}} var e: (Int,Int) = (1, 2, 3) // expected-error {{cannot convert value of type '(Int, Int, Int)' to specified type '(Int, Int)'}} var f: (Int,Int) = (1, 2, f : 3) // expected-error {{cannot convert value of type '(Int, Int, f: Int)' to specified type '(Int, Int)'}} // <rdar://problem/22426860> CrashTracer: [USER] swift at …mous_namespace::ConstraintGenerator::getTypeForPattern + 698 var (g1, g2, g3) = (1, 2) // expected-error {{'(Int, Int)' is not convertible to '(_, _, _)', tuples have a different number of elements}} } func acceptsInt(_ x: Int) {} acceptsInt(unknown_var) // expected-error {{use of unresolved identifier 'unknown_var'}} var test1a: (Int) -> (Int) -> Int = { { $0 } } // expected-error{{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{38-38= _ in}} var test1b = { 42 } var test1c = { { 42 } } var test1d = { { { 42 } } } func test2(_ a: Int, b: Int) -> (c: Int) { // expected-error{{cannot create a single-element tuple with an element label}} {{34-37=}} expected-note {{did you mean 'a'?}} expected-note {{did you mean 'b'?}} _ = a+b a+b+c // expected-error{{use of unresolved identifier 'c'}} return a+b } func test3(_ arg1: Int, arg2: Int) -> Int { return 4 } func test4() -> ((_ arg1: Int, _ arg2: Int) -> Int) { return test3 } func test5() { let a: (Int, Int) = (1,2) var _: ((Int) -> Int, Int) = a // expected-error {{cannot convert value of type '(Int, Int)' to specified type '((Int) -> Int, Int)'}} let c: (a: Int, b: Int) = (1,2) let _: (b: Int, a: Int) = c // Ok, reshuffle tuple. } // Functions can obviously take and return values. func w3(_ a: Int) -> Int { return a } func w4(_: Int) -> Int { return 4 } func b1() {} func foo1(_ a: Int, b: Int) -> Int {} func foo2(_ a: Int) -> (_ b: Int) -> Int {} func foo3(_ a: Int = 2, b: Int = 3) {} prefix operator ^^ prefix func ^^(a: Int) -> Int { return a + 1 } func test_unary1() { var x: Int x = ^^(^^x) x = *x // expected-error {{'*' is not a prefix unary operator}} x = x* // expected-error {{'*' is not a postfix unary operator}} x = +(-x) x = + -x // expected-error {{unary operator cannot be separated from its operand}} {{8-9=}} } func test_unary2() { var x: Int // FIXME: second diagnostic is redundant. x = &; // expected-error {{expected expression after unary operator}} expected-error {{expected expression in assignment}} } func test_unary3() { var x: Int // FIXME: second diagnostic is redundant. x = &, // expected-error {{expected expression after unary operator}} expected-error {{expected expression in assignment}} } func test_as_1() { var _: Int } func test_as_2() { let x: Int = 1 x as [] // expected-error {{expected element type}} } func test_lambda() { // A simple closure. var a = { (value: Int) -> () in markUsed(value+1) } // A recursive lambda. // FIXME: This should definitely be accepted. var fib = { (n: Int) -> Int in if (n < 2) { return n } return fib(n-1)+fib(n-2) // expected-error 2 {{variable used within its own initial value}} } } func test_lambda2() { { () -> protocol<Int> in // expected-warning @-1 {{'protocol<...>' composition syntax is deprecated and not needed here}} {{11-24=Int}} // expected-error @-2 {{non-protocol type 'Int' cannot be used within a protocol composition}} // expected-warning @-3 {{result of call is unused}} return 1 }() } func test_floating_point() { _ = 0.0 _ = 100.1 var _: Float = 0.0 var _: Double = 0.0 } func test_nonassoc(_ x: Int, y: Int) -> Bool { // FIXME: the second error and note here should arguably disappear return x == y == x // expected-error {{adjacent operators are in non-associative precedence group 'ComparisonPrecedence'}} expected-error {{binary operator '==' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{overloads for '==' exist with these partially matching parameter lists:}} } // More realistic examples. func fib(_ n: Int) -> Int { if (n < 2) { return n } return fib(n-2) + fib(n-1) } //===----------------------------------------------------------------------===// // Integer Literals //===----------------------------------------------------------------------===// // FIXME: Should warn about integer constants being too large <rdar://problem/14070127> var il_a: Bool = 4 // expected-error {{cannot convert value of type 'Int' to specified type 'Bool'}} var il_b: Int8 = 123123 var il_c: Int8 = 4 // ok struct int_test4 : ExpressibleByIntegerLiteral { typealias IntegerLiteralType = Int init(integerLiteral value: Int) {} // user type. } var il_g: int_test4 = 4 // This just barely fits in Int64. var il_i: Int64 = 18446744073709551615 // This constant is too large to fit in an Int64, but it is fine for Int128. // FIXME: Should warn about the first. <rdar://problem/14070127> var il_j: Int64 = 18446744073709551616 // var il_k: Int128 = 18446744073709551616 var bin_literal: Int64 = 0b100101 var hex_literal: Int64 = 0x100101 var oct_literal: Int64 = 0o100101 // verify that we're not using C rules var oct_literal_test: Int64 = 0123 assert(oct_literal_test == 123) // ensure that we swallow random invalid chars after the first invalid char var invalid_num_literal: Int64 = 0QWERTY // expected-error{{expected a digit after integer literal prefix}} var invalid_bin_literal: Int64 = 0bQWERTY // expected-error{{expected a digit after integer literal prefix}} var invalid_hex_literal: Int64 = 0xQWERTY // expected-error{{expected a digit after integer literal prefix}} var invalid_oct_literal: Int64 = 0oQWERTY // expected-error{{expected a digit after integer literal prefix}} var invalid_exp_literal: Double = 1.0e+QWERTY // expected-error{{expected a digit in floating point exponent}} // rdar://11088443 var negative_int32: Int32 = -1 // <rdar://problem/11287167> var tupleelemvar = 1 markUsed((tupleelemvar, tupleelemvar).1) func int_literals() { // Fits exactly in 64-bits - rdar://11297273 _ = 1239123123123123 // Overly large integer. // FIXME: Should warn about it. <rdar://problem/14070127> _ = 123912312312312312312 } // <rdar://problem/12830375> func tuple_of_rvalues(_ a:Int, b:Int) -> Int { return (a, b).1 } extension Int { func testLexingMethodAfterIntLiteral() {} func _0() {} // Hex letters func ffa() {} // Hex letters + non hex. func describe() {} // Hex letters + 'p'. func eap() {} // Hex letters + 'p' + non hex. func fpValue() {} } 123.testLexingMethodAfterIntLiteral() 0b101.testLexingMethodAfterIntLiteral() 0o123.testLexingMethodAfterIntLiteral() 0x1FFF.testLexingMethodAfterIntLiteral() 123._0() 0b101._0() 0o123._0() 0x1FFF._0() 0x1fff.ffa() 0x1FFF.describe() 0x1FFF.eap() 0x1FFF.fpValue() var separator1: Int = 1_ var separator2: Int = 1_000 var separator4: Int = 0b1111_0000_ var separator5: Int = 0b1111_0000 var separator6: Int = 0o127_777_ var separator7: Int = 0o127_777 var separator8: Int = 0x12FF_FFFF var separator9: Int = 0x12FF_FFFF_ //===----------------------------------------------------------------------===// // Float Literals //===----------------------------------------------------------------------===// var fl_a = 0.0 var fl_b: Double = 1.0 var fl_c: Float = 2.0 // FIXME: crummy diagnostic var fl_d: Float = 2.0.0 // expected-error {{expected named member of numeric literal}} var fl_e: Float = 1.0e42 var fl_f: Float = 1.0e+ // expected-error {{expected a digit in floating point exponent}} var fl_g: Float = 1.0E+42 var fl_h: Float = 2e-42 var vl_i: Float = -.45 // expected-error {{'.45' is not a valid floating point literal; it must be written '0.45'}} {{20-20=0}} var fl_j: Float = 0x1p0 var fl_k: Float = 0x1.0p0 var fl_l: Float = 0x1.0 // expected-error {{hexadecimal floating point literal must end with an exponent}} var fl_m: Float = 0x1.FFFFFEP-2 var fl_n: Float = 0x1.fffffep+2 var fl_o: Float = 0x1.fffffep+ // expected-error {{expected a digit in floating point exponent}} var fl_p: Float = 0x1p // expected-error {{expected a digit in floating point exponent}} var fl_q: Float = 0x1p+ // expected-error {{expected a digit in floating point exponent}} var fl_r: Float = 0x1.0fp // expected-error {{expected a digit in floating point exponent}} var fl_s: Float = 0x1.0fp+ // expected-error {{expected a digit in floating point exponent}} var fl_t: Float = 0x1.p // expected-error {{value of type 'Int' has no member 'p'}} var fl_u: Float = 0x1.p2 // expected-error {{value of type 'Int' has no member 'p2'}} var fl_v: Float = 0x1.p+ // expected-error {{'+' is not a postfix unary operator}} var fl_w: Float = 0x1.p+2 // expected-error {{value of type 'Int' has no member 'p'}} var if1: Double = 1.0 + 4 // integer literal ok as double. var if2: Float = 1.0 + 4 // integer literal ok as float. var fl_separator1: Double = 1_.2_ var fl_separator2: Double = 1_000.2_ var fl_separator3: Double = 1_000.200_001 var fl_separator4: Double = 1_000.200_001e1_ var fl_separator5: Double = 1_000.200_001e1_000 var fl_separator6: Double = 1_000.200_001e1_000 var fl_separator7: Double = 0x1_.0FFF_p1_ var fl_separator8: Double = 0x1_0000.0FFF_ABCDp10_001 var fl_bad_separator1: Double = 1e_ // expected-error {{expected a digit in floating point exponent}} var fl_bad_separator2: Double = 0x1p_ // expected-error {{expected a digit in floating point exponent}} expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} expected-error {{consecutive statements on a line must be separated by ';'}} {{37-37=;}} //===----------------------------------------------------------------------===// // String Literals //===----------------------------------------------------------------------===// var st_a = "" var st_b: String = "" var st_c = "asdfasd // expected-error {{unterminated string literal}} var st_d = " \t\n\r\"\'\\ " // Valid simple escapes var st_e = " \u{12}\u{0012}\u{00000078} " // Valid unicode escapes var st_u1 = " \u{1} " var st_u2 = " \u{123} " var st_u3 = " \u{1234567} " // expected-error {{invalid unicode scalar}} var st_u4 = " \q " // expected-error {{invalid escape sequence in literal}} var st_u5 = " \u{FFFFFFFF} " // expected-error {{invalid unicode scalar}} var st_u6 = " \u{D7FF} \u{E000} " // Fencepost UTF-16 surrogate pairs. var st_u7 = " \u{D800} " // expected-error {{invalid unicode scalar}} var st_u8 = " \u{DFFF} " // expected-error {{invalid unicode scalar}} var st_u10 = " \u{0010FFFD} " // Last valid codepoint, 0xFFFE and 0xFFFF are reserved in each plane var st_u11 = " \u{00110000} " // expected-error {{invalid unicode scalar}} func stringliterals(_ d: [String: Int]) { // rdar://11385385 let x = 4 "Hello \(x+1) world" // expected-warning {{expression of type 'String' is unused}} "Error: \(x+1"; // expected-error {{unterminated string literal}} "Error: \(x+1 // expected-error {{unterminated string literal}} ; // expected-error {{';' statements are not allowed}} // rdar://14050788 [DF] String Interpolations can't contain quotes "test \("nested")" "test \("\("doubly nested")")" "test \(d["hi"])" "test \("quoted-paren )")" "test \("quoted-paren (")" "test \("\\")" "test \("\n")" "test \("\")" // expected-error {{unterminated string literal}} "test \ // expected-error @-1 {{unterminated string literal}} expected-error @-1 {{invalid escape sequence in literal}} "test \("\ // expected-error @-1 {{unterminated string literal}} "test newline \("something" + "something else")" // expected-error @-2 {{unterminated string literal}} expected-error @-1 {{unterminated string literal}} // expected-warning @+2 {{variable 'x2' was never used; consider replacing with '_' or removing it}} // expected-error @+1 {{unterminated string literal}} var x2 : () = ("hello" + " ; } func testSingleQuoteStringLiterals() { _ = 'abc' // expected-error{{single-quoted string literal found, use '"'}}{{7-12="abc"}} _ = 'abc' + "def" // expected-error{{single-quoted string literal found, use '"'}}{{7-12="abc"}} _ = 'ab\nc' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab\\nc"}} _ = "abc\('def')" // expected-error{{single-quoted string literal found, use '"'}}{{13-18="def"}} _ = "abc' // expected-error{{unterminated string literal}} _ = 'abc" // expected-error{{unterminated string literal}} _ = "a'c" _ = 'ab\'c' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab'c"}} _ = 'ab"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-13="ab\\"c"}} _ = 'ab\"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-14="ab\\"c"}} _ = 'ab\\"c' // expected-error{{single-quoted string literal found, use '"'}}{{7-15="ab\\\\\\"c"}} } // <rdar://problem/17128913> var s = "" s.append(contentsOf: ["x"]) //===----------------------------------------------------------------------===// // InOut arguments //===----------------------------------------------------------------------===// func takesInt(_ x: Int) {} func takesExplicitInt(_ x: inout Int) { } func testInOut(_ arg: inout Int) { var x: Int takesExplicitInt(x) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{20-20=&}} takesExplicitInt(&x) takesInt(&x) // expected-error{{'&' used with non-inout argument of type 'Int'}} var y = &x // expected-error{{'&' can only appear immediately in a call argument list}} \ // expected-error {{type 'inout Int' of variable is not materializable}} var z = &arg // expected-error{{'&' can only appear immediately in a call argument list}} \ // expected-error {{type 'inout Int' of variable is not materializable}} takesExplicitInt(5) // expected-error {{cannot pass immutable value as inout argument: literals are not mutable}} } //===----------------------------------------------------------------------===// // Conversions //===----------------------------------------------------------------------===// var pi_f: Float var pi_d: Double struct SpecialPi {} // Type with no implicit construction. var pi_s: SpecialPi func getPi() -> Float {} // expected-note 3 {{found this candidate}} func getPi() -> Double {} // expected-note 3 {{found this candidate}} func getPi() -> SpecialPi {} enum Empty { } extension Empty { init(_ f: Float) { } } func conversionTest(_ a: inout Double, b: inout Int) { var f: Float var d: Double a = Double(b) a = Double(f) a = Double(d) // no-warning b = Int(a) f = Float(b) var pi_f1 = Float(pi_f) var pi_d1 = Double(pi_d) var pi_s1 = SpecialPi(pi_s) // expected-error {{argument passed to call that takes no arguments}} var pi_f2 = Float(getPi()) // expected-error {{ambiguous use of 'getPi()'}} var pi_d2 = Double(getPi()) // expected-error {{ambiguous use of 'getPi()'}} var pi_s2: SpecialPi = getPi() // no-warning var float = Float.self var pi_f3 = float.init(getPi()) // expected-error {{ambiguous use of 'getPi()'}} var pi_f4 = float.init(pi_f) var e = Empty(f) var e2 = Empty(d) // expected-error{{cannot convert value of type 'Double' to expected argument type 'Float'}} var e3 = Empty(Float(d)) } struct Rule { // expected-note {{'init(target:dependencies:)' declared here}} var target: String var dependencies: String } var ruleVar: Rule ruleVar = Rule("a") // expected-error {{missing argument for parameter 'dependencies' in call}} class C { var x: C? init(other: C?) { x = other } func method() {} } _ = C(3) // expected-error {{missing argument label 'other:' in call}} _ = C(other: 3) // expected-error {{cannot convert value of type 'Int' to expected argument type 'C?'}} //===----------------------------------------------------------------------===// // Unary Operators //===----------------------------------------------------------------------===// func unaryOps(_ i8: inout Int8, i64: inout Int64) { i8 = ~i8 i64 += 1 i8 -= 1 Int64(5) += 1 // expected-error{{left side of mutating operator isn't mutable: function call returns immutable value}} // <rdar://problem/17691565> attempt to modify a 'let' variable with ++ results in typecheck error not being able to apply ++ to Float let a = i8 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} a += 1 // expected-error {{left side of mutating operator isn't mutable: 'a' is a 'let' constant}} var b : Int { get { }} b += 1 // expected-error {{left side of mutating operator isn't mutable: 'b' is a get-only property}} } //===----------------------------------------------------------------------===// // Iteration //===----------------------------------------------------------------------===// func..<(x: Double, y: Double) -> Double { return x + y } func iterators() { _ = 0..<42 _ = 0.0..<42.0 } //===----------------------------------------------------------------------===// // Magic literal expressions //===----------------------------------------------------------------------===// func magic_literals() { _ = __FILE__ // expected-error {{__FILE__ has been replaced with #file in Swift 3}} _ = __LINE__ // expected-error {{__LINE__ has been replaced with #line in Swift 3}} _ = __COLUMN__ // expected-error {{__COLUMN__ has been replaced with #column in Swift 3}} _ = __DSO_HANDLE__ // expected-error {{__DSO_HANDLE__ has been replaced with #dsohandle in Swift 3}} _ = #file _ = #line + #column var _: UInt8 = #line + #column } //===----------------------------------------------------------------------===// // lvalue processing //===----------------------------------------------------------------------===// infix operator +-+= @discardableResult func +-+= (x: inout Int, y: Int) -> Int { return 0} func lvalue_processing() { var i = 0 i += 1 // obviously ok var fn = (+-+=) var n = 42 fn(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{6-6=&}} fn(&n, 12) // expected-warning {{result of call is unused, but produces 'Int'}} n +-+= 12 (+-+=)(&n, 12) // ok. (+-+=)(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}} } struct Foo { func method() {} } func test() { var x = Foo() // rdar://15708430 (&x).method() // expected-error {{'inout Foo' is not convertible to 'Foo'}} } // Unused results. func unusedExpressionResults() { // Unused l-value _ // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} // <rdar://problem/20749592> Conditional Optional binding hides compiler error let optionalc:C? = nil optionalc?.method() // ok optionalc?.method // expected-error {{expression resolves to an unused function}} } //===----------------------------------------------------------------------===// // Collection Literals //===----------------------------------------------------------------------===// func arrayLiterals() { let _ = [1,2,3] let _ : [Int] = [] let _ = [] // expected-error {{empty collection literal requires an explicit type}} } func dictionaryLiterals() { let _ = [1 : "foo",2 : "bar",3 : "baz"] let _: Dictionary<Int, String> = [:] let _ = [:] // expected-error {{empty collection literal requires an explicit type}} } func invalidDictionaryLiteral() { // FIXME: lots of unnecessary diagnostics. var a = [1: ; // expected-error {{expected value in dictionary literal}} var b = [1: ;] // expected-error {{expected value in dictionary literal}} var c = [1: "one" ;] // expected-error {{expected key expression in dictionary literal}} expected-error {{expected ',' separator}} {{20-20=,}} var d = [1: "one", ;] // expected-error {{expected key expression in dictionary literal}} var e = [1: "one", 2] // expected-error {{expected ':' in dictionary literal}} var f = [1: "one", 2 ;] // expected-error {{expected ':' in dictionary literal}} var g = [1: "one", 2: ;] // expected-error {{expected value in dictionary literal}} } // FIXME: The issue here is a type compatibility problem, there is no ambiguity. [4].joined(separator: [1]) // expected-error {{type of expression is ambiguous without more context}} [4].joined(separator: [[[1]]]) // expected-error {{type of expression is ambiguous without more context}} //===----------------------------------------------------------------------===// // nil/metatype comparisons //===----------------------------------------------------------------------===// _ = Int.self == nil // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns false}} _ = nil == Int.self // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns false}} _ = Int.self != nil // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns true}} _ = nil != Int.self // expected-warning {{comparing non-optional value of type 'Any.Type' to nil always returns true}} // <rdar://problem/19032294> Disallow postfix ? when not chaining func testOptionalChaining(_ a : Int?, b : Int!, c : Int??) { _ = a? // expected-error {{optional chain has no effect, expression already produces 'Int?'}} {{8-9=}} _ = a?.customMirror _ = b? // expected-error {{'?' must be followed by a call, member lookup, or subscript}} _ = b?.customMirror var _: Int? = c? // expected-error {{'?' must be followed by a call, member lookup, or subscript}} } // <rdar://problem/19657458> Nil Coalescing operator (??) should have a higher precedence func testNilCoalescePrecedence(cond: Bool, a: Int?, r: CountableClosedRange<Int>?) { // ?? should have higher precedence than logical operators like || and comparisons. if cond || (a ?? 42 > 0) {} // Ok. if (cond || a) ?? 42 > 0 {} // expected-error {{cannot be used as a boolean}} {{15-15=(}} {{16-16= != nil)}} if (cond || a) ?? (42 > 0) {} // expected-error {{cannot be used as a boolean}} {{15-15=(}} {{16-16= != nil)}} if cond || a ?? 42 > 0 {} // Parses as the first one, not the others. // ?? should have lower precedence than range and arithmetic operators. let r1 = r ?? (0...42) // ok let r2 = (r ?? 0)...42 // not ok: expected-error {{cannot convert value of type 'Int' to expected argument type 'CountableClosedRange<Int>'}} let r3 = r ?? 0...42 // parses as the first one, not the second. // <rdar://problem/27457457> [Type checker] Diagnose unsavory optional injections // Accidental optional injection for ??. let i = 42 _ = i ?? 17 // expected-warning {{left side of nil coalescing operator '??' has non-optional type 'Int', so the right side is never used}} {{9-15=}} } // <rdar://problem/19772570> Parsing of as and ?? regressed func testOptionalTypeParsing(_ a : AnyObject) -> String { return a as? String ?? "default name string here" } func testParenExprInTheWay() { let x = 42 if x & 4.0 {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} expected-note {{expected an argument list of type '(Int, Int)'}} if (x & 4.0) {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} expected-note {{expected an argument list of type '(Int, Int)'}} if !(x & 4.0) {} // expected-error {{binary operator '&' cannot be applied to operands of type 'Int' and 'Double'}} //expected-note @-1 {{expected an argument list of type '(Int, Int)'}} if x & x {} // expected-error {{'Int' is not convertible to 'Bool'}} } // <rdar://problem/21352576> Mixed method/property overload groups can cause a crash during constraint optimization public struct TestPropMethodOverloadGroup { public typealias Hello = String public let apply:(Hello) -> Int public func apply(_ input:Hello) -> Int { return apply(input) } } // <rdar://problem/18496742> Passing ternary operator expression as inout crashes Swift compiler func inoutTests(_ arr: inout Int) { var x = 1, y = 2 (true ? &x : &y) // expected-error 2 {{'&' can only appear immediately in a call argument list}} // expected-warning @-1 {{expression of type 'inout Int' is unused}} let a = (true ? &x : &y) // expected-error 2 {{'&' can only appear immediately in a call argument list}} // expected-error @-1 {{type 'inout Int' of variable is not materializable}} inoutTests(true ? &x : &y); // expected-error 2 {{'&' can only appear immediately in a call argument list}} &_ // expected-error {{expression type 'inout _' is ambiguous without more context}} inoutTests((&x)) // expected-error {{'&' can only appear immediately in a call argument list}} inoutTests(&x) // <rdar://problem/17489894> inout not rejected as operand to assignment operator &x += y // expected-error {{'&' can only appear immediately in a call argument list}} // <rdar://problem/23249098> func takeAny(_ x: Any) {} takeAny(&x) // expected-error{{'&' used with non-inout argument of type 'Any'}} func takeManyAny(_ x: Any...) {} takeManyAny(&x) // expected-error{{'&' used with non-inout argument of type 'Any'}} takeManyAny(1, &x) // expected-error{{'&' used with non-inout argument of type 'Any'}} func takeIntAndAny(_ x: Int, _ y: Any) {} takeIntAndAny(1, &x) // expected-error{{'&' used with non-inout argument of type 'Any'}} } // <rdar://problem/20802757> Compiler crash in default argument & inout expr var g20802757 = 2 func r20802757(_ z: inout Int = &g20802757) { // expected-error {{'&' can only appear immediately in a call argument list}} print(z) } _ = _.foo // expected-error {{type of expression is ambiguous without more context}} // <rdar://problem/22211854> wrong arg list crashing sourcekit func r22211854() { func f(_ x: Int, _ y: Int, _ z: String = "") {} // expected-note 2 {{'f' declared here}} func g<T>(_ x: T, _ y: T, _ z: String = "") {} // expected-note 2 {{'g' declared here}} f(1) // expected-error{{missing argument for parameter #2 in call}} g(1) // expected-error{{missing argument for parameter #2 in call}} func h() -> Int { return 1 } f(h() == 1) // expected-error{{missing argument for parameter #2 in call}} g(h() == 1) // expected-error{{missing argument for parameter #2 in call}} } // <rdar://problem/22348394> Compiler crash on invoking function with labeled defaulted param with non-labeled argument func r22348394() { func f(x: Int = 0) { } f(Int(3)) // expected-error{{missing argument label 'x:' in call}} } // <rdar://problem/23185177> Compiler crashes in Assertion failed: ((AllowOverwrite || !E->hasLValueAccessKind()) && "l-value access kind has already been set"), function visit protocol P { var y: String? { get } } func r23185177(_ x: P?) -> [String] { return x?.y // expected-error{{cannot convert return expression of type 'String?' to return type '[String]'}} } // <rdar://problem/22913570> Miscompile: wrong argument parsing when calling a function in swift2.0 func r22913570() { func f(_ from: Int = 0, to: Int) {} // expected-note {{'f(_:to:)' declared here}} f(1 + 1) // expected-error{{missing argument for parameter 'to' in call}} } // <rdar://problem/23708702> Emit deprecation warnings for ++/-- in Swift 2.2 func swift22_deprecation_increment_decrement() { var i = 0 var f = 1.0 i++ // expected-error {{'++' is unavailable}} {{4-6= += 1}} --i // expected-error {{'--' is unavailable}} {{3-5=}} {{6-6= -= 1}} _ = i++ // expected-error {{'++' is unavailable}} ++f // expected-error {{'++' is unavailable}} {{3-5=}} {{6-6= += 1}} f-- // expected-error {{'--' is unavailable}} {{4-6= -= 1}} _ = f-- // expected-error {{'--' is unavailable}} {{none}} // <rdar://problem/24530312> Swift ++fix-it produces bad code in nested expressions // This should not get a fixit hint. var j = 2 i = ++j // expected-error {{'++' is unavailable}} {{none}} } // SR-628 mixing lvalues and rvalues in tuple expression var x = 0 var y = 1 let _ = (x, x + 1).0 let _ = (x, 3).1 (x,y) = (2,3) (x,4) = (1,2) // expected-error {{cannot assign to value: literals are not mutable}} (x,y).1 = 7 // expected-error {{cannot assign to immutable expression of type 'Int'}} x = (x,(3,y)).1.1 // SE-0101 sizeof family functions are reconfigured into MemoryLayout protocol Pse0101 { associatedtype Value func getIt() -> Value } class Cse0101<U> { typealias T = U var val: U { fatalError() } } func se0101<P: Pse0101>(x: Cse0101<P>) { // Note: The first case is actually not allowed, but it is very common and can be compiled currently. _ = sizeof(P) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{15-16=>.size}} {{none}} // expected-warning@-1 {{missing '.self' for reference to metatype of type 'P'}} _ = sizeof(P.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{15-21=>.size}} {{none}} _ = sizeof(P.Value.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{21-27=>.size}} {{none}} _ = sizeof(Cse0101<P>.self) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-14=MemoryLayout<}} {{24-30=>.size}} {{none}} _ = alignof(Cse0101<P>.T.self) // expected-error {{'alignof' is unavailable: use MemoryLayout<T>.alignment instead.}} {{7-15=MemoryLayout<}} {{27-33=>.alignment}} {{none}} _ = strideof(P.Type.self) // expected-error {{'strideof' is unavailable: use MemoryLayout<T>.stride instead.}} {{7-16=MemoryLayout<}} {{22-28=>.stride}} {{none}} _ = sizeof(type(of: x)) // expected-error {{'sizeof' is unavailable: use MemoryLayout<T>.size instead.}} {{7-26=MemoryLayout<Cse0101<P>>.size}} {{none}} }
2cdd3956d758ef457df630630fe756e8
37.361298
310
0.60589
false
true
false
false
KrishMunot/swift
refs/heads/master
test/IRGen/objc_protocols.swift
apache-2.0
6
// RUN: rm -rf %t && mkdir %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t %S/Inputs/objc_protocols_Bas.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import gizmo import objc_protocols_Bas // -- Protocol "Frungible" inherits only objc protocols and should have no // out-of-line inherited witnesses in its witness table. // CHECK: [[ZIM_FRUNGIBLE_WITNESS:@_TWPC14objc_protocols3ZimS_9FrungibleS_]] = hidden constant [1 x i8*] [ // CHECK: i8* bitcast (void (%C14objc_protocols3Zim*, %swift.type*, i8**)* @_TTWC14objc_protocols3ZimS_9FrungibleS_FS1_6frungefT_T_ to i8*) // CHECK: ] protocol Ansible { func anse() } class Foo : NSRuncing, NSFunging, Ansible { @objc func runce() {} @objc func funge() {} @objc func foo() {} func anse() {} } // CHECK: @_INSTANCE_METHODS__TtC14objc_protocols3Foo = private constant { i32, i32, [3 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 3, // CHECK: [3 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC:@[0-9]+]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_TToFC14objc_protocols3Foo5runcefT_T_ to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_TToFC14objc_protocols3Foo5fungefT_T_ to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_TToFC14objc_protocols3Foo3foofT_T_ to i8*) // CHECK: }] // CHECK: }, section "__DATA, __objc_const", align 8 class Bar { func bar() {} } // -- Bar does not directly have objc methods... // CHECK-NOT: @_INSTANCE_METHODS_Bar extension Bar : NSRuncing, NSFunging { @objc func runce() {} @objc func funge() {} @objc func foo() {} func notObjC() {} } // -- ...but the ObjC protocol conformances on its extension add some // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC14objc_protocols3Bar_$_objc_protocols" = private constant { i32, i32, [3 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 3, // CHECK: [3 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_TToFC14objc_protocols3Bar5runcefT_T_ to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_TToFC14objc_protocols3Bar5fungefT_T_ to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_TToFC14objc_protocols3Bar3foofT_T_ to i8*) } // CHECK: ] // CHECK: }, section "__DATA, __objc_const", align 8 // class Bas from objc_protocols_Bas module extension Bas : NSRuncing { // -- The runce() implementation comes from the original definition. @objc public func foo() {} } // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC18objc_protocols_Bas3Bas_$_objc_protocols" = private constant { i32, i32, [1 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 1, // CHECK; [1 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_TToFE14objc_protocolsC18objc_protocols_Bas3Bas3foofT_T_ to i8*) } // CHECK: ] // CHECK: }, section "__DATA, __objc_const", align 8 // -- Swift protocol refinement of ObjC protocols. protocol Frungible : NSRuncing, NSFunging { func frunge() } class Zim : Frungible { @objc func runce() {} @objc func funge() {} @objc func foo() {} func frunge() {} } // CHECK: @_INSTANCE_METHODS__TtC14objc_protocols3Zim = private constant { i32, i32, [3 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 3, // CHECK: [3 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_TToFC14objc_protocols3Zim5runcefT_T_ to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_TToFC14objc_protocols3Zim5fungefT_T_ to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_TToFC14objc_protocols3Zim3foofT_T_ to i8*) } // CHECK: ] // CHECK: }, section "__DATA, __objc_const", align 8 // class Zang from objc_protocols_Bas module extension Zang : Frungible { @objc public func runce() {} // funge() implementation from original definition of Zang @objc public func foo() {} func frunge() {} } // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC18objc_protocols_Bas4Zang_$_objc_protocols" = private constant { i32, i32, [2 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 2, // CHECK: [2 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_TToFE14objc_protocolsC18objc_protocols_Bas4Zang5runcefT_T_ to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[ENC]], i64 0, i64 0), i8* bitcast (void (i8*, i8*)* @_TToFE14objc_protocolsC18objc_protocols_Bas4Zang3foofT_T_ to i8*) } // CHECK: ] // CHECK: }, section "__DATA, __objc_const", align 8 // -- Force generation of witness for Zim. // CHECK: define hidden { %objc_object*, i8** } @_TF14objc_protocols22mixed_heritage_erasure{{.*}} func mixed_heritage_erasure(_ x: Zim) -> Frungible { return x // CHECK: [[T0:%.*]] = insertvalue { %objc_object*, i8** } undef, %objc_object* {{%.*}}, 0 // CHECK: insertvalue { %objc_object*, i8** } [[T0]], i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* [[ZIM_FRUNGIBLE_WITNESS]], i32 0, i32 0), 1 } // CHECK-LABEL: define hidden void @_TF14objc_protocols12objc_generic{{.*}}(%objc_object*, %swift.type* %T) {{.*}} { func objc_generic<T : NSRuncing>(_ x: T) { x.runce() // CHECK: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[SELECTOR]]) } // CHECK-LABEL: define hidden void @_TF14objc_protocols17call_objc_generic{{.*}}(%objc_object*, %swift.type* %T) {{.*}} { // CHECK: call void @_TF14objc_protocols12objc_generic{{.*}}(%objc_object* %0, %swift.type* %T) func call_objc_generic<T : NSRuncing>(_ x: T) { objc_generic(x) } // CHECK-LABEL: define hidden void @_TF14objc_protocols13objc_protocol{{.*}}(%objc_object*) {{.*}} { func objc_protocol(_ x: NSRuncing) { x.runce() // CHECK: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[SELECTOR]]) } // CHECK: define hidden %objc_object* @_TF14objc_protocols12objc_erasure{{.*}}(%CSo7NSSpoon*) {{.*}} { func objc_erasure(_ x: NSSpoon) -> NSRuncing { return x // CHECK: [[RES:%.*]] = bitcast %CSo7NSSpoon* {{%.*}} to %objc_object* // CHECK: ret %objc_object* [[RES]] } // CHECK: define hidden void @_TF14objc_protocols25objc_protocol_composition{{.*}}(%objc_object*) func objc_protocol_composition(_ x: protocol<NSRuncing, NSFunging>) { x.runce() // CHECK: [[RUNCE:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[RUNCE]]) x.funge() // CHECK: [[FUNGE:%.*]] = load i8*, i8** @"\01L_selector(funge)", align 8 // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[FUNGE]]) } // CHECK: define hidden void @_TF14objc_protocols31objc_swift_protocol_composition{{.*}}(%objc_object*, i8**) func objc_swift_protocol_composition (_ x:protocol<NSRuncing, Ansible, NSFunging>) { x.runce() // CHECK: [[RUNCE:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[RUNCE]]) /* TODO: Abstraction difference from ObjC protocol composition to * opaque protocol x.anse() */ x.funge() // CHECK: [[FUNGE:%.*]] = load i8*, i8** @"\01L_selector(funge)", align 8 // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[FUNGE]]) } // TODO: Mixed class-bounded/fully general protocol compositions. @objc protocol SettableProperty { var reqt: NSRuncing { get set } } func instantiateArchetype<T: SettableProperty>(_ x: T) { let y = x.reqt x.reqt = y } // rdar://problem/21029254 @objc protocol Appaloosa { } protocol Palomino {} protocol Vanner : Palomino, Appaloosa { } struct Stirrup<T : Palomino> { } func canter<T : Palomino>(_ t: Stirrup<T>) {} func gallop<T : Vanner>(_ t: Stirrup<T>) { canter(t) }
b8a85ded0e8b3f612195f3a75eae906b
49.931707
300
0.611148
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Money/Tests/MoneyKitTests/Balance/CryptoCurrencyTests.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit @testable import MoneyKitMock import XCTest class CryptoCurrencyTests: XCTestCase { private var cryptoCurrencyDesiredOrder: [CryptoCurrency] { [ .bitcoin, .ethereum, .bitcoinCash, .stellar, .mockCoin(symbol: "A", displaySymbol: "A", name: "Custodial 1", sortIndex: 5), .mockCoin(symbol: "B", displaySymbol: "B", name: "Custodial 2", sortIndex: 11), .mockCoin(symbol: "C", displaySymbol: "C", name: "Custodial 3", sortIndex: 12), .mockCoin(symbol: "D", displaySymbol: "D", name: "Custodial 4", sortIndex: 13), .mockERC20(symbol: "E", displaySymbol: "E", name: "ERC20 1", sortIndex: 0), .mockERC20(symbol: "F", displaySymbol: "F", name: "ERC20 2", sortIndex: 1), .mockERC20(symbol: "G", displaySymbol: "G", name: "ERC20 3", sortIndex: 2), .mockERC20(symbol: "H", displaySymbol: "H", name: "ERC20 4", sortIndex: 3), .mockERC20(symbol: "I", displaySymbol: "I", name: "ERC20 5", sortIndex: 4) ] } func testSortedCryptoCurrencyArrayIsInCorrectOrder() { XCTAssertTrue( cryptoCurrencyDesiredOrder.shuffled().sorted() == cryptoCurrencyDesiredOrder, "sut.allEnabledCryptoCurrencies.sorted() is not as expected." ) } func testUniquenessERC20AssetModelIsBasedSolelyOnSymbol() { let currencies: [AssetModel] = [ .mockERC20(symbol: "A", displaySymbol: "A", name: "A", sortIndex: 0), .mockERC20(symbol: "A", displaySymbol: "X", name: "X", sortIndex: 1), .mockERC20(symbol: "B", displaySymbol: "B", name: "B", sortIndex: 2) ] let unique = currencies.unique XCTAssertEqual(unique.count, 2) let set = Set(currencies) XCTAssertEqual(set.count, 2) } func testUniquenessCoinAssetModelIsBasedSolelyOnSymbol() { let currencies: [AssetModel] = [ .mockCoin(symbol: "A", displaySymbol: "A", name: "A", sortIndex: 0), .mockCoin(symbol: "A", displaySymbol: "X", name: "X", sortIndex: 1), .mockCoin(symbol: "B", displaySymbol: "B", name: "B", sortIndex: 2) ] let unique = currencies.unique XCTAssertEqual(unique.count, 2) let set = Set(currencies) XCTAssertEqual(set.count, 2) } func testUniquenessCryptoCurrencyIsBasedSolelyOnSymbol() { let currencies: [CryptoCurrency] = [ .mockERC20(symbol: "A", displaySymbol: "A", name: "A", sortIndex: 0), .mockERC20(symbol: "A", displaySymbol: "A", name: "A", sortIndex: 1), .mockERC20(symbol: "B", displaySymbol: "B", name: "B", sortIndex: 2), .mockCoin(symbol: "A", displaySymbol: "A", name: "A", sortIndex: 0), .mockCoin(symbol: "A", displaySymbol: "A", name: "A", sortIndex: 1), .mockCoin(symbol: "B", displaySymbol: "B", name: "B", sortIndex: 2) ] let unique = currencies.unique XCTAssertEqual(unique.count, 2) let set = Set(currencies) XCTAssertEqual(set.count, 2) } }
c51ea750fa0caeb936dc0a0e250ef368
43.611111
91
0.5934
false
true
false
false
jpchmura/JPCPaperViewController
refs/heads/master
Source/PaperCollectionViewLayout.swift
mit
1
// // PaperCollectionViewLayout.swift // PaperExample // // Created by Jon Chmura on 1/31/15. // Copyright (c) 2015 Thinkering. All rights reserved. // import UIKit public class PaperCollectionViewLayout: UICollectionViewLayout { internal var _itemSize = CGSizeZero public var itemSize: CGSize { get { return CGSizeZero } } public var activeSection: Int = 0 { didSet { self.invalidateLayout() } } public override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { if self.collectionView == nil { return false } return !CGSizeEqualToSize(self.collectionView!.frame.size, newBounds.size) } internal var attrByPath = [NSIndexPath : UICollectionViewLayoutAttributes]() internal var totalContentWidth: CGFloat = 0.0 public override func collectionViewContentSize() -> CGSize { if self.collectionView == nil { return CGSizeZero } return CGSizeMake(totalContentWidth, self.collectionView!.frame.height - UIApplication.sharedApplication().statusBarFrame.height) } public override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { var result = [AnyObject]() for (indexPath , attr) in self.attrByPath { if (indexPath.section == self.activeSection) && CGRectIntersectsRect(rect, attr.frame) { result.append(attr) } } return result } public override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { return self.attrByPath[indexPath] } }
8206f9ad02c0cd0dc2342d603dbc08f9
27.516129
137
0.63405
false
false
false
false
coderwhy/DouYuZB
refs/heads/master
DYZB/DYZB/Classes/Home/Controller/AmuseViewController.swift
mit
1
// // AmuseViewController.swift // DYZB // // Created by 1 on 16/10/10. // Copyright © 2016年 小码哥. All rights reserved. // import UIKit private let kMenuViewH : CGFloat = 200 class AmuseViewController: BaseAnchorViewController { // MARK: 懒加载属性 fileprivate lazy var amuseVM : AmuseViewModel = AmuseViewModel() fileprivate lazy var menuView : AmuseMenuView = { let menuView = AmuseMenuView.amuseMenuView() menuView.frame = CGRect(x: 0, y: -kMenuViewH, width: kScreenW, height: kMenuViewH) return menuView }() } // MARK:- 设置UI界面 extension AmuseViewController { override func setupUI() { super.setupUI() // 将菜单的View添加到collectionView中 collectionView.addSubview(menuView) collectionView.contentInset = UIEdgeInsets(top: kMenuViewH, left: 0, bottom: 0, right: 0) } } // MARK:- 请求数据 extension AmuseViewController { override func loadData() { // 1.给父类中ViewModel进行赋值 baseVM = amuseVM // 2.请求数据 amuseVM.loadAmuseData { // 2.1.刷新表格 self.collectionView.reloadData() // 2.2.调整数据 var tempGroups = self.amuseVM.anchorGroups tempGroups.removeFirst() self.menuView.groups = tempGroups // 3.数据请求完成 self.loadDataFinished() } } }
958cdf63b6beda9ebf46dd8eddc7d780
22.762712
97
0.600571
false
false
false
false
aestesis/Aether
refs/heads/master
Sources/Aether/Foundation/Size.swift
apache-2.0
1
// // Size.swift // Aether // // Created by renan jegouzo on 23/02/2016. // Copyright © 2016 aestesis. All rights reserved. // // 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 import SwiftyJSON #if os(macOS) || os(iOS) || os(tvOS) import CoreGraphics #endif ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public struct Size : CustomStringConvertible,JsonConvertible { ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public var width:Double public var height:Double ////////////////////////////////////////////////////////////////////////////////////////////////////////// public var w:Double { get { return width; } set(w) { width=w; } } public var h:Double { get { return height; } set(h) { height=h; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// public var ceil: Size { return Size(Foundation.ceil(width),Foundation.ceil(height)) } public func crop(_ ratio:Double,margin:Double=0) -> Size { let dd = ratio let ds = self.ratio if ds>dd { let h=height-margin*2; let w=dd*h; return Size(w,h); } else { let w=width-margin*2; let h=w/dd; return Size(w,h); } } public func extend(_ border:Double) -> Size { return Size(width+border*2,height+border*2) } public func extend(w:Double,h:Double) -> Size { return Size(width+w*2,height+h*2) } public func extend(_ sz:Size) -> Size { return self + sz*2 } public var int: SizeI { return SizeI(Int(width),Int(height)) } public var floor: Size { return Size(Foundation.floor(width),Foundation.floor(height)) } public var length: Double { return sqrt(width*width+height*height) } public func lerp(_ to:Size,coef:Double) -> Size { return Size(to.width*coef+width*(1-coef),to.height*coef+height*(1-coef)) } public var normalize: Size { return Size(width/length,height/length) } public func point(_ px:Double,_ py:Double) -> Point { return Point(width*px,height*py) } public var point: Point { return Point(width,height) } public func point(px:Double,py:Double) -> Point { return Point(width*px,height*py) } public var ratio: Double { return width/height } public var round: Size { return Size(Foundation.round(width),Foundation.round(height)) } public var rotate: Size { return Size(height,width) } public func scale(_ scale:Double) -> Size { return Size(width*scale,height*scale) } public func scale(_ w:Double,_ h:Double) -> Size { return Size(width*w,height*h) } public var surface:Double { return width*height; } public var transposed:Size { return Size(h,w) } public var description: String { return "{w:\(width),h:\(height)}" } public var json: JSON { return JSON([w:w,h:h]) } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public init(_ s:CGSize) { width=Double(s.width) height=Double(s.height) } public init(_ s:SizeI) { width=Double(s.width) height=Double(s.height) } public init(_ p:PointI) { width=Double(p.x) height=Double(p.y) } public init(_ square:Double) { width=square; height=square; } public init(_ w:Double,_ h:Double) { width=w; height=h; } public init(_ w:Int,_ h:Int) { width=Double(w); height=Double(h); } public init(json: JSON) { if let w=json["width"].double { width=w } else if let w=json["w"].double { width=w } else { width=0; } if let h=json["height"].double { height=h } else if let h=json["h"].double { height=h } else { height=0; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public var system : CGSize { return CGSize(width:CGFloat(w),height: CGFloat(h)) } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public static var zero: Size { return Size(0,0) } public static var infinity: Size { return Size(Double.infinity,Double.infinity) } public static var unity: Size { return Size(1,1) } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public func ==(lhs: Size, rhs: Size) -> Bool { return (lhs.width==rhs.width)&&(lhs.height==rhs.height); } public func !=(lhs: Size, rhs: Size) -> Bool { return (lhs.width != rhs.width)||(lhs.height != rhs.height); } public func +(lhs: Size, rhs: Size) -> Size { return Size((lhs.w+rhs.w),(lhs.h+rhs.h)); } public func -(lhs: Size, rhs: Size) -> Size { return Size((lhs.w-rhs.w),(lhs.h-rhs.h)); } public func *(lhs: Size, rhs: Size) -> Size { return Size((lhs.w*rhs.w),(lhs.h*rhs.h)); } public func *(lhs: Size, rhs: Double) -> Size { return Size((lhs.w*rhs),(lhs.h*rhs)); } public func /(lhs: Size, rhs: Size) -> Size { return Size((lhs.w/rhs.w),(lhs.h/rhs.h)); } public func /(lhs: Size, rhs: Double) -> Size { return Size((lhs.w/rhs),(lhs.h/rhs)); } public prefix func - (size: Size) -> Size { return Size(-size.w,-size.h) } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public struct SizeI { ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public var width:Int public var height:Int ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public var w:Int { get { return width; } set(w) { width=w; } } public var h:Int { get { return height; } set(h) { height=h; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// public var point: PointI { return PointI(x:width,y:height) } public var surface:Int { return width*height; } public var description: String { return "{w:\(width),h:\(height)}" } public var json: JSON { return JSON.parse(string: description) } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public init(_ w:Int,_ h:Int) { width=w; height=h; } public init(json: JSON) { if let w=json["width"].number { width=Int(truncating:w) } else if let w=json["w"].number { width=Int(truncating:w) } else { width=0; } if let h=json["height"].number { height=Int(truncating:h) } else if let h=json["h"].number { height=Int(truncating:h) } else { height=0; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public static var zero: SizeI { return SizeI(0,0) } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// public func ==(lhs: SizeI, rhs: SizeI) -> Bool { return (lhs.width==rhs.width)&&(lhs.height==rhs.height); } public func !=(lhs: SizeI, rhs: SizeI) -> Bool { return (lhs.width != rhs.width)||(lhs.height != rhs.height); } public func +(lhs: SizeI, rhs: SizeI) -> SizeI { return SizeI((lhs.w+rhs.w),(lhs.h+rhs.h)); } public func -(lhs: SizeI, rhs: SizeI) -> SizeI { return SizeI((lhs.w-rhs.w),(lhs.h-rhs.h)); } public func *(lhs: SizeI, rhs: SizeI) -> SizeI { return SizeI((lhs.w*rhs.w),(lhs.h*rhs.h)); } public func *(lhs: SizeI, rhs: Int) -> SizeI { return SizeI((lhs.w*rhs),(lhs.h*rhs)); } public func /(lhs: SizeI, rhs: SizeI) -> SizeI { return SizeI((lhs.w/rhs.w),(lhs.h/rhs.h)); } public func /(lhs: SizeI, rhs: Int) -> SizeI { return SizeI((lhs.w/rhs),(lhs.h/rhs)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////
297782f47036763d0b4829330b0473fb
35.964169
110
0.370021
false
false
false
false
ReactiveKit/ReactiveKit
refs/heads/master
Sources/SignalProtocol+Result.swift
mit
1
// // The MIT License (MIT) // // Copyright (c) 2016-2019 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension SignalProtocol { /// Map element into a result, propagating success value as a next event or failure as a failed event. /// Shorthand for `map(transform).getValues()`. public func tryMap<U>(_ transform: @escaping (Element) -> Result<U, Error>) -> Signal<U, Error> { return map(transform).getValues() } } extension SignalProtocol where Error == Never { /// Map element into a result, propagating success value as a next event or failure as a failed event. /// Shorthand for `map(transform).getValues()`. public func tryMap<U, E>(_ transform: @escaping (Element) -> Result<U, E>) -> Signal<U, E> { return castError().map(transform).getValues() } } extension SignalProtocol where Element: _ResultProtocol { /// Map inner result. /// Shorthand for `map { $0.map(transform) }`. public func mapValue<NewSuccess>(_ transform: @escaping (Element.Value) -> NewSuccess) -> Signal<Result<NewSuccess, Element.Error>, Error> { return map { $0._unbox.map(transform) } } } extension SignalProtocol where Element: _ResultProtocol, Error == Element.Error { /// Unwraps values from result elements into elements of the signal. /// A failure result will trigger signal failure. public func getValues() -> Signal<Element.Value, Error> { return Signal { observer in return self.observe { event in switch event { case .next(let result): switch result._unbox { case .success(let element): observer.next(element) case .failure(let error): observer.failed(error) } case .completed: observer.completed() case .failed(let error): observer.failed(error) } } } } } extension SignalProtocol where Element: _ResultProtocol, Error == Never { /// Unwraps values from result elements into elements of the signal. /// A failure result will trigger signal failure. public func getValues() -> Signal<Element.Value, Element.Error> { return (castError() as Signal<Element, Element.Error>).getValues() } } public protocol _ResultProtocol { associatedtype Value associatedtype Error: Swift.Error var _unbox: Result<Value, Error> { get } } extension Result: _ResultProtocol { public var _unbox: Result { return self } }
f15eb34dc4d24440fd9cbfb94ddaeab0
36.646465
144
0.654682
false
false
false
false
CodePath2017Group4/travel-app
refs/heads/master
RoadTripPlanner/TripCell.swift
mit
1
// // TripCell.swift // RoadTripPlanner // // Created by Deepthy on 10/10/17. // Copyright © 2017 Deepthy. All rights reserved. // import UIKit class TripCell: UITableViewCell { @IBOutlet weak var tripImageView: UIImageView! @IBOutlet weak var tripTitleLabel: UILabel! @IBOutlet weak var profileImg1: UIImageView! @IBOutlet weak var profileImg2: UIImageView! @IBOutlet weak var profileImg3: UIImageView! var tripCell: TripCell! { didSet { if let tripTitle = tripCell.tripTitleLabel { } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code tripImageView.image = UIImage(named: "sf") tripImageView?.layer.cornerRadius = 3.0 tripImageView?.layer.masksToBounds = true profileImg1.layer.cornerRadius = profileImg1.frame.height / 2 profileImg2.layer.cornerRadius = profileImg2.frame.height / 2 profileImg3.layer.cornerRadius = profileImg3.frame.height / 2 } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
8fc0a2432cc216fa307277bf96274d99
22.75
69
0.607519
false
false
false
false
Zero-Xiong/GoogleMapKit
refs/heads/master
GoogleMapKit/Models/PlaceMarker.swift
gpl-3.0
1
// // PlaceMarker.swift // GoogleMapKit // // Created by xiong on 4/5/16. // Copyright © 2016 Zero Inc. All rights reserved. // import UIKit import GoogleMaps class PlaceMarker: GMSMarker { let place : GooglePlace init(place: GooglePlace) { self.place = place super.init() position = place.coordinate icon = UIImage(named: place.placeType+"_pin") groundAnchor = CGPoint(x: 0.5, y: 1) appearAnimation = kGMSMarkerAnimationPop } }
d47b2d73d3d3e12f79c7f30f8d7c572c
17.892857
53
0.597353
false
false
false
false
rsaenzi/MyMoviesListApp
refs/heads/master
MyMoviesListApp/MyMoviesListApp/AuthModule.swift
mit
1
// // AuthModule.swift // MyMoviesListApp // // Created by Rigoberto Sáenz Imbacuán on 5/29/17. // Copyright © 2017 Rigoberto Sáenz Imbacuán. All rights reserved. // import Foundation class AuthModule { var wireframe: AuthWireframe var interactor: AuthInteractor var presenter: AuthPresenter init() { wireframe = AuthWireframe() interactor = AuthInteractor() presenter = AuthPresenter() presenter.wireframe = wireframe presenter.interactor = interactor } }
3684486e9f2da815f41fc1183d51b651
19.740741
67
0.635714
false
false
false
false
SwiftAndroid/swift
refs/heads/master
test/ClangModules/cfuncs_parse.swift
apache-2.0
2
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify -I %S/Inputs %s // XFAIL: linux import cfuncs func test_cfunc1(_ i: Int) { cfunc1() // okay cfunc1(i) // expected-error{{argument passed to call that takes no arguments}} } func test_cfunc2(_ i: Int) { let f = cfunc2(i, 17) _ = f as Float cfunc2(b:17, a:i) // expected-error{{extraneous argument labels 'b:a:' in call}} cfunc2(17, i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Int32'}} } func test_cfunc3_a() { let b = cfunc3( { (a : Double, b : Double) -> Double in a + b } ) _ = b(1.5, 2.5) as Double _ = b as Double// expected-error{{cannot convert value of type 'double_bin_op_block!' to type 'Double' in coercion}} } func test_cfunc3_b() { let b = cfunc3( { a, b in a + b } ) _ = b(1.5, 2.5) as Double _ = b as Double// expected-error{{cannot convert value of type 'double_bin_op_block!' to type 'Double' in coercion}} } func test_cfunc3_c() { let b = cfunc3({ $0 + $1 }) _ = b(1.5, 2.5) as Double _ = b as Double// expected-error{{cannot convert value of type 'double_bin_op_block!' to type 'Double' in coercion}} } func test_cfunc3_d() { let x: Double = 0 let y: Double = 0 _ = cfunc3(nil)?(x, y) as Double? _ = cfunc3(nil)!(x, y) as Double } func test_cfunc4() { // Okay: has no prototype, so assume no parameters. cfunc4() } func test_pow() { pow(1.5, 2.5) } func test_puts(_ s: String) { _ = s.withCString { puts($0) + 32 }; } func test_fopen(_ filename: String) -> CInt { let file = filename.withCString { fopen($0, "r") } return file.pointee.inode } func test_cfunc_in_swift() -> Int { return cfunc_in_swift(5) } func test_inline_available() { createSomething() } func test_pointer() { var i: CInt = 0 var ia: [CInt] = [1, 2, 3] var f: CFloat = 0 var fa: [CFloat] = [1, 2, 3] param_pointer(nil as UnsafeMutablePointer<CInt>?) param_pointer(&i) param_pointer(&ia) param_const_pointer(nil as UnsafeMutablePointer<CInt>?) param_const_pointer(&i) param_const_pointer(ia) param_const_pointer([1, 2, 3]) param_void_pointer(nil as UnsafeMutablePointer<Void>?) param_void_pointer(nil as UnsafeMutablePointer<CInt>?) param_void_pointer(nil as UnsafeMutablePointer<CFloat>?) param_void_pointer(&i) param_void_pointer(&ia) param_void_pointer(&f) param_void_pointer(&fa) param_const_void_pointer(nil as UnsafeMutablePointer<Void>?) param_const_void_pointer(nil as UnsafeMutablePointer<CInt>?) param_const_void_pointer(nil as UnsafeMutablePointer<CFloat>?) param_const_void_pointer(nil as UnsafePointer<Void>?) param_const_void_pointer(nil as UnsafePointer<CInt>?) param_const_void_pointer(nil as UnsafePointer<CFloat>?) param_const_void_pointer(&i) param_const_void_pointer(ia) // FIXME: param_const_void_pointer([1, 2, 3]) param_const_void_pointer(&f) param_const_void_pointer(fa) // FIXME: param_const_void_pointer([1.0, 2.0, 3.0]) let op: OpaquePointer? = nil opaque_pointer_param(op) } func test_pointer_nonnull() { var i: CInt = 0 var ia: [CInt] = [1, 2, 3] var f: CFloat = 0 var fa: [CFloat] = [1, 2, 3] nonnull_param_pointer(&i) nonnull_param_pointer(&ia) nonnull_param_const_pointer(&i) nonnull_param_const_pointer(ia) nonnull_param_const_pointer([1, 2, 3]) nonnull_param_void_pointer(&i) nonnull_param_void_pointer(&ia) nonnull_param_void_pointer(&f) nonnull_param_void_pointer(&fa) nonnull_param_const_void_pointer(&i) nonnull_param_const_void_pointer(ia) // FIXME: nonnull_param_const_void_pointer([1, 2, 3]) nonnull_param_const_void_pointer(&f) nonnull_param_const_void_pointer(fa) // FIXME: nonnull_param_const_void_pointer([1.0, 2.0, 3.0]) } func test_decay() { decay_param_array(nil as UnsafeMutablePointer<CInt>?) var i: CInt = 0 var a: [CInt] = [1, 2, 3] decay_param_array(&i) decay_param_array(&a) decay_param_const_array(nil as UnsafeMutablePointer<CInt>?) decay_param_const_array(&i) decay_param_const_array(a) decay_param_const_array([1, 2, 3]) } func test_nested_pointers() { nested_pointer(nil) nested_pointer_audited(nil) nested_pointer_audited2(nil) // expected-error {{nil is not compatible with expected argument type 'UnsafePointer<UnsafePointer<Int32>?>'}} nested_pointer(0) // expected-error {{expected argument type 'UnsafePointer<UnsafePointer<Int32>?>!'}} nested_pointer_audited(0) // expected-error {{expected argument type 'UnsafePointer<UnsafePointer<Int32>>?'}} nested_pointer_audited2(0) // expected-error {{expected argument type 'UnsafePointer<UnsafePointer<Int32>?>'}} } func exit(_: Float) {} // expected-note {{found this candidate}} func test_ambiguous() { exit(5) // expected-error {{ambiguous use of 'exit'}} }
03f1443e55a04465d0d9eaae1954f188
28.567901
141
0.674322
false
true
false
false
OscarSwanros/swift
refs/heads/master
stdlib/public/core/ManagedBuffer.swift
apache-2.0
2
//===--- ManagedBuffer.swift - variable-sized buffer of aligned memory ----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("swift_bufferAllocate") internal func _swift_bufferAllocate( bufferType type: AnyClass, size: Int, alignmentMask: Int ) -> AnyObject /// A class whose instances contain a property of type `Header` and raw /// storage for an array of `Element`, whose size is determined at /// instance creation. /// /// Note that the `Element` array is suitably-aligned **raw memory**. /// You are expected to construct and---if necessary---destroy objects /// there yourself, using the APIs on `UnsafeMutablePointer<Element>`. /// Typical usage stores a count and capacity in `Header` and destroys /// any live elements in the `deinit` of a subclass. /// - Note: Subclasses must not have any stored properties; any storage /// needed should be included in `Header`. @_fixed_layout // FIXME(sil-serialize-all) open class ManagedBuffer<Header, Element> { /// Create a new instance of the most-derived class, calling /// `factory` on the partially-constructed object to generate /// an initial `Header`. @_inlineable // FIXME(sil-serialize-all) public final class func create( minimumCapacity: Int, makingHeaderWith factory: ( ManagedBuffer<Header, Element>) throws -> Header ) rethrows -> ManagedBuffer<Header, Element> { let p = Builtin.allocWithTailElems_1( self, minimumCapacity._builtinWordValue, Element.self) let initHeaderVal = try factory(p) p.headerAddress.initialize(to: initHeaderVal) // The _fixLifetime is not really needed, because p is used afterwards. // But let's be conservative and fix the lifetime after we use the // headerAddress. _fixLifetime(p) return p } /// The actual number of elements that can be stored in this object. /// /// This header may be nontrivial to compute; it is usually a good /// idea to store this information in the "header" area when /// an instance is created. @_inlineable // FIXME(sil-serialize-all) public final var capacity: Int { let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(self)) let endAddr = storageAddr + _swift_stdlib_malloc_size(storageAddr) let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress return realCapacity } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal final var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self)) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal final var headerAddress: UnsafeMutablePointer<Header> { return UnsafeMutablePointer<Header>(Builtin.addressof(&header)) } /// Call `body` with an `UnsafeMutablePointer` to the stored /// `Header`. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. @_inlineable // FIXME(sil-serialize-all) public final func withUnsafeMutablePointerToHeader<R>( _ body: (UnsafeMutablePointer<Header>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { (v, _) in return try body(v) } } /// Call `body` with an `UnsafeMutablePointer` to the `Element` /// storage. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. @_inlineable // FIXME(sil-serialize-all) public final func withUnsafeMutablePointerToElements<R>( _ body: (UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { return try body($1) } } /// Call `body` with `UnsafeMutablePointer`s to the stored `Header` /// and raw `Element` storage. /// /// - Note: These pointers are valid only for the duration of the /// call to `body`. @_inlineable // FIXME(sil-serialize-all) public final func withUnsafeMutablePointers<R>( _ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(headerAddress, firstElementAddress) } /// The stored `Header` instance. /// /// During instance creation, in particular during /// `ManagedBuffer.create`'s call to initialize, `ManagedBuffer`'s /// `header` property is as-yet uninitialized, and therefore /// reading the `header` property during `ManagedBuffer.create` is undefined. public final var header: Header //===--- internal/private API -------------------------------------------===// /// Make ordinary initialization unavailable @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(_doNotCallMe: ()) { _sanityCheckFailure("Only initialize these by calling create") } } /// Contains a buffer object, and provides access to an instance of /// `Header` and contiguous storage for an arbitrary number of /// `Element` instances stored in that buffer. /// /// For most purposes, the `ManagedBuffer` class works fine for this /// purpose, and can simply be used on its own. However, in cases /// where objects of various different classes must serve as storage, /// `ManagedBufferPointer` is needed. /// /// A valid buffer class is non-`@objc`, with no declared stored /// properties. Its `deinit` must destroy its /// stored `Header` and any constructed `Element`s. /// /// Example Buffer Class /// -------------------- /// /// class MyBuffer<Element> { // non-@objc /// typealias Manager = ManagedBufferPointer<(Int, String), Element> /// deinit { /// Manager(unsafeBufferObject: self).withUnsafeMutablePointers { /// (pointerToHeader, pointerToElements) -> Void in /// pointerToElements.deinitialize(count: self.count) /// pointerToHeader.deinitialize() /// } /// } /// /// // All properties are *computed* based on members of the Header /// var count: Int { /// return Manager(unsafeBufferObject: self).header.0 /// } /// var name: String { /// return Manager(unsafeBufferObject: self).header.1 /// } /// } /// @_fixed_layout public struct ManagedBufferPointer<Header, Element> : Equatable { /// Create with new storage containing an initial `Header` and space /// for at least `minimumCapacity` `element`s. /// /// - parameter bufferClass: The class of the object used for storage. /// - parameter minimumCapacity: The minimum number of `Element`s that /// must be able to be stored in the new buffer. /// - parameter factory: A function that produces the initial /// `Header` instance stored in the buffer, given the `buffer` /// object and a function that can be called on it to get the actual /// number of allocated elements. /// /// - Precondition: `minimumCapacity >= 0`, and the type indicated by /// `bufferClass` is a non-`@objc` class with no declared stored /// properties. The `deinit` of `bufferClass` must destroy its /// stored `Header` and any constructed `Element`s. @_inlineable // FIXME(sil-serialize-all) public init( bufferClass: AnyClass, minimumCapacity: Int, makingHeaderWith factory: (_ buffer: AnyObject, _ capacity: (AnyObject) -> Int) throws -> Header ) rethrows { self = ManagedBufferPointer( bufferClass: bufferClass, minimumCapacity: minimumCapacity) // initialize the header field try withUnsafeMutablePointerToHeader { $0.initialize(to: try factory( self.buffer, { ManagedBufferPointer(unsafeBufferObject: $0).capacity })) } // FIXME: workaround for <rdar://problem/18619176>. If we don't // access header somewhere, its addressor gets linked away _ = header } /// Manage the given `buffer`. /// /// - Precondition: `buffer` is an instance of a non-`@objc` class whose /// `deinit` destroys its stored `Header` and any constructed `Element`s. @_inlineable // FIXME(sil-serialize-all) public init(unsafeBufferObject buffer: AnyObject) { ManagedBufferPointer._checkValidBufferClass(type(of: buffer)) self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer) } /// Internal version for use by _ContiguousArrayBuffer where we know that we /// have a valid buffer class. /// This version of the init function gets called from /// _ContiguousArrayBuffer's deinit function. Since 'deinit' does not get /// specialized with current versions of the compiler, we can't get rid of the /// _debugPreconditions in _checkValidBufferClass for any array. Since we know /// for the _ContiguousArrayBuffer that this check must always succeed we omit /// it in this specialized constructor. @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_uncheckedUnsafeBufferObject buffer: AnyObject) { ManagedBufferPointer._sanityCheckValidBufferClass(type(of: buffer)) self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer) } /// The stored `Header` instance. @_inlineable // FIXME(sil-serialize-all) public var header: Header { addressWithNativeOwner { return (UnsafePointer(_headerPointer), _nativeBuffer) } mutableAddressWithNativeOwner { return (_headerPointer, _nativeBuffer) } } /// Returns the object instance being used for storage. @_inlineable // FIXME(sil-serialize-all) public var buffer: AnyObject { return Builtin.castFromNativeObject(_nativeBuffer) } /// The actual number of elements that can be stored in this object. /// /// This value may be nontrivial to compute; it is usually a good /// idea to store this information in the "header" area when /// an instance is created. @_inlineable // FIXME(sil-serialize-all) public var capacity: Int { return (_capacityInBytes &- _My._elementOffset) / MemoryLayout<Element>.stride } /// Call `body` with an `UnsafeMutablePointer` to the stored /// `Header`. /// /// - Note: This pointer is valid only /// for the duration of the call to `body`. @_inlineable // FIXME(sil-serialize-all) public func withUnsafeMutablePointerToHeader<R>( _ body: (UnsafeMutablePointer<Header>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { (v, _) in return try body(v) } } /// Call `body` with an `UnsafeMutablePointer` to the `Element` /// storage. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. @_inlineable // FIXME(sil-serialize-all) public func withUnsafeMutablePointerToElements<R>( _ body: (UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { return try body($1) } } /// Call `body` with `UnsafeMutablePointer`s to the stored `Header` /// and raw `Element` storage. /// /// - Note: These pointers are valid only for the duration of the /// call to `body`. @_inlineable // FIXME(sil-serialize-all) public func withUnsafeMutablePointers<R>( _ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(_nativeBuffer) } return try body(_headerPointer, _elementPointer) } /// Returns `true` iff `self` holds the only strong reference to its buffer. /// /// See `isUniquelyReferenced` for details. @_inlineable // FIXME(sil-serialize-all) public mutating func isUniqueReference() -> Bool { return _isUnique(&_nativeBuffer) } //===--- internal/private API -------------------------------------------===// /// Create with new storage containing space for an initial `Header` /// and at least `minimumCapacity` `element`s. /// /// - parameter bufferClass: The class of the object used for storage. /// - parameter minimumCapacity: The minimum number of `Element`s that /// must be able to be stored in the new buffer. /// /// - Precondition: `minimumCapacity >= 0`, and the type indicated by /// `bufferClass` is a non-`@objc` class with no declared stored /// properties. The `deinit` of `bufferClass` must destroy its /// stored `Header` and any constructed `Element`s. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init( bufferClass: AnyClass, minimumCapacity: Int ) { ManagedBufferPointer._checkValidBufferClass(bufferClass, creating: true) _precondition( minimumCapacity >= 0, "ManagedBufferPointer must have non-negative capacity") self.init( _uncheckedBufferClass: bufferClass, minimumCapacity: minimumCapacity) } /// Internal version for use by _ContiguousArrayBuffer.init where we know that /// we have a valid buffer class and that the capacity is >= 0. @_inlineable // FIXME(sil-serialize-all) @_versioned internal init( _uncheckedBufferClass: AnyClass, minimumCapacity: Int ) { ManagedBufferPointer._sanityCheckValidBufferClass(_uncheckedBufferClass, creating: true) _sanityCheck( minimumCapacity >= 0, "ManagedBufferPointer must have non-negative capacity") let totalSize = _My._elementOffset + minimumCapacity * MemoryLayout<Element>.stride let newBuffer: AnyObject = _swift_bufferAllocate( bufferType: _uncheckedBufferClass, size: totalSize, alignmentMask: _My._alignmentMask) self._nativeBuffer = Builtin.unsafeCastToNativeObject(newBuffer) } /// Manage the given `buffer`. /// /// - Note: It is an error to use the `header` property of the resulting /// instance unless it has been initialized. @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_ buffer: ManagedBuffer<Header, Element>) { _nativeBuffer = Builtin.unsafeCastToNativeObject(buffer) } internal typealias _My = ManagedBufferPointer @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static func _checkValidBufferClass( _ bufferClass: AnyClass, creating: Bool = false ) { _debugPrecondition( _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size || ( (!creating || bufferClass is ManagedBuffer<Header, Element>.Type) && _class_getInstancePositiveExtentSize(bufferClass) == _headerOffset + MemoryLayout<Header>.size), "ManagedBufferPointer buffer class has illegal stored properties" ) _debugPrecondition( _usesNativeSwiftReferenceCounting(bufferClass), "ManagedBufferPointer buffer class must be non-@objc" ) } @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static func _sanityCheckValidBufferClass( _ bufferClass: AnyClass, creating: Bool = false ) { _sanityCheck( _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size || ( (!creating || bufferClass is ManagedBuffer<Header, Element>.Type) && _class_getInstancePositiveExtentSize(bufferClass) == _headerOffset + MemoryLayout<Header>.size), "ManagedBufferPointer buffer class has illegal stored properties" ) _sanityCheck( _usesNativeSwiftReferenceCounting(bufferClass), "ManagedBufferPointer buffer class must be non-@objc" ) } /// The required alignment for allocations of this type, minus 1 @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var _alignmentMask: Int { return max( MemoryLayout<_HeapObject>.alignment, max(MemoryLayout<Header>.alignment, MemoryLayout<Element>.alignment)) &- 1 } /// The actual number of bytes allocated for this object. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _capacityInBytes: Int { return _swift_stdlib_malloc_size(_address) } /// The address of this instance in a convenient pointer-to-bytes form @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _address: UnsafeMutableRawPointer { return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_nativeBuffer)) } /// Offset from the allocated storage for `self` to the stored `Header` @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var _headerOffset: Int { _onFastPath() return _roundUp( MemoryLayout<_HeapObject>.size, toAlignment: MemoryLayout<Header>.alignment) } /// An **unmanaged** pointer to the storage for the `Header` /// instance. Not safe to use without _fixLifetime calls to /// guarantee it doesn't dangle @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _headerPointer: UnsafeMutablePointer<Header> { _onFastPath() return (_address + _My._headerOffset).assumingMemoryBound( to: Header.self) } /// An **unmanaged** pointer to the storage for `Element`s. Not /// safe to use without _fixLifetime calls to guarantee it doesn't /// dangle. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal var _elementPointer: UnsafeMutablePointer<Element> { _onFastPath() return (_address + _My._elementOffset).assumingMemoryBound( to: Element.self) } /// Offset from the allocated storage for `self` to the `Element` storage @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var _elementOffset: Int { _onFastPath() return _roundUp( _headerOffset + MemoryLayout<Header>.size, toAlignment: MemoryLayout<Element>.alignment) } @_inlineable // FIXME(sil-serialize-all) public static func == ( lhs: ManagedBufferPointer, rhs: ManagedBufferPointer ) -> Bool { return lhs._address == rhs._address } @_versioned // FIXME(sil-serialize-all) internal var _nativeBuffer: Builtin.NativeObject } // FIXME: when our calling convention changes to pass self at +0, // inout should be dropped from the arguments to these functions. // FIXME(docs): isKnownUniquelyReferenced should check weak/unowned counts too, // but currently does not. rdar://problem/29341361 /// Returns a Boolean value indicating whether the given object is known to /// have a single strong reference. /// /// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the /// copy-on-write optimization for the deep storage of value types: /// /// mutating func update(withValue value: T) { /// if !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// `isKnownUniquelyReferenced(_:)` checks only for strong references to the /// given object---if `object` has additional weak or unowned references, the /// result may still be `true`. Because weak and unowned references cannot be /// the only reference to an object, passing a weak or unowned reference as /// `object` always results in `false`. /// /// If the instance passed as `object` is being accessed by multiple threads /// simultaneously, this function may still return `true`. Therefore, you must /// only call this function from mutating methods with appropriate thread /// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)` /// only returns `true` when there is really one accessor, or when there is a /// race condition, which is already undefined behavior. /// /// - Parameter object: An instance of a class. This function does *not* modify /// `object`; the use of `inout` is an implementation artifact. /// - Returns: `true` if `object` is known to have a single strong reference; /// otherwise, `false`. @_inlineable public func isKnownUniquelyReferenced<T : AnyObject>(_ object: inout T) -> Bool { return _isUnique(&object) } @_inlineable @_versioned internal func _isKnownUniquelyReferencedOrPinned<T : AnyObject>(_ object: inout T) -> Bool { return _isUniqueOrPinned(&object) } /// Returns a Boolean value indicating whether the given object is known to /// have a single strong reference. /// /// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the /// copy-on-write optimization for the deep storage of value types: /// /// mutating func update(withValue value: T) { /// if !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// `isKnownUniquelyReferenced(_:)` checks only for strong references to the /// given object---if `object` has additional weak or unowned references, the /// result may still be `true`. Because weak and unowned references cannot be /// the only reference to an object, passing a weak or unowned reference as /// `object` always results in `false`. /// /// If the instance passed as `object` is being accessed by multiple threads /// simultaneously, this function may still return `true`. Therefore, you must /// only call this function from mutating methods with appropriate thread /// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)` /// only returns `true` when there is really one accessor, or when there is a /// race condition, which is already undefined behavior. /// /// - Parameter object: An instance of a class. This function does *not* modify /// `object`; the use of `inout` is an implementation artifact. /// - Returns: `true` if `object` is known to have a single strong reference; /// otherwise, `false`. If `object` is `nil`, the return value is `false`. @_inlineable public func isKnownUniquelyReferenced<T : AnyObject>( _ object: inout T? ) -> Bool { return _isUnique(&object) }
b2a0482af17c742800a297c83c861d9d
37.83564
92
0.689179
false
false
false
false
tamanyan/UnlimitedScrollView
refs/heads/master
UnlimitedScrollViewExample/UnlimitedScrollViewExample/TextScrollView.swift
mit
1
// // TextScrollView.swift // UnlimitedScrollViewExample // // Created by tamanyan on 2015/10/26. // Copyright © 2015年 tamanyan. All rights reserved. // import UIKit class TextScrollView: UIScrollView, UIScrollViewDelegate { var textLabel: UILabel? var parantView: UIView? override init(frame: CGRect) { super.init(frame: frame) self.parantView = UIView(frame: frame) self.textLabel = UILabel(frame: frame.insetBy(dx: 20, dy: 100)) self.textLabel?.textColor = UIColor.black self.textLabel?.font = UIFont.boldSystemFont(ofSize: 30) self.textLabel?.textAlignment = .center self.textLabel?.layer.borderColor = UIColor.black.cgColor self.textLabel?.layer.borderWidth = 2.0 self.addSubview(self.parantView!) self.parantView?.addSubview(self.textLabel!) self.clipsToBounds = false self.minimumZoomScale = 1 self.maximumZoomScale = 4.0 self.showsHorizontalScrollIndicator = false self.showsVerticalScrollIndicator = false self.contentSize = self.frame.size self.delegate = self } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.parantView } }
5c83af00adb890884f520baedc8809d7
30.595238
71
0.671439
false
false
false
false
ozgur/TestApp
refs/heads/master
TestApp/Models/Catalogue.swift
gpl-3.0
1
// // Catalogue.swift // TestApp // // Created by Ozgur on 15/02/2017. // Copyright © 2017 Ozgur. All rights reserved. // import ObjectMapper class Catalogue: Mappable { var id: Int = NSNotFound var name: String! var companies: [Company] = [] required init?(map: Map) {} func mapping(map: Map) { id <- map["id"] name <- map["name"] companies <- map["companies"] } } // MARK: Equatable extension Catalogue: Equatable {} func ==(lhs: Catalogue, rhs: Catalogue) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) } // MARK: CustomStringConvertible extension Catalogue: CustomStringConvertible { var description: String { return "Catalogue <\(name)>" } }
97ec107019791b350b476a0bc1699f9b
16.585366
55
0.647712
false
false
false
false
BENMESSAOUD/yousign
refs/heads/master
YouSign/YouSign/BussinesObjects/Signature.swift
apache-2.0
1
// // Signature.swift // YouSign // // Created by Mahmoud Ben Messaoud on 05/06/2017. // Copyright © 2017 Mahmoud Ben Messaoud. All rights reserved. // import Foundation @objc public class Token : NSObject{ public var token: String = kEmptyString public var mail: String? public var phone: String? } @objc public class FileInfo : NSObject{ public var id: String = kEmptyString public var fileName: String = kEmptyString public var sha1: String = kEmptyString } @objc public class Signature: NSObject { public var id: String var files = [FileInfo]() var tokens = [Token]() init(idDemand: String) { self.id = idDemand } public func addFileInfo(fileInfo: FileInfo){ files.append(fileInfo) } public func addToken(token: Token){ tokens.append(token) } public func getToken(forSigner signer: Signer) -> Token { let token = tokens.filter { (item: Token) -> Bool in return signer.mail == item.mail && signer.phone == item.phone } return token.first ?? Token() } }
9c9f75ba78cdfee64303ccc46ca2227c
22.340426
73
0.640839
false
false
false
false
Ivacker/swift
refs/heads/master
test/SILGen/address_only_types.swift
apache-2.0
9
// RUN: %target-swift-frontend -parse-as-library -parse-stdlib -emit-silgen %s | FileCheck %s typealias Int = Builtin.Int64 enum Bool { case true_, false_ } protocol Unloadable { func foo() -> Int var address_only_prop : Unloadable { get } var loadable_prop : Int { get } } // CHECK-LABEL: sil hidden @_TF18address_only_types21address_only_argument func address_only_argument(x: Unloadable) { // CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable): // CHECK: debug_value_addr [[XARG]] // CHECK-NEXT: destroy_addr [[XARG]] // CHECK-NEXT: tuple // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @_TF18address_only_types29address_only_ignored_argument func address_only_ignored_argument(_: Unloadable) { // CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable): // CHECK: destroy_addr [[XARG]] // CHECK-NOT: dealloc_stack {{.*}} [[XARG]] // CHECK: return } // CHECK-LABEL: sil hidden @_TF18address_only_types30address_only_curried_arguments func address_only_curried_arguments(x: Unloadable)(y: Unloadable) { // CHECK: bb0([[YARG:%[0-9]+]] : $*Unloadable, [[XARG:%[0-9]+]] : $*Unloadable): // CHECK-NEXT: debug_value_addr [[YARG]] : $*Unloadable // let y // CHECK-NEXT: debug_value_addr [[XARG]] : $*Unloadable // let x // CHECK-NEXT: destroy_addr [[XARG]] // CHECK-NEXT: destroy_addr [[YARG]] // CHECK-NEXT: tuple // CHECK-NEXT: return } // CHECK-LABEL: sil hidden @_TF18address_only_types41address_only_curried_arguments_and_return func address_only_curried_arguments_and_return(x: Unloadable)(y: Unloadable) -> Unloadable { // CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable, [[YARG:%[0-9]+]] : $*Unloadable, [[XARG:%[0-9]+]] : $*Unloadable): // CHECK-NEXT: debug_value_addr [[YARG]] : $*Unloadable // let y // CHECK-NEXT: debug_value_addr [[XARG]] : $*Unloadable // let x // CHECK-NEXT: copy_addr [take] [[XARG]] to [initialization] [[RET]] // CHECK-NEXT: destroy_addr [[YARG]] // CHECK-NEXT: tuple // CHECK-NEXT: return return x } // CHECK-LABEL: sil hidden @_TF18address_only_types19address_only_return func address_only_return(x: Unloadable, y: Int) -> Unloadable { // CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable, [[XARG:%[0-9]+]] : $*Unloadable, [[YARG:%[0-9]+]] : $Builtin.Int64): // CHECK-NEXT: debug_value_addr [[XARG]] : $*Unloadable // let x // CHECK-NEXT: debug_value [[YARG]] : $Builtin.Int64 // let y // CHECK-NEXT: copy_addr [take] [[XARG]] to [initialization] [[RET]] // CHECK-NEXT: [[VOID:%[0-9]+]] = tuple () // CHECK-NEXT: return [[VOID]] return x } // CHECK-LABEL: sil hidden @_TF18address_only_types27address_only_curried_return func address_only_curried_return(x: Unloadable)(y: Int) -> Unloadable { // CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable, [[YARG:%[0-9]+]] : $Builtin.Int64, [[XADDR:%[0-9]+]] : $*Unloadable): // CHECK-NEXT: debug_value [[YARG]] : $Builtin.Int64 // let y // CHECK-NEXT: debug_value_addr [[XADDR]] : $*Unloadable // let x // CHECK-NEXT: copy_addr [take] [[XADDR]] to [initialization] [[RET]] // CHECK-NEXT: [[VOID:%[0-9]+]] = tuple () // CHECK-NEXT: return [[VOID]] return x } // CHECK-LABEL: sil hidden @_TF18address_only_types27address_only_missing_return func address_only_missing_return() -> Unloadable { // CHECK: unreachable } // CHECK-LABEL: sil hidden @_TF18address_only_types39address_only_conditional_missing_return func address_only_conditional_missing_return(x: Unloadable) -> Unloadable { // CHECK: bb0({{%.*}} : $*Unloadable, {{%.*}} : $*Unloadable): // CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE:bb[0-9]+]] switch Bool.true_ { case .true_: // CHECK: [[TRUE]]: // CHECK: copy_addr [take] %1 to [initialization] %0 : $*Unloadable // CHECK: return return x case .false_: () } // CHECK: [[FALSE]]: // CHECK: unreachable } // CHECK-LABEL: sil hidden @_TF18address_only_types41address_only_conditional_missing_return func address_only_conditional_missing_return_2(x: Unloadable) -> Unloadable { // CHECK: bb0({{%.*}} : $*Unloadable, {{%.*}} : $*Unloadable): // CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE1:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE1:bb[0-9]+]] switch Bool.true_ { case .true_: return x case .false_: () } // CHECK: [[FALSE1]]: // CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE2:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE2:bb[0-9]+]] switch Bool.true_ { case .true_: return x case .false_: () } // CHECK: [[FALSE2]]: // CHECK: unreachable // CHECK: bb{{.*}}: // CHECK: return } var crap : Unloadable = some_address_only_function_1() func some_address_only_function_1() -> Unloadable { return crap } func some_address_only_function_2(x: Unloadable) -> () {} // CHECK-LABEL: sil hidden @_TF18address_only_types19address_only_call func address_only_call_1() -> Unloadable { // CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable): return some_address_only_function_1() // FIXME emit into // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_1FT_PS_10Unloadable_ // CHECK: apply [[FUNC]]([[RET]]) // CHECK: return } // CHECK-LABEL: sil hidden @_TF18address_only_types33address_only_call_1_ignore_returnFT_T_ func address_only_call_1_ignore_return() { // CHECK: bb0: some_address_only_function_1() // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_1FT_PS_10Unloadable_ // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: apply [[FUNC]]([[TEMP]]#1) // CHECK: destroy_addr [[TEMP]]#1 // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: return } // CHECK-LABEL: sil hidden @_TF18address_only_types19address_only_call_2 func address_only_call_2(x: Unloadable) { // CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable): // CHECK: debug_value_addr [[XARG]] : $*Unloadable some_address_only_function_2(x) // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_2 // CHECK: [[X_CALL_ARG:%[0-9]+]] = alloc_stack $Unloadable // CHECK: copy_addr [[XARG]] to [initialization] [[X_CALL_ARG]] // CHECK: apply [[FUNC]]([[X_CALL_ARG]]#1) // CHECK: dealloc_stack [[X_CALL_ARG]]#0 // CHECK: return } // CHECK-LABEL: sil hidden @_TF18address_only_types24address_only_call_1_in_2 func address_only_call_1_in_2() { // CHECK: bb0: some_address_only_function_2(some_address_only_function_1()) // CHECK: [[FUNC2:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_2 // CHECK: [[FUNC1:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_1 // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: apply [[FUNC1]]([[TEMP]]#1) // CHECK: apply [[FUNC2]]([[TEMP]]#1) // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: return } // CHECK-LABEL: sil hidden @_TF18address_only_types24address_only_materialize func address_only_materialize() -> Int { // CHECK: bb0: return some_address_only_function_1().foo() // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF18address_only_types28some_address_only_function_1 // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: apply [[FUNC]]([[TEMP]]#1) // CHECK: [[TEMP_PROJ:%[0-9]+]] = open_existential_addr [[TEMP]]#1 : $*Unloadable to $*[[OPENED:@opened(.*) Unloadable]] // CHECK: [[FOO_METHOD:%[0-9]+]] = witness_method $[[OPENED]], #Unloadable.foo!1 // CHECK: [[RET:%[0-9]+]] = apply [[FOO_METHOD]]<[[OPENED]]>([[TEMP_PROJ]]) // CHECK: destroy_addr [[TEMP_PROJ]] // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden @_TF18address_only_types33address_only_assignment_from_temp func address_only_assignment_from_temp(inout dest: Unloadable) { // CHECK: bb0([[DEST:%[0-9]+]] : $*Unloadable): // CHECK: [[DEST_LOCAL:%.*]] = alloc_box $Unloadable // CHECK: copy_addr [[DEST]] to [initialization] [[DEST_LOCAL]]#1 dest = some_address_only_function_1() // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: copy_addr [take] [[TEMP]]#1 to [[DEST_LOCAL]]#1 : // CHECK-NOT: destroy_addr [[TEMP]]#1 // CHECK: dealloc_stack [[TEMP]]#0 // CHECK: copy_addr [[DEST_LOCAL]]#1 to [[DEST]] // CHECK: release [[DEST_LOCAL]]#0 } // CHECK-LABEL: sil hidden @_TF18address_only_types31address_only_assignment_from_lv func address_only_assignment_from_lv(inout dest: Unloadable, v: Unloadable) { var v = v // CHECK: bb0([[DEST:%[0-9]+]] : $*Unloadable, [[VARG:%[0-9]+]] : $*Unloadable): // CHECK: [[DEST_LOCAL:%.*]] = alloc_box $Unloadable // CHECK: copy_addr [[DEST]] to [initialization] [[DEST_LOCAL]]#1 // CHECK: [[VBOX:%.*]] = alloc_box $Unloadable // CHECK: copy_addr [[VARG]] to [initialization] [[VBOX]]#1 dest = v // FIXME: emit into? // CHECK: copy_addr [[VBOX]]#1 to [[DEST_LOCAL]]#1 : // CHECK: release [[VBOX]]#0 // CHECK: copy_addr [[DEST_LOCAL]]#1 to [[DEST]] // CHECK: release [[DEST_LOCAL]]#0 } var global_prop : Unloadable { get { return crap } set {} } // CHECK-LABEL: sil hidden @_TF18address_only_types45address_only_assignment_from_temp_to_property func address_only_assignment_from_temp_to_property() { // CHECK: bb0: global_prop = some_address_only_function_1() // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: [[SETTER:%[0-9]+]] = function_ref @_TF18address_only_typess11global_propPS_10Unloadable_ // CHECK: apply [[SETTER]]([[TEMP]]#1) // CHECK: dealloc_stack [[TEMP]]#0 } // CHECK-LABEL: sil hidden @_TF18address_only_types43address_only_assignment_from_lv_to_property func address_only_assignment_from_lv_to_property(v: Unloadable) { // CHECK: bb0([[VARG:%[0-9]+]] : $*Unloadable): // CHECK: debug_value_addr [[VARG]] : $*Unloadable // CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable // CHECK: copy_addr [[VARG]] to [initialization] [[TEMP]] // CHECK: [[SETTER:%[0-9]+]] = function_ref @_TF18address_only_typess11global_propPS_10Unloadable_ // CHECK: apply [[SETTER]]([[TEMP]]#1) // CHECK: dealloc_stack [[TEMP]]#0 global_prop = v } // CHECK-LABEL: sil hidden @_TF18address_only_types16address_only_varFT_PS_10Unloadable_ func address_only_var() -> Unloadable { // CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable): var x = some_address_only_function_1() // CHECK: [[XBOX:%[0-9]+]] = alloc_box $Unloadable // CHECK: apply {{%.*}}([[XBOX]]#1) return x // CHECK: copy_addr [[XBOX]]#1 to [initialization] [[RET]] // CHECK: release [[XBOX]]#0 // CHECK: return } func unloadable_to_unloadable(x: Unloadable) -> Unloadable { return x } var some_address_only_nontuple_arg_function : (Unloadable) -> Unloadable = unloadable_to_unloadable // CHECK-LABEL: sil hidden @_TF18address_only_types39call_address_only_nontuple_arg_function func call_address_only_nontuple_arg_function(x: Unloadable) { some_address_only_nontuple_arg_function(x) }
b0af3b81dd485f6f7840bccf24bbcd21
40
127
0.637997
false
false
false
false
TheInfiniteKind/duckduckgo-iOS
refs/heads/develop
DuckDuckGo/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // DuckDuckGo // // Created by Mia Alexiou on 18/01/2017. // Copyright © 2017 DuckDuckGo. All rights reserved. // import UIKit import Core @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { private struct ShortcutKey { static let search = "com.duckduckgo.mobile.ios.newsearch" static let clipboard = "com.duckduckgo.mobile.ios.clipboard" } var window: UIWindow? private lazy var groupData = GroupDataStore() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if let shortcutItem = launchOptions?[.shortcutItem] { handleShortCutItem(shortcutItem as! UIApplicationShortcutItem) } return true } func applicationDidBecomeActive(_ application: UIApplication) { startOnboardingFlowIfNotSeenBefore() } private func startOnboardingFlowIfNotSeenBefore() { var settings = OnboardingSettings() if !settings.hasSeenOnboarding { startOnboardingFlow() settings.hasSeenOnboarding = true } } private func startOnboardingFlow() { guard let root = mainViewController() else { return } let onboardingController = OnboardingViewController.loadFromStoryboard() onboardingController.modalTransitionStyle = .flipHorizontal root.present(onboardingController, animated: false, completion: nil) } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { handleShortCutItem(shortcutItem) } private func handleShortCutItem(_ shortcutItem: UIApplicationShortcutItem) { Logger.log(text: "Handling shortcut item: \(shortcutItem.type)") if shortcutItem.type == ShortcutKey.search { clearNavigationStack() } if shortcutItem.type == ShortcutKey.clipboard, let query = UIPasteboard.general.string { mainViewController()?.loadQueryInNewWebTab(query: query) } } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { Logger.log(text: "App launched with url \(url.absoluteString)") clearNavigationStack() if AppDeepLinks.isLaunch(url: url) { return true } if AppDeepLinks.isQuickLink(url: url), let link = quickLink(from: url) { loadQuickLink(link: link) } return true } private func quickLink(from url: URL) -> Link? { guard let links = groupData.bookmarks else { return nil } guard let host = url.host else { return nil } guard let index = Int(host) else { return nil } guard index < links.count else { return nil } return links[index] } private func loadQuickLink(link: Link) { mainViewController()?.loadUrlInNewWebTab(url: link.url) } private func mainViewController() -> MainViewController? { return UIApplication.shared.keyWindow?.rootViewController?.childViewControllers.first as? MainViewController } private func clearNavigationStack() { if let navigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController { navigationController.popToRootViewController(animated: false) } } }
eb8957c27abc79baa773608e47004902
35.132653
155
0.672974
false
false
false
false
GuitarPlayer-Ma/Swiftweibo
refs/heads/master
weibo/weibo/AppDelegate.swift
mit
1
// // AppDelegate.swift // weibo // // Created by mada on 15/9/27. // Copyright © 2015年 MD. All rights reserved. // import UIKit let JSJSwitchRootViewController = "JSJSwitchRootViewController" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // 设置外观 UINavigationBar.appearance().tintColor = UIColor.orangeColor() UITabBar.appearance().tintColor = UIColor.orangeColor() window = UIWindow(frame: UIScreen.mainScreen().bounds) // 返回默认控制器 window?.rootViewController = defaultViewController() window?.makeKeyAndVisible() // 注册通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("switchRootViewController:"), name: JSJSwitchRootViewController, object: nil) return true } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func switchRootViewController(notify: NSNotification) { if notify.object != nil { window?.rootViewController = WelcomeController() } window?.rootViewController = MainTabbarController() } /** 判断是不是新版本 */ private func isNewUpdate() -> Bool { // 获取当前版本号 let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]! as! String // 从沙盒中取出上次版本号(??作用:如果为nil则取??后面的值) let lastVersion = NSUserDefaults.standardUserDefaults().valueForKey("version") ?? "" // 比较两个版本 if currentVersion.compare(lastVersion as! String) == NSComparisonResult.OrderedDescending { NSUserDefaults.standardUserDefaults().setValue(currentVersion, forKey: "version") return true } return false } private func defaultViewController() -> UIViewController { // 判断是否登录 if UserAccount.loadAccount() != nil { return isNewUpdate() ? NewfeatureController() : WelcomeController() } // 保存当前版本 isNewUpdate() return MainTabbarController() } } /** 自定义打印输出*/ func JSJLog<T>(message: T, fileName: String = __FILE__, line: Int = __LINE__, method: String = __FUNCTION__) { #if DEBUG print("<\((fileName as NSString).lastPathComponent)>**\(line)**[\(method)]--\(message)") #endif }
27e818ce2c4adc65da713f89b49f944b
30.594937
159
0.642628
false
false
false
false
lavenderofme/MySina
refs/heads/master
Sina/Sina/Classes/Main/VisitorView.swift
apache-2.0
1
// // VisitorView.swift // Sina // // Created by shasha on 15/11/9. // Copyright © 2015年 shasha. All rights reserved. // import UIKit class VisitorView: UIView { /** 中间的文字 */ @IBOutlet weak var titleLabel: UILabel! /** 登录按钮 */ @IBOutlet weak var loginButton: UIButton! /** 注册按钮 */ @IBOutlet weak var registerButton: UIButton! /** 大图片 */ @IBOutlet weak var imageVIew: UIImageView! /** 转盘 */ @IBOutlet weak var circleView: UIImageView! // MARK: - 外部控制方法 func setupVisitorInfo(imageNamed: String?, title:String) { guard let name = imageNamed else { starAnimation() return } imageVIew.image = UIImage(named: name) titleLabel.text = title circleView.hidden = true } /** 快速创建方法 */ class func visitorView() -> VisitorView { return NSBundle.mainBundle().loadNibNamed("VisitorView", owner: nil, options: nil).last as! VisitorView } // MARK: - 内部控制方法 func starAnimation(){ // 1.创建动画对象 let anim = CABasicAnimation(keyPath: "transform.rotation") // 2.设置动画属性 anim.toValue = 2 * M_PI anim.duration = 10.0 anim.repeatCount = MAXFLOAT // 告诉系统不要随便给我移除动画, 只有当控件销毁的时候才需要移除 anim.removedOnCompletion = false // 3.将动画添加到图层 circleView.layer.addAnimation(anim, forKey: nil) } }
52be094c1a420980d24be4ed0683c662
23.810345
111
0.584434
false
false
false
false
qinhaichuan/Microblog
refs/heads/master
microblog/microblog/Classes/OAuth/UserAccount.swift
mit
1
// // UserAccount.swift // microblog // // Created by QHC on 6/18/16. // Copyright © 2016 秦海川. All rights reserved. // import UIKit class UserAccount: NSObject, NSCoding { /// 用于调用access_token,接口获取授权后的access token。 var access_token: String? /// access_token的生命周期,单位是秒数。 var expires_in: NSNumber? { didSet{ expires_Date = NSDate(timeIntervalSinceNow: expires_in!.doubleValue) QHCLog("生命周期\(expires_Date)") } } /// 当前授权用户的UID。 var uid: String? /// 过期时间 var expires_Date: NSDate? static var userAccount: UserAccount? init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } override var description: String { let proterty = ["access_token", "expires_in", "uid"] let dict = dictionaryWithValuesForKeys(proterty) return "\(dict)" } // MARK: ----- 保存模型到文件中 static let filePath = "userAccount.plist".cacheDirectory() /** * 保存模型 */ func saveAccount() { NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.filePath) } /** * 取出模型 */ class func getUserAccount() -> UserAccount? { if userAccount != nil { return userAccount! } QHCLog("从文件中取出") // 如果没有就取出 userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.filePath) as? UserAccount // 把刚登录时的时间取出了, 对比是否过期 guard let date = userAccount?.expires_Date where date.compare(NSDate()) == NSComparisonResult.OrderedDescending else { QHCLog("已经过期\(userAccount)") userAccount = nil return userAccount } return userAccount! } /** * 判断是否登录 */ class func login() -> Bool { return getUserAccount() != nil } // MARK: ----- NSCoding /** * 归档 */ func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(access_token, forKey: "access_token") aCoder.encodeObject(expires_in, forKey: "expires_in") aCoder.encodeObject(uid, forKey: "uid") aCoder.encodeObject(expires_Date, forKey: "expires_Date") } /** * 解档 */ required init?(coder aDecoder: NSCoder) { access_token = aDecoder.decodeObjectForKey("access_token") as? String expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber uid = aDecoder.decodeObjectForKey("uid") as? String expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate } }
c1fee71ecc43e48100c7426b807e65e7
23
126
0.571225
false
false
false
false
sarukun99/CoreStore
refs/heads/master
CoreStore/Observing/ObjectMonitor.swift
mit
1
// // ObjectMonitor.swift // CoreStore // // Copyright (c) 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData // MARK: - ObjectMonitor /** The `ObjectMonitor` monitors changes to a single `NSManagedObject` instance. Observers that implement the `ObjectObserver` protocol may then register themselves to the `ObjectMonitor`'s `addObserver(_:)` method: let monitor = CoreStore.monitorObject(object) monitor.addObserver(self) The created `ObjectMonitor` instance needs to be held on (retained) for as long as the object needs to be observed. Observers registered via `addObserver(_:)` are not retained. `ObjectMonitor` only keeps a `weak` reference to all observers, thus keeping itself free from retain-cycles. */ public final class ObjectMonitor<T: NSManagedObject> { // MARK: Public /** Returns the `NSManagedObject` instance being observed, or `nil` if the object was already deleted. */ public var object: T? { return self.fetchedResultsController.fetchedObjects?.first as? T } /** Returns `true` if the `NSManagedObject` instance being observed still exists, or `false` if the object was already deleted. */ public var isObjectDeleted: Bool { return self.object?.managedObjectContext == nil } /** Registers an `ObjectObserver` to be notified when changes to the receiver's `object` are made. To prevent retain-cycles, `ObjectMonitor` only keeps `weak` references to its observers. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. Calling `addObserver(_:)` multiple times on the same observer is safe, as `ObjectMonitor` unregisters previous notifications to the observer before re-registering them. - parameter observer: an `ObjectObserver` to send change notifications to */ public func addObserver<U: ObjectObserver where U.ObjectEntityType == T>(observer: U) { CoreStore.assert( NSThread.isMainThread(), "Attempted to add an observer of type \(typeName(observer)) outside the main thread." ) self.removeObserver(observer) self.registerChangeNotification( &self.willChangeObjectKey, name: ObjectMonitorWillChangeObjectNotification, toObserver: observer, callback: { [weak observer] (monitor) -> Void in guard let object = monitor.object, let observer = observer else { return } observer.objectMonitor(monitor, willUpdateObject: object) } ) self.registerObjectNotification( &self.didDeleteObjectKey, name: ObjectMonitorDidDeleteObjectNotification, toObserver: observer, callback: { [weak observer] (monitor, object) -> Void in guard let observer = observer else { return } observer.objectMonitor(monitor, didDeleteObject: object) } ) self.registerObjectNotification( &self.didUpdateObjectKey, name: ObjectMonitorDidUpdateObjectNotification, toObserver: observer, callback: { [weak self, weak observer] (monitor, object) -> Void in guard let strongSelf = self, let observer = observer else { return } let previousCommitedAttributes = strongSelf.lastCommittedAttributes let currentCommitedAttributes = object.committedValuesForKeys(nil) as! [String: NSObject] var changedKeys = Set<String>() for key in currentCommitedAttributes.keys { if previousCommitedAttributes[key] != currentCommitedAttributes[key] { changedKeys.insert(key) } } strongSelf.lastCommittedAttributes = currentCommitedAttributes observer.objectMonitor( monitor, didUpdateObject: object, changedPersistentKeys: changedKeys ) } ) } /** Unregisters an `ObjectObserver` from receiving notifications for changes to the receiver's `object`. For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread. - parameter observer: an `ObjectObserver` to unregister notifications to */ public func removeObserver<U: ObjectObserver where U.ObjectEntityType == T>(observer: U) { CoreStore.assert( NSThread.isMainThread(), "Attempted to remove an observer of type \(typeName(observer)) outside the main thread." ) let nilValue: AnyObject? = nil setAssociatedRetainedObject(nilValue, forKey: &self.willChangeObjectKey, inObject: observer) setAssociatedRetainedObject(nilValue, forKey: &self.didDeleteObjectKey, inObject: observer) setAssociatedRetainedObject(nilValue, forKey: &self.didUpdateObjectKey, inObject: observer) } // MARK: Internal internal init(dataStack: DataStack, object: T) { let context = dataStack.mainContext let fetchRequest = NSFetchRequest() fetchRequest.entity = object.entity fetchRequest.fetchLimit = 0 fetchRequest.resultType = .ManagedObjectResultType fetchRequest.sortDescriptors = [] fetchRequest.includesPendingChanges = false fetchRequest.shouldRefreshRefetchedObjects = true let originalObjectID = object.objectID Where("SELF", isEqualTo: originalObjectID).applyToFetchRequest(fetchRequest) let fetchedResultsController = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil ) let fetchedResultsControllerDelegate = FetchedResultsControllerDelegate() self.fetchedResultsController = fetchedResultsController self.fetchedResultsControllerDelegate = fetchedResultsControllerDelegate self.parentStack = dataStack fetchedResultsControllerDelegate.handler = self fetchedResultsControllerDelegate.fetchedResultsController = fetchedResultsController try! fetchedResultsController.performFetch() self.lastCommittedAttributes = (self.object?.committedValuesForKeys(nil) as? [String: NSObject]) ?? [:] } // MARK: Private private let fetchedResultsController: NSFetchedResultsController private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate private var lastCommittedAttributes = [String: NSObject]() private weak var parentStack: DataStack? private var willChangeObjectKey: Void? private var didDeleteObjectKey: Void? private var didUpdateObjectKey: Void? private func registerChangeNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<T>) -> Void) { setAssociatedRetainedObject( NotificationObserver( notificationName: name, object: self, closure: { [weak self] (note) -> Void in guard let strongSelf = self else { return } callback(monitor: strongSelf) } ), forKey: notificationKey, inObject: observer ) } private func registerObjectNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<T>, object: T) -> Void) { setAssociatedRetainedObject( NotificationObserver( notificationName: name, object: self, closure: { [weak self] (note) -> Void in guard let strongSelf = self, let userInfo = note.userInfo, let object = userInfo[UserInfoKeyObject] as? T else { return } callback(monitor: strongSelf, object: object) } ), forKey: notificationKey, inObject: observer ) } } // MARK: - ObjectMonitor: Equatable public func ==<T: NSManagedObject>(lhs: ObjectMonitor<T>, rhs: ObjectMonitor<T>) -> Bool { return lhs === rhs } extension ObjectMonitor: Equatable { } // MARK: - ObjectMonitor: FetchedResultsControllerHandler extension ObjectMonitor: FetchedResultsControllerHandler { // MARK: FetchedResultsControllerHandler internal func controllerWillChangeContent(controller: NSFetchedResultsController) { NSNotificationCenter.defaultCenter().postNotificationName( ObjectMonitorWillChangeObjectNotification, object: self ) } internal func controllerDidChangeContent(controller: NSFetchedResultsController) { } internal func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Delete: NSNotificationCenter.defaultCenter().postNotificationName( ObjectMonitorDidDeleteObjectNotification, object: self, userInfo: [UserInfoKeyObject: anObject] ) case .Update: NSNotificationCenter.defaultCenter().postNotificationName( ObjectMonitorDidUpdateObjectNotification, object: self, userInfo: [UserInfoKeyObject: anObject] ) default: break } } internal func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { } internal func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String?) -> String? { return sectionName } } private let ObjectMonitorWillChangeObjectNotification = "ObjectMonitorWillChangeObjectNotification" private let ObjectMonitorDidDeleteObjectNotification = "ObjectMonitorDidDeleteObjectNotification" private let ObjectMonitorDidUpdateObjectNotification = "ObjectMonitorDidUpdateObjectNotification" private let UserInfoKeyObject = "UserInfoKeyObject"
13c67bde758c063461ee0d4c55b632c5
38.247649
220
0.639137
false
false
false
false
tarunon/NotificationKit
refs/heads/master
NotificationKitTests/NotificationKitTests.swift
mit
1
// // NotificationKitTests.swift // NotificationKitTests // // Created by Nobuo Saito on 2015/08/04. // Copyright © 2015年 tarunon. All rights reserved. // import XCTest @testable import NotificationKit class SampleNotification: Notification<NSObject, String> { override var name: String { return "SampleNotification" } } class SampleNotification2: SimpleNotification<Int> { override var name: String { return "SampleNotification2" } } class NotificationKitTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testPostNotification() { let sampleNotification = SampleNotification() let notificationObject = NSObject() let notificationValue = "It is SampleNotification" let observer = sampleNotification.addObserver(notificationObject, queue: nil) { object, value in XCTAssertNotNil(object) XCTAssertEqual(object!, notificationObject) XCTAssertEqual(value, notificationValue) } sampleNotification.postNotification(notificationObject, value: notificationValue) sampleNotification.postNotification(nil, value: "It is not observed at \(observer)") } func testPostNotification2() { let sampleNotification = SampleNotification2() let notificationValue = 1984 sampleNotification.addObserver(nil) { value in XCTAssertEqual(value, notificationValue) } sampleNotification.postNotification(notificationValue) } func testRemoveNotification() { var sampleNotification: SampleNotification! autoreleasepool { sampleNotification = SampleNotification() let observer = sampleNotification.addObserver(nil, queue: nil) { object, value in XCTFail() } sampleNotification.removeObserver(observer) } sampleNotification.postNotification(nil, value: "It is not observed.") } func testRemoveNotification2() { var sampleNotification: SampleNotification2! autoreleasepool { sampleNotification = SampleNotification2() let observer = sampleNotification.addObserver(nil, handler: { value in XCTFail() }) sampleNotification.removeObserver(observer) } sampleNotification.postNotification(1984) } }
efb822dfa79a629b13a782b65a389e50
29.265957
111
0.633392
false
true
false
false
Ryan-Vanderhoef/Antlers
refs/heads/master
AppIdea/ViewControllers/FriendsViewController.swift
mit
1
// // FriendsViewController.swift // AppIdea // // Created by Ryan Vanderhoef on 7/23/15. // Copyright (c) 2015 Ryan Vanderhoef. All rights reserved. // import UIKit import Parse class FriendsViewController: UIViewController { @IBOutlet weak var friendsTableView: UITableView! var users: [PFUser] = []//? // All users // var followingUsers: [PFUser]? { // didSet { // friendsTableView.reloadData() // } // } @IBOutlet weak var segmentedControl: UISegmentedControl! @IBAction func segmentedControlAction(sender: AnyObject) { viewDidAppear(true) } // @IBOutlet weak var segmentedControl: UISegmentedControl! // @IBAction func segmentedControlAction(sender: AnyObject) { //// println("seg pressed") // viewDidAppear(true) // } override func viewDidLoad() { super.viewDidLoad() // self.friendsTableView.delegate = self // Do any additional setup after loading the view. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //let friendPostQuery = PFQuery(className: "FriendRelation") // if segmentedControl.selectedSegmentIndex == 0 { // // Only want my friends // let friendPostQuery = PFQuery(className: "FriendRelation") //// println("first: \(friendPostQuery)") // friendPostQuery.whereKey("fromUser", equalTo: PFUser.currentUser()!) //// println("second: \(friendPostQuery)") // friendPostQuery.selectKeys(["toUser"]) //// println("thrid: \(friendPostQuery)") // friendPostQuery.orderByAscending("fromUser") //// println("fourth: \(friendPostQuery)") // friendPostQuery.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in //// println("results: \(result)") // self.users = result as? [PFUser] ?? [] //// println("in here") //// println("\(self.users)") // self.friendsTableView.reloadData() // } // // } // else if segmentedControl.selectedSegmentIndex == 1 { // Want all users // if segmentedControl.selectedSegmentIndex == 1{ let friendPostQuery = PFUser.query()! friendPostQuery.whereKey("username", notEqualTo: PFUser.currentUser()!.username!) // exclude the current user friendPostQuery.orderByAscending("username") // Order first by username, alphabetically friendPostQuery.addAscendingOrder("ObjectId") // Then order by ObjectId, alphabetically friendPostQuery.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in // println("qwerty: \(result)") self.users = result as? [PFUser] ?? [] self.friendsTableView.reloadData() println("\(self.users)") } // } // else if segmentedControl.selectedSegmentIndex == 0 { // println("my herd") // let friendsPostQuery = PFQuery(className: "FriendRelation") // friendsPostQuery.whereKey("fromUser", equalTo: PFUser.currentUser()!) // friendsPostQuery.selectKeys(["toUser"]) // friendsPostQuery.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in // // println("qwerty: \(result)") // var holding = result// as? [NSObject] // println("holding : \(holding)") //// var thing = holding![0] //// println("thing : \(thing)") // // self.users = result as? [PFUser] ?? [] // self.friendsTableView.reloadData() // println("\(self.users)") // } // } // } } 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. println("preparing for segue") println("segue is \(segue.identifier)") if segue.identifier == "segueToSelectedFawn" { let friendViewController = segue.destinationViewController as! SelectedFriendViewController let indexPath = friendsTableView.indexPathForSelectedRow() self.friendsTableView.deselectRowAtIndexPath(indexPath!, animated: false) let selectedFriend = users[indexPath!.row] friendViewController.friend = selectedFriend } } } extension FriendsViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.users/*?*/.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("FriendCell") as! FriendsTableViewCell // cell.titleLabel!.text = "\(moviePosts[indexPath.row].Title)" // cell.yearLabel!.text = "\(moviePosts[indexPath.row].Year)" // cell.statusLabel!.text = "\(moviePosts[indexPath.row].Status)" cell.friendsLabel!.text = "\(self.users/*!*/[indexPath.row].username!)" //cell.friendsLabel!.text = "hello" // let query = PFQuery(className: "FriendRelation") // let test = PFQuery(className: "user") // println("good1") // var name = test.getObjectInBackgroundWithId(users![indexPath.row].objectId!) as! PFObject // println("good2") // query.whereKey("toUser", equalTo: name) // println("good3") // query.whereKey("fromUser", equalTo: PFUser.currentUser()!) // println("good4") // query.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in //// println("qwerty: \(result)") //// self.users = result as? [PFUser] ?? [] //// self.friendsTableView.reloadData() // println("toUser: \(self.users![indexPath.row].username!)") // println(result) // // } // if segmentedControl.selectedSegmentIndex == 0 { // // Color To Watch movies as gray // if moviePosts[indexPath.row].Status == "To Watch" { // cell.backgroundColor = UIColor(red: 128/255, green: 128/255, blue: 128/255, alpha: 0.06) // } // // Color Have Watched movies as white // else if moviePosts[indexPath.row].Status == "Have Watched" { // cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.16) // } // } // else { // // Color all movies white // cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.16) // } // // if moviePosts[indexPath.row].Status == "Have Watched" { // // If a movie has been watched, show rating // var rate = moviePosts[indexPath.row].Rating // if rate == 1 {cell.ratingLabel!.text = "Rating: ★☆☆☆☆"} // else if rate == 2 {cell.ratingLabel!.text = "Rating: ★★☆☆☆"} // else if rate == 3 {cell.ratingLabel!.text = "Rating: ★★★☆☆"} // else if rate == 4 {cell.ratingLabel!.text = "Rating: ★★★★☆"} // else if rate == 5 {cell.ratingLabel!.text = "Rating: ★★★★★"} // else {cell.ratingLabel!.text = ""} // // } // else { // // If a movie has not been watched, don't show a rating // cell.ratingLabel!.text = "" // } return cell } @IBAction func unwindToSegueFriends(segue: UIStoryboardSegue) { if let identifier = segue.identifier { println("indentifier is \(identifier)") } } }
2416dbb733fb55d16dbdad3e5a68d987
39.365385
123
0.571701
false
false
false
false
nerdycat/Cupcake
refs/heads/master
Cupcake/Label.swift
mit
1
// // Label.swift // Cupcake // // Created by nerdycat on 2017/3/17. // Copyright © 2017 nerdycat. All rights reserved. // import UIKit public var Label: UILabel { cpk_swizzleMethodsIfNeed() let label = UILabel() return label } public extension UILabel { /** * Setting text or attributedText * str can take any kind of value, even primitive type like Int. * Usages: .str(1024) .str("hello world") .str( AttStr("hello world").strikethrough() ) ... */ @objc @discardableResult func str(_ any: Any?) -> Self { if let attStr = any as? NSAttributedString { self.attributedText = attStr } else if let any = any { self.text = String(describing: any) } else { self.text = nil } return self } /** * Setting font * font use Font() internally, so it can take any kind of values that Font() supported. * See Font.swift for more information. * Usages: .font(15) .font("20") .font("body") .font("Helvetica,15") .font(someLabel.font) ... **/ @objc @discardableResult func font(_ any: Any) -> Self { self.font = Font(any) return self } /** * Setting textColor * color use Color() internally, so it can take any kind of values that Color() supported. * See Color.swift for more information. * Usages: .color(@"red") .color(@"#F00") .color(@"255,0,0") .color(someLabel.textColor) ... */ @objc @discardableResult func color(_ any: Any) -> Self { self.textColor = Color(any) return self } /** * Setting numberOfLines * Usages: .lines(2) .lines(0) //multilines .lines() //same as .lines(0) */ @objc @discardableResult func lines(_ numberOfLines: CGFloat = 0) -> Self { self.numberOfLines = Int(numberOfLines) return self } /** * Setting lineSpacing * Usages: .lineGap(8) */ @objc @discardableResult func lineGap(_ lineSpacing: CGFloat) -> Self { self.cpkLineGap = lineSpacing return self } /** * Setting textAlignment * Usages: .align(.center) .align(.justified) ... */ @objc @discardableResult func align(_ textAlignment: NSTextAlignment) -> Self { self.textAlignment = textAlignment return self } /** * Setup link handler. * Use onLink in conjunction with AttStr's link method to make text clickable. * This will automatically set isUserInteractionEnabled to true as well. * Be aware of retain cycle when using this method. * Usages: .onLink({ text in print(text) }) .onLink({ [weak self] text in //capture self as weak reference when needed print(text) }) */ @discardableResult func onLink(_ closure: @escaping (String)->()) -> Self { self.isUserInteractionEnabled = true self.cpkLinkHandler = closure return self } }
393353974556e59253e8533d4ed0b2db
24.886179
94
0.556533
false
false
false
false
git-hushuai/MOMO
refs/heads/master
MMHSMeterialProject/UINavigationController/BusinessFile/简历库Item/TKOptimizeCell.swift
mit
1
// // TKOptimizeCell.swift // MMHSMeterialProject // // Created by hushuaike on 16/4/12. // Copyright © 2016年 hushuaike. All rights reserved. // import UIKit class TKOptimizeCell: UITableViewCell { var logoView:UIImageView = UIImageView(); var jobNameLabel:UILabel = UILabel(); var firstBaseInfoLabel:UILabel = UILabel(); var secondBaseInfoLabel:UILabel = UILabel(); var threeBaseInfoLabel :UILabel = UILabel(); var fourBaseInfoLabel:UILabel = UILabel(); var baseInfoLogoView:UIImageView = UIImageView(); var baseInfoPhoneView:UIImageView = UIImageView(); var baseInfoEmailView :UIImageView = UIImageView(); var baseInfoLogoLabel:UILabel = UILabel(); var baseInfoPhoneLabel:UILabel = UILabel(); var baseInfoEmailLabel:UILabel = UILabel.init(); var advisorContentButton:UIButton = UIButton.init(type:UIButtonType.Custom); var CaverView:UILabel = UILabel.init(); var topCaverView:UILabel = UILabel.init(); var bottomCaverView: UILabel = UILabel.init(); var resumeModel:TKJobItemModel?{ didSet{ self.setCellSubInfoWithModle(resumeModel!); } } func setCellSubInfoWithModle(resumeModel:TKJobItemModel){ self.logoView.sd_setImageWithURL(NSURL.init(string: resumeModel.logo), placeholderImage: UIImage.init(named: "缺X3"), options: SDWebImageOptions.RetryFailed); self.jobNameLabel.text = resumeModel.expected_job; self.jobNameLabel.sizeToFit(); if Int(resumeModel.sex) == 0{ self.firstBaseInfoLabel.text = "女"; }else if(Int(resumeModel.sex) == 1){ self.firstBaseInfoLabel.text = "男"; }else{ self.firstBaseInfoLabel.text = ""; } self.secondBaseInfoLabel.text = resumeModel.position; self.threeBaseInfoLabel.text = resumeModel.degree; self.fourBaseInfoLabel.text = String.init(format: "%@年工作年限", resumeModel.year_work); self.baseInfoLogoView.image = UIImage.init(named: "姓名@2x"); self.baseInfoLogoView.updateLayout(); self.baseInfoPhoneView.image = UIImage.init(named: "电话@2x"); self.baseInfoPhoneView.updateLayout(); self.baseInfoEmailView.image = UIImage.init(named: "邮箱@2x"); self.baseInfoEmailView.updateLayout(); self.baseInfoLogoLabel.text = resumeModel.name.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 ? resumeModel.name : "暂无"; let phoneStr = String.init(format: "%@", (resumeModel.phone)!); if phoneStr != "<null>" && resumeModel.phone.intValue > 0{ self.baseInfoPhoneLabel.text = phoneStr; }else{ self.baseInfoPhoneLabel.text = "暂无"; } if resumeModel.email != nil{ self.baseInfoEmailLabel.text = resumeModel.email.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 ? resumeModel.email : "暂无";}else{ self.baseInfoEmailLabel.text = "暂无"; } self.contentView.layoutSubviews(); } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier); self.contentView.addSubview(self.topCaverView); self.topCaverView.backgroundColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0); self.topCaverView.sd_layout() .leftEqualToView(self.contentView) .rightEqualToView(self.contentView) .heightIs(0.5) .topEqualToView(self.contentView); self.contentView.addSubview(self.logoView); self.logoView.sd_layout() .leftSpaceToView(self.contentView,14.0) .topSpaceToView(self.contentView,10) .widthIs(50) .heightIs(50); self.contentView.addSubview(self.jobNameLabel); self.jobNameLabel.sd_layout() .leftSpaceToView(self.logoView,14) .topSpaceToView(self.contentView,10) .heightIs(20); self.jobNameLabel.setSingleLineAutoResizeWithMaxWidth(200); self.jobNameLabel.textAlignment = .Left; self.jobNameLabel.textColor = RGBA(0xff, g: 0x8a, b: 0x00, a: 1.0); self.contentView.addSubview(self.firstBaseInfoLabel); self.firstBaseInfoLabel.font = UIFont.systemFontOfSize(16.0); self.firstBaseInfoLabel.textAlignment = NSTextAlignment.Left; self.firstBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0); self.firstBaseInfoLabel.sd_layout() .leftEqualToView(self.jobNameLabel) .topSpaceToView(self.jobNameLabel,10) .heightIs(20.0); self.firstBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(40); self.firstBaseInfoLabel.isAttributedContent = false; self.firstBaseInfoLabel.textAlignment = .Left; self.contentView.addSubview(self.secondBaseInfoLabel); self.secondBaseInfoLabel.font = UIFont.systemFontOfSize(16.0); self.secondBaseInfoLabel.textAlignment = NSTextAlignment.Left; self.secondBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0); self.secondBaseInfoLabel.sd_layout() .leftSpaceToView(self.firstBaseInfoLabel,20) .topSpaceToView(self.jobNameLabel,10) .heightIs(20); self.secondBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(120); self.secondBaseInfoLabel.isAttributedContent = false; self.secondBaseInfoLabel.textAlignment = .Left; self.contentView.addSubview(self.threeBaseInfoLabel); self.threeBaseInfoLabel.font = UIFont.systemFontOfSize(16.0); self.threeBaseInfoLabel.textAlignment = NSTextAlignment.Left; self.threeBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0); self.threeBaseInfoLabel.sd_layout() .leftSpaceToView(self.secondBaseInfoLabel,20) .topSpaceToView(self.jobNameLabel,10) .heightIs(20); self.threeBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(120); self.threeBaseInfoLabel.isAttributedContent = false; self.threeBaseInfoLabel.textAlignment = .Left; self.contentView.addSubview(self.fourBaseInfoLabel); self.fourBaseInfoLabel.font = UIFont.systemFontOfSize(16.0); self.fourBaseInfoLabel.textAlignment = NSTextAlignment.Left; self.fourBaseInfoLabel.textColor=RGBA(0x46, g: 0x46, b: 0x46, a: 1.0); self.fourBaseInfoLabel.sd_layout() .leftSpaceToView(self.threeBaseInfoLabel,20) .topSpaceToView(self.jobNameLabel,10) .heightIs(20); self.fourBaseInfoLabel.setSingleLineAutoResizeWithMaxWidth(120); self.fourBaseInfoLabel.isAttributedContent = false; self.fourBaseInfoLabel.textAlignment = .Left; self.contentView.addSubview(self.baseInfoLogoView); self.baseInfoLogoView.sd_layout() .leftSpaceToView(self.logoView,14.0) .topSpaceToView(self.firstBaseInfoLabel,10) .widthIs(16.0) .heightIs(16.0); self.contentView.addSubview(self.baseInfoLogoLabel); self.baseInfoLogoLabel.sd_layout() .leftSpaceToView(self.baseInfoLogoView,14) .topEqualToView(self.baseInfoLogoView) .heightIs(16) self.baseInfoLogoLabel.setSingleLineAutoResizeWithMaxWidth(100); self.baseInfoLogoLabel.textAlignment = .Left; self.baseInfoLogoLabel.font = UIFont.systemFontOfSize(12.0); self.baseInfoLogoLabel.textColor = RGBA(0x91, g: 0x91, b: 0x91, a: 1.0); self.contentView.addSubview(self.baseInfoPhoneView); self.baseInfoPhoneView.sd_layout() .leftSpaceToView(self.baseInfoLogoView,100) .topEqualToView(self.baseInfoLogoView) .widthIs(16) .heightIs(16); self.contentView.addSubview(self.baseInfoPhoneLabel); self.baseInfoPhoneLabel.sd_layout() .leftSpaceToView(self.baseInfoPhoneView,14) .topEqualToView(self.baseInfoLogoView) .heightIs(16); self.baseInfoPhoneLabel.setSingleLineAutoResizeWithMaxWidth(120); self.baseInfoPhoneLabel.textAlignment = .Left; self.baseInfoPhoneLabel.font = UIFont.systemFontOfSize(12.0); self.baseInfoPhoneLabel.textColor = RGBA(0x91, g: 0x91, b: 0x91, a: 1.0); self.contentView.addSubview(self.baseInfoEmailView); self.baseInfoEmailView.sd_layout() .leftEqualToView(self.baseInfoLogoView) .topSpaceToView(self.baseInfoLogoView,10) .widthIs(16.0) .heightIs(16.0); self.contentView.addSubview(self.baseInfoEmailLabel); self.baseInfoEmailLabel.sd_layout() .leftSpaceToView(self.baseInfoEmailView,14) .topEqualToView(self.baseInfoEmailView) .heightIs(16); self.baseInfoEmailLabel.setSingleLineAutoResizeWithMaxWidth(240); self.baseInfoEmailLabel.textAlignment = .Left; self.baseInfoEmailLabel.font = UIFont.systemFontOfSize(12.0); self.baseInfoEmailLabel.textColor = RGBA(0x91, g: 0x91, b: 0x91, a: 1.0); self.contentView.addSubview(self.CaverView); self.CaverView.sd_layout() .leftEqualToView(self.contentView) .rightEqualToView(self.contentView) .heightIs(0.5) .topSpaceToView(self.baseInfoEmailView,6); self.CaverView.backgroundColor = RGBA(0xda, g: 0xe2, b: 0xea, a: 1.0); self.contentView.addSubview(self.advisorContentButton); self.advisorContentButton.sd_layout() .leftEqualToView(self.contentView) .rightEqualToView(self.contentView) .topSpaceToView(self.CaverView,0) .heightIs(44); self.advisorContentButton.addTarget(self, action: "onClickCallPhoneBtn:", forControlEvents:.TouchUpInside) self.advisorContentButton.setTitle("拨打电话", forState: .Normal); self.advisorContentButton.titleLabel?.font = UIFont.systemFontOfSize(16); self.advisorContentButton.titleLabel?.textAlignment = .Center; self.advisorContentButton.setTitleColor(RGBA(0x3c, g: 0xb3, b: 0xec, a: 1.0), forState:.Normal); self.contentView.addSubview(self.bottomCaverView); self.bottomCaverView.backgroundColor = self.topCaverView.backgroundColor; self.bottomCaverView.sd_layout() .leftEqualToView(self.contentView) .rightEqualToView(self.contentView) .heightIs(0.5) .topSpaceToView(self.advisorContentButton,0); self.setupAutoHeightWithBottomView(self.bottomCaverView, bottomMargin: 0); } func onClickCallPhoneBtn(sender:UIButton){ print("onClickCallPhoneBtn"); let phoneInfo = String.init(format: "tel:%@", (self.resumeModel?.phone)!); let webView = UIWebView.init(); webView.loadRequest(NSURLRequest.init(URL: NSURL.init(string: phoneInfo)!)); dispatch_async(dispatch_get_main_queue()) { () -> Void in self.superview?.addSubview(webView); } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: rgb color func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat)->UIColor { return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
cae8caf3e6b5381cbc69aaee0ef42b7a
43.826923
165
0.665809
false
false
false
false
dkalaitzidis/SwiftyTextfields
refs/heads/master
Example/SwiftyTextfields/SwiftyTextfields.swift
mit
1
// // SwiftyTextfields.swift // SwiftyTextfields // // Created by Dimitrios Kalaitzidis on 18/12/2016. // Copyright © 2016 Dimitrios Kalaitzidis. All rights reserved. // import UIKit @IBDesignable class SwiftyTextfields: UITextField{ @IBInspectable var cornerRadius: CGFloat = 0 { didSet { updateView() } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { updateView() } } @IBInspectable var borderColor: UIColor = UIColor.clear { didSet { updateView() } } @IBInspectable var leftImage: UIImage? { didSet { updateView() } } @IBInspectable var leftImageWidthHeight:CGRect = CGRect(x:0, y:0, width:14, height:14) { didSet { updateView() } } @IBInspectable var bgColor: UIColor = UIColor.white { didSet { updateView() } } @IBInspectable var placeholderColor: UIColor = UIColor.lightGray { didSet { updateView() } } @IBInspectable var enableShadow: Bool = false { didSet { updateView() } } @IBInspectable var shadowColor: UIColor = UIColor.darkGray { didSet { updateView() } } @IBInspectable var shadowRadius: CGFloat = 1 { didSet { updateView() } } @IBInspectable var shadowOpacity: Float = 0.5 { didSet { updateView() } } @IBInspectable var leftPadding: CGFloat = 0 @IBInspectable var textfieldHeight: CGFloat = 30 override func layoutSubviews() { super.layoutSubviews() var frameRect = self.frame frameRect.size.height = self.textfieldHeight self.frame = frameRect layer.backgroundColor = bgColor.cgColor layer.cornerRadius = cornerRadius layer.borderColor = borderColor.cgColor layer.borderWidth = borderWidth if(enableShadow == true){ let shadowPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)) layer.shadowColor = shadowColor.cgColor layer.shadowOffset = CGSize(width: 0.2, height: 0.2) layer.shadowOpacity = shadowOpacity layer.shadowRadius = shadowRadius layer.masksToBounds = false layer.shadowPath = shadowPath.cgPath } } func updateView() { if let image = leftImage { leftViewMode = UITextFieldViewMode.always let imageView = UIImageView(frame: leftImageWidthHeight) imageView.image = image imageView.tintColor = UIColor.clear leftView = imageView } else { leftViewMode = UITextFieldViewMode.never leftView = nil } // Placeholder text color attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSForegroundColorAttributeName: placeholderColor]) } // Padding for images override func leftViewRect(forBounds bounds: CGRect) -> CGRect { var textRect = super.leftViewRect(forBounds: bounds) textRect.origin.x += leftPadding return textRect } // Padding for placeholder override func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: leftImageWidthHeight.width + leftPadding * 2, dy: 0) } // Padding for text override func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: leftImageWidthHeight.width + leftPadding * 2, dy: 0) } }
800951746fb806ddff401b56db712e5a
26.15
162
0.583268
false
false
false
false
domenicosolazzo/practice-swift
refs/heads/master
playgrounds/Generics.playground/section-1.swift
mit
1
// Playground: Generics /* /* ==== Subclassing ==== */ Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. Yo can write code that avoids duplication and expresses its intent in a clear, abstracted manner. */ import Cocoa // This function can work with any type func swapTwoValues<T>( a:inout T, b:inout T){ let temporaryA = a a = b b = temporaryA } var firstInt = 3 var secondInt = 103 // Int example swapTwoValues(a: &firstInt, b: &secondInt) print("\(firstInt)" + " - \(secondInt)" ) // String example var firstString = "First" var secondString = "Second" swapTwoValues(a: &firstString, b: &secondString) print(firstString + " - " + secondString) // Not-generic version of a Stack struct InStack{ var items = [Int]() mutating func push(i:Int){ items.append(i) } mutating func pop() -> Int{ return items.removeLast() } } // Generic version of Stack // Example for the GenericInStack var stackOfStrings = Stack<String>() stackOfStrings.push("First") stackOfStrings.push("Second") stackOfStrings.push("Third") var pullElement = stackOfStrings.pop() print(pullElement) /* ====== Type constraints ====== */ /** It is sometimes useful to enforce certain type constraints on the types that can be used with generic functions and generic types. Type constraints specify that a type parameter must inherit from a specific class, or conform to a particular protocol or protocol composition */ /* Not-generic example Here’s a non-generic function called findStringIndex, which is given a String value to find and an array of String values within which to find it. The findStringIndex function returns an optional Int value, which will be the index of the first matching string in the array if it is found, or nil if the string cannot be found */ func findStringIndex(array:[String], valueToFind: String)->Int?{ for (index, value) in array.enumerated(){ if(value == valueToFind){ return index } } return nil } let strings = ["cats", "dogs", "tigers"] var index = findStringIndex(array: strings, valueToFind: "dogs") print("The index is \(index)") /* Generic example You must use Equatable protocol if you want to compare values using == and != */ func findIndex<T: Equatable>(array: [T], valueToFind: T)->Int?{ for (index, value) in array.enumerated(){ if value == valueToFind{ return index } } return nil } let doubleIndex = findIndex(array: [1.23, 22.11, 424.11, 3.2], valueToFind: 3.2) let stringIndex = findIndex(array: ["Domenico", "Sandro", "Guido"], valueToFind: "Domenico") /* ====== Associated Types ====== When defining a protocol, it is sometimes useful to declare one or more associated types as part of the protocol’s definition. An associated type gives a placeholder name (or alias) to a type that is used as part of the protocol. The actual type to use for that associated type is not specified until the protocol is adopted. Associated types are specified with the typealias keyword. */ protocol Container{ associatedtype ItemType mutating func append(item:ItemType) var count:Int {get} subscript(i:Int) -> ItemType{get} } // Switft can infer the appropriate ItemType to use struct Stack<T>:Container{ var items = [T]() mutating func push(item:T){ items.append(item) } mutating func pop() -> T{ return items.removeLast() } // conformance to the Container protocol mutating func append(item:T){ self.push(item: item) } var count:Int{ return items.count } subscript(i:Int) -> T{ return items[i] } } /* ====== Where clauses ======= It can also be useful to define requirements for associated types. You do this by defining where clauses as part of a type parameter list. A where clause enables you to require that an associated type conforms to a certain protocol, and or that certain type parameters and associated types be the same. You write a where clause by placing the where keyword immediately after the list of type parameters, followed by one or more constraints for associated types, and/or one or more equality relationships between types and associated types. */ func allItemsMatch<C1: Container, C2: Container> (someContainer:C1, anotherContainer:C2) -> Bool where C1.ItemType == C2.ItemType, C1.ItemType: Equatable{ // Check that both containers contain the same number of items if someContainer.count != anotherContainer.count{ return false } // Check each pair of items to see if they are equivalent for i in (0 ..< someContainer.count){ if someContainer[i] != anotherContainer[i]{ return false } } return true }
fd7272b563b2eb6a4109994d2d9e6e0a
27.417143
92
0.681681
false
false
false
false
AkikoZ/PocketHTTP
refs/heads/master
PocketHTTP/PocketHTTP/Request/VariableEditingViewController.swift
gpl-3.0
1
// // VariableEditingViewController.swift // PocketHTTP // // Created by 朱子秋 on 2017/2/1. // Copyright © 2017年 朱子秋. All rights reserved. // import UIKit import CoreData class VariableEditingViewController: UITableViewController { @IBOutlet fileprivate weak var nameTextField: UITextField! @IBOutlet fileprivate weak var valueTextField: UITextField! @IBOutlet fileprivate weak var saveButton: UIBarButtonItem! var managedObjectContext: NSManagedObjectContext! var variable: PHVariable? @IBAction private func save(_ sender: UIBarButtonItem) { let variableToSave = variable == nil ? PHVariable(context: managedObjectContext) : variable! variableToSave.name = nameTextField.text! variableToSave.value = valueTextField.text! do { try managedObjectContext.save() } catch { let error = error as NSError if error.code == 133021 { let alert = UIAlertController(title: "Name Conflict", message: "Variable's name already existed, try another name.", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default) { _ in self.nameTextField.becomeFirstResponder() } alert.addAction(okAction) present(alert, animated: true, completion: nil) return } else { fatalError("Could not save data: \(error)") } } performSegue(withIdentifier: "EditedVariable", sender: nil) } override func viewDidLoad() { super.viewDidLoad() if let variable = variable { title = "Edit Variable" nameTextField.text = variable.name valueTextField.text = variable.value } else { title = "Add Variable" saveButton.isEnabled = false } } } extension VariableEditingViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let oldText = textField.text! as NSString let newText = oldText.replacingCharacters(in: range, with: string) as NSString if textField == nameTextField { saveButton.isEnabled = newText.length > 0 } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == nameTextField { valueTextField.becomeFirstResponder() } else { valueTextField.resignFirstResponder() } return true } }
d44a4339884aeda46a682044c6d67e3f
32.594937
156
0.623964
false
false
false
false
uwinkler/commons
refs/heads/master
commons/Array.swift
mit
1
// // Array.swift // // Created by Ulrich Winkler on 09/01/2015. // Copyright (c) 2015 Ulrich Winkler. All rights reserved. // import Foundation extension Array { mutating func removeObject(obj: NSObject) { var idx = -1 for var i = 0; i < self.count; i++ { if self[i] as! NSObject == obj { idx = i break } } if idx > -1 { self.removeAtIndex(idx) } } mutating func appendAll(array: Array) { for obj in array { self.append(obj) } } // // Simulate simple FIFO and STACK queue operations // mutating func pop() -> T? { return self.count > 0 ? self.removeAtIndex(0) : nil } mutating func push(obj: T) { self.insert(obj, atIndex: 0) } mutating func add(obj: T) { self.append(obj) } mutating func peek() -> T? { return self.first } var nono: String { get { var ret = "" for var i = 0; i < self.count; i++ { if i % 4 == 0 { ret += "\n\t\(i)\t" } ret += NSString(format: "0x%.2X ", self[i] as! UInt8) as String } return ret; } } }
dbefaee97c8147f69150dd426a0b4c22
17.742857
79
0.450457
false
false
false
false
kumabook/FeedlyKit
refs/heads/master
Source/Entry.swift
mit
1
// // Entry.swift // MusicFav // // Created by Hiroki Kumamoto on 12/23/14. // Copyright (c) 2014 Hiroki Kumamoto. All rights reserved. // import Foundation import SwiftyJSON public final class Entry: Equatable, Hashable, ResponseObjectSerializable, ResponseCollectionSerializable, ParameterEncodable { public var id: String public var title: String? public var content: Content? public var summary: Content? public var author: String? public var crawled: Int64 = 0 public var recrawled: Int64 = 0 public var published: Int64 = 0 public var updated: Int64? public var alternate: [Link]? public var origin: Origin? public var keywords: [String]? public var visual: Visual? public var unread: Bool = true public var tags: [Tag]? public var categories: [Category] = [] public var engagement: Int? public var actionTimestamp: Int64? public var enclosure: [Link]? public var fingerprint: String? public var originId: String? public var sid: String? public class func collection(_ response: HTTPURLResponse, representation: Any) -> [Entry]? { let json = JSON(representation) return json.arrayValue.map({ Entry(json: $0) }) } @objc required public convenience init?(response: HTTPURLResponse, representation: Any) { let json = JSON(representation) self.init(json: json) } public static var instanceDidInitialize: ((Entry, JSON) -> Void)? public init(id: String) { self.id = id } public init(json: JSON) { self.id = json["id"].stringValue self.title = json["title"].string self.content = Content(json: json["content"]) self.summary = Content(json: json["summary"]) self.author = json["author"].string self.crawled = json["crawled"].int64Value self.recrawled = json["recrawled"].int64Value self.published = json["published"].int64Value self.updated = json["updated"].int64 self.origin = Origin(json: json["origin"]) self.keywords = json["keywords"].array?.map({ $0.string! }) self.visual = Visual(json: json["visual"]) self.unread = json["unread"].boolValue self.tags = json["tags"].array?.map({ Tag(json: $0) }) self.categories = json["categories"].arrayValue.map({ Category(json: $0) }) self.engagement = json["engagement"].int self.actionTimestamp = json["actionTimestamp"].int64 self.fingerprint = json["fingerprint"].string self.originId = json["originId"].string self.sid = json["sid"].string if let alternates = json["alternate"].array { self.alternate = alternates.map({ Link(json: $0) }) } else { self.alternate = nil } if let enclosures = json["enclosure"].array { self.enclosure = enclosures.map({ Link(json: $0) }) } else { self.enclosure = nil } Entry.instanceDidInitialize?(self, json) } public func hash(into hasher: inout Hasher) { return id.hash(into: &hasher) } public func toParameters() -> [String : Any] { var params: [String: Any] = ["published": NSNumber(value: published)] if let title = title { params["title"] = title as AnyObject? } if let content = content { params["content"] = content.toParameters() as AnyObject? } if let summary = summary { params["summary"] = summary.toParameters() as AnyObject? } if let author = author { params["author"] = author as AnyObject? } if let enclosure = enclosure { params["enclosure"] = enclosure.map({ $0.toParameters() }) } if let alternate = alternate { params["alternate"] = alternate.map({ $0.toParameters() }) } if let keywords = keywords { params["keywords"] = keywords as AnyObject? } if let tags = tags { params["tags"] = tags.map { $0.toParameters() }} if let origin = origin { params["origin"] = origin.toParameters() as AnyObject? } return params } public var thumbnailURL: URL? { if let v = visual, let url = v.url.toURL() { return url } if let links = enclosure { for link in links { if let url = link.href.toURL() { if link.type.contains("image") { return url } } } } if let url = extractImgSrc() { return url } return nil } func extractImgSrc() -> URL? { if let html = content?.content { let regex = try? NSRegularExpression(pattern: "<img.*src\\s*=\\s*[\"\'](.*?)[\"\'].*>", options: NSRegularExpression.Options()) if let r = regex { let range = NSRange(location: 0, length: html.count) if let result = r.firstMatch(in: html, options: NSRegularExpression.MatchingOptions(), range: range) { for i in 0...result.numberOfRanges - 1 { let range = result.range(at: i) let str = html as NSString if let url = str.substring(with: range).toURL() { return url } } } } } return nil } } public func == (lhs: Entry, rhs: Entry) -> Bool { return lhs.id == rhs.id }
3c7dd8691ff875587fce202139267a97
39.047619
119
0.536776
false
false
false
false
bazelbuild/tulsi
refs/heads/master
src/TulsiGenerator/CommandLineSplitter.swift
apache-2.0
2
// Copyright 2016 The Tulsi Authors. All rights reserved. // // 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 /// Splits a string containing commandline arguments into an array of strings suitable for use by /// Process. class CommandLineSplitter { let scriptPath: String init() { scriptPath = Bundle(for: type(of: self)).path(forResource: "command_line_splitter", ofType: "sh")! } /// WARNING: This method utilizes a shell instance to evaluate the commandline and may have side /// effects. func splitCommandLine(_ commandLine: String) -> [String]? { if commandLine.isEmpty { return [] } var splitCommands: [String]? = nil let semaphore = DispatchSemaphore(value: 0) let process = ProcessRunner.createProcess(scriptPath, arguments: [commandLine]) { completionInfo in defer { semaphore.signal() } guard completionInfo.terminationStatus == 0, let stdout = NSString(data: completionInfo.stdout, encoding: String.Encoding.utf8.rawValue) else { return } let split = stdout.components(separatedBy: CharacterSet.newlines) splitCommands = [String](split.dropLast()) } process.launch() _ = semaphore.wait(timeout: DispatchTime.distantFuture) return splitCommands } }
1a2061c4a79c708f4cf3b8a389561ceb
35.862745
110
0.681915
false
false
false
false
erolbaykal/EBColorEyes
refs/heads/master
EBColorEyes/EBImageColorAnalyser.swift
gpl-3.0
1
// // EBImageColorAnalyser.swift // EBColorEyes // // Created by beta on 18/04/16. // Copyright © 2016 Baykal. All rights reserved. // import Foundation import QuartzCore import CoreImage enum imageColorOrder:Int{ case rgb = 0 case bgr = 1 } enum imageColorMode: Int{ case standard = 0 case increasedSaturation = 1 } class EBImageColorAnalyser: NSObject { var colorNamer = EBColorNamer() func analayseImageColor(image: CGImage, colorOrder: imageColorOrder = imageColorOrder.rgb, colorMode:imageColorMode = imageColorMode.increasedSaturation)->String{ var theImage = image; var theColorOrder = colorOrder; //first apply color filters if(colorMode == imageColorMode.increasedSaturation){ // Create an image object from the Quartz image let filter = CIFilter(name: "CIColorControls") filter!.setValue(CIImage(CGImage: theImage), forKey: kCIInputImageKey) filter!.setValue(2.0, forKey: "inputSaturation") theImage = convertCIImageToCGImage(filter!.outputImage!) theColorOrder = imageColorOrder.bgr } //only then resize the image let f:Int = 20 let width = CGImageGetWidth(image) let height = CGImageGetHeight(image) let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.NoneSkipFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue) let resizeContext = CGBitmapContextCreate(nil, width/f, height/f, 8, width/f*4, colorSpace, bitmapInfo.rawValue) CGContextSetInterpolationQuality(resizeContext, CGInterpolationQuality.None) CGContextDrawImage(resizeContext, CGRectMake(0, 0, CGFloat(width/f), CGFloat(height/f)), theImage) theImage = CGBitmapContextCreateImage(resizeContext)! //process pixels only after all tranformations and filters have been applied, as otherwise results may not be as expected let rawData = CGDataProviderCopyData(CGImageGetDataProvider(theImage)) let buf:UnsafePointer<UInt8> = CFDataGetBytePtr(rawData) let length:Int = CFDataGetLength(rawData) var i:Int = 0 var c:Int = 0 var sumTable = [String:Int]() //walk over the pixels in order to analyse then and populate the frequency table while i < length { var b:UInt8 = 0 var g:UInt8 = 0 var r:UInt8 = 0 if(theColorOrder == imageColorOrder.rgb){ r = buf.advancedBy(i+0).memory g = buf.advancedBy(i+1).memory b = buf.advancedBy(i+2).memory } else if (theColorOrder == imageColorOrder.bgr){ b = buf.advancedBy(i+0).memory g = buf.advancedBy(i+1).memory r = buf.advancedBy(i+2).memory } c += 1 i = i+4 let colorName:EBColor = self.colorNamer.rgbToColorName(Float(r)/255, green: Float(g)/255, blue: Float(b)/255) if((sumTable[colorName.rawValue]) != nil){ sumTable[colorName.rawValue] = (sumTable[colorName.rawValue]! + 1) }else{ sumTable[colorName.rawValue] = 1 } } let sortedTable:Array = Array(sumTable).sort {$0.1 > $1.1} var colorNameString = String() if(sortedTable[0].1 > Int(Double(c)/1.7)){ colorNameString = "\(sortedTable[0].0)" }else if(sortedTable[0].1 > c/2){ colorNameString = "mostly \(sortedTable[0].0)" }else if (sortedTable[0].1 + sortedTable[0].1 > c/2){ colorNameString = "mostly \(sortedTable[0].0) and some \(sortedTable[1].0)" } return colorNameString } /* from http://wiki.hawkguide.com/wiki/Swift:_Convert_between_CGImage,_CIImage_and_UIImage*/ func convertCIImageToCGImage(inputImage: CIImage) -> CGImage! { let context = CIContext(options: nil) return context.createCGImage(inputImage, fromRect: inputImage.extent) } }
aeb1cd8060c433c828047c7d12278772
36.4375
166
0.617844
false
false
false
false
pasmall/WeTeam
refs/heads/master
WeTools/WeTools/ViewController/Login/RegistViewController.swift
apache-2.0
1
// // RegistViewController.swift // WeTools // // Created by lhtb on 2016/11/17. // Copyright © 2016年 lhtb. All rights reserved. // import UIKit import Alamofire class RegistViewController: BaseViewController { let accTF = LoginTextField.init(frame: CGRect.init(x: 0, y: 140, width: SCREEN_WIDTH, height: 44), placeholderStr: "请输入手机号码") let psdTF = LoginTextField.init(frame: CGRect.init(x: 0, y: 184, width: SCREEN_WIDTH, height: 44), placeholderStr: "请输入密码") override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "注册" setUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) self.navigationController?.navigationBar.isHidden = false } func setUI () { view.addSubview(accTF) view.addSubview(psdTF) let line = UIView.init(frame: CGRect.init(x: 0, y: 184, width: SCREEN_WIDTH, height: 0.4)) line.backgroundColor = backColor view.addSubview(line) psdTF.isSecureTextEntry = true //登录 let logBtn = UIButton() logBtn.frame = CGRect.init(x: 10, y: 248, width: SCREEN_WIDTH - 20, height: 44) logBtn.backgroundColor = blueColor logBtn.setTitle("注册", for: .normal) logBtn.layer.cornerRadius = 4 logBtn.layer.masksToBounds = true logBtn.addTarget(self, action: #selector(LoginViewController.tapLoginBtn), for: .touchUpInside) view.addSubview(logBtn) } func tapLoginBtn() { self.showSimpleHUD() Alamofire.request( IP + "regist.php", method: .post, parameters: ["name":accTF.text!,"psd":psdTF.text!]).responseJSON { (data) in if let json = data.result.value as? [String:Any]{ print(json) if json["code"] as! Int == 200{ self.hidSimpleHUD() _ = self.alert.showAlert("", subTitle: "注册成功", style: AlertStyle.success, buttonTitle: "返回登录", action: { (true) in _ = self.navigationController?.popViewController(animated: true) }) } else if json["code"] as! Int == 202{ _ = self.alert.showAlert("该账号已被注册") } } } } }
6f6eac3f20171464cad65e2cd5e17fbd
29.275862
137
0.555049
false
false
false
false
bryancmiller/rockandmarty
refs/heads/master
Text Adventure/Text Adventure/CGFloatExtensions.swift
apache-2.0
1
// // CGFloatExtensions.swift // Text Adventure // // Created by Bryan Miller on 9/9/17. // Copyright © 2017 Bryan Miller. All rights reserved. // import Foundation import UIKit extension CGFloat { static func convertHeight(h: CGFloat, screenSize: CGRect) -> CGFloat { // iPhone 5 height is 568 and designed on iPhone 5 let iPhone5Height: CGFloat = 568.0 let currentPhoneHeight: CGFloat = screenSize.height // calculate ratio between iPhone 5 and current let phoneRatio: CGFloat = currentPhoneHeight / iPhone5Height return (h * phoneRatio) } static func convertWidth(w: CGFloat, screenSize: CGRect) -> CGFloat { // iPhone 5 width is 320 let iPhone5Width: CGFloat = 320.0 let currentPhoneWidth: CGFloat = screenSize.width // calculate ratio between iPhone 5 and current let phoneRatio: CGFloat = currentPhoneWidth / iPhone5Width return (w * phoneRatio) } }
2255423feb57df200b91fdd1b5abf5b1
31.633333
74
0.670072
false
false
false
false
aitim/XXWaterFlow
refs/heads/master
XXWaterFlow/XXCollectionViewLayout.swift
gpl-2.0
1
// // XXCollectionViewLayout.swift // XXWaterFlow // // Created by xin.xin on 3/12/15. // Copyright (c) 2015 aitim. All rights reserved. // import UIKit class XXCollectionViewLayout: UICollectionViewFlowLayout { private var cellAttributes:[XXCollectionViewLayoutAttributes] = [] // private var columnHeights:[CGFloat] = [] //保存每一列的高度 override var collectionView:XXCollectionView?{ get{ return super.collectionView as? XXCollectionView } } override func prepareLayout() { NSLog("prepare") super.prepareLayout() //初始化各cell的attributes var columnHeights:[CGFloat] = [] //记录每一列的高度 for i in 0..<self.collectionView!.columnCount{ columnHeights.append(0) } var section = 0 var itemCount = self.collectionView!.numberOfItemsInSection(section) for i in 0..<itemCount{ var size:CGSize = (self.collectionView!.delegate! as XXCollectionViewDelegate).collectionView(self.collectionView!, sizeForItemAtIndexPath: NSIndexPath(forItem:i, inSection: section)) //找出高度最小的列 var minColumnHeight:CGFloat = CGFloat.max var minColumnIndex:Int = 0 for j in 0..<self.collectionView!.columnCount{ if minColumnHeight > columnHeights[j]{ minColumnHeight = columnHeights[j] minColumnIndex = j } } columnHeights[minColumnIndex] = minColumnHeight + (size.height + self.collectionView!.margin) //得到cell的frame var frame = CGRectMake(CGFloat(minColumnIndex+1)*self.collectionView!.margin + CGFloat(minColumnIndex)*size.width, minColumnHeight + self.collectionView!.margin, size.width, size.height) var attributes = XXCollectionViewLayoutAttributes(forCellWithIndexPath: NSIndexPath(forItem: i , inSection: section)) attributes.frame = frame attributes.alpha = 1 // NSLog("cell \(i) frame:\(frame) heights:\(columnHeights)") self.cellAttributes.append(attributes) } } //返回collectionView的内容的尺寸 override func collectionViewContentSize() -> CGSize { NSLog("返回contentSize") var height:CGFloat = 0 for i in 0..<self.cellAttributes.count{ if (self.cellAttributes[i].frame.height+self.cellAttributes[i].frame.origin.y) > height { height = (self.cellAttributes[i].frame.height + self.cellAttributes[i].frame.origin.y) } } return CGSizeMake(self.collectionView!.frame.width, height + self.collectionView!.margin) } //返回rect中的所有的元素的布局属性 override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { NSLog("返回rect中的所有的元素的布局属性") var attributes:[UICollectionViewLayoutAttributes] = [] for i in 0..<self.cellAttributes.count{ if CGRectIntersectsRect(rect, self.cellAttributes[i].frame){ attributes.append(self.cellAttributes[i]) } } return attributes } //返回对应于indexPath的位置的cell的布局属性 override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { NSLog("返回对应于indexPath的位置的cell的布局属性") return self.cellAttributes[indexPath.item] } }
257fa041a82f90a978b351aa0957ab83
37.752809
198
0.632647
false
false
false
false
pigigaldi/Pock
refs/heads/develop
Pock/Widgets/WidgetsLoader.swift
mit
1
// // WidgetsLoader.swift // Pock // // Created by Pierluigi Galdi on 10/03/21. // import Foundation import PockKit // MARK: Notifications extension NSNotification.Name { static let didLoadWidgets = NSNotification.Name("didLoadWidgets") } // MARK: Helpers private var kApplicationSupportPockFolder: String { let prefix: String if let path = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?.path { prefix = path } else { prefix = FileManager.default.homeDirectoryForCurrentUser.path + "/Library/Application Support" } return prefix + "/Pock" } internal let kWidgetsPath: String = kApplicationSupportPockFolder + "/Widgets" internal let kWidgetsPathURL: URL = URL(fileURLWithPath: kWidgetsPath) internal let kWidgetsTempPathURL: URL = URL(fileURLWithPath: kWidgetsPath + "/tmp") // MARK: Loader internal final class WidgetsLoader { /// Typealias typealias WidgetsLoaderHandler = ([PKWidgetInfo]) -> Void /// File manager private let fileManager = FileManager.default /// Data public static var loadedWidgets: [PKWidgetInfo] { return installedWidgets.filter({ $0.loaded == true }) } /// List of installed widgets (loaded or not) public static var installedWidgets: [PKWidgetInfo] = [] init() { /// Create support folders, if needed guard createSupportFoldersIfNeeded() else { AppController.shared.showMessagePanelWith( title: "error.title.default".localized, message: "error.message.cant_create_support_folders".localized, style: .critical ) return } } /// Create support folders, if needed private func createSupportFoldersIfNeeded() -> Bool { return fileManager.createFolderIfNeeded(at: kApplicationSupportPockFolder) && fileManager.createFolderIfNeeded(at: kWidgetsPath) } /// Load installed widgets internal func loadInstalledWidgets(_ completion: @escaping WidgetsLoaderHandler) { WidgetsLoader.installedWidgets.removeAll() let widgetURLs = fileManager.filesInFolder(kWidgetsPath, filter: { $0.contains(".pock") && !$0.contains("disabled") && !$0.contains("/") }) var widgets: [PKWidgetInfo] = [] for widgetFilePathURL in widgetURLs { guard let widget = loadWidgetAtURL(widgetFilePathURL) else { continue } widgets.append(widget) } completion(widgets) NotificationCenter.default.post(name: .didLoadWidgets, object: nil) } /// Load single widget private func loadWidgetAtURL(_ url: URL) -> PKWidgetInfo? { do { let info = try PKWidgetInfo(path: url) if !WidgetsLoader.installedWidgets.contains(info) { WidgetsLoader.installedWidgets.append(info) } return info } catch let error1 { do { let info = try PKWidgetInfo(unloadableWidgetAtPath: url) if !WidgetsLoader.installedWidgets.contains(info) { WidgetsLoader.installedWidgets.append(info) } return info } catch let error2 { Roger.error(error2.localizedDescription) } Roger.error(error1.localizedDescription) return nil } } }
1d3cfbf625cadd1fce6bacf056c9b48c
28.018692
130
0.706924
false
false
false
false
carambalabs/Curt
refs/heads/master
Example/CurtTests/Tests.swift
mit
1
// // Created by Sergi Gracia on 30/01/2017. // Copyright © 2017 Caramba. All rights reserved. // import XCTest import Quick import Nimble class CurtTests: QuickSpec { override func spec() { var view: UIView! var viewA: UIView! var viewB: UIView! var viewC: UIView! var cA: NSLayoutConstraint! var cB: NSLayoutConstraint! var constantFloat: CGFloat! var constantNegativeFloat: CGFloat! var constantInt: Int! var multiplierFloat: CGFloat! var multiplierInt: Int! beforeEach { view = UIView() viewA = UIView() viewB = UIView() viewC = UIView() [viewA, viewB, viewC].forEach { view.addSubview($0) } constantFloat = 12 constantNegativeFloat = -constantFloat constantInt = Int(constantFloat) multiplierFloat = 2.0 multiplierInt = Int(multiplierFloat) } describe("constraint(equalTo anchor: NSLayoutAnchor<AnchorType>)") { it("creates valid constraint") { cA = viewA.topAnchor.constraint(equalTo: viewB.topAnchor) cA.isActive = true cB = viewA.topAnchor ~ viewB.topAnchor expect(cA) == cB } } describe("constraint(greaterThanOrEqualTo anchor: NSLayoutAnchor<AnchorType>)") { it("creates valid constraint") { cA = viewA.topAnchor.constraint(greaterThanOrEqualTo: viewB.topAnchor) cA.isActive = true cB = viewA.topAnchor >~ viewB.topAnchor expect(cA) == cB } } describe("constraint(lessThanOrEqualTo anchor: NSLayoutAnchor<AnchorType>)") { it("creates valid constraint") { cA = viewA.topAnchor.constraint(lessThanOrEqualTo: viewB.topAnchor) cA.isActive = true cB = viewA.topAnchor <~ viewB.topAnchor expect(cA) == cB } } describe("constraint(equalTo anchor: NSLayoutAnchor<AnchorType>, constant c: CGFloat)") { it("creates valid constraint") { cA = viewA.topAnchor.constraint(equalTo: viewB.topAnchor, constant: constantFloat) cA.isActive = true cB = viewA.topAnchor ~ viewB.topAnchor + constantFloat expect(cA) == cB } } describe("constraint(equalTo anchor: NSLayoutAnchor<AnchorType>, constant c: CGFloat) (Negative Constant)") { it("creates valid constraint") { cA = viewA.topAnchor.constraint(equalTo: viewB.topAnchor, constant: constantNegativeFloat) cA.isActive = true cB = viewA.topAnchor ~ viewB.topAnchor - constantFloat expect(cA) == cB } } describe("constraint(equalTo anchor: NSLayoutAnchor<AnchorType>, constant c: CGFloat) (Int)") { it("creates valid constraint") { cA = viewA.topAnchor.constraint(equalTo: viewB.topAnchor, constant: constantFloat) cA.isActive = true cB = viewA.topAnchor ~ viewB.topAnchor + constantInt expect(cA) == cB } } describe("constraint(equalTo anchor: NSLayoutAnchor<AnchorType>, constant c: CGFloat) (Negative Int)") { it("creates valid constraint") { cA = viewA.topAnchor.constraint(equalTo: viewB.topAnchor, constant: constantNegativeFloat) cA.isActive = true cB = viewA.topAnchor ~ viewB.topAnchor - constantInt expect(cA) == cB } } describe("constraint(greaterThanOrEqualTo anchor: NSLayoutAnchor<AnchorType>, constant c: CGFloat)") { it("creates valid constraint") { cA = viewA.topAnchor.constraint(greaterThanOrEqualTo: viewB.topAnchor, constant: constantFloat) cA.isActive = true cB = viewA.topAnchor >~ viewB.topAnchor + constantFloat expect(cA) == cB } } describe("constraint(lessThanOrEqualTo anchor: NSLayoutAnchor<AnchorType>, constant c: CGFloat)") { it("creates valid constraint") { cA = viewA.topAnchor.constraint(lessThanOrEqualTo: viewB.topAnchor, constant: constantFloat) cA.isActive = true cB = viewA.topAnchor <~ viewB.topAnchor + constantFloat expect(cA) == cB } } describe("constraint(equalToConstant c: CGFloat)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(equalToConstant: constantFloat) cA.isActive = true cB = viewA.widthAnchor ~ constantFloat expect(cA) == cB } } describe("constraint(equalToConstant c: CGFloat) (Int)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(equalToConstant: constantFloat) cA.isActive = true cB = viewA.widthAnchor ~ constantInt expect(cA) == cB } } describe("constraint(greaterThanOrEqualToConstant c: CGFloat)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(greaterThanOrEqualToConstant: constantFloat) cA.isActive = true cB = viewA.widthAnchor >~ constantFloat expect(cA) == cB } } describe("constraint(greaterThanOrEqualToConstant c: CGFloat) (Int)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(greaterThanOrEqualToConstant: constantFloat) cA.isActive = true cB = viewA.widthAnchor >~ constantInt expect(cA) == cB } } describe("constraint(lessThanOrEqualToConstant c: CGFloat)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(lessThanOrEqualToConstant: constantFloat) cA.isActive = true cB = viewA.widthAnchor <~ constantFloat expect(cA) == cB } } describe("constraint(lessThanOrEqualToConstant c: CGFloat) (Int)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(lessThanOrEqualToConstant: constantFloat) cA.isActive = true cB = viewA.widthAnchor <~ constantInt expect(cA) == cB } } describe("constraint(equalTo anchor: NSLayoutDimension, multiplier m: CGFloat)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(equalTo: viewB.widthAnchor, multiplier: multiplierFloat) cA.isActive = true cB = viewA.widthAnchor ~ viewB.widthAnchor * multiplierFloat expect(cA) == cB } } describe("constraint(equalTo anchor: NSLayoutDimension, multiplier m: CGFloat) (Int)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(equalTo: viewB.widthAnchor, multiplier: multiplierFloat) cA.isActive = true cB = viewA.widthAnchor ~ viewB.widthAnchor * multiplierInt expect(cA) == cB } } describe("constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(greaterThanOrEqualTo: viewB.widthAnchor, multiplier: multiplierFloat) cA.isActive = true cB = viewA.widthAnchor >~ viewB.widthAnchor * multiplierFloat expect(cA) == cB } } describe("constraint(lessThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(lessThanOrEqualTo: viewB.widthAnchor, multiplier: multiplierFloat) cA.isActive = true cB = viewA.widthAnchor <~ viewB.widthAnchor * multiplierFloat expect(cA) == cB } } describe("constraint(equalTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(equalTo: viewB.widthAnchor, multiplier: multiplierFloat, constant: constantFloat) cA.isActive = true cB = viewA.widthAnchor ~ viewB.widthAnchor * multiplierFloat + constantFloat expect(cA) == cB } } describe("constraint(greaterThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(greaterThanOrEqualTo: viewB.widthAnchor, multiplier: multiplierFloat, constant: constantFloat) cA.isActive = true cB = viewA.widthAnchor >~ viewB.widthAnchor * multiplierFloat + constantFloat expect(cA) == cB } } describe("constraint(lessThanOrEqualTo anchor: NSLayoutDimension, multiplier m: CGFloat, constant c: CGFloat)") { it("creates valid constraint") { cA = viewA.widthAnchor.constraint(lessThanOrEqualTo: viewB.widthAnchor, multiplier: multiplierFloat, constant: constantFloat) cA.isActive = true cB = viewA.widthAnchor <~ viewB.widthAnchor * multiplierFloat + constantFloat expect(cA) == cB } } // MARK: - Extra operations describe("constrain to all X, Y anchors") { it("creates valid constraint") { let csA = [viewA.topAnchor.constraint(equalTo: viewB.topAnchor), viewA.leadingAnchor.constraint(equalTo: viewB.leadingAnchor), viewA.trailingAnchor.constraint(equalTo: viewB.trailingAnchor), viewA.bottomAnchor.constraint(equalTo: viewB.bottomAnchor)] NSLayoutConstraint.activate(csA) let csB = viewA ~ viewB for (coA, coB) in zip(csA, csB) { expect(coA) == coB } } } } }
e89b020df542cb635ea586467181fdb1
40.783465
144
0.570338
false
false
false
false
biohazardlover/ByTrain
refs/heads/master
ByTrain/Filter.swift
mit
1
import Foundation class Filter: NSObject, NSCopying { var fromStations: [FilterItem] = [] var toStations: [FilterItem] = [] var trainTypes: [FilterItem] = [ FilterItem(type: .gcTrain, name: "GC-高铁/城际", selected: true), FilterItem(type: .dTrain, name: "D-动车", selected: true), FilterItem(type: .zTrain, name: "Z-直达", selected: true), FilterItem(type: .tTrain, name: "T-特快", selected: true), FilterItem(type: .kTrain, name: "K-快速", selected: true), FilterItem(type: .otherTrain, name: "其他", selected: true) ] var timeRanges: [FilterItem] = [ FilterItem(type: .timeFrom00To24, name: "00:00--24:00", selected: true), FilterItem(type: .timeFrom00To06, name: "00:00--06:00", selected: false), FilterItem(type: .timeFrom06To12, name: "06:00--12:00", selected: false), FilterItem(type: .timeFrom12To18, name: "12:00--18:00", selected: false), FilterItem(type: .timeFrom18To24, name: "18:00--24:00", selected: false) ] func copy(with zone: NSZone? = nil) -> Any { let filter = Filter() filter.fromStations = [] for fromStation in fromStations { filter.fromStations.append(fromStation.copy() as! FilterItem) } filter.toStations = [] for toStation in toStations { filter.toStations.append(toStation.copy() as! FilterItem) } filter.trainTypes = [] for trainType in trainTypes { filter.trainTypes.append(trainType.copy() as! FilterItem) } filter.timeRanges = [] for timeRange in timeRanges { filter.timeRanges.append(timeRange.copy() as! FilterItem) } return filter } }
f5a2be0a5928d8fd3ca85b51fbe6601b
33.226415
81
0.582139
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureCoin/Sources/FeatureCoinDomain/HistoricalPrice/Model/Series.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public struct Series: Hashable { public let window: Interval public let scale: Scale } extension Series { public static let now = Self(window: ._15_minutes, scale: ._15_minutes) public static let day = Self(window: .day, scale: ._15_minutes) public static let week = Self(window: .week, scale: ._1_hour) public static let month = Self(window: .month, scale: ._2_hours) public static let year = Self(window: .year, scale: ._1_day) public static let all = Self(window: .all, scale: ._5_days) }
80699b322d5e1258652eed3d911cec92
34.764706
75
0.682566
false
false
false
false
CPRTeam/CCIP-iOS
refs/heads/master
Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift
gpl-3.0
3
// // 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. // /// A type that supports incremental updates. For example Digest or Cipher may be updatable /// and calculate result incerementally. public protocol Updatable { /// Update given bytes in chunks. /// /// - parameter bytes: Bytes to process. /// - parameter isLast: Indicate if given chunk is the last one. No more updates after this call. /// - returns: Processed partial result data or empty array. mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8> /// Update given bytes in chunks. /// /// - Parameters: /// - bytes: Bytes to process. /// - isLast: Indicate if given chunk is the last one. No more updates after this call. /// - output: Resulting bytes callback. /// - Returns: Processed partial result data or empty array. mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool, output: (_ bytes: Array<UInt8>) -> Void) throws } extension Updatable { public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false, output: (_ bytes: Array<UInt8>) -> Void) throws { let processed = try update(withBytes: bytes, isLast: isLast) if !processed.isEmpty { output(processed) } } public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { try self.update(withBytes: bytes, isLast: isLast) } public mutating func update(withBytes bytes: Array<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { try self.update(withBytes: bytes.slice, isLast: isLast) } public mutating func update(withBytes bytes: Array<UInt8>, isLast: Bool = false, output: (_ bytes: Array<UInt8>) -> Void) throws { try self.update(withBytes: bytes.slice, isLast: isLast, output: output) } /// Finish updates. This may apply padding. /// - parameter bytes: Bytes to process /// - returns: Processed data. public mutating func finish(withBytes bytes: ArraySlice<UInt8>) throws -> Array<UInt8> { try self.update(withBytes: bytes, isLast: true) } public mutating func finish(withBytes bytes: Array<UInt8>) throws -> Array<UInt8> { try self.finish(withBytes: bytes.slice) } /// Finish updates. May add padding. /// /// - Returns: Processed data /// - Throws: Error public mutating func finish() throws -> Array<UInt8> { try self.update(withBytes: [], isLast: true) } /// Finish updates. This may apply padding. /// - parameter bytes: Bytes to process /// - parameter output: Resulting data /// - returns: Processed data. public mutating func finish(withBytes bytes: ArraySlice<UInt8>, output: (_ bytes: Array<UInt8>) -> Void) throws { let processed = try update(withBytes: bytes, isLast: true) if !processed.isEmpty { output(processed) } } public mutating func finish(withBytes bytes: Array<UInt8>, output: (_ bytes: Array<UInt8>) -> Void) throws { try self.finish(withBytes: bytes.slice, output: output) } /// Finish updates. May add padding. /// /// - Parameter output: Processed data /// - Throws: Error public mutating func finish(output: (Array<UInt8>) -> Void) throws { try self.finish(withBytes: [], output: output) } }
24b9d8813b75961a883a65196a0e91b8
41.453608
217
0.703497
false
false
false
false
lulee007/GankMeizi
refs/heads/master
GankMeizi/Splash/SplashViewController.swift
mit
1
// // WelcomeViewController.swift // GankMeizi // // Created by 卢小辉 on 16/5/19. // Copyright © 2016年 lulee007. All rights reserved. // import UIKit import EAIntroView import CocoaLumberjack class SplashViewController: UIViewController,EAIntroDelegate { let pageTitles = [ "技术干货", "精选妹纸美图", "午间放松视频" ] let pageDescriptions = [ "为大家精选的技术干货,充电充电充电", "每天一张精选的美丽妹纸图,放空你的思绪", "中午小憩一会儿,戴上耳机以免可能影响他人" ] override func viewDidLoad() { super.viewDidLoad() buildAndShowIntroView() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func introDidFinish(introView: EAIntroView!) { DDLogDebug("欢迎页结束,进入主页") let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.setupRootVCWithNC(MainTabBarViewController.buildController()) } func buildAndShowIntroView() { self.view.backgroundColor = ThemeUtil.colorWithHexString(ThemeUtil.PRIMARY_COLOR) var pages = [EAIntroPage]() for pageIndex in 0..<3{ let page = EAIntroPage.init() page.title = pageTitles[pageIndex] page.desc = pageDescriptions[pageIndex] pages.append(page) } let eaIntroView = EAIntroView.init(frame: (self.view.bounds), andPages: pages) eaIntroView.titleView = UIImageView.init(image: scaleImage(UIImage(named: "SplashTitle")!, toSize: CGSize.init(width: 135, height: 135))) eaIntroView.titleViewY = 90 eaIntroView.backgroundColor = ThemeUtil.colorWithHexString(ThemeUtil.PRIMARY_COLOR) eaIntroView.skipButton.setTitle("跳过", forState: UIControlState.Normal) eaIntroView.delegate = self eaIntroView.showInView(self.view, animateDuration: 0.3) DDLogDebug("初始化完成并显示欢迎页") } func scaleImage(image: UIImage, toSize newSize: CGSize) -> (UIImage) { let newRect = CGRectIntegral(CGRectMake(0,0, newSize.width, newSize.height)) UIGraphicsBeginImageContextWithOptions(newSize, false, 0) let context = UIGraphicsGetCurrentContext() CGContextSetInterpolationQuality(context, .High) let flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height) CGContextConcatCTM(context, flipVertical) CGContextDrawImage(context, newRect, image.CGImage) let newImage = UIImage(CGImage: CGBitmapContextCreateImage(context)!) UIGraphicsEndImageContext() return newImage } // 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. } }
f618e4badc08c5e5a149d583a96666bd
32.55914
145
0.658122
false
false
false
false
russbishop/swift
refs/heads/master
test/Sema/object_literals_ios.swift
apache-2.0
1
// RUN: %target-parse-verify-swift // REQUIRES: OS=ios struct S: _ColorLiteralConvertible { init(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float) {} } let y: S = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) let y2 = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) // expected-error{{could not infer type of color literal}} expected-note{{import UIKit to use 'UIColor' as the default color literal type}} let y3 = #colorLiteral(red: 1, bleen: 0, grue: 0, alpha: 1) // expected-error{{cannot convert value of type '(red: Int, bleen: Int, grue: Int, alpha: Int)' to expected argument type '(red: Float, green: Float, blue: Float, alpha: Float)'}} struct I: _ImageLiteralConvertible { init(imageLiteralResourceName: String) {} } let z: I = #imageLiteral(resourceName: "hello.png") let z2 = #imageLiteral(resourceName: "hello.png") // expected-error{{could not infer type of image literal}} expected-note{{import UIKit to use 'UIImage' as the default image literal type}} struct Path: _FileReferenceLiteralConvertible { init(fileReferenceLiteralResourceName: String) {} } let p1: Path = #fileLiteral(resourceName: "what.txt") let p2 = #fileLiteral(resourceName: "what.txt") // expected-error{{could not infer type of file reference literal}} expected-note{{import Foundation to use 'URL' as the default file reference literal type}}
d078e39780ab7a45042c3373b8163b50
55.875
239
0.727473
false
false
false
false
eure/ReceptionApp
refs/heads/master
iOS/ReceptionApp/Screens/TopButton.swift
mit
1
// // TopButton.swift // ReceptionApp // // Created by Hiroshi Kimura on 8/23/15. // Copyright © 2016 eureka, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import UIKit // MARK: - TopButton final class TopButton: UIControl { // MARK: Internal @IBOutlet dynamic var titleLabel: UILabel? @IBOutlet dynamic var subtitleLabel: UILabel? var title: String? { get { return self.titleLabel?.text } set { self.titleLabel?.text = newValue } } // MARK: NSObject override func awakeFromNib() { super.awakeFromNib() self.backgroundColor = UIColor.clearColor() self.tintColor = UIColor.clearColor() self.layer.addSublayer(self.shape) self.clipsToBounds = true } // MARK: UIView override var tintColor: UIColor? { get{ return super.tintColor } set { super.tintColor = newValue self.titleLabel?.textColor = newValue self.subtitleLabel?.textColor = newValue self.imageView?.tintColor = newValue } } override func layoutSublayersOfLayer(layer: CALayer) { super.layoutSublayersOfLayer(layer) let width = (1.0 / UIScreen.mainScreen().scale) * 2.0 let path = UIBezierPath( roundedRect: self.bounds.insetBy(dx: width / 2, dy: width / 2), cornerRadius: self.bounds.height / 2 ) self.shape.path = path.CGPath self.shape.fillColor = UIColor.clearColor().CGColor self.shape.lineWidth = width self.shape.strokeColor = Configuration.Color.largeButtonBorderColor.CGColor } // MARK: UIControl override var highlighted: Bool { get { return super.highlighted } set { super.highlighted = newValue UIView.animateWithDuration( 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: .BeginFromCurrentState, animations: { if newValue { self.alpha = 0.6 self.layer.transform = CATransform3DMakeScale(0.99, 0.99, 1) self.shape.fillColor = UIColor(white: 0, alpha: 0.02).CGColor } else { self.alpha = 1 self.layer.transform = CATransform3DIdentity self.shape.fillColor = UIColor.clearColor().CGColor } }, completion: { _ in } ) } } // MARK: Private @IBOutlet private dynamic var imageView: UIImageView? @IBOutlet private dynamic var iconImageView: UIImageView? private let shape = CAShapeLayer() }
4068eab531570de93e0f25db189dee05
29.194245
85
0.570884
false
false
false
false
orta/Tinker
refs/heads/master
Tinker/Library/Room.swift
mit
1
// // Room.swift // Relate // // Created by Orta on 8/23/14. // Copyright (c) 2014 Orta. All rights reserved. // public class Room: TinkerObject { public var roomDescription:String? public var northRoom: Room? public var eastRoom: Room? public var westRoom: Room? public var southRoom: Room? public var items: [Item] = [] public var people: [Person] = [] var visited = false public func connectNorth(room: Room) { self.northRoom = room room.southRoom = self } public func connectSouth(room:Room) { self.southRoom = room room.northRoom = self } public func connectEast(room: Room) { self.eastRoom = room room.westRoom = self } public func connectWest(room: Room) { self.westRoom = room room.eastRoom = self } func describeInsideRoom() { for item in items { TQ.print(item.descriptionInRoom); } } public func addPerson(person: Person) { people.append(person) heldObjects.append(person) } public func addItem(item: Item) { items.append(item) heldObjects.append(item) } public func pickUpItem(itemID: String) { if let item = itemForID(itemID) { heldObjects.remove(item) items.remove(item) if item.onPickUp != nil { item.onPickUp!() } Tinker.sharedInstance.player.addItem(item) } } func itemForID(itemID: String) -> Item? { for item in items { if item.id == itemID { return item } } return nil } }
2195f85b5c66f1260db3ece8c24da0a2
21.15
54
0.534989
false
false
false
false
Cleverlance/Pyramid
refs/heads/master
Example/Tests/Scope Management/Injection/AssemblerScopeImplTests.swift
mit
1
// // Copyright © 2016 Cleverlance. All rights reserved. // import XCTest import Nimble import Pyramid import Swinject class AssemblerScopeImplTests: XCTestCase { func test_ItConformsToScopeProtocol() { let _: Scope? = (nil as AssemblerScopeImpl<SpecDummy>?) } func testGetInstanceOf_GivenSpecWithInt42Assembly_WhenRequestingInt_ItShouldReturn42() { let scope = AssemblerScopeImpl<SpecStubWithInt42Assembly>(parent: nil) let result = scope.getInstance(of: Int.self) expect(result) == 42 } func test_GetInstanceOf_GivenParentWithSpecWithInt42_WhenRequestingInt_itShouldReturn42() { let scope = AssemblerScopeImpl<SpecDummy>(parent: ScopeStubInt42(parent: nil)) let result = scope.getInstance(of: Int.self) expect(result) == 42 } } private struct SpecDummy: AssemblerScopeSpec { static var assemblies = [Assembly]() } private struct SpecStubWithInt42Assembly: AssemblerScopeSpec { static var assemblies: [Assembly] = [AssemblyStubInt42()] } private struct AssemblyStubInt42: Assembly { func assemble(container: Container) { container.register(Int.self) { _ in 42 } } } private typealias ScopeStubInt42 = AssemblerScopeImpl<SpecStubWithInt42Assembly>
b5b4206e9a3e0d5414feeef588412dd9
27.704545
95
0.729216
false
true
false
false
HipHipArr/PocketCheck
refs/heads/master
Cheapify 2.0/TaskManager.swift
mit
1
// // TaskManager.swift // Cheapify 2.0 // // Created by Christine Wen on 7/1/15. // Copyright (c) 2015 Your Friend. All rights reserved. // import UIKit var taskMgr: TaskManager = TaskManager() struct Task { var event = "Name" var category = "Description" var price = "0.00" var tax = "0.00" var tip = "0.00" } class TaskManager: NSObject { var tasks = [Task]() func addTask(event: String, category: String, price: String, tax: String, tip: String){ tasks.append(Task(event: event, category: category, price: price, tax: tax, tip: tip)) } func removeTask(index:Int){ tasks.removeAtIndex(index) } }
0959db76526e3e51ebe4f862e0b6ca9f
18.052632
94
0.578729
false
false
false
false
IngmarStein/swift
refs/heads/master
stdlib/public/core/ArrayCast.swift
apache-2.0
4
//===--- ArrayCast.swift - Casts and conversions for Array ----------------===// // // 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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Because NSArray is effectively an [AnyObject], casting [T] -> [U] // is an integral part of the bridging process and these two issues // are handled together. // //===----------------------------------------------------------------------===// @_silgen_name("_swift_arrayDownCastIndirect") public func _arrayDownCastIndirect<SourceValue, TargetValue>( _ source: UnsafePointer<Array<SourceValue>>, _ target: UnsafeMutablePointer<Array<TargetValue>>) { target.initialize(to: _arrayForceCast(source.pointee)) } /// Implements `source as! [TargetElement]`. /// /// - Note: When SourceElement and TargetElement are both bridged verbatim, type /// checking is deferred until elements are actually accessed. public func _arrayForceCast<SourceElement, TargetElement>( _ source: Array<SourceElement> ) -> Array<TargetElement> { #if _runtime(_ObjC) if _isClassOrObjCExistential(SourceElement.self) && _isClassOrObjCExistential(TargetElement.self) { let src = source._buffer if let native = src.requestNativeBuffer() { if native.storesOnlyElementsOfType(TargetElement.self) { // A native buffer that is known to store only elements of the // TargetElement can be used directly return Array(_buffer: src.cast(toBufferOf: TargetElement.self)) } // Other native buffers must use deferred element type checking return Array(_buffer: src.downcast(toBufferWithDeferredTypeCheckOf: TargetElement.self)) } return Array(_immutableCocoaArray: source._buffer._asCocoaArray()) } #endif return source.map { $0 as! TargetElement } } internal struct _UnwrappingFailed : Error {} extension Optional { internal func unwrappedOrError() throws -> Wrapped { if let x = self { return x } throw _UnwrappingFailed() } } @_silgen_name("_swift_arrayDownCastConditionalIndirect") public func _arrayDownCastConditionalIndirect<SourceValue, TargetValue>( _ source: UnsafePointer<Array<SourceValue>>, _ target: UnsafeMutablePointer<Array<TargetValue>> ) -> Bool { if let result: Array<TargetValue> = _arrayConditionalCast(source.pointee) { target.initialize(to: result) return true } return false } /// Implements `source as? [TargetElement]`: convert each element of /// `source` to a `TargetElement` and return the resulting array, or /// return `nil` if any element fails to convert. /// /// - Complexity: O(n), because each element must be checked. public func _arrayConditionalCast<SourceElement, TargetElement>( _ source: [SourceElement] ) -> [TargetElement]? { return try? source.map { try ($0 as? TargetElement).unwrappedOrError() } }
0e8d93a2e0c3e34b61cf759acc66056b
37.048193
80
0.684611
false
false
false
false