repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
achimk/Swift-Playgrounds | Playgrounds/Swift-SequenceType.playground/Contents.swift | 1 | 1581 | //: Playground - noun: a place where people can play
import UIKit
import Foundation
// MARK: Stack example
struct Stack<T>: CustomStringConvertible, SequenceType, CollectionType {
typealias Element = T
private var contents: [T] = []
// MARK: Init
init() { }
init<S: SequenceType where S.Generator.Element == T>(_ sequence: S) {
contents = Array<T>(sequence)
}
// MARK: Push / Pop
mutating func push(newElement: T) {
contents.append(newElement)
}
mutating func pop() {
if contents.count > 0 {
contents.removeLast()
}
}
// MARK: CustomStringConvertible
var description: String {
return "Stack {content: \(contents)}"
}
// MARK: SequenceType
typealias Generator = AnyGenerator<T>
func generate() -> Generator {
return AnyGenerator(contents.generate())
}
// MARK: CollectionType
typealias Index = Int
var startIndex: Int {
return 0
}
var endIndex: Int {
return contents.count
}
subscript(i: Int) -> T {
return contents[i]
}
}
// MARK: Example
let initial = [1, 2, 3]
var stack = Stack<Int>(initial)
print(stack)
stack.push(10)
print(stack)
stack.pop()
print(stack)
print("\nSequenceType enumeration:")
for (index, value) in stack.enumerate() {
print("[\(index)] -> \(value)")
}
print("\nCollectionType enumeration:")
for index in stack.startIndex ..< stack.endIndex {
print("[\(index)] -> \(stack[index])")
}
| mit |
imex94/compiler-swift | SwiftCompiler/SwiftCompiler/RegExp.swift | 1 | 3658 | //
// Regex.swift
// SwiftCompiler
//
// Created by Alex Telek on 27/12/2015.
// Copyright © 2015 Alex Telek. All rights reserved.
//
import Cocoa
enum Regex {
case NULL
case EMPTY
case CHAR(Character)
indirect case ALT(Regex, Regex)
indirect case SEQ(Regex, Regex)
indirect case STAR(Regex)
indirect case NTIMES(Regex, Int)
indirect case NOT(Regex)
indirect case RECORD(String, Regex)
}
func ==(a: Regex, b: Regex) -> Bool {
switch (a, b) {
case (.NULL, .NULL): return true
case (.EMPTY, .EMPTY): return true
case (.CHAR(let c1), .CHAR(let c2)) where c1 == c2: return true
case (.ALT(let x, let y), .ALT(let z, let v)) where x == z && y == v: return true
case (.SEQ(let x, let y), .SEQ(let z, let v)) where x == z && y == v: return true
case (.STAR(let x), .STAR(let y)) where x == y: return true
case (.NTIMES(let x, let y), .NTIMES(let z, let v)) where x == z && y == v: return true
case (.NOT(let x), .NOT(let y)) where x == y: return true
case (.RECORD(let x, let y), .RECORD(let z, let v)) where x == z && y == v: return true
default: return false
}
}
class RegExp: NSObject {
class func nullable(r: Regex) -> Bool {
switch r {
case .NULL: return false
case .EMPTY: return true
case .CHAR(_): return false
case .ALT(let r1, let r2): return nullable(r1) || nullable(r2)
case .SEQ(let r1, let r2): return nullable(r1) && nullable(r2)
case .STAR(_): return true
case .NTIMES(let r1, let n): return n == 0 ? true : nullable(r1)
case .NOT(let r1): return !nullable(r1)
case .RECORD(_, let r1): return nullable(r1)
}
}
class func der(c: Character, _ r: Regex) -> Regex {
switch r {
case .NULL: return .NULL
case .EMPTY: return .NULL
case .CHAR(let d): return c == d ? .EMPTY : .NULL
case .ALT(let r1, let r2): return .ALT(der(c, r1), der(c, r2))
case .SEQ(let r1, let r2):
if nullable(r1) {
return .ALT(.SEQ(der(c, r1), r2), der(c, r2))
} else {
return .SEQ(der(c, r1), r2)
}
case .STAR(let r1): return .SEQ(der(c, r1), .STAR(r1))
case .NTIMES(let r1, let n): return n == 0 ? .NULL : .SEQ(der(c, r1), .NTIMES(r1, n - 1))
case .NOT(let r1): return .NOT(der(c, r1))
case .RECORD(_, let r1): return der(c, r1)
}
}
class func ders(s: Array<Character>, _ r: Regex) -> Regex {
switch s.count {
case 0: return r
//TODO: Simplification
default:
let (c, rest) = (s.first!, s.dropFirst())
return ders(Array(rest), RegExp.simp(der(c, r)))
}
}
class func matches(r: Regex, s: String) -> Bool {
return nullable(ders(Array(s.characters), r))
}
class func simp(r: Regex) -> Regex {
switch r {
case .ALT(let r1, let r2):
switch (simp(r1), simp(r2)) {
case (.NULL, let re2): return re2
case (let re1, .NULL): return re1
case (let re1, let re2): return re1 == r2 ? re1 : .ALT(re1, re2)
}
case .SEQ(let r1, let r2):
switch (simp(r1), simp(r2)) {
case (.NULL, _): return .NULL
case (_, .NULL): return .NULL
case (.EMPTY, let re2): return re2
case (let re1, .EMPTY): return re1
case (let re1, let re2): return .SEQ(re1, re2)
}
case .NTIMES(let re1, let n): return .NTIMES(simp(re1), n)
default: return r
}
}
} | mit |
BGDigital/MCPai | MCPai/MCPai/ViewController.swift | 1 | 502 | //
// ViewController.swift
// MCPai
//
// Created by XingfuQiu on 15/4/29.
// Copyright (c) 2015年 XingfuQiu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
AdilSoomro/ASBottomSheet | ASBottomSheet/Classes/ASBottomSheet.swift | 1 | 10291 | //
// ASBottomSheet.swift
// Imagitor
//
// Created by Adil Soomro on 3/13/17.
// Copyright © 2017 BooleanBites Ltd. All rights reserved.
//
import UIKit
/**
* `ASBottomSheet` is a UIActionSheet like menu controller that can be used to
* show custom menu from bottom of the presenting view controller.
* It uses UICollectionView to show menu options provided by the developer.
* It is greatly inspired by the FCVerticalMenu
*/
@objc open class ASBottomSheet: UIViewController{
var menuItems:[ASBottomSheetItem]? = nil
@IBOutlet var collectionView: UICollectionView!
public var tintColor:UIColor?
private var bottomConstraints: NSLayoutConstraint!
private var heigthConstraints: NSLayoutConstraint!
@IBOutlet private var collectionViewLeadingConstraints: NSLayoutConstraint!
@IBOutlet private var collectionViewTrailingConstraints: NSLayoutConstraint!
@IBOutlet private var collectionViewBottomConstraints: NSLayoutConstraint!
@objc public var isOpen = false
/**
* Makes a `ASBottomSheet` that can be shown from bottom of screen.
* - parameter array: the options to be shown in menu collection view
*/
@objc public static func menu(withOptions array:[ASBottomSheetItem]) -> ASBottomSheet?{
let podBundle:Bundle? = Bundle(for:ASBottomSheet.classForCoder())
let storyboard:UIStoryboard?
//FROM COCOAPOD
if let bundleURL = podBundle {
storyboard = UIStoryboard.init(name: "ASBottomSheetStoryBoard", bundle: bundleURL)
//FROM MANUAL INSTALL
}else {
storyboard = UIStoryboard.init(name: "ASBottomSheetStoryBoard", bundle: nil)
}
if let main = storyboard {
let bottomMenu:ASBottomSheet = main.instantiateViewController(withIdentifier: "ASBottomSheet") as! ASBottomSheet
bottomMenu.menuItems = array
bottomMenu.tintColor = UIColor.white
return bottomMenu
}
return nil
}
open override func viewDidLoad() {
super.viewDidLoad()
// collectionView.backgroundColor = UIColor.orange
}
/**
* Shows the menu from bottom of the provided view controller
* - parameter viewController: the host view controller
*/
@objc public func showMenu(fromViewController viewController:UIViewController) {
if isOpen {
return
}
let view = self.view // force to load the view
let parentView = viewController.view // force to load the view
self.collectionView.reloadData()
viewController.addChild(self)
viewController.view.addSubview(view!)
self.didMove(toParent: viewController)
// view?.removeConstraints(view!.constraints)
view?.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
let insets = parentView!.safeAreaInsets
collectionViewTrailingConstraints.constant = 0 - insets.right
collectionViewLeadingConstraints.constant = insets.left
} else {
let margins = parentView!.layoutMargins
collectionViewTrailingConstraints.constant = 0 - margins.right
collectionViewLeadingConstraints.constant = margins.left
}
NSLayoutConstraint.activate([
view!.leadingAnchor.constraint(equalTo: parentView!.leadingAnchor),
view!.trailingAnchor.constraint(equalTo: parentView!.trailingAnchor)
])
var bottomPadding:CGFloat = 0.0
if #available(iOS 11.0, *) {
bottomPadding = viewController.view?.safeAreaInsets.bottom ?? 0.0
}
let viewHeight = (self.calculateHeight()) + bottomPadding + 10.0
bottomConstraints = NSLayoutConstraint(item: view!, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: parentView, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: viewHeight)
bottomConstraints.isActive = true
collectionViewBottomConstraints.constant = 0 - bottomPadding - 10
if heigthConstraints == nil {
heigthConstraints = NSLayoutConstraint(item: view!, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: viewHeight)
heigthConstraints.isActive = true
} else {
heigthConstraints.constant = viewHeight
}
parentView?.layoutIfNeeded()
self.collectionView.reloadData()
bottomConstraints.constant = 0
UIView.animate(withDuration: 0.2, animations: {
self.setupHeight()
parentView?.layoutIfNeeded()
}) { (complettion) in
}
view?.backgroundColor = UIColor.clear
isOpen = true
}
/**
* Hides the bottom menu with animation.
*
*/
@objc open func hide() {
//first take the menu frame and set its y origin to its bottom by adding
//its current origin plus height
let frame = self.view.frame
UIView.animate(withDuration: 0.2, animations: {
self.bottomConstraints.constant = frame.origin.y + frame.size.height
self.parent?.view.layoutIfNeeded()
}) { (finished:Bool) in
//cleanup
self.willMove(toParent: nil)
self.view.removeFromSuperview()
self.removeFromParent()
self.didMove(toParent: nil)
self.isOpen = false
};
}
override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.collectionView.collectionViewLayout.invalidateLayout()
coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) in
self.setupHeight()
}) { (UIViewControllerTransitionCoordinatorContext) in
self.collectionView.reloadData()
}
}
func setupHeight() {
var bottomPadding:CGFloat = 0.0
if #available(iOS 11.0, *) {
bottomPadding = self.parent!.view?.safeAreaInsets.bottom ?? 0.0
}
let viewHeight = (self.calculateHeight()) + bottomPadding + 10.0
heigthConstraints.constant = viewHeight
}
}
extension ASBottomSheet : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (menuItems?.count)!
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:ASBottomSheetCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ASBottomSheetCell", for: indexPath) as! ASBottomSheetCell
let menuItem: ASBottomSheetItem = menuItems![indexPath.row]
cell.itemImageView.image = menuItem.tintedImage(withColor: self.tintColor)
cell.itemTitleLabel.text = menuItem.title
cell.itemTitleLabel.textColor = tintColor
cell.itemImageView.tintColor = tintColor
// cell.backgroundColor = UIColor.red
return cell
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let menuItem: ASBottomSheetItem = menuItems![indexPath.row]
hide()
if menuItem.action != nil {
menuItem.action!()
}
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0;
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0;
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let numberOfItems = CGFloat(collectionView.numberOfItems(inSection: section))
let totalWidth = (numberOfItems * flowLayout.itemSize.width)
if totalWidth > collectionView.frame.width {
let numItemsInRow:CGFloat = CGFloat(Int(collectionView.frame.width / flowLayout.itemSize.width));
let totalWidthForRow = flowLayout.itemSize.width * numItemsInRow
let combinedWidthRow = totalWidthForRow + ((numItemsInRow - 1) * flowLayout.minimumInteritemSpacing)
let paddingRow = (collectionView.frame.width - combinedWidthRow) / 2
return UIEdgeInsets(top: 0, left: paddingRow, bottom: 0, right: paddingRow)
}
let combinedItemWidth = totalWidth + ((numberOfItems - 1) * flowLayout.minimumInteritemSpacing)
let padding = (collectionView.frame.width - combinedItemWidth) / 2
return UIEdgeInsets(top: 0, left: padding, bottom: 0, right: padding)
}
/**
* Calculates and returns the height to be consumed by the menu
* - return menu height
*
*/
func calculateHeight() -> CGFloat {
let topPadding:CGFloat = 10.0; //40 is top padding of collection view.
let bottomPadding:CGFloat = 10.0 // 10 is bottom padding of collection view.
return topPadding + collectionView.collectionViewLayout.collectionViewContentSize.height + bottomPadding
}
}
| mit |
darthpelo/LedsControl | iOSLedsControl/LedsControll/AppDelegate.swift | 1 | 516 | //
// AppDelegate.swift
// LedsControl
//
// Created by Alessio Roberto on 28/01/2017.
// Copyright © 2017 Alessio Roberto. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
}
| mit |
onekiloparsec/siesta | Examples/GithubBrowser/Source/UI/UserViewController.swift | 1 | 4200 | import UIKit
import Siesta
class UserViewController: UIViewController, UISearchBarDelegate, ResourceObserver {
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var userInfoView: UIView!
@IBOutlet weak var usernameLabel, fullNameLabel: UILabel!
@IBOutlet weak var avatar: RemoteImageView!
var statusOverlay = ResourceStatusOverlay()
var repoListVC: RepositoryListViewController?
var userResource: Resource? {
didSet {
// One call to removeObservers() removes both self and statusOverlay as observers of the old resource,
// since both observers are owned by self (see below).
oldValue?.removeObservers(ownedBy: self)
oldValue?.cancelLoadIfUnobserved(afterDelay: 0.1)
// Adding ourselves as an observer triggers an immediate call to resourceChanged().
userResource?.addObserver(self)
.addObserver(statusOverlay, owner: self)
.loadIfNeeded()
}
}
func resourceChanged(resource: Resource, event: ResourceEvent) {
// typedContent() infers that we want a User from context: showUser() expects one. Our content tranformer
// configuation in GithubAPI makes it so that the userResource actually holds a User. It is up to a Siesta
// client to ensure that the transformer output and the expected content type line up like this.
//
// If there were a type mismatch, typedContent() would return nil. (We could also provide a default value with
// the ifNone: param.)
showUser(userResource?.typedContent())
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = SiestaTheme.darkColor
userInfoView.hidden = true
statusOverlay.embedIn(self)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
setNeedsStatusBarAppearanceUpdate()
updateLoginButton()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent;
}
override func viewDidLayoutSubviews() {
statusOverlay.positionToCover(userInfoView)
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if let searchText = searchBar.text where !searchText.isEmpty {
// Setting userResource triggers a load and display of the new user data. Note that Siesta’s redunant
// request elimination and model caching make it reasonable to do this on every keystroke.
userResource = GithubAPI.user(searchText)
}
}
func showUser(user: User?) {
userInfoView.hidden = (user == nil)
// It's often easiest to make the same code path handle both the “data” and “no data” states.
// If this UI update were more expensive, we could choose to do it only on ObserverAdded or NewData.
usernameLabel.text = user?.login
fullNameLabel.text = user?.name
avatar.imageURL = user?.avatarURL
// Setting the reposResource property of the embedded VC triggers load & display of the user’s repos.
repoListVC?.reposResource =
userResource?
.optionalRelative(user?.repositoriesURL)?
.withParam("type", "all")
.withParam("sort", "updated")
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "repos" {
repoListVC = segue.destinationViewController as? RepositoryListViewController
}
}
@IBAction func logInOrOut() {
if(GithubAPI.isAuthenticated) {
GithubAPI.logOut()
updateLoginButton()
} else {
performSegueWithIdentifier("login", sender: loginButton)
}
}
private func updateLoginButton() {
loginButton.setTitle(GithubAPI.isAuthenticated ? "Log Out" : "Log In", forState: .Normal)
userResource?.loadIfNeeded()
}
}
| mit |
PlusR/AAMFeedback | Feedback/ViewController.swift | 1 | 1290 | //
// ViewController.swift
// Feedback
//
// Created by akuraru on 2020/04/12.
// Copyright © 2020 Art & Mobile. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func openModal(_ sender: Any) {
let viewController = createViewController()
let feedbackNavigation = UINavigationController(rootViewController: viewController)
present(feedbackNavigation, animated: true)
}
@IBAction func pushAsViewController(_ sender: Any) {
let viewController = createViewController()
navigationController?.pushViewController(viewController, animated: true)
}
func createViewController() -> UIViewController {
let viewController = FeedbackViewController()
viewController.context = Context(
toRecipients: ["YOUR_CONTACT@email.com"],
descriptionPlaceHolder: "Please write for details in modal."
)
viewController.beforeShowAction = { (controller) in
controller.addAttachmentData("text".data(using: .utf8)!, mimeType: "text/plain", fileName: "example.text")
}
viewController.view.backgroundColor = .white
return viewController
}
}
| bsd-3-clause |
bolshedvorsky/swift-corelibs-foundation | Foundation/Locale.swift | 9 | 19094 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import CoreFoundation
internal func __NSLocaleIsAutoupdating(_ locale: NSLocale) -> Bool {
return false // Auto-updating is only on Darwin
}
internal func __NSLocaleCurrent() -> NSLocale {
return CFLocaleCopyCurrent()._nsObject
}
/**
`Locale` encapsulates information about linguistic, cultural, and technological conventions and standards. Examples of information encapsulated by a locale include the symbol used for the decimal separator in numbers and the way dates are formatted.
Locales are typically used to provide, format, and interpret information about and according to the user’s customs and preferences. They are frequently used in conjunction with formatters. Although you can use many locales, you usually use the one associated with the current user.
*/
public struct Locale : CustomStringConvertible, CustomDebugStringConvertible, Hashable, Equatable, ReferenceConvertible {
public typealias ReferenceType = NSLocale
public typealias LanguageDirection = NSLocale.LanguageDirection
internal var _wrapped : NSLocale
internal var _autoupdating : Bool
/// Returns the user's current locale.
public static var current : Locale {
return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: false)
}
/// Returns a locale which tracks the user's current preferences.
///
/// If mutated, this Locale will no longer track the user's preferences.
///
/// - note: The autoupdating Locale will only compare equal to another autoupdating Locale.
public static var autoupdatingCurrent : Locale {
// swift-corelibs-foundation does not yet support autoupdating, but we can return the current locale (which will not change).
return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: true)
}
@available(*, unavailable, message: "Consider using the user's locale or nil instead, depending on use case")
public static var system : Locale { fatalError() }
// MARK: -
//
/// Return a locale with the specified identifier.
public init(identifier: String) {
_wrapped = NSLocale(localeIdentifier: identifier)
_autoupdating = false
}
internal init(reference: NSLocale) {
_wrapped = reference.copy() as! NSLocale
if __NSLocaleIsAutoupdating(reference) {
_autoupdating = true
} else {
_autoupdating = false
}
}
private init(adoptingReference reference: NSLocale, autoupdating: Bool) {
_wrapped = reference
_autoupdating = autoupdating
}
// MARK: -
//
/// Returns a localized string for a specified identifier.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forIdentifier identifier: String) -> String? {
return _wrapped.displayName(forKey: .identifier, value: identifier)
}
/// Returns a localized string for a specified language code.
///
/// For example, in the "en" locale, the result for `"es"` is `"Spanish"`.
public func localizedString(forLanguageCode languageCode: String) -> String? {
return _wrapped.displayName(forKey: .languageCode, value: languageCode)
}
/// Returns a localized string for a specified region code.
///
/// For example, in the "en" locale, the result for `"fr"` is `"France"`.
public func localizedString(forRegionCode regionCode: String) -> String? {
return _wrapped.displayName(forKey: .countryCode, value: regionCode)
}
/// Returns a localized string for a specified script code.
///
/// For example, in the "en" locale, the result for `"Hans"` is `"Simplified Han"`.
public func localizedString(forScriptCode scriptCode: String) -> String? {
return _wrapped.displayName(forKey: .scriptCode, value: scriptCode)
}
/// Returns a localized string for a specified variant code.
///
/// For example, in the "en" locale, the result for `"POSIX"` is `"Computer"`.
public func localizedString(forVariantCode variantCode: String) -> String? {
return _wrapped.displayName(forKey: .variantCode, value: variantCode)
}
/// Returns a localized string for a specified `Calendar.Identifier`.
///
/// For example, in the "en" locale, the result for `.buddhist` is `"Buddhist Calendar"`.
public func localizedString(for calendarIdentifier: Calendar.Identifier) -> String? {
// NSLocale doesn't export a constant for this
let result = CFLocaleCopyDisplayNameForPropertyValue(unsafeBitCast(_wrapped, to: CFLocale.self), kCFLocaleCalendarIdentifier, Calendar._toNSCalendarIdentifier(calendarIdentifier).rawValue._cfObject)._swiftObject
return result
}
/// Returns a localized string for a specified ISO 4217 currency code.
///
/// For example, in the "en" locale, the result for `"USD"` is `"US Dollar"`.
/// - seealso: `Locale.isoCurrencyCodes`
public func localizedString(forCurrencyCode currencyCode: String) -> String? {
return _wrapped.displayName(forKey: .currencyCode, value: currencyCode)
}
/// Returns a localized string for a specified ICU collation identifier.
///
/// For example, in the "en" locale, the result for `"phonebook"` is `"Phonebook Sort Order"`.
public func localizedString(forCollationIdentifier collationIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collationIdentifier, value: collationIdentifier)
}
/// Returns a localized string for a specified ICU collator identifier.
public func localizedString(forCollatorIdentifier collatorIdentifier: String) -> String? {
return _wrapped.displayName(forKey: .collatorIdentifier, value: collatorIdentifier)
}
// MARK: -
//
/// Returns the identifier of the locale.
public var identifier: String {
return _wrapped.localeIdentifier
}
/// Returns the language code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "zh".
public var languageCode: String? {
return _wrapped.object(forKey: .languageCode) as? String
}
/// Returns the region code of the locale, or nil if it has none.
///
/// For example, for the locale "zh-Hant-HK", returns "HK".
public var regionCode: String? {
// n.b. this is called countryCode in ObjC
if let result = _wrapped.object(forKey: .countryCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the script code of the locale, or nil if has none.
///
/// For example, for the locale "zh-Hant-HK", returns "Hant".
public var scriptCode: String? {
return _wrapped.object(forKey: .scriptCode) as? String
}
/// Returns the variant code for the locale, or nil if it has none.
///
/// For example, for the locale "en_POSIX", returns "POSIX".
public var variantCode: String? {
if let result = _wrapped.object(forKey: .variantCode) as? String {
if result.isEmpty {
return nil
} else {
return result
}
} else {
return nil
}
}
/// Returns the exemplar character set for the locale, or nil if has none.
public var exemplarCharacterSet: CharacterSet? {
return _wrapped.object(forKey: .exemplarCharacterSet) as? CharacterSet
}
/// Returns the calendar for the locale, or the Gregorian calendar as a fallback.
public var calendar: Calendar {
// NSLocale should not return nil here
if let result = _wrapped.object(forKey: .calendar) as? Calendar {
return result
} else {
return Calendar(identifier: .gregorian)
}
}
/// Returns the collation identifier for the locale, or nil if it has none.
///
/// For example, for the locale "en_US@collation=phonebook", returns "phonebook".
public var collationIdentifier: String? {
return _wrapped.object(forKey: .collationIdentifier) as? String
}
/// Returns true if the locale uses the metric system.
///
/// -seealso: MeasurementFormatter
public var usesMetricSystem: Bool {
// NSLocale should not return nil here, but just in case
if let result = _wrapped.object(forKey: .usesMetricSystem) as? Bool {
return result
} else {
return false
}
}
/// Returns the decimal separator of the locale.
///
/// For example, for "en_US", returns ".".
public var decimalSeparator: String? {
return _wrapped.object(forKey: .decimalSeparator) as? String
}
/// Returns the grouping separator of the locale.
///
/// For example, for "en_US", returns ",".
public var groupingSeparator: String? {
return _wrapped.object(forKey: .groupingSeparator) as? String
}
/// Returns the currency symbol of the locale.
///
/// For example, for "zh-Hant-HK", returns "HK$".
public var currencySymbol: String? {
return _wrapped.object(forKey: .currencySymbol) as? String
}
/// Returns the currency code of the locale.
///
/// For example, for "zh-Hant-HK", returns "HKD".
public var currencyCode: String? {
return _wrapped.object(forKey: .currencyCode) as? String
}
/// Returns the collator identifier of the locale.
public var collatorIdentifier: String? {
return _wrapped.object(forKey: .collatorIdentifier) as? String
}
/// Returns the quotation begin delimiter of the locale.
///
/// For example, returns `“` for "en_US", and `「` for "zh-Hant-HK".
public var quotationBeginDelimiter: String? {
return _wrapped.object(forKey: .quotationBeginDelimiterKey) as? String
}
/// Returns the quotation end delimiter of the locale.
///
/// For example, returns `”` for "en_US", and `」` for "zh-Hant-HK".
public var quotationEndDelimiter: String? {
return _wrapped.object(forKey: .quotationEndDelimiterKey) as? String
}
/// Returns the alternate quotation begin delimiter of the locale.
///
/// For example, returns `‘` for "en_US", and `『` for "zh-Hant-HK".
public var alternateQuotationBeginDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationBeginDelimiterKey) as? String
}
/// Returns the alternate quotation end delimiter of the locale.
///
/// For example, returns `’` for "en_US", and `』` for "zh-Hant-HK".
public var alternateQuotationEndDelimiter: String? {
return _wrapped.object(forKey: .alternateQuotationEndDelimiterKey) as? String
}
// MARK: -
//
/// Returns a list of available `Locale` identifiers.
public static var availableIdentifiers: [String] {
return NSLocale.availableLocaleIdentifiers
}
/// Returns a list of available `Locale` language codes.
public static var isoLanguageCodes: [String] {
return NSLocale.isoLanguageCodes
}
/// Returns a list of available `Locale` region codes.
public static var isoRegionCodes: [String] {
// This was renamed from Obj-C
return NSLocale.isoCountryCodes
}
/// Returns a list of available `Locale` currency codes.
public static var isoCurrencyCodes: [String] {
return NSLocale.isoCurrencyCodes
}
/// Returns a list of common `Locale` currency codes.
public static var commonISOCurrencyCodes: [String] {
return NSLocale.commonISOCurrencyCodes
}
/// Returns a list of the user's preferred languages.
///
/// - note: `Bundle` is responsible for determining the language that your application will run in, based on the result of this API and combined with the languages your application supports.
/// - seealso: `Bundle.preferredLocalizations(from:)`
/// - seealso: `Bundle.preferredLocalizations(from:forPreferences:)`
public static var preferredLanguages: [String] {
return NSLocale.preferredLanguages
}
/// Returns a dictionary that splits an identifier into its component pieces.
public static func components(fromIdentifier string: String) -> [String : String] {
return NSLocale.components(fromLocaleIdentifier: string)
}
/// Constructs an identifier from a dictionary of components.
public static func identifier(fromComponents components: [String : String]) -> String {
return NSLocale.localeIdentifier(fromComponents: components)
}
/// Returns a canonical identifier from the given string.
public static func canonicalIdentifier(from string: String) -> String {
return NSLocale.canonicalLocaleIdentifier(from: string)
}
/// Returns a canonical language identifier from the given string.
public static func canonicalLanguageIdentifier(from string: String) -> String {
return NSLocale.canonicalLanguageIdentifier(from: string)
}
/// Returns the `Locale` identifier from a given Windows locale code, or nil if it could not be converted.
public static func identifier(fromWindowsLocaleCode code: Int) -> String? {
return NSLocale.localeIdentifier(fromWindowsLocaleCode: UInt32(code))
}
/// Returns the Windows locale code from a given identifier, or nil if it could not be converted.
public static func windowsLocaleCode(fromIdentifier identifier: String) -> Int? {
let result = NSLocale.windowsLocaleCode(fromLocaleIdentifier: identifier)
if result == 0 {
return nil
} else {
return Int(result)
}
}
/// Returns the character direction for a specified language code.
public static func characterDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.characterDirection(forLanguage: isoLangCode)
}
/// Returns the line direction for a specified language code.
public static func lineDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection {
return NSLocale.lineDirection(forLanguage: isoLangCode)
}
// MARK: -
@available(*, unavailable, renamed: "init(identifier:)")
public init(localeIdentifier: String) { fatalError() }
@available(*, unavailable, renamed: "identifier")
public var localeIdentifier: String { fatalError() }
@available(*, unavailable, renamed: "localizedString(forIdentifier:)")
public func localizedString(forLocaleIdentifier localeIdentifier: String) -> String { fatalError() }
@available(*, unavailable, renamed: "availableIdentifiers")
public static var availableLocaleIdentifiers: [String] { fatalError() }
@available(*, unavailable, renamed: "components(fromIdentifier:)")
public static func components(fromLocaleIdentifier string: String) -> [String : String] { fatalError() }
@available(*, unavailable, renamed: "identifier(fromComponents:)")
public static func localeIdentifier(fromComponents dict: [String : String]) -> String { fatalError() }
@available(*, unavailable, renamed: "canonicalIdentifier(from:)")
public static func canonicalLocaleIdentifier(from string: String) -> String { fatalError() }
@available(*, unavailable, renamed: "identifier(fromWindowsLocaleCode:)")
public static func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { fatalError() }
@available(*, unavailable, renamed: "windowsLocaleCode(fromIdentifier:)")
public static func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { fatalError() }
@available(*, unavailable, message: "use regionCode instead")
public var countryCode: String { fatalError() }
@available(*, unavailable, message: "use localizedString(forRegionCode:) instead")
public func localizedString(forCountryCode countryCode: String) -> String { fatalError() }
@available(*, unavailable, renamed: "isoRegionCodes")
public static var isoCountryCodes: [String] { fatalError() }
// MARK: -
//
public var description: String {
return _wrapped.description
}
public var debugDescription : String {
return _wrapped.debugDescription
}
public var hashValue : Int {
if _autoupdating {
return 1
} else {
return _wrapped.hash
}
}
public static func ==(lhs: Locale, rhs: Locale) -> Bool {
if lhs._autoupdating || rhs._autoupdating {
return lhs._autoupdating == rhs._autoupdating
} else {
return lhs._wrapped.isEqual(rhs._wrapped)
}
}
}
extension Locale : _ObjectTypeBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSLocale {
return _wrapped
}
public static func _forceBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) {
if !_conditionallyBridgeFromObjectiveC(input, result: &result) {
fatalError("Unable to bridge \(NSLocale.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) -> Bool {
result = Locale(reference: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSLocale?) -> Locale {
var result: Locale? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension Locale : Codable {
private enum CodingKeys : Int, CodingKey {
case identifier
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let identifier = try container.decode(String.self, forKey: .identifier)
self.init(identifier: identifier)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.identifier, forKey: .identifier)
}
}
| apache-2.0 |
YoungGary/Sina | Sina/Sina/Classes/Main主要/welcome/WelcomeViewController.swift | 1 | 1167 | //
// WelcomeViewController.swift
// Sina
//
// Created by YOUNG on 16/9/11.
// Copyright © 2016年 Young. All rights reserved.
//
import UIKit
import SDWebImage
class WelcomeViewController: UIViewController {
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var distance2bottom: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
//头像设置
let iconString = UserAccountViewModel.sharedInstance.account?.avatar_large
let url = NSURL(string: iconString ?? "")
icon.sd_setImageWithURL(url, placeholderImage: UIImage(named: "avatar_default_big" ))
//animation
distance2bottom.constant = UIScreen.mainScreen().bounds.height-200
UIView.animateWithDuration(3.0, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 2.0, options: .CurveEaseInOut, animations: {
self.view.layoutIfNeeded()
}) { (finished) in
UIApplication.sharedApplication().keyWindow?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
}
}
}
| apache-2.0 |
johnlui/FireUpYourVPN | UIButton.swift | 1 | 339 | //
// UIButton.swift
// FireUpYourVPN
//
// Created by 吕文翰 on 15/11/29.
// Copyright © 2015年 JohnLui. All rights reserved.
//
import UIKit
extension UIButton {
func disable() {
self.isEnabled = false
self.alpha = 0.5
}
func enable() {
self.isEnabled = true
self.alpha = 1
}
}
| mit |
Shirley0202/notes | 下载器/MZDownloadManager-master/Example/MZDownloadManager/MZDownloadingCell.swift | 2 | 2700 | //
// MZDownloadingCell.swift
// MZDownloadManager
//
// Created by Muhammad Zeeshan on 22/10/2014.
// Copyright (c) 2014 ideamakerz. All rights reserved.
//
import UIKit
import MZDownloadManager
class MZDownloadingCell: UITableViewCell {
@IBOutlet var lblTitle : UILabel?
@IBOutlet var lblDetails : UILabel?
@IBOutlet var progressDownload : UIProgressView?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func updateCellForRowAtIndexPath(_ indexPath : IndexPath, downloadModel: MZDownloadModel) {
self.lblTitle?.text = "File Title: \(downloadModel.fileName!)"
self.progressDownload?.progress = downloadModel.progress
var remainingTime: String = ""
if downloadModel.progress == 1.0 {
remainingTime = "Please wait..."
} else if let _ = downloadModel.remainingTime {
if (downloadModel.remainingTime?.hours)! > 0 {
remainingTime = "\(downloadModel.remainingTime!.hours) Hours "
}
if (downloadModel.remainingTime?.minutes)! > 0 {
remainingTime = remainingTime + "\(downloadModel.remainingTime!.minutes) Min "
}
if (downloadModel.remainingTime?.seconds)! > 0 {
remainingTime = remainingTime + "\(downloadModel.remainingTime!.seconds) sec"
}
} else {
remainingTime = "Calculating..."
}
var fileSize = "Getting information..."
if let _ = downloadModel.file?.size {
fileSize = String(format: "%.2f %@", (downloadModel.file?.size)!, (downloadModel.file?.unit)!)
}
var speed = "Calculating..."
if let _ = downloadModel.speed?.speed {
speed = String(format: "%.2f %@/sec", (downloadModel.speed?.speed)!, (downloadModel.speed?.unit)!)
}
var downloadedFileSize = "Calculating..."
if let _ = downloadModel.downloadedFile?.size {
downloadedFileSize = String(format: "%.2f %@", (downloadModel.downloadedFile?.size)!, (downloadModel.downloadedFile?.unit)!)
}
let detailLabelText = NSMutableString()
detailLabelText.appendFormat("File Size: \(fileSize)\nDownloaded: \(downloadedFileSize) (%.2f%%)\nSpeed: \(speed)\nTime Left: \(remainingTime)\nStatus: \(downloadModel.status)" as NSString, downloadModel.progress * 100.0)
lblDetails?.text = detailLabelText as String
}
}
| mit |
poodarchu/iDaily | iDaily/iDaily/PDProfile.swift | 1 | 3076 | //
// PDProfile.swift
// iDaily
//
// Created by P. Chu on 6/2/16.
// Copyright © 2016 Poodar. All rights reserved.
//
import Foundation
import UIKit
class PDProfile: UIViewController {
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .None
tableView.frame = CGRectMake(20, (self.view.frame.size.height - 54 * 5) / 2.0, self.view.frame.size.width, 54 * 5)
tableView.autoresizingMask = [.FlexibleTopMargin, .FlexibleBottomMargin, .FlexibleWidth]
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.opaque = false
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView = nil
tableView.bounces = false
return tableView
}()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clearColor()
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK : TableViewDataSource & Delegate Methods
extension PDProfile: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 54
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let titles: [String] = ["Home", "Diaries", "Profile", "Settings", "Log Out"]
let images: [String] = ["IconHome", "IconCalendar", "IconProfile", "IconSettings", "IconEmpty"]
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.font = UIFont(name: "HelveticaNeue", size: 21)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.text = titles[indexPath.row]
cell.selectionStyle = .None
cell.imageView?.image = UIImage(named: images[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row {
case 0:
sideMenuViewController?.contentViewController = PDNavController()
sideMenuViewController?.hideMenuViewController()
break
default:
sideMenuViewController?.hideMenuViewController()
break
}
}
} | gpl-3.0 |
vincentherrmann/multilinear-math | FastWaveletTransform.playground/Contents.swift | 1 | 3269 | //: Playground - noun: a place where people can play
import Cocoa
import MultilinearMath
print("start")
let h0: [Float] = [-0.00252085552, 0.0188991688, 0.0510309711, -0.0490589067, 0.0589671507, 0.79271543, 1.0953089, 0.32142213, -0.227000564, -0.0872127786, 0.0242141522, 0.0032346386]
let g0: [Float] = [-0.000504171127, -0.000253534876, 0.0460915789, 0.0190168768, -0.0825454742, 0.388706058, 1.10255682, 0.764762938, -0.0572841614, -0.188405827, -0.00831478462, 0.0161731932]
//
//let cReal = Wavelet(h0: h0, f0: h0.reversed())
//let cImag = Wavelet(h0: g0, f0: g0.reversed())
//
//let count: Int = 1024
//let length: Float = 10
//let xArray = Array(0..<count).map({Float($0) * length / Float(count)})
//let signal = Array(0..<128).map({Float($0)/10}).map({sin(3*$0)})
//var currentSignal = signal
//var analysis: [[Float]] = []
//
//var a: (r0: [Float], r1: [Float]) = ([], [])
//for _ in 0..<4 {
// a = waveletTransformForwardStep(signal: currentSignal, h0: db4.h0, h1: db4.h1)
// currentSignal = a.r0
//
// analysis.append(a.r1)
//}
//
//analysis.append(a.r0)
//let h0: [Float] = [0.6830127, 1.1830127, 0.3169873, -0.1830127]
let wReal = Wavelet(h0: h0, f0: h0.reversed())
let wImag = Wavelet(h0: g0, f0: g0.reversed())
let count: Int = 2048
let sampleFrequency: Float = 1
let frequency: Float = 5.2 //64 * pow(2, 0.5) / 32
let xArray = Array(0..<count).map({Float($0) / sampleFrequency})
let signal = xArray.map({sin(2*Float.pi*frequency*$0)})
let (fSignalReal, fSignalImag) = waveletTransformForwardStep(signal: signal, h0: h0, h1: [0] + h0.dropLast())
var packetsReal: [WaveletPacket] = waveletPacketTransform(signal: fSignalReal, wavelet: wReal, innerCodes: [68])
var packetsImag: [WaveletPacket] = waveletPacketTransform(signal: fSignalImag, wavelet: wImag, innerCodes: [68])
var packetsAbs: [WaveletPacket] = zip(packetsReal, packetsImag).map({
WaveletPacket(values: zip($0.0.values, $0.1.values).map({($0.0 + i*$0.1).absoluteValue}), code: $0.0.code)})
print("plotting...")
FastWaveletPlot(packets: packetsAbs)
FastWaveletPlot(packets: packetsReal)
FastWaveletPlot(packets: packetsImag)
let dSignal: [Float] = [0] + signal.dropLast()
let (dfSignalReal, dfSignalImag) = waveletTransformForwardStep(signal: dSignal, h0: h0, h1: [0] + h0.dropLast())
var dPacketsReal: [WaveletPacket] = waveletPacketTransform(signal: dfSignalReal, wavelet: wReal, innerCodes: [68])
var dPacketsImag: [WaveletPacket] = waveletPacketTransform(signal: dfSignalImag, wavelet: wImag, innerCodes: [68])
//estimate frequency for code 17
let code: UInt = 68
let oReal = packetsReal.filter({$0.code == code})[0].values
let oImag = packetsImag.filter({$0.code == code})[0].values
let dReal = dPacketsReal.filter({$0.code == code})[0].values
let dImag = dPacketsImag.filter({$0.code == code})[0].values
var estimatedFrequencies: [Float] = []
for n in 0..<oReal.count {
let oR = oReal[n] / sampleFrequency
let oI = oImag[n] / sampleFrequency
let dR = dReal[n] / sampleFrequency
let dI = dImag[n] / sampleFrequency
let p1 = ((dR + i*dI) * (oR - i*oI)).imaginary
let p2 = p1 / (2 * Float.pi * pow((oR + i*oI).absoluteValue, 2))
estimatedFrequencies.append(p2*sampleFrequency)
}
QuickArrayPlot(array: estimatedFrequencies)
| apache-2.0 |
roambotics/swift | validation-test/compiler_crashers_2_fixed/issue-53012.swift | 2 | 336 | // RUN: %target-swift-frontend -typecheck %s
// https://github.com/apple/swift/issues/53012
protocol P1: class {
associatedtype P1P1: P1
associatedtype P1AnyP2: AnyP2<P1P1>
var anyP2: P1AnyP2? { get set }
}
protocol P2 {
associatedtype P2P1: P1
}
final class AnyP2<AP2P1: P1>: P2 {
typealias P2P1 = AP2P1
}
| apache-2.0 |
asurinsaka/swift_examples_2.1 | LocationTraker/LocationTraker/LocationInfo+CoreDataProperties.swift | 2 | 777 | //
// LocationInfo+CoreDataProperties.swift
// LocationTraker
//
// Created by larryhou on 27/7/2015.
// Copyright © 2015 larryhou. All rights reserved.
//
// Delete this file and regenerate it using "Create NSManagedObject Subclass…"
// to keep your implementation up to date with your model.
//
import Foundation
import CoreData
extension LocationInfo {
@NSManaged var course: NSNumber?
@NSManaged var horizontalAccuracy: NSNumber?
@NSManaged var latitude: NSNumber?
@NSManaged var longitude: NSNumber?
@NSManaged var speed: NSNumber?
@NSManaged var timestamp: NSDate?
@NSManaged var verticalAccuracy: NSNumber?
@NSManaged var altitude: NSNumber?
@NSManaged var backgroundMode: NSNumber?
@NSManaged var date: TrackTime?
}
| mit |
LedgerHQ/u2f-ble-test-ios | u2f-ble-test-ios/Managers/DeviceManager.swift | 1 | 9400 | //
// DeviceManager.swift
// u2f-ble-test-ios
//
// Created by Nicolas Bigot on 13/05/2016.
// Copyright © 2016 Ledger. All rights reserved.
//
import Foundation
import CoreBluetooth
enum DeviceManagerState: String {
case NotBound
case Binding
case Bound
}
final class DeviceManager: NSObject {
static let deviceServiceUUID = "0000FFFD-0000-1000-8000-00805F9B34FB"
static let writeCharacteristicUUID = "F1D0FFF1-DEAA-ECEE-B42F-C9BA7ED623BB"
static let notifyCharacteristicUUID = "F1D0FFF2-DEAA-ECEE-B42F-C9BA7ED623BB"
static let controlpointLengthCharacteristicUUID = "F1D0FFF3-DEAA-ECEE-B42F-C9BA7ED623BB"
let peripheral: CBPeripheral
var deviceName: String? { return peripheral.name }
var onStateChanged: ((DeviceManager, DeviceManagerState) -> Void)?
var onDebugMessage: ((DeviceManager, String) -> Void)?
var onAPDUReceived: ((DeviceManager, NSData) -> Void)?
private var chunksize = 0
private var pendingChunks: [NSData] = []
private var writeCharacteristic: CBCharacteristic?
private var notifyCharacteristic: CBCharacteristic?
private var controlpointLengthCharacteristic: CBCharacteristic?
private(set) var state = DeviceManagerState.NotBound {
didSet {
onStateChanged?(self, self.state)
}
}
init(peripheral: CBPeripheral) {
self.peripheral = peripheral
super.init()
self.peripheral.delegate = self
}
func bindForReadWrite() {
guard state == .NotBound else {
onDebugMessage?(self, "Trying to bind but alreay busy")
return
}
// discover services
onDebugMessage?(self, "Discovering services...")
state = .Binding
let serviceUUID = CBUUID(string: self.dynamicType.deviceServiceUUID)
peripheral.discoverServices([serviceUUID])
}
func exchangeAPDU(data: NSData) {
guard state == .Bound else {
onDebugMessage?(self, "Trying to send APDU \(data) but not bound yet")
return
}
// slice APDU
onDebugMessage?(self, "Trying to split APDU into chunks...")
if let chunks = TransportHelper.split(data, command: .Message, chuncksize: chunksize) where chunks.count > 0 {
onDebugMessage?(self, "Successfully split APDU into \(chunks.count) part(s)")
pendingChunks = chunks
writeNextPendingChunk()
}
else {
onDebugMessage?(self, "Unable to split APDU into chunks")
resetState()
}
}
private func writeNextPendingChunk() {
guard pendingChunks.count > 0 else {
onDebugMessage?(self, "Trying to write pending chunk but nothing left to write")
return
}
let chunk = pendingChunks.removeFirst()
onDebugMessage?(self, "Writing pending chunk = \(chunk)")
peripheral.writeValue(chunk, forCharacteristic: writeCharacteristic!, type: .WithResponse)
}
private func handleReceivedChunk(chunk: NSData) {
// get chunk type
switch TransportHelper.getChunkType(chunk) {
case .Continuation:
//onDebugMessage?(self, "Received CONTINUATION chunk")
break
case .Message:
//onDebugMessage?(self, "Received MESSAGE chunk")
break
case .Error:
//onDebugMessage?(self, "Received ERROR chunk")
return
case .KeepAlive:
//onDebugMessage?(self, "Received KEEPALIVE chunk")
return
default:
//onDebugMessage?(self, "Received UNKNOWN chunk")
break
}
// join APDU
pendingChunks.append(chunk)
if let APDU = TransportHelper.join(pendingChunks, command: .Message) {
onDebugMessage?(self, "Successfully joined APDU = \(APDU)")
pendingChunks.removeAll()
onAPDUReceived?(self, APDU)
}
}
private func resetState() {
writeCharacteristic = nil
notifyCharacteristic = nil
controlpointLengthCharacteristic = nil
chunksize = 0
state = .NotBound
}
}
extension DeviceManager: CBPeripheralDelegate {
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
guard state == .Binding else { return }
guard
let services = peripheral.services where services.count > 0,
let service = services.first
else {
onDebugMessage?(self, "Unable to discover services")
resetState()
return
}
// discover characteristics
onDebugMessage?(self, "Successfully discovered services")
let writeCharacteristicUUID = CBUUID(string: self.dynamicType.writeCharacteristicUUID)
let notifyCharacteristicUUID = CBUUID(string: self.dynamicType.notifyCharacteristicUUID)
let controlpointLengthCharacteristicUUID = CBUUID(string: self.dynamicType.controlpointLengthCharacteristicUUID)
onDebugMessage?(self, "Discovering characteristics...")
peripheral.discoverCharacteristics([writeCharacteristicUUID, notifyCharacteristicUUID, controlpointLengthCharacteristicUUID], forService: service)
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
guard state == .Binding else { return }
guard
let characteristics = service.characteristics where characteristics.count >= 3,
let writeCharacteristic = characteristics.filter({ $0.UUID.UUIDString == self.dynamicType.writeCharacteristicUUID }).first,
let notifyCharacteristic = characteristics.filter({ $0.UUID.UUIDString == self.dynamicType.notifyCharacteristicUUID }).first,
let controlpointLengthCharacteristic = characteristics.filter({ $0.UUID.UUIDString == self.dynamicType.controlpointLengthCharacteristicUUID }).first
else {
onDebugMessage?(self, "Unable to discover characteristics")
resetState()
return
}
// retain characteristics
onDebugMessage?(self, "Successfully discovered characteristics")
self.writeCharacteristic = writeCharacteristic
self.notifyCharacteristic = notifyCharacteristic
self.controlpointLengthCharacteristic = controlpointLengthCharacteristic
// ask for notifications
onDebugMessage?(self, "Enabling notifications...")
peripheral.setNotifyValue(true, forCharacteristic: notifyCharacteristic)
}
func peripheral(peripheral: CBPeripheral, didUpdateNotificationStateForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
guard state == .Binding else { return }
guard characteristic == notifyCharacteristic && characteristic.isNotifying && error == nil else {
onDebugMessage?(self, "Unable to enable notifications, error = \(error)")
resetState()
return
}
// ask for chunksize
onDebugMessage?(self, "Successfully enabled notifications")
onDebugMessage?(self, "Reading chunksize...")
peripheral.readValueForCharacteristic(self.controlpointLengthCharacteristic!)
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
guard state == .Bound || state == .Binding else { return }
guard
(characteristic == notifyCharacteristic || characteristic == controlpointLengthCharacteristic) && error == nil,
let data = characteristic.value
else {
onDebugMessage?(self, "Unable to read data, error = \(error), data = \(characteristic.value)")
resetState()
return
}
// received data
onDebugMessage?(self, "Received data of size \(data.length) = \(data)")
if characteristic == controlpointLengthCharacteristic {
// extract chunksize
let reader = DataReader(data: data)
guard let chunksize = reader.readNextBigEndianUInt16() else {
onDebugMessage?(self, "Unable to read chunksize")
resetState()
return
}
// successfully bound
onDebugMessage?(self, "Successfully read chuncksize = \(chunksize)")
self.chunksize = Int(chunksize)
state = .Bound
}
else if characteristic == notifyCharacteristic {
// handle received data
handleReceivedChunk(data)
}
else {
// unknown characteristic
onDebugMessage?(self, "Received data from unknown characteristic, ignoring")
}
}
func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
guard state == .Bound else { return }
guard characteristic == writeCharacteristic && error == nil else {
onDebugMessage?(self, "Unable to write data, error = \(error)")
resetState()
return
}
// write pending chunks
writeNextPendingChunk()
}
} | apache-2.0 |
davidhariri/done | DoneTests/TodoMethodsTests.swift | 1 | 901 | //
// DoneTests.swift
// DoneTests
//
// Created by David Hariri on 2017-03-09.
// Copyright © 2017 David Hariri. All rights reserved.
//
import XCTest
@testable import Done
class TodoMethodsTests: XCTestCase {
var todo: Todo!
override func setUp() {
super.setUp()
todo = Todo(withText: "Test")
}
override func tearDown() {
super.tearDown()
todo = nil
}
func testThatToggleDoneTogglesDone() {
todo.toggleDone()
XCTAssert(todo.done, ".done was not true after toggleDone()")
todo.toggleDone()
XCTAssert(!todo.done, ".done was not false after toggleDone()")
}
func testThatUpdateTextUpdatesTheText() {
let updatedText = "Buy coffee ☕️"
todo.updateText(withText: updatedText)
XCTAssert(todo.text == updatedText, ".text was not '\(updatedText)'")
}
}
| apache-2.0 |
recruit-lifestyle/HistoryView | Pod/Classes/UIView+UIImage.swift | 1 | 576 | //
// UIView+UIImage.swift
// HistoryView
//
// Created by Takeshi Ihara on 2015/09/13.
// Copyright (c) 2015年 Takeshi Ihara. All rights reserved.
//
import UIKit
extension UIView {
func screenshot() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(context, 0.0, 0.0)
self.layer.renderInContext(context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| mit |
mohitathwani/swift-corelibs-foundation | TestFoundation/TestProcess.swift | 1 | 10156 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2015 - 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
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
import CoreFoundation
class TestProcess : XCTestCase {
static var allTests: [(String, (TestProcess) -> () throws -> Void)] {
return [
("test_exit0" , test_exit0),
("test_exit1" , test_exit1),
("test_exit100" , test_exit100),
("test_sleep2", test_sleep2),
("test_sleep2_exit1", test_sleep2_exit1),
("test_terminationReason_uncaughtSignal", test_terminationReason_uncaughtSignal),
("test_pipe_stdin", test_pipe_stdin),
("test_pipe_stdout", test_pipe_stdout),
("test_pipe_stderr", test_pipe_stderr),
// disabled for now
// ("test_pipe_stdout_and_stderr_same_pipe", test_pipe_stdout_and_stderr_same_pipe),
("test_file_stdout", test_file_stdout),
// disabled for now
// ("test_passthrough_environment", test_passthrough_environment),
// ("test_no_environment", test_no_environment),
// ("test_custom_environment", test_custom_environment),
]
}
func test_exit0() {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", "exit 0"]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 0)
XCTAssertEqual(process.terminationReason, .exit)
}
func test_exit1() {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", "exit 1"]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 1)
XCTAssertEqual(process.terminationReason, .exit)
}
func test_exit100() {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", "exit 100"]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 100)
XCTAssertEqual(process.terminationReason, .exit)
}
func test_sleep2() {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", "sleep 2"]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 0)
XCTAssertEqual(process.terminationReason, .exit)
}
func test_sleep2_exit1() {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", "sleep 2; exit 1"]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 1)
XCTAssertEqual(process.terminationReason, .exit)
}
func test_terminationReason_uncaughtSignal() {
let process = Process()
process.launchPath = "/bin/bash"
process.arguments = ["-c", "kill -TERM $$"]
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 15)
XCTAssertEqual(process.terminationReason, .uncaughtSignal)
}
func test_pipe_stdin() {
let process = Process()
process.launchPath = "/bin/cat"
let outputPipe = Pipe()
process.standardOutput = outputPipe
let inputPipe = Pipe()
process.standardInput = inputPipe
process.launch()
inputPipe.fileHandleForWriting.write("Hello, 🐶.\n".data(using: .utf8)!)
// Close the input pipe to send EOF to cat.
inputPipe.fileHandleForWriting.closeFile()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 0)
let data = outputPipe.fileHandleForReading.availableData
guard let string = String(data: data, encoding: .utf8) else {
XCTFail("Could not read stdout")
return
}
XCTAssertEqual(string, "Hello, 🐶.\n")
}
func test_pipe_stdout() {
let process = Process()
process.launchPath = "/usr/bin/which"
process.arguments = ["which"]
let pipe = Pipe()
process.standardOutput = pipe
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 0)
let data = pipe.fileHandleForReading.availableData
guard let string = String(data: data, encoding: .ascii) else {
XCTFail("Could not read stdout")
return
}
XCTAssertTrue(string.hasSuffix("/which\n"))
}
func test_pipe_stderr() {
let process = Process()
process.launchPath = "/bin/cat"
process.arguments = ["invalid_file_name"]
let errorPipe = Pipe()
process.standardError = errorPipe
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 1)
let data = errorPipe.fileHandleForReading.availableData
guard let _ = String(data: data, encoding: .ascii) else {
XCTFail("Could not read stdout")
return
}
// testing the return value of an external process is does not port well, and may change.
// XCTAssertEqual(string, "/bin/cat: invalid_file_name: No such file or directory\n")
}
func test_pipe_stdout_and_stderr_same_pipe() {
let process = Process()
process.launchPath = "/bin/cat"
process.arguments = ["invalid_file_name"]
let pipe = Pipe()
process.standardOutput = pipe
process.standardError = pipe
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 1)
let data = pipe.fileHandleForReading.availableData
guard let string = String(data: data, encoding: .ascii) else {
XCTFail("Could not read stdout")
return
}
XCTAssertEqual(string, "/bin/cat: invalid_file_name: No such file or directory\n")
}
func test_file_stdout() {
let process = Process()
process.launchPath = "/usr/bin/which"
process.arguments = ["which"]
mkstemp(template: "TestProcess.XXXXXX") { handle in
process.standardOutput = handle
process.launch()
process.waitUntilExit()
XCTAssertEqual(process.terminationStatus, 0)
handle.seek(toFileOffset: 0)
let data = handle.readDataToEndOfFile()
guard let string = String(data: data, encoding: .ascii) else {
XCTFail("Could not read stdout")
return
}
XCTAssertTrue(string.hasSuffix("/which\n"))
}
}
func test_passthrough_environment() {
do {
let output = try runTask(["/usr/bin/env"], environment: nil)
let env = try parseEnv(output)
XCTAssertGreaterThan(env.count, 0)
} catch let error {
XCTFail("Test failed: \(error)")
}
}
func test_no_environment() {
do {
let output = try runTask(["/usr/bin/env"], environment: [:])
let env = try parseEnv(output)
XCTAssertEqual(env.count, 0)
} catch let error {
XCTFail("Test failed: \(error)")
}
}
func test_custom_environment() {
do {
let input = ["HELLO": "WORLD", "HOME": "CUPERTINO"]
let output = try runTask(["/usr/bin/env"], environment: input)
let env = try parseEnv(output)
XCTAssertEqual(env, input)
} catch let error {
XCTFail("Test failed: \(error)")
}
}
}
private func mkstemp(template: String, body: (FileHandle) throws -> Void) rethrows {
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("TestProcess.XXXXXX")
try url.withUnsafeFileSystemRepresentation {
switch mkstemp(UnsafeMutablePointer(mutating: $0!)) {
case -1: XCTFail("Could not create temporary file")
case let fd:
defer { url.withUnsafeFileSystemRepresentation { _ = unlink($0!) } }
try body(FileHandle(fileDescriptor: fd, closeOnDealloc: true))
}
}
}
private enum Error: Swift.Error {
case TerminationStatus(Int32)
case UnicodeDecodingError(Data)
case InvalidEnvironmentVariable(String)
}
private func runTask(_ arguments: [String], environment: [String: String]? = nil) throws -> String {
let process = Process()
var arguments = arguments
process.launchPath = arguments.removeFirst()
process.arguments = arguments
process.environment = environment
let pipe = Pipe()
process.standardOutput = pipe
process.standardError = pipe
process.launch()
process.waitUntilExit()
guard process.terminationStatus == 0 else {
throw Error.TerminationStatus(process.terminationStatus)
}
let data = pipe.fileHandleForReading.availableData
guard let output = String(data: data, encoding: .utf8) else {
throw Error.UnicodeDecodingError(data)
}
return output
}
private func parseEnv(_ env: String) throws -> [String: String] {
var result = [String: String]()
for line in env.components(separatedBy: "\n") where line != "" {
guard let range = line.range(of: "=") else {
throw Error.InvalidEnvironmentVariable(line)
}
result[line.substring(to: range.lowerBound)] = line.substring(from: range.upperBound)
}
return result
}
| apache-2.0 |
kywix/iamsblog | WatchApps/DinoBasic/DinoBasic WatchKit Extension/ExtensionDelegate.swift | 1 | 3000 | //
// ExtensionDelegate.swift
// DinoBasic WatchKit Extension
//
// Created by Mario Esposito on 9/29/19.
// Copyright © 2019 The Garage Innovation. All rights reserved.
//
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
}
func applicationDidBecomeActive() {
// 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 applicationWillResignActive() {
// 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, etc.
}
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
for task in backgroundTasks {
// Use a switch statement to check the task type
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
// Be sure to complete the background task once you’re done.
backgroundTask.setTaskCompletedWithSnapshot(false)
case let snapshotTask as WKSnapshotRefreshBackgroundTask:
// Snapshot tasks have a unique completion call, make sure to set your expiration date
snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
// Be sure to complete the connectivity task once you’re done.
connectivityTask.setTaskCompletedWithSnapshot(false)
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// Be sure to complete the URL session task once you’re done.
urlSessionTask.setTaskCompletedWithSnapshot(false)
case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask:
// Be sure to complete the relevant-shortcut task once you're done.
relevantShortcutTask.setTaskCompletedWithSnapshot(false)
case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask:
// Be sure to complete the intent-did-run task once you're done.
intentDidRunTask.setTaskCompletedWithSnapshot(false)
default:
// make sure to complete unhandled task types
task.setTaskCompletedWithSnapshot(false)
}
}
}
}
| mit |
ephread/CocoaHeadsPod | Example/Tests/Tests.swift | 1 | 768 | import UIKit
import XCTest
import CocoaHeadsPod
class Tests: 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 testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
gowansg/firefox-ios | SyncTests/InfoTests.swift | 52 | 2337 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCTest
class InfoTests: XCTestCase {
func testSame() {
let empty = JSON.parse("{}")
let oneA = JSON.parse("{\"foo\": 1234.0, \"bar\": 456.12}")
let oneB = JSON.parse("{\"bar\": 456.12, \"foo\": 1234.0}")
let twoA = JSON.parse("{\"bar\": 456.12}")
let twoB = JSON.parse("{\"foo\": 1234.0}")
let iEmpty = InfoCollections.fromJSON(empty)!
let iOneA = InfoCollections.fromJSON(oneA)!
let iOneB = InfoCollections.fromJSON(oneB)!
let iTwoA = InfoCollections.fromJSON(twoA)!
let iTwoB = InfoCollections.fromJSON(twoB)!
XCTAssertTrue(iEmpty.same(iEmpty, collections: nil))
XCTAssertTrue(iEmpty.same(iEmpty, collections: []))
XCTAssertTrue(iEmpty.same(iEmpty, collections: ["anything"]))
XCTAssertTrue(iEmpty.same(iOneA, collections: []))
XCTAssertTrue(iEmpty.same(iOneA, collections: ["anything"]))
XCTAssertTrue(iOneA.same(iEmpty, collections: []))
XCTAssertTrue(iOneA.same(iEmpty, collections: ["anything"]))
XCTAssertFalse(iEmpty.same(iOneA, collections: ["foo"]))
XCTAssertFalse(iOneA.same(iEmpty, collections: ["foo"]))
XCTAssertFalse(iEmpty.same(iOneA, collections: nil))
XCTAssertFalse(iOneA.same(iEmpty, collections: nil))
XCTAssertTrue(iOneA.same(iOneA, collections: nil))
XCTAssertTrue(iOneA.same(iOneA, collections: ["foo", "bar", "baz"]))
XCTAssertTrue(iOneA.same(iOneB, collections: ["foo", "bar", "baz"]))
XCTAssertTrue(iOneB.same(iOneA, collections: ["foo", "bar", "baz"]))
XCTAssertFalse(iTwoA.same(iOneA, collections: nil))
XCTAssertTrue(iTwoA.same(iOneA, collections: ["bar", "baz"]))
XCTAssertTrue(iOneA.same(iTwoA, collections: ["bar", "baz"]))
XCTAssertTrue(iTwoB.same(iOneA, collections: ["foo", "baz"]))
XCTAssertFalse(iTwoA.same(iTwoB, collections: nil))
XCTAssertFalse(iTwoA.same(iTwoB, collections: ["foo"]))
XCTAssertFalse(iTwoA.same(iTwoB, collections: ["bar"]))
}
} | mpl-2.0 |
huonw/swift | test/Driver/Dependencies/fail-added.swift | 36 | 1862 | /// bad ==> main | bad --> other
// RUN: rm -rf %t && cp -r %S/Inputs/fail-simple/ %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s
// CHECK-INITIAL-NOT: warning
// CHECK-INITIAL: Handled main.swift
// CHECK-INITIAL: Handled other.swift
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies-bad.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift ./bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-ADDED %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD-ADDED %s < %t/main~buildrecord.swiftdeps
// CHECK-ADDED-NOT: Handled
// CHECK-ADDED: Handled bad.swift
// CHECK-ADDED-NOT: Handled
// CHECK-RECORD-ADDED-DAG: "./bad.swift": !dirty [
// CHECK-RECORD-ADDED-DAG: "./main.swift": [
// CHECK-RECORD-ADDED-DAG: "./other.swift": [
// RUN: rm -rf %t && cp -r %S/Inputs/fail-simple/ %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path %S/Inputs/update-dependencies-bad.py -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./bad.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-ADDED %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD-ADDED %s < %t/main~buildrecord.swiftdeps
| apache-2.0 |
matheusbc/virtus | VirtusApp/VirtusApp/ViewController/LocalViewController.swift | 1 | 2361 | //
// LocalViewController.swift
// VirtusApp
//
// Copyright © 2017 Matheus B Campos. All rights reserved.
//
import MapKit
/// The local map view controller.
class LocalViewController: UIViewController, Loadable {
// MARK: Outlets
/// The map view instance.
@IBOutlet weak var mapView: MKMapView!
// MARK: Properties
/// The local map view model.
let localViewModel = LocalViewModel()
override func viewDidLoad() {
super.viewDidLoad()
let loading = self.showLoading(self)
self.setupMap()
self.dismissLoading(loading)
}
// MARK: Private Methods
/**
Setup the map.
Sets the initial position, the delegate and the pin.
*/
private func setupMap() {
mapView.delegate = self
centerMapOnLocation(location: localViewModel.initialLocation)
mapView.addAnnotation(localViewModel.virtusPin)
}
/**
Center the map to the location point.
- Parameter location: The center location point.
*/
private func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
localViewModel.regionRadius * 2.0,
localViewModel.regionRadius * 2.0)
mapView.setRegion(coordinateRegion, animated: true)
}
}
extension LocalViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if let annotation = annotation as? MapLocal {
let identifier = "virtusPin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton.init(type: .detailDisclosure) as UIView
}
return view
}
return nil
}
}
| mit |
361425281/swift-snia | Swift-Sina/Classs/Home/Controller/DQBaseTableViewController.swift | 1 | 2504 |
//
// DQBaseTableViewController.swift
// Swift - sina
//
// Created by 熊德庆 on 15/10/26.
// Copyright © 2015年 熊德庆. All rights reserved.
//
import UIKit
class DQBaseTableViewController: UITableViewController
{
let userLogin = false
override func loadView()
{
userLogin ? super.loadView():setupVistorView()
}
func setupVistorView()
{
let vistorView = DQVistorView()
view = vistorView
//设置代理
//vistorView.vistorViewDelegate = self
view.backgroundColor = UIColor.whiteColor()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "vistorViewRegistClick()")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登陆", style:UIBarButtonItemStyle.Plain, target: self, action: "vistorViewLoginClick()")
if self is DQHomeTabBarController
{
vistorView.startRotationAnimation()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActive", name: UIApplicationDidBecomeActiveNotification, object: nil)
}
else if self is DQMessageTableViewController
{
vistorView.setupVistorView("visitordiscover_image_message", message: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知")
}
else if self is DQDiscoverTabBarController
{
vistorView.setupVistorView("visitordiscover_image_message", message: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知")
}
else if self is DQMeTableViewController
{
vistorView.setupVistorView("visitordiscover_image_profile", message: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人")
}
}
func didEnterBackgroud()
{
(view as? DQVistorView)?.pauseAnimation()
}
func didBecomeActive()
{
(view as? DQVistorView)?.resumeAnimation()
}
}
extension DQBaseTableViewController : DQVistorViewDelegate
{
func vistViewRegistClick()
{
print(__FUNCTION__)
}
func vistorViewLoginClick()
{
print(__FUNCTION__)
}
}
| apache-2.0 |
samwyndham/DictateSRS | DictateSRSTests/Import/ImportParserTests.swift | 1 | 2826 | //
// ImportParserTests.swift
// DictateSRS
//
// Created by Sam Wyndham on 27/01/2017.
// Copyright © 2017 Sam Wyndham. All rights reserved.
//
import XCTest
@testable import DictateSRS
class ImportParserTests: XCTestCase {
func testInit_withInvalidHeading_thowsError() {
let content = row("sentence", "reading", "translation", "notes", "audio", "extra")
XCTAssertThrowsError(try ImportParser(content: content)) { (error) in
if case ImportError.invalidHeadings = error {} else { XCTFail("Threw wrong error") }
}
}
func testInit_withoutSentenceHeading_throwsError() {
let content = row("reading", "translation", "notes", "audio")
XCTAssertThrowsError(try ImportParser(content: content)) { (error) in
if case ImportError.invalidHeadings = error {} else { XCTFail("Threw wrong error") }
}
}
func testInit_withOnlySentenceHeading_doesNotThrowsError() {
let content = row("sentence")
AssertNoThrow(try ImportParser(content: content))
}
func testInit_withEmptyFile_throwsError() {
XCTAssertThrowsError(try ImportParser(content: "")) { (error) in
if case ImportError.invalidHeadings = error {} else { XCTFail("Threw wrong error") }
}
}
func testHeadings_withValidContent_returnsCorrectHeaders() {
let parser = try! ImportParser(content: row("sentence", "reading", "translation", "notes", "audio"))
let expected: [ImportHeader] = [.sentence, .reading, .translation, .notes, .audio]
XCTAssertEqual(parser.headers, expected)
}
func testIteration_withValidContent_returnsCorrectRows() {
let content = row("sentence", "reading", "translation", "notes", "audio")
.row("sentence 1", "reading 1", "translation 2", "notes 3", "audio 4")
.row("sentence 2")
.row(" sentence 1 ", " reading 1 ", " translation 2 ", " notes 3 ", " audio 4 ", " extra ")
let parser = try! ImportParser(content: content)
let expected: [[String]] = [
["sentence 1", "reading 1", "translation 2", "notes 3", "audio 4"],
["sentence 2"],
[" sentence 1 ", " reading 1 ", " translation 2 ", " notes 3 ", " audio 4 ", " extra "]
]
var rows: [[String]] = []
for (index, row) in parser.enumerated() {
XCTAssertEqual(row, expected[index])
rows.append(row)
}
XCTAssertEqual(rows.count, expected.count)
}
}
private func row(_ fields: String ...) -> String {
return fields.joined(separator: "\t")
}
private extension String {
func row(_ fields: String ...) -> String {
return self + "\n" + fields.joined(separator: "\t")
}
}
| mit |
kiwitechnologies/ServiceClientiOS | ServiceClient/ServiceClient/TSGServiceClient/External/ImageCaching/ImageDownloader.swift | 1 | 24319 | // ImageDownloader.swift
//
// Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
/// The `RequestReceipt` is an object vended by the `ImageDownloader` when starting a download request. It can be used
/// to cancel active requests running on the `ImageDownloader` session. As a general rule, image download requests
/// should be cancelled using the `RequestReceipt` instead of calling `cancel` directly on the `request` itself. The
/// `ImageDownloader` is optimized to handle duplicate request scenarios as well as pending versus active downloads.
public class RequestReceipt {
/// The download request created by the `ImageDownloader`.
public let request: Request
/// The unique identifier for the image filters and completion handlers when duplicate requests are made.
public let receiptID: String
init(request: Request, receiptID: String) {
self.request = request
self.receiptID = receiptID
}
}
/// The `ImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming
/// downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded
/// image is cached in the underlying `NSURLCache` as well as the in-memory image cache that supports image filters.
/// By default, any download request with a cached image equivalent in the image cache will automatically be served the
/// cached image representation. Additional advanced features include supporting multiple image filters and completion
/// handlers for a single request.
public class ImageDownloader {
/// The completion handler closure used when an image download completes.
public typealias CompletionHandler = Response<Image, NSError> -> Void
/// The progress handler closure called periodically during an image download.
public typealias ProgressHandler = (bytesRead: Int64, totalBytesRead: Int64, totalExpectedBytesToRead: Int64) -> Void
/**
Defines the order prioritization of incoming download requests being inserted into the queue.
- FIFO: All incoming downloads are added to the back of the queue.
- LIFO: All incoming downloads are added to the front of the queue.
*/
public enum DownloadPrioritization {
case FIFO, LIFO
}
class ResponseHandler {
let identifier: String
let request: Request
var operations: [(id: String, filter: ImageFilter?, completion: CompletionHandler?)]
init(request: Request, id: String, filter: ImageFilter?, completion: CompletionHandler?) {
self.request = request
self.identifier = ImageDownloader.identifierForURLRequest(request.request!)
self.operations = [(id: id, filter: filter, completion: completion)]
}
}
// MARK: - Properties
/// The image cache used to store all downloaded images in.
public let imageCache: ImageRequestCache?
/// The credential used for authenticating each download request.
public private(set) var credential: NSURLCredential?
/// The underlying Alamofire `Manager` instance used to handle all download requests.
public let sessionManager:Manager
let downloadPrioritization: DownloadPrioritization
let maximumActiveDownloads: Int
var activeRequestCount = 0
var queuedRequests: [Request] = []
var responseHandlers: [String: ResponseHandler] = [:]
private let synchronizationQueue: dispatch_queue_t = {
let name = String(format: "com.alamofire.imagedownloader.synchronizationqueue-%08%08", arc4random(), arc4random())
return dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL)
}()
private let responseQueue: dispatch_queue_t = {
let name = String(format: "com.alamofire.imagedownloader.responsequeue-%08%08", arc4random(), arc4random())
return dispatch_queue_create(name, DISPATCH_QUEUE_CONCURRENT)
}()
// MARK: - Initialization
/// The default instance of `ImageDownloader` initialized with default values.
public static let defaultInstance = ImageDownloader()
/**
Creates a default `NSURLSessionConfiguration` with common usage parameter values.
- returns: The default `NSURLSessionConfiguration` instance.
*/
public class func defaultURLSessionConfiguration() -> NSURLSessionConfiguration {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
configuration.HTTPShouldSetCookies = true
configuration.HTTPShouldUsePipelining = false
configuration.requestCachePolicy = .UseProtocolCachePolicy
configuration.allowsCellularAccess = true
configuration.timeoutIntervalForRequest = 60
configuration.URLCache = ImageDownloader.defaultURLCache()
return configuration
}
/**
Creates a default `NSURLCache` with common usage parameter values.
- returns: The default `NSURLCache` instance.
*/
public class func defaultURLCache() -> NSURLCache {
return NSURLCache(
memoryCapacity: 20 * 1024 * 1024, // 20 MB
diskCapacity: 150 * 1024 * 1024, // 150 MB
diskPath: "com.alamofire.imagedownloader"
)
}
/**
Initializes the `ImageDownloader` instance with the given configuration, download prioritization, maximum active
download count and image cache.
- parameter configuration: The `NSURLSessionConfiguration` to use to create the underlying Alamofire
`Manager` instance.
- parameter downloadPrioritization: The download prioritization of the download queue. `.FIFO` by default.
- parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time.
- parameter imageCache: The image cache used to store all downloaded images in.
- returns: The new `ImageDownloader` instance.
*/
public init(
configuration: NSURLSessionConfiguration = ImageDownloader.defaultURLSessionConfiguration(),
downloadPrioritization: DownloadPrioritization = .FIFO,
maximumActiveDownloads: Int = 4,
imageCache: ImageRequestCache? = AutoPurgingImageCache())
{
self.sessionManager = Manager(configuration: configuration)
self.sessionManager.startRequestsImmediately = false
self.downloadPrioritization = downloadPrioritization
self.maximumActiveDownloads = maximumActiveDownloads
self.imageCache = imageCache
}
/**
Initializes the `ImageDownloader` instance with the given sesion manager, download prioritization, maximum
active download count and image cache.
- parameter sessionManager: The Alamofire `Manager` instance to handle all download requests.
- parameter downloadPrioritization: The download prioritization of the download queue. `.FIFO` by default.
- parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time.
- parameter imageCache: The image cache used to store all downloaded images in.
- returns: The new `ImageDownloader` instance.
*/
public init(
sessionManager: Manager,
downloadPrioritization: DownloadPrioritization = .FIFO,
maximumActiveDownloads: Int = 4,
imageCache: ImageRequestCache? = AutoPurgingImageCache())
{
self.sessionManager = sessionManager
self.sessionManager.startRequestsImmediately = false
self.downloadPrioritization = downloadPrioritization
self.maximumActiveDownloads = maximumActiveDownloads
self.imageCache = imageCache
}
// MARK: - Authentication
/**
Associates an HTTP Basic Auth credential with all future download requests.
- parameter user: The user.
- parameter password: The password.
- parameter persistence: The URL credential persistence. `.ForSession` by default.
*/
public func addAuthentication(
user user: String,
password: String,
persistence: NSURLCredentialPersistence = .ForSession)
{
let credential = NSURLCredential(user: user, password: password, persistence: persistence)
addAuthentication(usingCredential: credential)
}
/**
Associates the specified credential with all future download requests.
- parameter credential: The credential.
*/
public func addAuthentication(usingCredential credential: NSURLCredential) {
dispatch_sync(synchronizationQueue) {
self.credential = credential
}
}
// MARK: - Download
/**
Creates a download request using the internal Alamofire `Manager` instance for the specified URL request.
If the same download request is already in the queue or currently being downloaded, the filter and completion
handler are appended to the already existing request. Once the request completes, all filters and completion
handlers attached to the request are executed in the order they were added. Additionally, any filters attached
to the request with the same identifiers are only executed once. The resulting image is then passed into each
completion handler paired with the filter.
You should not attempt to directly cancel the `request` inside the request receipt since other callers may be
relying on the completion of that request. Instead, you should call `cancelRequestForRequestReceipt` with the
returned request receipt to allow the `ImageDownloader` to optimize the cancellation on behalf of all active
callers.
- parameter URLRequest: The URL request.
- parameter receiptID: The `identifier` for the `RequestReceipt` returned. Defaults to a new, randomly
generated UUID.
- parameter filter: The image filter to apply to the image after the download is complete. Defaults
to `nil`.
- parameter progress: The closure to be executed periodically during the lifecycle of the request.
Defaults to `nil`.
- parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue.
- parameter completion: The closure called when the download request is complete. Defaults to `nil`.
- returns: The request receipt for the download request if available. `nil` if the image is stored in the image
cache and the URL request cache policy allows the cache to be used.
*/
public func downloadImage(
URLRequest URLRequest: URLRequestConvertible,
receiptID: String = NSUUID().UUIDString,
filter: ImageFilter? = nil,
progress: ProgressHandler? = nil,
progressQueue: dispatch_queue_t = dispatch_get_main_queue(),
completion: CompletionHandler?)
-> RequestReceipt?
{
var request: Request!
dispatch_sync(synchronizationQueue) {
// 1) Append the filter and completion handler to a pre-existing request if it already exists
let identifier = ImageDownloader.identifierForURLRequest(URLRequest)
if let responseHandler = self.responseHandlers[identifier] {
responseHandler.operations.append(id: receiptID, filter: filter, completion: completion)
request = responseHandler.request
return
}
// 2) Attempt to load the image from the image cache if the cache policy allows it
switch URLRequest.URLRequest.cachePolicy {
case .UseProtocolCachePolicy, .ReturnCacheDataElseLoad, .ReturnCacheDataDontLoad:
if let image = self.imageCache?.imageForRequest(
URLRequest.URLRequest,
withAdditionalIdentifier: filter?.identifier)
{
dispatch_async(dispatch_get_main_queue()) {
let response = Response<Image, NSError>(
request: URLRequest.URLRequest,
response: nil,
data: nil,
result: .Success(image)
)
completion?(response)
}
return
}
default:
break
}
// 3) Create the request and set up authentication, validation and response serialization
request = self.sessionManager.request(URLRequest)
if let credential = self.credential {
request.authenticate(usingCredential: credential)
}
request.validate()
if let progress = progress {
request.progress { bytesRead, totalBytesRead, totalExpectedBytesToRead in
dispatch_async(progressQueue) {
progress(
bytesRead: bytesRead,
totalBytesRead: totalBytesRead,
totalExpectedBytesToRead: totalExpectedBytesToRead
)
}
}
}
request.response(
queue: self.responseQueue,
responseSerializer: Request.imageResponseSerializer(),
completionHandler: { [weak self] response in
guard let strongSelf = self, let request = response.request else { return }
let responseHandler = strongSelf.safelyRemoveResponseHandlerWithIdentifier(identifier)
switch response.result {
case .Success(let image):
var filteredImages: [String: Image] = [:]
for (_, filter, completion) in responseHandler.operations {
var filteredImage: Image
if let filter = filter {
if let alreadyFilteredImage = filteredImages[filter.identifier] {
filteredImage = alreadyFilteredImage
} else {
filteredImage = filter.filter(image)
filteredImages[filter.identifier] = filteredImage
}
} else {
filteredImage = image
}
strongSelf.imageCache?.addImage(
filteredImage,
forRequest: request,
withAdditionalIdentifier: filter?.identifier
)
dispatch_async(dispatch_get_main_queue()) {
let response = Response<Image, NSError>(
request: response.request,
response: response.response,
data: response.data,
result: .Success(filteredImage),
timeline: response.timeline
)
completion?(response)
}
}
case .Failure:
for (_, _, completion) in responseHandler.operations {
dispatch_async(dispatch_get_main_queue()) { completion?(response) }
}
}
strongSelf.safelyDecrementActiveRequestCount()
strongSelf.safelyStartNextRequestIfNecessary()
}
)
// 4) Store the response handler for use when the request completes
let responseHandler = ResponseHandler(
request: request,
id: receiptID,
filter: filter,
completion: completion
)
self.responseHandlers[identifier] = responseHandler
// 5) Either start the request or enqueue it depending on the current active request count
if self.isActiveRequestCountBelowMaximumLimit() {
self.startRequest(request)
} else {
self.enqueueRequest(request)
}
}
if let request = request {
return RequestReceipt(request: request, receiptID: receiptID)
}
return nil
}
/**
Creates a download request using the internal Alamofire `Manager` instance for each specified URL request.
For each request, if the same download request is already in the queue or currently being downloaded, the
filter and completion handler are appended to the already existing request. Once the request completes, all
filters and completion handlers attached to the request are executed in the order they were added.
Additionally, any filters attached to the request with the same identifiers are only executed once. The
resulting image is then passed into each completion handler paired with the filter.
You should not attempt to directly cancel any of the `request`s inside the request receipts array since other
callers may be relying on the completion of that request. Instead, you should call
`cancelRequestForRequestReceipt` with the returned request receipt to allow the `ImageDownloader` to optimize
the cancellation on behalf of all active callers.
- parameter URLRequests: The URL requests.
- parameter filter The image filter to apply to the image after each download is complete.
- parameter progress: The closure to be executed periodically during the lifecycle of the request. Defaults
to `nil`.
- parameter progressQueue: The dispatch queue to call the progress closure on. Defaults to the main queue.
- parameter completion: The closure called when each download request is complete.
- returns: The request receipts for the download requests if available. If an image is stored in the image
cache and the URL request cache policy allows the cache to be used, a receipt will not be returned
for that request.
*/
public func downloadImages(
URLRequests URLRequests: [URLRequestConvertible],
filter: ImageFilter? = nil,
progress: ProgressHandler? = nil,
progressQueue: dispatch_queue_t = dispatch_get_main_queue(),
completion: CompletionHandler? = nil)
-> [RequestReceipt]
{
return URLRequests.flatMap {
downloadImage(
URLRequest: $0,
filter: filter,
progress: progress,
progressQueue: progressQueue,
completion: completion
)
}
}
/**
Cancels the request in the receipt by removing the response handler and cancelling the request if necessary.
If the request is pending in the queue, it will be cancelled if no other response handlers are registered with
the request. If the request is currently executing or is already completed, the response handler is removed and
will not be called.
- parameter requestReceipt: The request receipt to cancel.
*/
public func cancelRequestForRequestReceipt(requestReceipt: RequestReceipt) {
dispatch_sync(synchronizationQueue) {
let identifier = ImageDownloader.identifierForURLRequest(requestReceipt.request.request!)
guard let responseHandler = self.responseHandlers[identifier] else { return }
if let index = responseHandler.operations.indexOf({ $0.id == requestReceipt.receiptID }) {
let operation = responseHandler.operations.removeAtIndex(index)
let response: Response<Image, NSError> = {
let URLRequest = requestReceipt.request.request!
let error: NSError = {
let failureReason = "ImageDownloader cancelled URL request: \(URLRequest.URLString)"
let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
return NSError(domain: Error.Domain, code: NSURLErrorCancelled, userInfo: userInfo)
}()
return Response(request: URLRequest, response: nil, data: nil, result: .Failure(error))
}()
dispatch_async(dispatch_get_main_queue()) { operation.completion?(response) }
}
if responseHandler.operations.isEmpty && requestReceipt.request.task.state == .Suspended {
requestReceipt.request.cancel()
}
}
}
// MARK: - Internal - Thread-Safe Request Methods
func safelyRemoveResponseHandlerWithIdentifier(identifier: String) -> ResponseHandler {
var responseHandler: ResponseHandler!
dispatch_sync(synchronizationQueue) {
responseHandler = self.responseHandlers.removeValueForKey(identifier)
}
return responseHandler
}
func safelyStartNextRequestIfNecessary() {
dispatch_sync(synchronizationQueue) {
guard self.isActiveRequestCountBelowMaximumLimit() else { return }
while (!self.queuedRequests.isEmpty) {
if let request = self.dequeueRequest() where request.task.state == .Suspended {
self.startRequest(request)
break
}
}
}
}
func safelyDecrementActiveRequestCount() {
dispatch_sync(self.synchronizationQueue) {
if self.activeRequestCount > 0 {
self.activeRequestCount -= 1
}
}
}
// MARK: - Internal - Non Thread-Safe Request Methods
func startRequest(request: Request) {
request.resume()
activeRequestCount += 1
}
func enqueueRequest(request: Request) {
switch downloadPrioritization {
case .FIFO:
queuedRequests.append(request)
case .LIFO:
queuedRequests.insert(request, atIndex: 0)
}
}
func dequeueRequest() -> Request? {
var request: Request?
if !queuedRequests.isEmpty {
request = queuedRequests.removeFirst()
}
return request
}
func isActiveRequestCountBelowMaximumLimit() -> Bool {
return activeRequestCount < maximumActiveDownloads
}
static func identifierForURLRequest(URLRequest: URLRequestConvertible) -> String {
return URLRequest.URLRequest.URLString
}
}
| mit |
allevato/swift | test/ScanDependencies/module_deps.swift | 1 | 5510 | // RUN: %empty-directory(%t)
// RUN: mkdir -p %t/clang-module-cache
// RUN: %target-swift-frontend -scan-dependencies -module-cache-path %t/clang-module-cache %s -o %t/deps.json -I %S/Inputs/CHeaders -I %S/Inputs/Swift -emit-dependencies -emit-dependencies-path %t/deps.d -import-objc-header %S/Inputs/CHeaders/Bridging.h -swift-version 4 -disable-implicit-swift-modules -Xcc -Xclang -Xcc -fno-implicit-modules
// Check the contents of the JSON output
// RUN: %FileCheck %s < %t/deps.json
// Check the contents of the JSON output
// RUN: %FileCheck %s -check-prefix CHECK-NO-SEARCH-PATHS < %t/deps.json
// Check the make-style dependencies file
// RUN: %FileCheck %s -check-prefix CHECK-MAKE-DEPS < %t/deps.d
// Check that the JSON parses correctly into the canonical Swift data
// structures.
// RUN: mkdir -p %t/PrintGraph
// RUN: cp %S/Inputs/PrintGraph.swift %t/main.swift
// RUN: %target-build-swift %S/Inputs/ModuleDependencyGraph.swift %t/main.swift -o %t/main
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main %t/deps.json
// REQUIRES: executable_test
// REQUIRES: objc_interop
import C
import E
import G
import SubE
// CHECK: "mainModuleName": "deps"
/// --------Main module
// CHECK-LABEL: "modulePath": "deps.swiftmodule",
// CHECK-NEXT: sourceFiles
// CHECK-NEXT: module_deps.swift
// CHECK: directDependencies
// CHECK-NEXT: {
// CHECK-NEXT: "clang": "C"
// CHECK-NEXT: }
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "E"
// CHECK-NEXT: }
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "G"
// CHECK-NEXT: }
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "SubE"
// CHECK-NEXT: }
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "Swift"
// CHECK-NEXT: }
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "SwiftOnoneSupport"
// CHECK-NEXT: }
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "_cross_import_E"
// CHECK-NEXT: }
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "F"
// CHECK-NEXT: }
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "A"
// CHECK-NEXT: }
// CHECK-NEXT: ],
// CHECK: "extraPcmArgs": [
// CHECK-NEXT: "-Xcc",
// CHECK-NEXT: "-target",
// CHECK-NEXT: "-Xcc",
// CHECK: "-fapinotes-swift-version=4"
// CHECK-NOT: "error: cannot open Swift placeholder dependency module map from"
// CHECK: "bridgingHeader":
// CHECK-NEXT: "path":
// CHECK-SAME: Bridging.h
// CHECK-NEXT: "sourceFiles":
// CHECK-NEXT: Bridging.h
// CHECK-NEXT: BridgingOther.h
// CHECK: "moduleDependencies": [
// CHECK-NEXT: "F"
// CHECK-NEXT: ]
/// --------Clang module C
// CHECK-LABEL: "modulePath": "C.pcm",
// CHECK: "sourceFiles": [
// CHECK-DAG: module.modulemap
// CHECK-DAG: C.h
// CHECK: directDependencies
// CHECK-NEXT: {
// CHECK-NEXT: "clang": "B"
// CHECK: "moduleMapPath"
// CHECK-SAME: module.modulemap
// CHECK: "contextHash"
// CHECK-SAME: "{{.*}}"
// CHECK: "commandLine": [
// CHECK-NEXT: "-frontend"
// CHECK-NEXT: "-only-use-extra-clang-opts"
// CHECK-NEXT: "-Xcc"
// CHECK-NEXT: "clang"
// CHECK: "-fno-implicit-modules"
/// --------Swift module E
// CHECK: "swift": "E"
// CHECK-LABEL: modulePath": "E.swiftmodule"
// CHECK: "directDependencies"
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "Swift"
// CHECK: "moduleInterfacePath"
// CHECK-SAME: E.swiftinterface
/// --------Swift module G
// CHECK-LABEL: "modulePath": "G.swiftmodule"
// CHECK: "directDependencies"
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "Swift"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "clang": "G"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "SwiftOnoneSupport"
// CHECK-NEXT: }
// CHECK-NEXT: ],
// CHECK-NEXT: "details": {
// CHECK: "contextHash": "{{.*}}",
// CHECK: "commandLine": [
// CHECK: "-compile-module-from-interface"
// CHECK: "-target"
// CHECK: "-module-name"
// CHECK: "G"
// CHECK: "-swift-version"
// CHECK: "5"
// CHECK: ],
// CHECK" "extraPcmArgs": [
// CHECK" "-target",
// CHECK" "-fapinotes-swift-version=5"
// CHECK" ]
/// --------Swift module Swift
// CHECK-LABEL: "modulePath": "Swift.swiftmodule",
// CHECK: directDependencies
// CHECK-NEXT: {
// CHECK-NEXT: "clang": "SwiftShims"
/// --------Swift module F
// CHECK: "modulePath": "F.swiftmodule",
// CHECK-NEXT: "sourceFiles": [
// CHECK-NEXT: ],
// CHECK-NEXT: "directDependencies": [
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "Swift"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "clang": "F"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "SwiftOnoneSupport"
// CHECK-NEXT: }
// CHECK-NEXT: ],
/// --------Swift module A
// CHECK-LABEL: "modulePath": "A.swiftmodule",
// CHECK: directDependencies
// CHECK-NEXT: {
// CHECK-NEXT: "swift": "Swift"
// CHECK-NEXT: },
// CHECK-NEXT: {
// CHECK-NEXT: "clang": "A"
// CHECK-NEXT: }
/// --------Clang module B
// CHECK-LABEL: "modulePath": "B.pcm"
// CHECK-NEXT: sourceFiles
// CHECK-DAG: module.modulemap
// CHECK-DAG: B.h
// CHECK: directDependencies
// CHECK-NEXT: {
// CHECK-NEXT: "clang": "A"
// CHECK-NEXT: }
/// --------Clang module SwiftShims
// CHECK-LABEL: "modulePath": "SwiftShims.pcm",
// CHECK-NO-SEARCH-PATHS-NOT: "-I"
// CHECK-NO-SEARCH-PATHS-NOT: "-sdk"
// CHECK-NO-SEARCH-PATHS-NOT: "-F"
// CHECK-NO-SEARCH-PATHS-NOT: "-prebuilt-module-cache-path"
// Check make-style dependencies
// CHECK-MAKE-DEPS: module_deps.swift
// CHECK-MAKE-DEPS-SAME: A.swiftinterface
// CHECK-MAKE-DEPS-SAME: G.swiftinterface
// CHECK-MAKE-DEPS-SAME: B.h
// CHECK-MAKE-DEPS-SAME: F.h
// CHECK-MAKE-DEPS-SAME: Bridging.h
// CHECK-MAKE-DEPS-SAME: BridgingOther.h
// CHECK-MAKE-DEPS-SAME: module.modulemap
| apache-2.0 |
Julyyq/ALHUD | ALHUD/AppDelegate.swift | 1 | 2142 | //
// AppDelegate.swift
// ALHUD
//
// Created by Allen.Young on 18/11/14.
// Copyright (c) 2014 Allen.Young. All rights reserved.
//
import UIKit
@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:.
}
}
| mit |
hshidara/iOS | Ready?/Ready?/Runner.swift | 1 | 3008 | //
// Run.swift
// Ready?
//
// Created by Hidekazu Shidara on 9/20/15.
// Copyright © 2015 Hidekazu Shidara. All rights reserved.
//
import UIKit
import MapKit
import CoreData
import HealthKit
import CoreLocation
class Runner: UIViewController, CLLocationManagerDelegate {
var managedObjectContext: NSManagedObjectContext?
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("RunningStart") as UIViewController!
self.presentViewController(vc, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.backgroundColor = UIColor(hex: "#283E51")
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.allowsBackgroundLocationUpdates = true
self.locationManager.startUpdatingLocation()
locationManager.requestWhenInUseAuthorization()
self.mapView.mapType = MKMapType.HybridFlyover
self.mapView.showsUserLocation = true
self.mapView.zoomEnabled = false
self.mapView.userInteractionEnabled = false
self.mapView.rotateEnabled = false
self.mapView.pitchEnabled = false
}
func setUserLocation(){
let userLocation = mapView.userLocation
let region = MKCoordinateRegionMakeWithDistance(
userLocation.location!.coordinate, 2000, 2000)
mapView.setRegion(region, animated: true)
}
override func viewWillAppear(animated: Bool) {
if self.mapView.userLocationVisible {
let region = MKCoordinateRegionMakeWithDistance((self.mapView.userLocation.location?.coordinate)!, 400 , 400)
self.mapView.setRegion(region, animated: false)
}
else{
//Warning, no internet connection.
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Location Delegate Methods
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.latitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
// print("Errors: " + error.localizedDescription)
}
}
| mit |
vikmeup/MDCSwipeToChoose | Examples/SwiftLikedOrNope/SwiftLikedOrNope/AppDelegate.swift | 1 | 6166 | //
// AppDelegate.swift
// SwiftLikedOrNope
//
// Created by richard burdish on 3/28/15.
// Copyright (c) 2015 Richard Burdish. 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 "MDCSwipeToChoose.SwiftLikedOrNope" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
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("SwiftLikedOrNope", 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.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SwiftLikedOrNope.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
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 {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// 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()
}
}
}
}
| mit |
mcjcloud/Show-And-Sell | Show And Sell/ChooseLocationViewController.swift | 1 | 3861 | //
// ChooseLocationViewController.swift
// Show And Sell
//
// Created by Brayden Cloud on 2/1/17.
// Copyright © 2017 Brayden Cloud. All rights reserved.
//
import UIKit
import MapKit
class ChooseLocationViewController: UIViewController, UISearchBarDelegate, MKMapViewDelegate {
@IBOutlet var doneButton: UIBarButtonItem!
@IBOutlet var mapView: MKMapView!
@IBOutlet var searchBar: UISearchBar!
var selectedAnnotation: MKPointAnnotation?
override func viewDidLoad() {
super.viewDidLoad()
// setup searchbar
searchBar.delegate = self
// enable/disable button
doneButton.isEnabled = selectedAnnotation != nil
}
// MARK: Searchbar Delegate
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
// asign map delegate
mapView.delegate = self
// put down keyboard
searchBar.resignFirstResponder()
// remove any annotations
mapView.removeAnnotations(mapView.annotations)
// create search request
let localSearchRequest = MKLocalSearchRequest()
localSearchRequest.naturalLanguageQuery = searchBar.text
let localSearch = MKLocalSearch(request: localSearchRequest)
// start the search
localSearch.start { searchResponse, error in
if searchResponse == nil {
let alert = UIAlertController(title: nil, message: "Location not found", preferredStyle: .alert)
let dismiss = UIAlertAction(title: "Dismiss", style: .default, handler: nil)
alert.addAction(dismiss)
self.present(alert, animated: true, completion: nil)
return
}
let pointAnnotation = MKPointAnnotation()
var annText: String? = searchBar.text
if let point = searchResponse?.mapItems[0] {
print("address dict: \(point.placemark.addressDictionary?["FormattedAddressLines"])")
annText = point.name
pointAnnotation.subtitle = self.concat(point.placemark.addressDictionary!["FormattedAddressLines"] as! [Any])
}
pointAnnotation.title = annText
let centerCoord = searchResponse!.boundingRegion.center
pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: centerCoord.latitude, longitude: centerCoord.longitude)
// create the pin
let pinAnnotationView = MKPinAnnotationView(annotation: pointAnnotation, reuseIdentifier: nil)
pinAnnotationView.animatesDrop = true
self.mapView.setCenter(pointAnnotation.coordinate, animated: true)
self.mapView.addAnnotation(pinAnnotationView.annotation!)
// set zoom
var region = MKCoordinateRegion(center: pointAnnotation.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
region = self.mapView.regionThatFits(region)
self.mapView.setRegion(region, animated: true)
print("coordinate: \(pointAnnotation.coordinate)")
}
}
// MARK: MKMapView Delegate
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
selectedAnnotation = view.annotation as? MKPointAnnotation
doneButton.isEnabled = selectedAnnotation != nil
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
selectedAnnotation = nil
doneButton.isEnabled = selectedAnnotation != nil
}
func concat(_ arr: [Any]) -> String {
var result = ""
for i in 0..<arr.count {
result += i == arr.count - 1 ? "\(arr[i])" : "\(arr[i]) "
}
return result
}
}
| apache-2.0 |
Antondomashnev/Sourcery | Pods/SourceKittenFramework/Source/SourceKittenFramework/Module.swift | 3 | 5365 | //
// Module.swift
// SourceKitten
//
// Created by JP Simard on 2015-01-07.
// Copyright (c) 2015 SourceKitten. All rights reserved.
//
import Foundation
import Yams
/// Represents source module to be documented.
public struct Module {
/// Module Name.
public let name: String
/// Compiler arguments required by SourceKit to process the source files in this Module.
public let compilerArguments: [String]
/// Source files to be documented in this Module.
public let sourceFiles: [String]
/// Documentation for this Module. Typically expensive computed property.
public var docs: [SwiftDocs] {
var fileIndex = 1
let sourceFilesCount = sourceFiles.count
return sourceFiles.flatMap {
let filename = $0.bridge().lastPathComponent
if let file = File(path: $0) {
fputs("Parsing \(filename) (\(fileIndex)/\(sourceFilesCount))\n", stderr)
fileIndex += 1
return SwiftDocs(file: file, arguments: compilerArguments)
}
fputs("Could not parse `\(filename)`. Please open an issue at https://github.com/jpsim/SourceKitten/issues with the file contents.\n", stderr)
return nil
}
}
public init?(spmName: String) {
let yamlPath = ".build/debug.yaml"
guard let yaml = try? Yams.compose(yaml: String(contentsOfFile: yamlPath, encoding: .utf8)),
let commands = yaml?["commands"]?.mapping?.values else {
fatalError("SPM build manifest does not exist at `\(yamlPath)` or does not match expected format.")
}
guard let moduleCommand = commands.first(where: { $0["module-name"]?.string == spmName }) else {
fputs("Could not find SPM module '\(spmName)'. Here are the modules available:\n", stderr)
let availableModules = commands.flatMap({ $0["module-name"]?.string })
fputs("\(availableModules.map({ " - " + $0 }).joined(separator: "\n"))\n", stderr)
return nil
}
guard let imports = moduleCommand["import-paths"]?.array(of: String.self),
let otherArguments = moduleCommand["other-args"]?.array(of: String.self),
let sources = moduleCommand["sources"]?.array(of: String.self) else {
fatalError("SPM build manifest does not match expected format.")
}
name = spmName
compilerArguments = {
var arguments = sources
arguments.append(contentsOf: ["-module-name", spmName])
arguments.append(contentsOf: otherArguments)
arguments.append(contentsOf: ["-I"])
arguments.append(contentsOf: imports)
return arguments
}()
sourceFiles = sources
}
/**
Failable initializer to create a Module by the arguments necessary pass in to `xcodebuild` to build it.
Optionally pass in a `moduleName` and `path`.
- parameter xcodeBuildArguments: The arguments necessary pass in to `xcodebuild` to build this Module.
- parameter name: Module name. Will be parsed from `xcodebuild` output if nil.
- parameter path: Path to run `xcodebuild` from. Uses current path by default.
*/
public init?(xcodeBuildArguments: [String], name: String? = nil, inPath path: String = FileManager.default.currentDirectoryPath) {
let xcodeBuildOutput = runXcodeBuild(arguments: xcodeBuildArguments, inPath: path) ?? ""
guard let arguments = parseCompilerArguments(xcodebuildOutput: xcodeBuildOutput.bridge(), language: .swift,
moduleName: name ?? moduleName(fromArguments: xcodeBuildArguments)) else {
fputs("Could not parse compiler arguments from `xcodebuild` output.\n", stderr)
fputs("Please confirm that `xcodebuild` is building a Swift module.\n", stderr)
let file = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("xcodebuild-\(NSUUID().uuidString).log")
try! xcodeBuildOutput.data(using: .utf8)?.write(to: file)
fputs("Saved `xcodebuild` log file: \(file.path)\n", stderr)
return nil
}
guard let moduleName = moduleName(fromArguments: arguments) else {
fputs("Could not parse module name from compiler arguments.\n", stderr)
return nil
}
self.init(name: moduleName, compilerArguments: arguments)
}
/**
Initializer to create a Module by name and compiler arguments.
- parameter name: Module name.
- parameter compilerArguments: Compiler arguments required by SourceKit to process the source files in this Module.
*/
public init(name: String, compilerArguments: [String]) {
self.name = name
self.compilerArguments = compilerArguments
sourceFiles = compilerArguments.filter({
$0.bridge().isSwiftFile() && $0.isFile
}).map {
return URL(fileURLWithPath: $0).resolvingSymlinksInPath().path
}
}
}
// MARK: CustomStringConvertible
extension Module: CustomStringConvertible {
/// A textual representation of `Module`.
public var description: String {
return "Module(name: \(name), compilerArguments: \(compilerArguments), sourceFiles: \(sourceFiles))"
}
}
| mit |
alskipp/Argo | Argo/Types/Decoded/Alternative.swift | 1 | 753 | /**
return the left `Decoded` value if it is `.Success`, otherwise return the right side
- If the left hand side is successful, this will return the left hand side
- If the left hand side is unsuccesful, this will return the right hand side
- parameter lhs: A value of type `Decoded<T>`
- parameter rhs: A value of type `Decoded<T>`
- returns: A value of type `Decoded<T>`
*/
infix operator <|> { associativity left precedence 140 }
public func <|> <T>(lhs: Decoded<T>, @autoclosure rhs: () -> Decoded<T>) -> Decoded<T> {
return lhs.or(rhs)
}
public extension Decoded {
func or(@autoclosure other: () -> Decoded<T>) -> Decoded<T> {
switch self {
case .Success: return self
case .Failure: return other()
}
}
}
| mit |
google/flatbuffers | swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_10.swift | 4 | 2360 | import FlatBuffers
import Foundation
func run() {
// create a `FlatBufferBuilder`, which will be used to serialize objects
let builder = FlatBufferBuilder(initialSize: 1024)
let weapon1Name = builder.create(string: "Sword")
let weapon2Name = builder.create(string: "Axe")
// start creating the weapon by calling startWeapon
let weapon1Start = Weapon.startWeapon(&builder)
Weapon.add(name: weapon1Name, &builder)
Weapon.add(damage: 3, &builder)
// end the object by passing the start point for the weapon 1
let sword = Weapon.endWeapon(&builder, start: weapon1Start)
let weapon2Start = Weapon.startWeapon(&builder)
Weapon.add(name: weapon2Name, &builder)
Weapon.add(damage: 5, &builder)
let axe = Weapon.endWeapon(&builder, start: weapon2Start)
// Create a FlatBuffer `vector` that contains offsets to the sword and axe
// we created above.
let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
// Name of the Monster.
let name = builder.create(string: "Orc")
let pathOffset = fbb.createVector(ofStructs: [
Vec3(x: 0, y: 0),
Vec3(x: 5, y: 5),
])
// startVector(len, elementSize: MemoryLayout<Offset>.size)
// for o in offsets.reversed() {
// push(element: o)
// }
// endVector(len: len)
let orc = Monster.createMonster(
&builder,
pos: Vec3(x: 1, y: 2),
hp: 300,
nameOffset: name,
color: .red,
weaponsVectorOffset: weaponsOffset,
equippedType: .weapon,
equippedOffset: axe,
pathOffset: pathOffset)
// let start = Monster.startMonster(&builder)
// Monster.add(pos: Vec3(x: 1, y: 2), &builder)
// Monster.add(hp: 300, &builder)
// Monster.add(name: name, &builder)
// Monster.add(color: .red, &builder)
// Monster.addVectorOf(weapons: weaponsOffset, &builder)
// Monster.add(equippedType: .weapon, &builder)
// Monster.addVectorOf(paths: weaponsOffset, &builder)
// Monster.add(equipped: axe, &builder)
// var orc = Monster.endMonster(&builder, start: start)
// Call `finish(offset:)` to instruct the builder that this monster is complete.
builder.finish(offset: orc)
// This must be called after `finish()`.
// `sizedByteArray` returns the finished buf of type [UInt8].
let buf = builder.sizedByteArray
// or you can use to get an object of type Data
let bufData = ByteBuffer(data: builder.sizedBuffer)
}
| apache-2.0 |
PureSwift/Bluetooth | Sources/BluetoothGAP/GAPLESecureConnectionsRandom.swift | 1 | 1506 | //
// GAPLESecureConnectionsRandom.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/13/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// Specifies the LE Secure Connections Random Value
/// Size: 16 octets
/// Format defined in [Vol 3], Part H, Section 2.3.5.6.4
@frozen
public struct GAPLESecureConnectionsRandom: GAPData, Equatable, Hashable {
public static let dataType: GAPDataType = .lowEnergySecureConnectionsRandom
public let random: UInt16
public init(random: UInt16) {
self.random = random
}
}
public extension GAPLESecureConnectionsRandom {
init?(data: Data) {
guard data.count == 2
else { return nil }
let random = UInt16(littleEndian: UInt16(bytes: (data[0],
data[1])))
self.init(random: random)
}
func append(to data: inout Data) {
data += random.littleEndian
}
var dataLength: Int {
return 2
}
}
// MARK: - ExpressibleByIntegerLiteral
extension GAPLESecureConnectionsRandom: ExpressibleByIntegerLiteral {
public init(integerLiteral value: UInt16) {
self.init(random: value)
}
}
// MARK: - CustomStringConvertible
extension GAPLESecureConnectionsRandom: CustomStringConvertible {
public var description: String {
return random.description
}
}
| mit |
trujillo138/MyExpenses | MyExpenses/Shared/Model/ExpensesBalance.swift | 1 | 2615 | //
// ExpensesBalance.swift
// MyExpenses
//
// Created by Tomas Trujillo on 7/15/18.
// Copyright © 2018 TOMApps. All rights reserved.
//
import Foundation
//
// ExpensesBalance.swift
// ExpenseManager
//
// Created by Tomas Trujillo on 6/21/18.
// Copyright © 2018 Tomas Trujillo. All rights reserved.
//
import Foundation
class ExpensesBalance: NSObject, NSCoding {
//MARK: Keys
private struct Keys {
static let LastExpenseKey = "LastExpense"
static let AmountSavedKey = "AmountSaved"
static let AmountSpentKey = "AmountSpent"
static let DateOfBalanceKey = "DateOfBalance"
static let GoalKey = "Goal"
}
//MARK: Properties
var lastExpense: Expense
var amountSaved: Double
var amountSpent: Double
var dateOfBalance: Date
var goal: Double
//MARK: Initializers
init(lastExpense: Expense, amountSaved: Double, amountSpent: Double, dateOfBalance: Date, goal: Double) {
self.lastExpense = lastExpense
self.amountSaved = amountSaved
self.amountSpent = amountSpent
self.dateOfBalance = dateOfBalance
self.goal = goal
}
//MARK: Coding
required init?(coder aDecoder: NSCoder) {
self.lastExpense = aDecoder.decodeObject(forKey: Keys.LastExpenseKey) as! Expense
self.amountSaved = aDecoder.decodeDouble(forKey: Keys.AmountSavedKey)
self.amountSpent = aDecoder.decodeDouble(forKey: Keys.AmountSpentKey)
self.dateOfBalance = aDecoder.decodeObject(forKey: Keys.DateOfBalanceKey) as? Date ?? Date()
self.goal = aDecoder.decodeDouble(forKey: Keys.GoalKey)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(lastExpense, forKey: Keys.LastExpenseKey)
aCoder.encode(amountSaved, forKey: Keys.AmountSavedKey)
aCoder.encode(amountSpent, forKey: Keys.AmountSpentKey)
aCoder.encode(dateOfBalance, forKey: Keys.DateOfBalanceKey)
}
//MARK: Helper methods
static func createBalanceFromExpenses(_ expenses: [Expense], goal: Double, income: Double) -> ExpensesBalance? {
guard let lastExpenseOfPeriod = expenses.last else { return nil }
let currentDate = Date()
let totalAmountSpent = expenses.reduce(0, { x, e in
x + e.amount
})
let totalAmountSaved = income - totalAmountSpent
return ExpensesBalance(lastExpense: lastExpenseOfPeriod, amountSaved: totalAmountSaved,
amountSpent: totalAmountSpent, dateOfBalance: currentDate, goal: goal)
}
}
| apache-2.0 |
stripe/stripe-ios | StripeUICore/StripeUICore/Source/Validators/BSBNumber.swift | 1 | 1059 | //
// BSBNumber.swift
// StripeUICore
//
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeCore
@_spi(STP) public struct BSBNumber {
private let number: String
private let pattern: String
public init(number: String) {
self.number = number
self.pattern = "###-###"
}
public var isComplete: Bool {
return formattedNumber().count >= pattern.count
}
public func formattedNumber() -> String {
guard let formatter = TextFieldFormatter(format: pattern) else {
return number
}
let allowedCharacterSet = CharacterSet.stp_asciiDigit
let result = formatter.applyFormat(
to: number.stp_stringByRemovingCharacters(from: allowedCharacterSet.inverted),
shouldAppendRemaining: true
)
guard result.count > 0 else {
return ""
}
return result
}
public func bsbNumberText() -> String {
return number.filter {$0 != "-"}
}
}
| mit |
tinypass/piano-sdk-for-ios | Sources/Composer/Composer/Models/CustomParams.swift | 1 | 1269 | import Foundation
@objcMembers
public class CustomParams: NSObject {
private var content: Dictionary<String, Array<String>> = Dictionary<String, Array<String>>()
private var user: Dictionary<String, Array<String>> = Dictionary<String, Array<String>>()
private var request: Dictionary<String, Array<String>> = Dictionary<String, Array<String>>()
public func content(key: String, value: String) -> CustomParams {
put(dict: &content, key: key, value: value)
return self;
}
public func user(key: String, value: String) -> CustomParams {
put(dict: &user, key: key, value: value)
return self;
}
public func request(key: String, value: String) -> CustomParams {
put(dict: &request, key: key, value: value)
return self;
}
private func put(dict: inout Dictionary<String, Array<String>>, key: String, value: String) {
if dict[key] == nil {
dict[key] = [String]()
}
dict[key]?.append(value)
}
public func toDictionary() -> [String: Any] {
var dict = [String: Any]()
dict["content"] = content
dict["user"] = user
dict["request"] = request
return dict
}
}
| apache-2.0 |
fgengine/quickly | Quickly/Compositions/Standart/Placeholders/QPlaceholderImageTitleDetailValueComposition.swift | 1 | 8233 | //
// Quickly
//
open class QPlaceholderImageTitleDetailValueComposable : QComposable {
public var imageStyle: QImageViewStyleSheet
public var imageWidth: CGFloat
public var imageSpacing: CGFloat
public var titleStyle: QPlaceholderStyleSheet
public var titleHeight: CGFloat
public var titleSpacing: CGFloat
public var detailStyle: QPlaceholderStyleSheet
public var detailHeight: CGFloat
public var valueStyle: QPlaceholderStyleSheet
public var valueSize: CGSize
public var valueSpacing: CGFloat
public init(
edgeInsets: UIEdgeInsets = UIEdgeInsets.zero,
imageStyle: QImageViewStyleSheet,
imageWidth: CGFloat = 96,
imageSpacing: CGFloat = 4,
titleStyle: QPlaceholderStyleSheet,
titleHeight: CGFloat,
titleSpacing: CGFloat = 4,
detailStyle: QPlaceholderStyleSheet,
detailHeight: CGFloat,
valueStyle: QPlaceholderStyleSheet,
valueSize: CGSize,
valueSpacing: CGFloat = 4
) {
self.imageStyle = imageStyle
self.imageWidth = imageWidth
self.imageSpacing = imageSpacing
self.titleStyle = titleStyle
self.titleHeight = titleHeight
self.titleSpacing = titleSpacing
self.detailStyle = detailStyle
self.detailHeight = detailHeight
self.valueStyle = valueStyle
self.valueSize = valueSize
self.valueSpacing = valueSpacing
super.init(edgeInsets: edgeInsets)
}
}
open class QPlaceholderImageTitleDetailValueComposition< Composable: QPlaceholderImageTitleDetailValueComposable > : QComposition< Composable > {
public private(set) lazy var imageView: QImageView = {
let view = QImageView(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var titleView: QPlaceholderView = {
let view = QPlaceholderView(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var detailView: QPlaceholderView = {
let view = QPlaceholderView(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
public private(set) lazy var valueView: QPlaceholderView = {
let view = QPlaceholderView(frame: self.contentView.bounds)
view.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(view)
return view
}()
private var _edgeInsets: UIEdgeInsets?
private var _imageWidth: CGFloat?
private var _imageSpacing: CGFloat?
private var _titleHeight: CGFloat?
private var _titleSpacing: CGFloat?
private var _detailHeight: CGFloat?
private var _valueSize: CGSize?
private var _valueSpacing: CGFloat?
private var _constraints: [NSLayoutConstraint] = [] {
willSet { self.contentView.removeConstraints(self._constraints) }
didSet { self.contentView.addConstraints(self._constraints) }
}
private var _imageConstraints: [NSLayoutConstraint] = [] {
willSet { self.imageView.removeConstraints(self._imageConstraints) }
didSet { self.imageView.addConstraints(self._imageConstraints) }
}
private var _titleConstraints: [NSLayoutConstraint] = [] {
willSet { self.titleView.removeConstraints(self._titleConstraints) }
didSet { self.titleView.addConstraints(self._titleConstraints) }
}
private var _detailConstraints: [NSLayoutConstraint] = [] {
willSet { self.detailView.removeConstraints(self._detailConstraints) }
didSet { self.detailView.addConstraints(self._detailConstraints) }
}
private var _valueConstraints: [NSLayoutConstraint] = [] {
willSet { self.valueView.removeConstraints(self._valueConstraints) }
didSet { self.valueView.addConstraints(self._valueConstraints) }
}
open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize {
let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right)
let imageSize = composable.imageStyle.size(CGSize(width: composable.imageWidth, height: availableWidth))
return CGSize(
width: spec.containerSize.width,
height: composable.edgeInsets.top + max(imageSize.height, composable.titleHeight + composable.titleSpacing + composable.detailHeight, composable.valueSize.height) + composable.edgeInsets.bottom
)
}
open override func preLayout(composable: Composable, spec: IQContainerSpec) {
if self._edgeInsets != composable.edgeInsets || self._imageSpacing != composable.imageSpacing || self._titleSpacing != composable.titleSpacing || self._valueSpacing != composable.valueSpacing {
self._edgeInsets = composable.edgeInsets
self._imageSpacing = composable.imageSpacing
self._titleSpacing = composable.titleSpacing
self._valueSpacing = composable.valueSpacing
self._constraints = [
self.imageView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.imageView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left),
self.imageView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top),
self.titleView.leadingLayout == self.imageView.trailingLayout.offset(composable.imageSpacing),
self.titleView.trailingLayout == self.valueView.leadingLayout.offset(-composable.valueSpacing),
self.titleView.bottomLayout <= self.detailView.topLayout.offset(-composable.titleSpacing),
self.detailView.leadingLayout == self.imageView.trailingLayout.offset(composable.imageSpacing),
self.detailView.trailingLayout == self.valueView.leadingLayout.offset(-composable.valueSpacing),
self.detailView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.valueView.topLayout >= self.contentView.topLayout.offset(composable.edgeInsets.top),
self.valueView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right),
self.valueView.bottomLayout <= self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom),
self.valueView.centerYLayout == self.contentView.centerYLayout
]
}
if self._imageWidth != composable.imageWidth {
self._imageWidth = composable.imageWidth
self._imageConstraints = [
self.imageView.widthLayout == composable.imageWidth
]
}
if self._titleHeight != composable.titleHeight {
self._titleHeight = composable.titleHeight
self._titleConstraints = [
self.titleView.heightLayout == composable.titleHeight
]
}
if self._detailHeight != composable.detailHeight {
self._detailHeight = composable.detailHeight
self._detailConstraints = [
self.detailView.heightLayout == composable.detailHeight
]
}
if self._valueSize != composable.valueSize {
self._valueSize = composable.valueSize
self._valueConstraints = [
self.valueView.widthLayout == composable.valueSize.width,
self.valueView.heightLayout == composable.valueSize.height
]
}
}
open override func apply(composable: Composable, spec: IQContainerSpec) {
self.imageView.apply(composable.imageStyle)
self.titleView.apply(composable.titleStyle)
self.detailView.apply(composable.detailStyle)
self.valueView.apply(composable.valueStyle)
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/07011-swift-typebase-getcanonicaltype.swift | 11 | 244 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {
struct S<T {
func f: c
protocol c {
protocol k {
typealias B : B
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/08503-swift-sourcemanager-getmessage.swift | 11 | 244 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
extension g {
struct g {
protocol e {
enum b {
let NSObject {
class
case ,
| mit |
freeskys/ShakeToChange | ShakeToChange/Sources/ShakeToChangeViewController.swift | 1 | 762 | //
// ShakeToChangeViewController.swift
// ShakeToChange
//
// Created by Harditya on 10/13/16.
// Copyright © 2016 Blezcode. All rights reserved.
//
import UIKit
class ShakeToChangeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/19023-swift-sourcemanager-getmessage.swift | 11 | 251 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func g( ) { {
var d {
protocol b {
{
}
var d = [ a Int> ( {
enum e {
class
case ,
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/19966-swift-modulefile-getdecl.swift | 10 | 228 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true{enum k{{}struct B{class A<b where T:B,A:b{let a=B?{ | mit |
hmtinc/Z80-Swift | Source/ports.swift | 1 | 645 | //
// ports.swift
// Z80-Swift
//
// Created by Harsh Mistry on 2017-12-15.
// Copyright © 2017 Harsh Mistry. All rights reserved.
//
import Foundation
class Ports {
var data : [UInt8] = [];
var NMI : Bool = false;
var MI : Bool = false;
var portData = [uint16 : uint8]()
func readPort(_ address : uint16) -> uint8{
print("Reading port at " + String(address))
return portData[address] ?? uint8(0)
}
func writePort(_ address : uint16, _ value : uint8){
print("Writing value = " + String(value) + " to port at " + String(address))
portData[address] = value
}
}
| mit |
mita4829/Iris | Iris/AppDelegate.swift | 1 | 2231 | //
// AppDelegate.swift
// Iris
//
// Created by Michael Tang on 4/22/17.
// Copyright (c) 2017 Michael Tang. All rights reserved.
// Tesseract OCR, Lyndsey Scott
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private 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:.
}
}
| apache-2.0 |
RobertGummesson/BuildTimeAnalyzer-for-Xcode | BuildTimeAnalyzerTests/ViewControllerDataSourceTest.swift | 1 | 8226 | //
// ViewControllerDataSourceTest.swift
// BuildTimeAnalyzerTests
//
// Created by Dmitrii on 02/12/2017.
// Copyright © 2017 Cane Media Ltd. All rights reserved.
//
import XCTest
@testable import BuildTimeAnalyzer
class ViewControllerDataSourceTest: XCTestCase {
var measArray: [CompileMeasure]!
override func setUp() {
super.setUp()
let meas1 = CompileMeasure(rawPath: "FileName1.swift:1:1", time: 10)
let meas2 = CompileMeasure(rawPath: "FileName2.swift:2:2", time: 2)
let meas3 = CompileMeasure(rawPath: "FileName3.swift:3:3", time: 8)
let meas4 = CompileMeasure(rawPath: "FileName3.swift:4:4", time: 0)
let meas5 = CompileMeasure(rawPath: "FileName1.swift:5:5", time: 2)
measArray = [meas4!, meas5!, meas2!, meas3!, meas1!]
}
func testInit() {
let dataSource = ViewControllerDataSource()
XCTAssertFalse(dataSource.aggregateByFile)
XCTAssertEqual(dataSource.filter, "")
XCTAssertNotNil(dataSource.sortDescriptors)
XCTAssertEqual(dataSource.sortDescriptors.count, 0)
XCTAssertTrue(dataSource.isEmpty())
}
func testAggregate() {
let dataSource = ViewControllerDataSource()
dataSource.resetSourceData(newSourceData: measArray)
dataSource.aggregateByFile = true
XCTAssertEqual(dataSource.count(), 3)
XCTAssertFalse(dataSource.isEmpty())
}
func testFilter_1() {
let dataSource = ViewControllerDataSource()
dataSource.resetSourceData(newSourceData: measArray)
dataSource.filter = "1"
XCTAssertFalse(dataSource.isEmpty())
XCTAssertEqual(dataSource.count(), 2)
XCTAssertEqual(dataSource.measure(index: 0)!.filename, "FileName1.swift")
XCTAssertEqual(dataSource.measure(index: 1)!.filename, "FileName1.swift")
}
func testFilter_2() {
let dataSource = ViewControllerDataSource()
dataSource.resetSourceData(newSourceData: measArray)
dataSource.filter = "2"
XCTAssertFalse(dataSource.isEmpty())
XCTAssertEqual(dataSource.count(), 1)
XCTAssertEqual(dataSource.measure(index: 0)!.filename, "FileName2.swift")
}
func testFilter_noMatch() {
let dataSource = ViewControllerDataSource()
dataSource.resetSourceData(newSourceData: measArray)
dataSource.filter = "noMatch"
XCTAssertTrue(dataSource.isEmpty())
XCTAssertEqual(dataSource.count(), 0)
}
func testSortTimeAscending() {
let dataSource = ViewControllerDataSource()
dataSource.resetSourceData(newSourceData: measArray)
let desc = NSSortDescriptor(key: "time", ascending: true)
dataSource.sortDescriptors = [desc]
XCTAssertFalse(dataSource.isEmpty())
XCTAssertEqual(dataSource.count(), 5)
XCTAssertEqual(dataSource.measure(index: 0)!.filename, "FileName3.swift")
XCTAssertEqual(dataSource.measure(index: 1)!.filename, "FileName1.swift")
XCTAssertEqual(dataSource.measure(index: 2)!.filename, "FileName2.swift")
XCTAssertEqual(dataSource.measure(index: 3)!.filename, "FileName3.swift")
XCTAssertEqual(dataSource.measure(index: 4)!.filename, "FileName1.swift")
}
func testSortFilenameDescending() {
let dataSource = ViewControllerDataSource()
dataSource.resetSourceData(newSourceData: measArray)
let desc = NSSortDescriptor(key: "filename", ascending: false)
dataSource.sortDescriptors = [desc]
XCTAssertFalse(dataSource.isEmpty())
XCTAssertEqual(dataSource.count(), 5)
XCTAssertEqual(dataSource.measure(index: 0)!.filename, "FileName3.swift")
XCTAssertEqual(dataSource.measure(index: 1)!.filename, "FileName3.swift")
XCTAssertEqual(dataSource.measure(index: 2)!.filename, "FileName2.swift")
XCTAssertEqual(dataSource.measure(index: 3)!.filename, "FileName1.swift")
XCTAssertEqual(dataSource.measure(index: 4)!.filename, "FileName1.swift")
}
func testSortFilenameAscending_TimeAscending() {
let dataSource = ViewControllerDataSource()
dataSource.resetSourceData(newSourceData: measArray)
let descFilename = NSSortDescriptor(key: "filename", ascending: true)
let descTime = NSSortDescriptor(key: "time", ascending: true)
dataSource.sortDescriptors = [descFilename, descTime]
XCTAssertFalse(dataSource.isEmpty())
XCTAssertEqual(dataSource.count(), 5)
XCTAssertEqual(dataSource.measure(index: 0)!.filename, "FileName1.swift")
XCTAssertEqual(dataSource.measure(index: 0)!.time, 2)
XCTAssertEqual(dataSource.measure(index: 1)!.filename, "FileName1.swift")
XCTAssertEqual(dataSource.measure(index: 1)!.time, 10)
XCTAssertEqual(dataSource.measure(index: 2)!.filename, "FileName2.swift")
XCTAssertEqual(dataSource.measure(index: 3)!.filename, "FileName3.swift")
XCTAssertEqual(dataSource.measure(index: 3)!.time, 0)
XCTAssertEqual(dataSource.measure(index: 4)!.filename, "FileName3.swift")
XCTAssertEqual(dataSource.measure(index: 4)!.time, 8)
}
func testSortTimeAscending_FilenameDescending() {
let dataSource = ViewControllerDataSource()
dataSource.resetSourceData(newSourceData: measArray)
let descTime = NSSortDescriptor(key: "time", ascending: true)
let descFilename = NSSortDescriptor(key: "filename", ascending: false)
dataSource.sortDescriptors = [descTime, descFilename]
XCTAssertFalse(dataSource.isEmpty())
XCTAssertEqual(dataSource.count(), 5)
XCTAssertEqual(dataSource.measure(index: 0)!.filename, "FileName3.swift")
XCTAssertEqual(dataSource.measure(index: 0)!.time, 0)
XCTAssertEqual(dataSource.measure(index: 1)!.filename, "FileName2.swift")
XCTAssertEqual(dataSource.measure(index: 1)!.time, 2)
XCTAssertEqual(dataSource.measure(index: 2)!.filename, "FileName1.swift")
XCTAssertEqual(dataSource.measure(index: 2)!.time, 2)
XCTAssertEqual(dataSource.measure(index: 3)!.filename, "FileName3.swift")
XCTAssertEqual(dataSource.measure(index: 3)!.time, 8)
XCTAssertEqual(dataSource.measure(index: 4)!.filename, "FileName1.swift")
XCTAssertEqual(dataSource.measure(index: 4)!.time, 10)
}
func testSortTimeAscending_Filter3() {
let dataSource = ViewControllerDataSource()
dataSource.resetSourceData(newSourceData: measArray)
let descTime = NSSortDescriptor(key: "time", ascending: true)
dataSource.sortDescriptors = [descTime]
dataSource.filter = "3"
XCTAssertFalse(dataSource.isEmpty())
XCTAssertEqual(dataSource.count(), 2)
XCTAssertEqual(dataSource.measure(index: 0)!.filename, "FileName3.swift")
XCTAssertEqual(dataSource.measure(index: 0)!.time, 0)
XCTAssertEqual(dataSource.measure(index: 1)!.filename, "FileName3.swift")
XCTAssertEqual(dataSource.measure(index: 1)!.time, 8)
}
func testFilter3_Aggregate() {
let dataSource = ViewControllerDataSource()
dataSource.resetSourceData(newSourceData: measArray)
dataSource.filter = "3"
dataSource.aggregateByFile = true
XCTAssertFalse(dataSource.isEmpty())
XCTAssertEqual(dataSource.count(), 1)
XCTAssertEqual(dataSource.measure(index: 0)!.filename, "FileName3.swift")
}
func testSortFilenameDescending_FilterCanceled_Aggregate() {
let dataSource = ViewControllerDataSource()
dataSource.resetSourceData(newSourceData: measArray)
let descFilename = NSSortDescriptor(key: "filename", ascending: false)
dataSource.sortDescriptors = [descFilename]
dataSource.filter = "2"
dataSource.aggregateByFile = true
dataSource.filter = ""
XCTAssertFalse(dataSource.isEmpty())
XCTAssertEqual(dataSource.count(), 3)
XCTAssertEqual(dataSource.measure(index: 0)!.filename, "FileName3.swift")
XCTAssertEqual(dataSource.measure(index: 1)!.filename, "FileName2.swift")
XCTAssertEqual(dataSource.measure(index: 2)!.filename, "FileName1.swift")
}
}
| mit |
Senspark/ee-x | src/ios/ee/facebook_ads/FacebookNativeAd.swift | 1 | 7244 | //
// FacebookNativeAd.swift
// Pods
//
// Created by eps on 6/25/20.
//
import FBAudienceNetwork
private let kTag = "\(FacebookNativeAd.self)"
internal class FacebookNativeAd:
NSObject, IBannerAd, FBNativeAdDelegate {
private let _bridge: IMessageBridge
private let _logger: ILogger
private let _adId: String
private let _layoutName: String
private let _messageHelper: MessageHelper
private var _helper: BannerAdHelper?
private let _viewHelper: ViewHelper
private var _isLoaded = false
private var _ad: FBNativeAd?
private var _view: EEFacebookNativeAdView?
init(_ bridge: IMessageBridge,
_ logger: ILogger,
_ adId: String,
_ layoutName: String) {
_bridge = bridge
_logger = logger
_adId = adId
_layoutName = layoutName
_messageHelper = MessageHelper("FacebookNativeAd", _adId)
_viewHelper = ViewHelper(CGPoint.zero, CGSize.zero, false)
super.init()
_helper = BannerAdHelper(_bridge, self, _messageHelper)
registerHandlers()
createInternalAd()
createView()
}
func destroy() {
deregisterHandlers()
destroyView()
destroyInternalAd()
}
func registerHandlers() {
_helper?.registerHandlers()
_bridge.registerHandler(_messageHelper.createInternalAd) { _ in
self.createInternalAd()
return ""
}
_bridge.registerHandler(_messageHelper.destroyInternalAd) { _ in
self.destroyInternalAd()
return ""
}
}
func deregisterHandlers() {
_helper?.deregisterHandlers()
_bridge.deregisterHandler(_messageHelper.createInternalAd)
_bridge.deregisterHandler(_messageHelper.destroyInternalAd)
}
func createInternalAd() {
Thread.runOnMainThread {
if self._ad != nil {
return
}
self._isLoaded = false
let ad = FBNativeAd(placementID: self._adId)
ad.delegate = self
self._ad = ad
}
}
func destroyInternalAd() {
Thread.runOnMainThread {
guard let ad = self._ad else {
return
}
self._isLoaded = false
ad.delegate = nil
ad.unregisterView()
self._ad = nil
}
}
func createAdView() -> EEFacebookNativeAdView? {
guard let nibObjects = Bundle(for: EEFacebookNativeAdView.self).loadNibNamed(_layoutName,
owner: nil,
options: nil) else {
assert(false, "Invalid layout")
return nil
}
guard let view = nibObjects[0] as? EEFacebookNativeAdView else {
assert(false, "Invalid layout class")
return nil
}
return view
}
func createView() {
Thread.runOnMainThread {
assert(self._view == nil)
guard let view = self.createAdView() else {
assert(false, "Cannot create ad view")
return
}
view.adchoicesView.corner = UIRectCorner.topRight
self._view = view
self._viewHelper.view = view
let rootView = Utils.getCurrentRootViewController()
rootView?.view.addSubview(view)
}
}
func destroyView() {
Thread.runOnMainThread {
guard let view = self._view else {
return
}
view.removeFromSuperview()
self._view = nil
self._viewHelper.view = nil
}
}
var isLoaded: Bool {
return _isLoaded
}
func load() {
Thread.runOnMainThread {
guard let ad = self._ad else {
assert(false, "Ad is not initialized")
return
}
ad.loadAd(withMediaCachePolicy: FBNativeAdsCachePolicy.all)
}
}
var position: CGPoint {
get { return _viewHelper.position }
set(value) { _viewHelper.position = value }
}
var size: CGSize {
get { return _viewHelper.size }
set(value) { _viewHelper.size = value }
}
var isVisible: Bool {
get { return _viewHelper.isVisible }
set(value) {
_viewHelper.isVisible = value
if value {
Thread.runOnMainThread {
self._view?.subviews.forEach { $0.setNeedsDisplay() }
}
}
}
}
func nativeAdDidLoad(_ ad: FBNativeAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function)")
assert(ad == self._ad)
guard let view = self._view else {
assert(false, "Ad view is not initialized")
return
}
ad.unregisterView()
if view.callToActionButton != nil {
let rootView = Utils.getCurrentRootViewController()
ad.registerView(forInteraction: view,
mediaView: view.mediaView,
iconView: view.iconView,
viewController: rootView,
clickableViews: [view.callToActionButton])
}
view.adchoicesView.nativeAd = ad
view.bodyLabel.text = ad.bodyText
view.callToActionButton.setTitle(ad.callToAction,
for: UIControl.State.normal)
view.socialContextLabel.text = ad.socialContext
view.sponsorLabel.text = ad.sponsoredTranslation
view.titleLabel.text = ad.headline
self._isLoaded = true
self._bridge.callCpp(self._messageHelper.onLoaded)
}
}
func nativeAd(_ nativeAd: FBNativeAd, didFailWithError error: Error) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function): \(error.localizedDescription)")
self._bridge.callCpp(self._messageHelper.onFailedToLoad, EEJsonUtils.convertDictionary(toString: [
"code": (error as NSError).code,
"message": error.localizedDescription
]))
}
}
func nativeAdWillLogImpression(_ nativeAd: FBNativeAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function)")
}
}
func nativeAdDidClick(_ nativeAd: FBNativeAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function)")
self._bridge.callCpp(self._messageHelper.onClicked)
}
}
func nativeAdDidFinishHandlingClick(_ nativeAd: FBNativeAd) {
Thread.runOnMainThread {
self._logger.debug("\(kTag): \(#function)")
}
}
func nativeAdDidDownloadMedia(_ nativeAd: FBNativeAd) {
Thread.runOnMainThread {
self._logger.debug("\(#function)")
}
}
}
| mit |
apple/swift | test/Interop/SwiftToCxx/structs/resilient-struct-in-cxx.swift | 1 | 10566 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -enable-library-evolution -typecheck -module-name Structs -clang-header-expose-decls=all-public -emit-clang-header-path %t/structs.h
// RUN: %FileCheck %s < %t/structs.h
// RUN: %check-interop-cxx-header-in-clang(%t/structs.h)
public struct FirstSmallStruct {
public var x: UInt32
#if CHANGE_LAYOUT
public var y: UInt32 = 0
#endif
public func dump() {
print("find - small dump")
#if CHANGE_LAYOUT
print("x&y = \(x)&\(y)")
#else
print("x = \(x)")
#endif
}
public mutating func mutate() {
x = x * 2
#if CHANGE_LAYOUT
y = ~y
#endif
}
}
// CHECK: class FirstSmallStruct;
// CHECK: template<>
// CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<Structs::FirstSmallStruct> = true;
// CHECK: class FirstSmallStruct final {
// CHECK-NEXT: public:
// CHECK: inline FirstSmallStruct(const FirstSmallStruct &other) {
// CHECK-NEXT: auto metadata = _impl::$s7Structs16FirstSmallStructVMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: _storage = swift::_impl::OpaqueStorage(vwTable->size, vwTable->getAlignment());
// CHECK-NEXT: vwTable->initializeWithCopy(_getOpaquePointer(), const_cast<char *>(other._getOpaquePointer()), metadata._0);
// CHECK-NEXT: }
// CHECK: private:
// CHECK-NEXT: inline FirstSmallStruct(swift::_impl::ValueWitnessTable * _Nonnull vwTable) : _storage(vwTable->size, vwTable->getAlignment()) {}
// CHECK-NEXT: static inline FirstSmallStruct _make() {
// CHECK-NEXT: auto metadata = _impl::$s7Structs16FirstSmallStructVMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: return FirstSmallStruct(vwTable);
// CHECK-NEXT: }
// CHECK-NEXT: inline const char * _Nonnull _getOpaquePointer() const { return _storage.getOpaquePointer(); }
// CHECK-NEXT: inline char * _Nonnull _getOpaquePointer() { return _storage.getOpaquePointer(); }
// CHECK-EMPTY:
// CHECK-NEXT: swift::_impl::OpaqueStorage _storage;
// CHECK-NEXT: friend class _impl::_impl_FirstSmallStruct;
// CHECK-NEXT:};
// CHECK: class _impl_FirstSmallStruct {
// CHECK: };
// CHECK-EMPTY:
// CHECK-NEXT: }
// CHECK-EMPTY:
// CHECK-NEXT: } // end namespace
// CHECK-EMPTY:
// CHECK-NEXT: namespace swift {
// CHECK-NEXT: #pragma clang diagnostic push
// CHECK-NEXT: #pragma clang diagnostic ignored "-Wc++17-extensions"
// CHECK-NEXT: template<>
// CHECK-NEXT: struct TypeMetadataTrait<Structs::FirstSmallStruct> {
// CHECK-NEXT: inline void * _Nonnull getTypeMetadata() {
// CHECK-NEXT: return Structs::_impl::$s7Structs16FirstSmallStructVMa(0)._0;
// CHECK-NEXT: }
// CHECK-NEXT: };
// CHECK-NEXT: namespace _impl{
// CHECK-NEXT: template<>
// CHECK-NEXT: static inline const constexpr bool isValueType<Structs::FirstSmallStruct> = true;
// CHECK-NEXT: template<>
// CHECK-NEXT: static inline const constexpr bool isOpaqueLayout<Structs::FirstSmallStruct> = true;
// CHECK-NEXT: template<>
// CHECK-NEXT: struct implClassFor<Structs::FirstSmallStruct> { using type = Structs::_impl::_impl_FirstSmallStruct; };
// CHECK-NEXT: } // namespace
// CHECK-NEXT: #pragma clang diagnostic pop
// CHECK-NEXT: } // namespace swift
// CHECK-EMPTY:
// CHECK-NEXT: namespace Structs __attribute__((swift_private)) {
@frozen public struct FrozenStruct {
private let storedInt: Int32
}
// CHECK: class FrozenStruct final {
// CHECK: alignas(4) char _storage[4];
// CHECK-NEXT: friend class _impl::_impl_FrozenStruct;
// CHECK-NEXT: };
public struct LargeStruct {
public let x1: Int
let x2, x3, x4, x5, x6: Int
public var firstSmallStruct: FirstSmallStruct {
return FirstSmallStruct(x: 65)
}
public func dump() {
print("x.1 = \(x1), .2 = \(x2), .3 = \(x3), .4 = \(x4), .5 = \(x5)")
}
}
// CHECK: class LargeStruct final {
// CHECK-NEXT: public:
// CHECK: inline LargeStruct(const LargeStruct &other) {
// CHECK-NEXT: auto metadata = _impl::$s7Structs11LargeStructVMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: _storage = swift::_impl::OpaqueStorage(vwTable->size, vwTable->getAlignment());
// CHECK-NEXT: vwTable->initializeWithCopy(_getOpaquePointer(), const_cast<char *>(other._getOpaquePointer()), metadata._0);
// CHECK-NEXT: }
// CHECK: private:
// CHECK-NEXT: inline LargeStruct(swift::_impl::ValueWitnessTable * _Nonnull vwTable) : _storage(vwTable->size, vwTable->getAlignment()) {}
// CHECK-NEXT: static inline LargeStruct _make() {
// CHECK-NEXT: auto metadata = _impl::$s7Structs11LargeStructVMa(0);
// CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1;
// CHECK-NEXT: #ifdef __arm64e__
// CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839)));
// CHECK-NEXT: #else
// CHECK-NEXT: auto *vwTable = *vwTableAddr;
// CHECK-NEXT: #endif
// CHECK-NEXT: return LargeStruct(vwTable);
// CHECK-NEXT: }
// CHECK-NEXT: inline const char * _Nonnull _getOpaquePointer() const { return _storage.getOpaquePointer(); }
// CHECK-NEXT: inline char * _Nonnull _getOpaquePointer() { return _storage.getOpaquePointer(); }
// CHECK-EMPTY:
// CHECK-NEXT: swift::_impl::OpaqueStorage _storage;
// CHECK-NEXT: friend class _impl::_impl_LargeStruct;
// CHECK-NEXT: };
private class RefCountedClass {
let x: Int
init(x: Int) {
self.x = x
print("create RefCountedClass \(x)")
}
deinit {
print("destroy RefCountedClass \(x)")
}
}
public struct StructWithRefCountStoredProp {
private let storedRef: RefCountedClass
init(x: Int) {
storedRef = RefCountedClass(x: x)
}
public func dump() {
print("storedRef = \(storedRef.x)")
}
}
// CHECK: inline StructWithRefCountStoredProp(swift::_impl::ValueWitnessTable * _Nonnull vwTable) : _storage(vwTable->size, vwTable->getAlignment()) {}
public func createLargeStruct(_ x: Int) -> LargeStruct {
return LargeStruct(x1: x, x2: -x, x3: x * 2, x4: x - 4, x5: 0, x6: 21)
}
public func printSmallAndLarge(_ x: FirstSmallStruct, _ y: LargeStruct) {
x.dump()
y.dump()
}
public func createStructWithRefCountStoredProp() -> StructWithRefCountStoredProp {
return StructWithRefCountStoredProp(x: 0)
}
public func mutateSmall(_ x: inout FirstSmallStruct) {
#if CHANGE_LAYOUT
let y = x.y
x.y = x.x
x.x = y
#else
x.x += 1
#endif
}
// CHECK: inline LargeStruct createLargeStruct(swift::Int x) noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Structs17createLargeStructyAA0cD0VSiF(result, x);
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline StructWithRefCountStoredProp createStructWithRefCountStoredProp() noexcept SWIFT_WARN_UNUSED_RESULT {
// CHECK-NEXT: return _impl::_impl_StructWithRefCountStoredProp::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Structs34createStructWithRefCountStoredPropAA0cdefgH0VyF(result);
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline void mutateSmall(FirstSmallStruct& x) noexcept {
// CHECK-NEXT: return _impl::$s7Structs11mutateSmallyyAA05FirstC6StructVzF(_impl::_impl_FirstSmallStruct::getOpaquePointer(x));
// CHECK-NEXT: }
// CHECK: inline void printSmallAndLarge(const FirstSmallStruct& x, const LargeStruct& y) noexcept {
// CHECK-NEXT: return _impl::$s7Structs18printSmallAndLargeyyAA05FirstC6StructV_AA0eG0VtF(_impl::_impl_FirstSmallStruct::getOpaquePointer(x), _impl::_impl_LargeStruct::getOpaquePointer(y));
// CHECK-NEXT: }
// CHECK: inline uint32_t FirstSmallStruct::getX() const {
// CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV1xs6UInt32Vvg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline void FirstSmallStruct::setX(uint32_t value) {
// CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV1xs6UInt32Vvs(value, _getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline void FirstSmallStruct::dump() const {
// CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV4dumpyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline void FirstSmallStruct::mutate() {
// CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV6mutateyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline swift::Int LargeStruct::getX1() const {
// CHECK-NEXT: return _impl::$s7Structs11LargeStructV2x1Sivg(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct LargeStruct::getFirstSmallStruct() const {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Structs11LargeStructV010firstSmallC0AA05FirsteC0Vvg(result, _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline void LargeStruct::dump() const {
// CHECK-NEXT: return _impl::$s7Structs11LargeStructV4dumpyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK: inline void StructWithRefCountStoredProp::dump() const {
// CHECK-NEXT: return _impl::$s7Structs28StructWithRefCountStoredPropV4dumpyyF(_getOpaquePointer());
// CHECK-NEXT: }
| apache-2.0 |
muhlenXi/SwiftEx | projects/Swift4Demo/Swift4Demo/main.swift | 1 | 538 | //
// main.swift
// Swift4Demo
//
// Created by 席银军 on 2017/10/19.
// Copyright © 2017年 muhlenXi. All rights reserved.
//
import Foundation
struct JSON {
var data: [String: Any] = [:]
init(data: [String: Any]) {
self.data = data
}
subscript<T>(key: String) -> T? {
return data[key] as? T
}
}
let json = JSON(data: ["title": "Generic subscript", "duration": 300])
let title: String? = json["title"]
let duration: Int? = json["duration"]
print(title)
print(duration)
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/19855-swift-typechecker-checkinheritanceclause.swift | 10 | 263 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A{
init(){
class B{
struct B
struct D{
func a
func a<T{}
}
class B<T where h:a{
struct B | mit |
maximveksler/Developing-iOS-8-Apps-with-Swift | lesson-013/Trax Segue/Trax/GPX.swift | 2 | 7403 | //
// GPX.swift
// Trax
//
// Created by CS193p Instructor.
// Copyright (c) 2015 Stanford University. All rights reserved.
//
// Very simple GPX file parser.
// Only verified to work for CS193p demo purposes!
import Foundation
class GPX: NSObject, Printable, NSXMLParserDelegate
{
// MARK: - Public API
var waypoints = [Waypoint]()
var tracks = [Track]()
var routes = [Track]()
typealias GPXCompletionHandler = (GPX?) -> Void
class func parse(url: NSURL, completionHandler: GPXCompletionHandler) {
GPX(url: url, completionHandler: completionHandler).parse()
}
// MARK: - Public Classes
class Track: Entry, Printable
{
var fixes = [Waypoint]()
override var description: String {
let waypointDescription = "fixes=[\n" + "\n".join(fixes.map { $0.description }) + "\n]"
return " ".join([super.description, waypointDescription])
}
}
class Waypoint: Entry, Printable
{
var latitude: Double
var longitude: Double
init(latitude: Double, longitude: Double) {
self.latitude = latitude
self.longitude = longitude
super.init()
}
var info: String? {
set { attributes["desc"] = newValue }
get { return attributes["desc"] }
}
lazy var date: NSDate? = self.attributes["time"]?.asGpxDate
override var description: String {
return " ".join(["lat=\(latitude)", "lon=\(longitude)", super.description])
}
}
class Entry: NSObject, Printable
{
var links = [Link]()
var attributes = [String:String]()
var name: String? {
set { attributes["name"] = newValue }
get { return attributes["name"] }
}
override var description: String {
var descriptions = [String]()
if attributes.count > 0 { descriptions.append("attributes=\(attributes)") }
if links.count > 0 { descriptions.append("links=\(links)") }
return " ".join(descriptions)
}
}
class Link: Printable
{
var href: String
var linkattributes = [String:String]()
init(href: String) { self.href = href }
var url: NSURL? { return NSURL(string: href) }
var text: String? { return linkattributes["text"] }
var type: String? { return linkattributes["type"] }
var description: String {
var descriptions = [String]()
descriptions.append("href=\(href)")
if linkattributes.count > 0 { descriptions.append("linkattributes=\(linkattributes)") }
return "[" + " ".join(descriptions) + "]"
}
}
// MARK: - Printable
override var description: String {
var descriptions = [String]()
if waypoints.count > 0 { descriptions.append("waypoints = \(waypoints)") }
if tracks.count > 0 { descriptions.append("tracks = \(tracks)") }
if routes.count > 0 { descriptions.append("routes = \(routes)") }
return "\n".join(descriptions)
}
// MARK: - Private Implementation
private let url: NSURL
private let completionHandler: GPXCompletionHandler
private init(url: NSURL, completionHandler: GPXCompletionHandler) {
self.url = url
self.completionHandler = completionHandler
}
private func complete(success success: Bool) {
dispatch_async(dispatch_get_main_queue()) {
self.completionHandler(success ? self : nil)
}
}
private func fail() { complete(success: false) }
private func succeed() { complete(success: true) }
private func parse() {
let qos = Int(QOS_CLASS_USER_INITIATED.value)
dispatch_async(dispatch_get_global_queue(qos, 0)) {
if let data = NSData(contentsOfURL: self.url) {
let parser = NSXMLParser(data: data)
parser.delegate = self
parser.shouldProcessNamespaces = false
parser.shouldReportNamespacePrefixes = false
parser.shouldResolveExternalEntities = false
parser.parse()
} else {
self.fail()
}
}
}
func parserDidEndDocument(parser: NSXMLParser) { succeed() }
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) { fail() }
func parser(parser: NSXMLParser, validationErrorOccurred validationError: NSError) { fail() }
private var input = ""
func parser(parser: NSXMLParser!foundCharacters string: String!{
input += string
}
private var waypoint: Waypoint?
private var track: Track?
private var link: Link?
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) {
switch elementName {
case "trkseg":
if track == nil { fallthrough }
case "trk":
tracks.append(Track())
track = tracks.last
case "rte":
routes.append(Track())
track = routes.last
case "rtept", "trkpt", "wpt":
let latitude = (attributeDict["lat"] as! NSString).doubleValue
let longitude = (attributeDict["lon"] as! NSString).doubleValue
waypoint = Waypoint(latitude: latitude, longitude: longitude)
case "link":
link = Link(href: attributeDict["href"] as! String)
default: break
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
switch elementName {
case "wpt":
if waypoint != nil { waypoints.append(waypoint!); waypoint = nil }
case "trkpt", "rtept":
if waypoint != nil { track?.fixes.append(waypoint!); waypoint = nil }
case "trk", "trkseg", "rte":
track = nil
case "link":
if link != nil {
if waypoint != nil {
waypoint!.links.append(link!)
} else if track != nil {
track!.links.append(link!)
}
}
link = nil
default:
if link != nil {
link!.linkattributes[elementName] = input.trimmed
} else if waypoint != nil {
waypoint!.attributes[elementName] = input.trimmed
} else if track != nil {
track!.attributes[elementName] = input.trimmed
}
input = ""
}
}
}
// MARK: - Extensions
private extension String {
var trimmed: String {
return (self as NSString).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
}
extension String {
var asGpxDate: NSDate? {
get {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z"
return dateFormatter.dateFromString(self)
}
}
}
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/20747-no-stacktrace.swift | 11 | 236 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var d {
case
var
[ {
class
self
{
init( ) {
if true {
class
case ,
| mit |
GoodMorningCody/EverybodySwift | UIKitSample/UIKitSample/EasyTableViewController.swift | 1 | 3785 | //
// EasyTableViewController.swift
// UIKitSample
//
// Created by Cody on 2014. 12. 29..
// Copyright (c) 2014년 tiekle. All rights reserved.
//
import UIKit
class EasyTableViewController: UITableViewController {
var arrayOfStoryboardID : [String] = ["DatePickerTestViewController","WebViewTestViewController","MapViewTestViewController"]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "모두의 Swift"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return arrayOfStoryboardID.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = arrayOfStoryboardID[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var storyboarId = arrayOfStoryboardID[indexPath.row]
var viewController = storyboard?.instantiateViewControllerWithIdentifier(storyboarId) as UIViewController
self.navigationController?.pushViewController(viewController, animated: true)
//self.presentViewController(viewController, animated: true, completion: nil)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit |
gfjalar/pavo | Pavo/ImageHelpers.swift | 1 | 5178 | //
// ImageHelpers.swift
// Pavo
//
// Created by Piotr Galar on 01/05/2015.
// Copyright (c) 2015 Piotr Galar. All rights reserved.
//
import Cocoa
import ImageIO
import AVFoundation
public extension CGImage {
// ADD: async execution, completed callback
public func saveAsPNG(to dir: String, with name: String) {
let path = "\(dir)\(name).png"
let url = CFURLCreateWithFileSystemPath(nil, path, .CFURLPOSIXPathStyle,
false)
// TODO: catch
guard let destination = CGImageDestinationCreateWithURL(url, kUTTypePNG,
1, nil) else { return }
CGImageDestinationAddImage(destination, self, nil)
CGImageDestinationFinalize(destination)
}
func toCVPixelBuffer(width: Int, _ height: Int,
_ pixelFormat: OSType) -> CVPixelBuffer {
let settings = [
kCVPixelBufferCGImageCompatibilityKey as String: true,
kCVPixelBufferCGBitmapContextCompatibilityKey as String: true
]
let baseAddress = UnsafeMutablePointer<Void>(CFDataGetBytePtr(
CGDataProviderCopyData(CGImageGetDataProvider(self)))
)
let bytesPerRow = CGImageGetBytesPerRow(self)
var buffer : CVPixelBuffer?
CVPixelBufferCreateWithBytes(kCFAllocatorDefault, width, height,
pixelFormat, baseAddress, bytesPerRow, nil, nil, settings,
&buffer
)
return buffer!
}
func size() -> (Int, Int) {
return (CGImageGetWidth(self), CGImageGetHeight(self))
}
}
extension Array where Element:CGImage {
// ADD: async execution, completed callback
func saveAsPNG(to dir: String, with name: String) {
var count = 0
for image in self {
image.saveAsPNG(to: dir, with: "\(name)\(count)")
count++
}
}
// ADD: async execution, completed callback
func saveAsMPEG4(to dir: String, with name: String, _ fps: Int,
_ pixelFormat: Int, _ bitRate: Int, _ profileLevel: String) {
if self.count == 0 {
return
}
let url = NSURL(fileURLWithPath: "\(dir)\(name).mp4")
// TODO: catch
let video = try! AVAssetWriter(URL: url, fileType: AVFileTypeMPEG4)
let (width, height) = self.first!.size()
let osPixelFormat = OSType(pixelFormat)
let settings: [String : AnyObject] = [
AVVideoCodecKey: AVVideoCodecH264,
AVVideoWidthKey: width,
AVVideoHeightKey: height,
AVVideoCompressionPropertiesKey: [
AVVideoAverageBitRateKey: bitRate,
AVVideoProfileLevelKey: profileLevel,
AVVideoMaxKeyFrameIntervalKey: 1
]
]
let input = AVAssetWriterInput(mediaType: AVMediaTypeVideo,
outputSettings: settings)
let adaptor = AVAssetWriterInputPixelBufferAdaptor(
assetWriterInput: input, sourcePixelBufferAttributes: nil)
input.expectsMediaDataInRealTime = false
video.addInput(input)
video.startWriting()
video.startSessionAtSourceTime(kCMTimeZero)
var count = 0
func isReady() -> Bool {
return adaptor.assetWriterInput.readyForMoreMediaData
}
func getTime() -> CMTime {
return CMTimeMake(Int64(count), Int32(fps))
}
for image in self {
let buffer = image.toCVPixelBuffer(width, height, osPixelFormat)
let time = getTime()
ExponentialBackoff(isReady, base: 0.1, multiplier: 2.0) {
adaptor.appendPixelBuffer(buffer,
withPresentationTime: time)
}
count++
}
input.markAsFinished()
video.endSessionAtSourceTime(getTime())
video.finishWritingWithCompletionHandler({})
}
}
extension Dictionary {
func get(key: Key, or defaultValue: Value) -> Value {
if let value = self[key] {
return value
}
return defaultValue
}
}
// ADD: maximum number of backoffs, error closure
func ExponentialBackoff(condition: () -> Bool, base: NSTimeInterval,
multiplier: NSTimeInterval, closure: () -> ()) {
var backoff = base
while !condition() {
NSRunLoop.currentRunLoop().runUntilDate(
NSDate(timeIntervalSinceNow: backoff))
backoff *= multiplier
}
closure()
}
public func SaveAsMPEG4(images: [CGImage], to dir: String, with name: String,
fps: Int,
_ pixelFormat: Int = Int(kCVPixelFormatType_32BGRA),
_ bitRate: Int = 20000*1000,
_ profileLevel: String = AVVideoProfileLevelH264HighAutoLevel) {
images.saveAsMPEG4(to: dir, with: name, fps, pixelFormat, bitRate,
profileLevel)
}
public func SaveAsPNG(images: [CGImage], to dir: String, with name: String) {
images.saveAsPNG(to: dir, with: name)
}
| mit |
ijoshsmith/swift-tic-tac-toe | Framework/TicTacToeTests/AI/EmptyCornerTacticTests.swift | 1 | 2210 | //
// EmptyCornerTacticTests.swift
// TicTacToe
//
// Created by Joshua Smith on 11/30/15.
// Copyright © 2015 iJoshSmith. All rights reserved.
//
import XCTest
class EmptyCornerTacticTests: XCTestCase {
func test_choosePositionForMark_noCornersAreEmpty_returnsNil() {
XCTAssertNil(EmptyCornerTactic().choosePositionForMark(.X, onGameBoard: board3x3(
"X X",
" ",
"X X")))
}
func test_choosePositionForMark_topLeftIsEmpty_returnsTopLeft() {
let position = (EmptyCornerTactic().choosePositionForMark(.X, onGameBoard: board3x3(
" X",
" ",
"X X")))
if let position = position {
XCTAssertTrue(position == (row: 0, column: 0))
}
else {
XCTFail("Did not detect that the top left corner is empty.")
}
}
func test_choosePositionForMark_topRightIsEmpty_returnsTopRight() {
let position = (EmptyCornerTactic().choosePositionForMark(.X, onGameBoard: board3x3(
"X ",
" ",
"X X")))
if let position = position {
XCTAssertTrue(position == (row: 0, column: 2))
}
else {
XCTFail("Did not detect that the top right corner is empty.")
}
}
func test_choosePositionForMark_bottomRightIsEmpty_returnsBottomRight() {
let position = (EmptyCornerTactic().choosePositionForMark(.X, onGameBoard: board3x3(
"X X",
" ",
"X ")))
if let position = position {
XCTAssertTrue(position == (row: 2, column: 2))
}
else {
XCTFail("Did not detect that the bottom right corner is empty.")
}
}
func test_choosePositionForMark_bottomLeftIsEmpty_returnsBottomLeft() {
let position = (EmptyCornerTactic().choosePositionForMark(.X, onGameBoard: board3x3(
"X X",
" ",
" X")))
if let position = position {
XCTAssertTrue(position == (row: 2, column: 0))
}
else {
XCTFail("Did not detect that the bottom left corner is empty.")
}
}
}
| mit |
jakeheis/Shout | Tests/ShoutTests/SSHTests.swift | 1 | 1685 | //
// SSHTests.swift
// ShoutTests
//
// Created by Jake Heiser on 3/4/18.
//
import Shout
import XCTest
struct ShoutServer {
static let host = ""
static let username = ""
static let password = ""
static let agentAuth = SSHAgent()
static let passwordAuth = SSHPassword(password)
static let authMethod = agentAuth
}
class ShoutTests: XCTestCase {
func testCapture() throws {
let ssh = try SSH(host: ShoutServer.host)
try ssh.authenticate(username: ShoutServer.username, authMethod: ShoutServer.authMethod)
let (result, contents) = try ssh.capture("ls /")
XCTAssertEqual(result, 0)
XCTAssertTrue(contents.contains("bin"))
}
func testConnect() throws {
try SSH.connect(host: ShoutServer.host, username: ShoutServer.username, authMethod: ShoutServer.authMethod) { (ssh) in
let (result, contents) = try ssh.capture("ls /")
XCTAssertEqual(result, 0)
XCTAssertTrue(contents.contains("bin"))
}
}
func testSendFile() throws {
try SSH.connect(host: ShoutServer.host, username: ShoutServer.username, authMethod: ShoutServer.authMethod) { (ssh) in
try ssh.sendFile(localURL: URL(fileURLWithPath: String(#file)), remotePath: "/tmp/shout_upload_test.swift")
let (status, contents) = try ssh.capture("cat /tmp/shout_upload_test.swift")
XCTAssertEqual(status, 0)
XCTAssertEqual(contents.components(separatedBy: "\n")[1], "// SSHTests.swift")
XCTAssertEqual(try ssh.execute("rm /tmp/shout_upload_test.swift", silent: false), 0)
}
}
}
| mit |
sergdort/CleanArchitectureRxSwift | RealmPlatform/Entities/RMUser.swift | 1 | 2180 | //
// RMUser.swift
// CleanArchitectureRxSwift
//
// Created by Andrey Yastrebov on 10.03.17.
// Copyright © 2017 sergdort. All rights reserved.
//
import QueryKit
import Domain
import RealmSwift
import Realm
final class RMUser: Object {
@objc dynamic var address: RMAddress?
@objc dynamic var company: RMCompany?
@objc dynamic var email: String = ""
@objc dynamic var name: String = ""
@objc dynamic var phone: String = ""
@objc dynamic var uid: String = ""
@objc dynamic var username: String = ""
@objc dynamic var website: String = ""
override class func primaryKey() -> String? {
return "uid"
}
}
extension RMUser {
static var website: Attribute<String> { return Attribute("website")}
static var email: Attribute<String> { return Attribute("email")}
static var name: Attribute<String> { return Attribute("name")}
static var phone: Attribute<String> { return Attribute("phone")}
static var username: Attribute<String> { return Attribute("username")}
static var uid: Attribute<String> { return Attribute("uid")}
static var address: Attribute<RMAddress> { return Attribute("address")}
static var company: Attribute<RMCompany> { return Attribute("company")}
}
extension RMUser: DomainConvertibleType {
typealias DomainType = Domain.User
func asDomain() -> Domain.User {
return User(address: address!.asDomain(),
company: company!.asDomain(),
email: email,
name: name,
phone: phone,
uid: uid,
username: username,
website: website)
}
}
extension Domain.User: RealmRepresentable {
typealias RealmType = RealmPlatform.RMUser
func asRealm() -> RealmPlatform.RMUser {
return RMUser.build { object in
object.uid = uid
object.address = address.asRealm()
object.company = company.asRealm()
object.email = email
object.name = name
object.phone = phone
object.username = username
object.website = website
}
}
}
| mit |
nathan/hush | Hush/KeyboardEmulator.swift | 1 | 2566 | import Cocoa
class KeyboardEmulator {
class func pressAndReleaseChar(_ char: UniChar, flags: CGEventFlags_ = [], eventSource es: CGEventSource) {
pressChar(char, flags: flags, eventSource: es)
releaseChar(char, flags: flags, eventSource: es)
}
class func pressChar(_ char: UniChar, keyDown: Bool = true, flags: CGEventFlags_ = [], eventSource es: CGEventSource) {
var char = char
let event = CGEvent(keyboardEventSource: es, virtualKey: 0, keyDown: keyDown)
if !flags.isEmpty {
let flags = CGEventFlags(rawValue: UInt64(flags.rawValue))
event?.flags = flags
}
event?.keyboardSetUnicodeString(stringLength: 1, unicodeString: &char)
event?.post(tap: CGEventTapLocation.cghidEventTap)
}
class func releaseChar(_ char: UniChar, flags: CGEventFlags_ = [], eventSource es: CGEventSource) {
pressChar(char, keyDown: false, flags: flags, eventSource: es)
}
}
extension KeyboardEmulator {
class func pressAndReleaseKey(_ key: CGKeyCode, flags: CGEventFlags_ = [], eventSource es: CGEventSource) {
pressKey(key, flags: flags, eventSource: es)
releaseKey(key, flags: flags, eventSource: es)
}
class func pressKey(_ key: CGKeyCode, keyDown: Bool = true, flags: CGEventFlags_ = [], eventSource es: CGEventSource) {
let event = CGEvent(keyboardEventSource: es, virtualKey: key, keyDown: keyDown)
if !flags.isEmpty {
let flags = CGEventFlags(rawValue: UInt64(flags.rawValue))
event?.flags = flags
}
event?.post(tap: CGEventTapLocation.cghidEventTap)
}
class func releaseKey(_ key: CGKeyCode, flags: CGEventFlags_ = [], eventSource es: CGEventSource) {
pressKey(key, keyDown: false, flags: flags, eventSource: es)
}
}
extension KeyboardEmulator {
class func replaceText(_ text: String, eventSource es: CGEventSource) {
selectAll(eventSource: es)
OperationQueue.main.addOperation {self.typeText(text, eventSource: es)}
}
class func typeText(_ text: String, eventSource es: CGEventSource) {
for char in text.utf16 {
self.pressAndReleaseChar(char, eventSource: es)
}
}
class func deleteAll(eventSource es: CGEventSource) {
selectAll(eventSource: es)
OperationQueue.main.addOperation {
self.pressAndReleaseKey(CGKeyCode(kVK_Delete), eventSource: es)
}
}
class func selectAll(eventSource es: CGEventSource) {
pressKey(CGKeyCode(kVK_Command), eventSource: es)
pressAndReleaseKey(CGKeyCode(kVK_ANSI_A), flags: CGEventFlags_.Command, eventSource: es)
releaseKey(CGKeyCode(kVK_Command), eventSource: es)
}
}
| unlicense |
lorentey/swift | test/ClangImporter/cvars_parse.swift | 66 | 406 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -verify %s
import cvars
func getPI() -> Float {
return PI
}
func testPointers() {
let cp = globalConstPointer
cp.abcde() // expected-error {{value of type 'UnsafeRawPointer?' has no member 'abcde'}}
let mp = globalPointer
mp.abcde() // expected-error {{value of type 'UnsafeMutableRawPointer?' has no member 'abcde'}}
}
| apache-2.0 |
cookpad/Phakchi | Tests/Phakchi/InteractionBuilderTest.swift | 1 | 4912 | import XCTest
@testable import Phakchi
class InteractionBuilderTestCase: XCTestCase {
var builder: InteractionBuilder!
override func setUp() {
super.setUp()
self.builder = InteractionBuilder()
}
fileprivate func makeInteractionWithRequestHeaders(_ headers: Headers?) -> Interaction! {
self.builder.uponReceiving("Hello")
.with(.get, path: "/integrates",
query: nil, headers:
headers,
body: nil)
.willRespondWith(status: 200)
return self.builder.makeInteraction()
}
fileprivate func makeInteractionWithResponseHeaders(_ headers: Headers?) -> Interaction! {
self.builder.uponReceiving("Hello")
.with(.get, path: "/integrates")
.willRespondWith(status: 200, headers: headers, body: nil)
return self.builder.makeInteraction()
}
func testIsValid() {
XCTAssertFalse(self.builder.isValid)
XCTAssertFalse(self.builder.uponReceiving("Hello").isValid)
XCTAssertFalse(self.builder
.uponReceiving("Hello")
.with(.get, path: "/integrates/")
.isValid)
XCTAssertTrue(self.builder.uponReceiving("Hello")
.with(.get, path: "/integrates/")
.willRespondWith(status: 200)
.isValid)
}
func testDefaultRequestHeader() {
self.builder.defaultRequestHeaders = [
"Content-Type": "application/json",
"Authorization": "authtoken"
]
let interaction0 = makeInteractionWithRequestHeaders(["Host": "example.com"])
XCTAssertEqual(interaction0?.request.headers?["Authorization"] as? String, "authtoken")
XCTAssertEqual(interaction0?.request.headers?["Host"] as? String, "example.com")
self.builder.defaultRequestHeaders = [
"Content-Type": "application/json",
"Authorization": "authtoken"
]
let interaction1 = makeInteractionWithRequestHeaders(["Content-Type": "text/plain"])
XCTAssertEqual(interaction1?.request.headers?["Content-Type"] as? String, "text/plain")
XCTAssertEqual(interaction1?.request.headers?["Authorization"] as? String, "authtoken")
self.builder.defaultRequestHeaders = [
"Content-Type": "application/json",
"Authorization": "authtoken"
]
let interaction2 = makeInteractionWithRequestHeaders(nil)
XCTAssertEqual(interaction2?.request.headers?["Content-Type"] as? String, "application/json")
XCTAssertEqual(interaction2?.request.headers?["Authorization"] as? String, "authtoken")
self.builder.defaultRequestHeaders = nil
let interaction3 = makeInteractionWithRequestHeaders(["Content-Type": "text/plain"])
XCTAssertEqual(interaction3?.request.headers?["Content-Type"] as? String, "text/plain")
self.builder.defaultRequestHeaders = nil
let interaction4 = makeInteractionWithRequestHeaders(nil)
XCTAssertNil(interaction4?.request.headers)
}
func testDefaultResponseHeader() {
self.builder.defaultResponseHeaders = [
"Content-Type": "application/json",
"Authorization": "authtoken"
]
let interaction0 = makeInteractionWithResponseHeaders(["Host": "example.com"])
XCTAssertEqual(interaction0?.response.headers?["Content-Type"] as? String, "application/json")
XCTAssertEqual(interaction0?.response.headers?["Authorization"] as? String, "authtoken")
XCTAssertEqual(interaction0?.response.headers?["Host"] as? String, "example.com")
self.builder.defaultResponseHeaders = [
"Content-Type": "application/json",
"Authorization": "authtoken"
]
let interaction1 = makeInteractionWithResponseHeaders(["Content-Type": "text/plain"])
XCTAssertEqual(interaction1?.response.headers?["Content-Type"] as? String, "text/plain")
XCTAssertEqual(interaction1?.response.headers?["Authorization"] as? String, "authtoken")
self.builder.defaultResponseHeaders = [
"Content-Type": "application/json",
"Authorization": "authtoken"
]
let interaction2 = makeInteractionWithResponseHeaders(nil)
XCTAssertEqual(interaction2?.response.headers?["Content-Type"] as? String, "application/json")
XCTAssertEqual(interaction2?.response.headers?["Authorization"] as? String, "authtoken")
self.builder.defaultResponseHeaders = nil
let interaction3 = makeInteractionWithResponseHeaders(["Content-Type": "text/plain"])
XCTAssertEqual(interaction3?.response.headers?["Content-Type"] as? String, "text/plain")
self.builder.defaultResponseHeaders = nil
let interaction4 = makeInteractionWithResponseHeaders(nil)
XCTAssertNil(interaction4?.response.headers)
}
}
| mit |
git-hushuai/MOMO | MMHSMeterialProject/UINavigationController/BusinessFile/ModelAnalysis/Reflect/Reflect.swift | 1 | 1999 | //
// Reflect.swift
// Reflect
//
// Created by 冯成林 on 15/8/19.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
class Reflect: NSObject, NSCoding{
lazy var mirror: Mirror = {Mirror(reflecting: self)}()
required override init(){}
required convenience init?(coder aDecoder: NSCoder) {
self.init()
let ignorePropertiesForCoding = self.ignoreCodingPropertiesForCoding()
self.properties { (name, type, value) -> Void in
assert(type.check(), "[Charlin Feng]: Property '\(name)' type can not be a '\(type.realType.rawValue)' Type,Please use 'NSNumber' instead!")
let hasValue = ignorePropertiesForCoding != nil
if hasValue {
let ignore = (ignorePropertiesForCoding!).contains(name)
if !ignore {
self.setValue(aDecoder.decodeObjectForKey(name), forKeyPath: name)
}
}else{
self.setValue(aDecoder.decodeObjectForKey(name), forKeyPath: name)
}
}
}
func encodeWithCoder(aCoder: NSCoder) {
let ignorePropertiesForCoding = self.ignoreCodingPropertiesForCoding()
self.properties { (name, type, value) -> Void in
print("name:\(name)--type:\(type)---value:\(value)");
let hasValue = ignorePropertiesForCoding != nil
if hasValue {
let ignore = (ignorePropertiesForCoding!).contains(name)
if !ignore {
aCoder.encodeObject(value as? AnyObject, forKey: name)
}
}else{
aCoder.encodeObject(value as? AnyObject, forKey: name)
}
}
}
func parseOver(){}
}
| mit |
lbkchen/cvicu-app | complicationsapp/Pods/CVCalendar/CVCalendar/CVCalendarManager.swift | 1 | 8355 | //
// CVCalendarManager.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/26/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
private let YearUnit = NSCalendarUnit.Year
private let MonthUnit = NSCalendarUnit.Month
private let WeekUnit = NSCalendarUnit.WeekOfMonth
private let WeekdayUnit = NSCalendarUnit.Weekday
private let DayUnit = NSCalendarUnit.Day
private let AllUnits = YearUnit.union(MonthUnit).union(WeekUnit).union(WeekdayUnit).union(DayUnit)
public final class CVCalendarManager {
// MARK: - Private properties
private var components: NSDateComponents
private unowned let calendarView: CalendarView
public var calendar: NSCalendar
// MARK: - Public properties
public var currentDate: NSDate
// MARK: - Private initialization
public var starterWeekday: Int
public init(calendarView: CalendarView) {
self.calendarView = calendarView
currentDate = NSDate()
calendar = NSCalendar.currentCalendar()
components = calendar.components(MonthUnit.union(DayUnit), fromDate: currentDate)
starterWeekday = calendarView.firstWeekday.rawValue
calendar.firstWeekday = starterWeekday
}
// MARK: - Common date analysis
public func monthDateRange(date: NSDate) -> (countOfWeeks: NSInteger, monthStartDate: NSDate, monthEndDate: NSDate) {
let units = (YearUnit.union(MonthUnit).union(WeekUnit))
let components = calendar.components(units, fromDate: date)
// Start of the month.
components.day = 1
let monthStartDate = calendar.dateFromComponents(components)!
// End of the month.
components.month += 1
components.day -= 1
let monthEndDate = calendar.dateFromComponents(components)!
// Range of the month.
let range = calendar.rangeOfUnit(WeekUnit, inUnit: MonthUnit, forDate: date)
let countOfWeeks = range.length
return (countOfWeeks, monthStartDate, monthEndDate)
}
public static func dateRange(date: NSDate) -> (year: Int, month: Int, weekOfMonth: Int, day: Int) {
let components = componentsForDate(date)
let year = components.year
let month = components.month
let weekOfMonth = components.weekOfMonth
let day = components.day
return (year, month, weekOfMonth, day)
}
public func weekdayForDate(date: NSDate) -> Int {
let units = WeekdayUnit
let components = calendar.components(units, fromDate: date)
//println("NSDate: \(date), Weekday: \(components.weekday)")
// let weekday = calendar.ordinalityOfUnit(units, inUnit: WeekUnit, forDate: date)
return Int(components.weekday)
}
// MARK: - Analysis sorting
public func weeksWithWeekdaysForMonthDate(date: NSDate) -> (weeksIn: [[Int : [Int]]], weeksOut: [[Int : [Int]]]) {
let countOfWeeks = self.monthDateRange(date).countOfWeeks
let totalCountOfDays = countOfWeeks * 7
let firstMonthDateIn = self.monthDateRange(date).monthStartDate
let lastMonthDateIn = self.monthDateRange(date).monthEndDate
let countOfDaysIn = Manager.dateRange(lastMonthDateIn).day
let countOfDaysOut = totalCountOfDays - countOfDaysIn
// Find all dates in.
var datesIn = [NSDate]()
for day in 1...countOfDaysIn {
let components = Manager.componentsForDate(firstMonthDateIn)
components.day = day
let date = calendar.dateFromComponents(components)!
datesIn.append(date)
}
// Find all dates out.
let firstMonthDateOut: NSDate? = {
let firstMonthDateInWeekday = self.weekdayForDate(firstMonthDateIn)
if firstMonthDateInWeekday == self.starterWeekday {
return firstMonthDateIn
}
let components = Manager.componentsForDate(firstMonthDateIn)
for _ in 1...7 {
components.day -= 1
let updatedDate = self.calendar.dateFromComponents(components)!
updatedDate
let updatedDateWeekday = self.weekdayForDate(updatedDate)
if updatedDateWeekday == self.starterWeekday {
updatedDate
return updatedDate
}
}
let diff = 7 - firstMonthDateInWeekday
for _ in diff..<7 {
components.day += 1
let updatedDate = self.calendar.dateFromComponents(components)!
let updatedDateWeekday = self.weekdayForDate(updatedDate)
if updatedDateWeekday == self.starterWeekday {
updatedDate
return updatedDate
}
}
return nil
}()
// Constructing weeks.
var firstWeekDates = [NSDate]()
var lastWeekDates = [NSDate]()
var firstWeekDate = (firstMonthDateOut != nil) ? firstMonthDateOut! : firstMonthDateIn
let components = Manager.componentsForDate(firstWeekDate)
components.day += 6
var lastWeekDate = calendar.dateFromComponents(components)!
func nextWeekDateFromDate(date: NSDate) -> NSDate {
let components = Manager.componentsForDate(date)
components.day += 7
let nextWeekDate = calendar.dateFromComponents(components)!
return nextWeekDate
}
for weekIndex in 1...countOfWeeks {
firstWeekDates.append(firstWeekDate)
lastWeekDates.append(lastWeekDate)
firstWeekDate = nextWeekDateFromDate(firstWeekDate)
lastWeekDate = nextWeekDateFromDate(lastWeekDate)
}
// Dictionaries.
var weeksIn = [[Int : [Int]]]()
var weeksOut = [[Int : [Int]]]()
let count = firstWeekDates.count
for i in 0..<count {
var weekdaysIn = [Int : [Int]]()
var weekdaysOut = [Int : [Int]]()
let firstWeekDate = firstWeekDates[i]
let lastWeekDate = lastWeekDates[i]
let components = Manager.componentsForDate(firstWeekDate)
for weekday in 1...7 {
let weekdate = calendar.dateFromComponents(components)!
components.day += 1
let day = Manager.dateRange(weekdate).day
func addDay(inout weekdays: [Int : [Int]]) {
var days = weekdays[weekday]
if days == nil {
days = [Int]()
}
days!.append(day)
weekdays.updateValue(days!, forKey: weekday)
}
if i == 0 && day > 20 {
addDay(&weekdaysOut)
} else if i == countOfWeeks - 1 && day < 10 {
addDay(&weekdaysOut)
} else {
addDay(&weekdaysIn)
}
}
if weekdaysIn.count > 0 {
weeksIn.append(weekdaysIn)
}
if weekdaysOut.count > 0 {
weeksOut.append(weekdaysOut)
}
}
return (weeksIn, weeksOut)
}
// MARK: - Util methods
public static func componentsForDate(date: NSDate) -> NSDateComponents {
let units = YearUnit.union(MonthUnit).union(WeekUnit).union(DayUnit)
let components = NSCalendar.currentCalendar().components(units, fromDate: date)
return components
}
public static func dateFromYear(year: Int, month: Int, week: Int, day: Int) -> NSDate? {
let comps = Manager.componentsForDate(NSDate())
comps.year = year
comps.month = month
comps.weekOfMonth = week
comps.day = day
return NSCalendar.currentCalendar().dateFromComponents(comps)
}
} | mit |
fakerabbit/LucasBot | LucasBot/Utils.swift | 1 | 3441 | //
// Utils.swift
// LucasBot
//
// Created by Mirko Justiniano on 1/9/17.
// Copyright © 2017 LB. All rights reserved.
//
import Foundation
import UIKit
struct Utils {
/*
* MARK:- FONTS
*/
/*
** Avenir
Avenir-Medium
Avenir-HeavyOblique
Avenir-Book
Avenir-Light
Avenir-Roman
Avenir-BookOblique
Avenir-MediumOblique
Avenir-Black
Avenir-BlackOblique
Avenir-Heavy
Avenir-LightOblique
Avenir-Oblique
** San Francisco Display
SanFranciscoDisplay-Regular
SanFranciscoDisplay-Medium
SanFranciscoDisplay-Bold
*/
static func printFontNamesInSystem() {
for family in UIFont.familyNames {
print("*", family);
for name in UIFont.fontNames(forFamilyName: family ) {
print(name);
}
}
}
static func chatFont() -> UIFont {
return UIFont(name: "SanFranciscoDisplay-Regular", size: 18.0)!
}
static func LucasFont() -> UIFont {
return UIFont(name: "Avenir-Roman", size: 50.0)!
}
static func BotFont() -> UIFont {
return UIFont(name: "Avenir-Roman", size: 50.0)!
}
static func buttonFont() -> UIFont {
return UIFont(name: "SanFranciscoDisplay-Medium", size: 18.0)!
}
static func boldFont() -> UIFont {
return UIFont(name: "SanFranciscoDisplay-Bold", size: 18.0)!
}
/*
* MARK:- COLORS
*/
static func backgroundColor() -> UIColor {
return UIColor(colorLiteralRed: 209/255, green: 225/255, blue: 232/255, alpha: 1.0)
}
static func darkBackgroundColor() -> UIColor {
return UIColor(colorLiteralRed: 122/255, green: 178/255, blue: 206/255, alpha: 1.0)
}
static func lucasColor() -> UIColor {
return UIColor(colorLiteralRed: 209/255, green: 225/255, blue: 232/255, alpha: 1.0)
}
static func botColor() -> UIColor {
return UIColor(colorLiteralRed: 46/255, green: 62/255, blue: 70/255, alpha: 1.0)
}
static func chatBotColor() -> UIColor {
return UIColor.white
}
static func chatUserColor() -> UIColor {
return UIColor(colorLiteralRed: 47/255, green: 62/255, blue: 70/255, alpha: 1.0)
}
static func redColor() -> UIColor {
return UIColor(colorLiteralRed: 237/255, green: 20/255, blue: 91/255, alpha: 1.0)
}
static func botBubbleColor() -> UIColor {
return UIColor(colorLiteralRed: 177/255, green: 203/255, blue: 70/255, alpha: 1.0)
}
static func userBubbleColor() -> UIColor {
return UIColor.white
}
static func greenColor() -> UIColor {
return UIColor(colorLiteralRed: 177/255, green: 203/255, blue: 70/255, alpha: 1.0)
}
static func lineColor() -> UIColor {
return UIColor(colorLiteralRed: 227/255, green: 229/255, blue: 230/255, alpha: 1.0)
}
/*
* MARK:- IMAGES
*/
static let kDefaultGif:String = "wave-chat"
static let kSandwich:String = "sandwich"
static let kPopBg:String = "popBg"
/*
* MARK:- VALUES
*/
static var interBubbleSpace: CGFloat = 20.00
static var menuItemHeight = "40"
static var menuItemWidth = "200"
static var galleryItemHeight = "200"
static var galleryItemWidth = "200"
}
| gpl-3.0 |
noodlewerk/NWATools | Projects/Continental/Continental/CLPlacemark+Continental.swift | 1 | 449 | //
// CLPlacemark+Continental.swift
// Continental
//
// Created by Bruno Scheele on 29/10/15.
// Copyright © 2015 Noodlewerk Apps. All rights reserved.
//
import Foundation
import CoreLocation
extension CLPlacemark {
var continentCode: String? {
get {
guard let countryCode = ISOcountryCode else {
return nil
}
return continentCodeForCountryCode(countryCode)
}
}
}
| mit |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/SpeechToTextV1/Models/SpeakerLabelsResult.swift | 1 | 2148 | /**
* Copyright IBM Corporation 2018
*
* 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
/** SpeakerLabelsResult. */
public struct SpeakerLabelsResult: Decodable {
/// The start time of a word from the transcript. The value matches the start time of a word from the `timestamps` array.
public var from: Double
/// The end time of a word from the transcript. The value matches the end time of a word from the `timestamps` array.
public var to: Double
/// The numeric identifier that the service assigns to a speaker from the audio. Speaker IDs begin at `0` initially but can evolve and change across interim results (if supported by the method) and between interim and final results as the service processes the audio. They are not guaranteed to be sequential, contiguous, or ordered.
public var speaker: Int
/// A score that indicates the service's confidence in its identification of the speaker in the range of 0 to 1.
public var confidence: Double
/// An indication of whether the service might further change word and speaker-label results. A value of `true` means that the service guarantees not to send any further updates for the current or any preceding results; `false` means that the service might send further updates to the results.
public var finalResults: Bool
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case from = "from"
case to = "to"
case speaker = "speaker"
case confidence = "confidence"
case finalResults = "final"
}
}
| mit |
MastodonKit/MastodonKit | Tests/MastodonKitTests/Foundation/URLComponentsTests.swift | 1 | 1519 | //
// URLComponentsTests.swift
// MastodonKit
//
// Created by Ornithologist Coder on 4/22/17.
// Copyright © 2017 MastodonKit. All rights reserved.
//
import XCTest
@testable import MastodonKit
class URLComponentsTests: XCTestCase {
func testURLComponentsWithValidBaseURL() {
let request = Request<String>(path: "/string")
let components = URLComponents(baseURL: "https://mastodon.technology", request: request)
XCTAssertEqual(components?.url, URL(string: "https://mastodon.technology/string"))
}
func testURLComponentsWithInvalidBaseURL() {
let request = Request<String>(path: "/string")
let components = URLComponents(baseURL: "this is an invalid base url", request: request)
XCTAssertNil(components)
}
func testURLComponentsWithInValidRequestPath() {
let request = Request<String>(path: "invalid endpoint")
let components = URLComponents(baseURL: "https://mastodon.technology", request: request)
XCTAssertNil(components)
}
func testURLComponentsWithBaseURLAndQueryItems() {
let parameters = [
Parameter(name: "a", value: "0"),
Parameter(name: "b", value: "1")
]
let request = Request<String>(path: "/string", method: .get(.parameters(parameters)))
let components = URLComponents(baseURL: "https://mastodon.technology", request: request)
XCTAssertEqual(components?.url, URL(string: "https://mastodon.technology/string?a=0&b=1"))
}
}
| mit |
rtoal/ple | swift/anagrams.swift | 2 | 561 | import Foundation
func generatePermutations(of a: inout [Character], upTo n: Int) {
if n == 0 {
print(String(a))
} else {
for i in 0..<n {
generatePermutations(of: &a, upTo: n-1)
a.swapAt(n % 2 == 0 ? 0 : i, n)
}
generatePermutations(of: &a, upTo: n-1)
}
}
if CommandLine.arguments.count != 2 {
fputs("Exactly one argument is required\n", stderr)
exit(1)
}
let word = CommandLine.arguments[1]
var charArray = Array(word)
generatePermutations(of: &charArray, upTo: charArray.count-1)
| mit |
chris-wood/reveiller | reveiller/Pods/SwiftCharts/SwiftCharts/Axis/ChartAxisXLowLayerDefault.swift | 6 | 1111 | //
// ChartAxisXLowLayerDefault.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
class ChartAxisXLowLayerDefault: ChartAxisXLayerDefault {
override var low: Bool {return true}
override var lineP1: CGPoint {
return self.p1
}
override var lineP2: CGPoint {
return self.p2
}
override func chartViewDrawing(context context: CGContextRef, chart: Chart) {
super.chartViewDrawing(context: context, chart: chart)
}
override func initDrawers() {
self.lineDrawer = self.generateLineDrawer(offset: 0)
let labelsOffset = (self.settings.axisStrokeWidth / 2) + self.settings.labelsToAxisSpacingX
let labelDrawers = self.generateLabelDrawers(offset: labelsOffset)
let definitionLabelsOffset = labelsOffset + self.labelsTotalHeight + self.settings.axisTitleLabelsToLabelsSpacing
self.axisTitleLabelDrawers = self.generateAxisTitleLabelsDrawers(offset: definitionLabelsOffset)
self.labelDrawers = labelDrawers
}
}
| mit |
wealon/MyNav | testNav/testNavTests/testNavTests.swift | 1 | 892 | //
// testNavTests.swift
// testNavTests
//
// Created by wealon on 15/7/14.
// Copyright (c) 2015年 xxtao. All rights reserved.
//
import UIKit
import XCTest
class testNavTests: 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 testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
insidegui/WWDC | WWDC/FeaturedSectionViewModel.swift | 1 | 792 | //
// FeaturedSectionViewModel.swift
// WWDC
//
// Created by Guilherme Rambo on 26/05/18.
// Copyright © 2018 Guilherme Rambo. All rights reserved.
//
import Foundation
import ConfCore
import RxRealm
import RxSwift
import RxCocoa
import RealmSwift
final class FeaturedSectionViewModel {
let section: FeaturedSection
init(section: FeaturedSection) {
self.section = section
}
lazy var rxTitle: Observable<String> = {
return Observable.from(object: section).map({ $0.title })
}()
lazy var rxSubtitle: Observable<String> = {
return Observable.from(object: section).map({ $0.summary })
}()
lazy var contents: [FeaturedContentViewModel] = {
return section.content.map { FeaturedContentViewModel(content: $0) }
}()
}
| bsd-2-clause |
mansoor92/MaksabComponents | Example/Pods/StylingBoilerPlate/StylingBoilerPlate/Classes/Helper/Alert.swift | 1 | 2124 | //
// Alert.swift
// Cap
//
// Created by Pantera Engineering on 20/12/2016.
// Copyright © 2016 Incubasys IT Solutions. All rights reserved.
//
import UIKit
public class Alert{
static public func showMessage(viewController:UIViewController?,title:String? = nil,msg:String? = nil,actions:[UIAlertAction]? = nil,showOnlyDismissBtn:Bool=true, dismissBtnTitle: String) {
guard viewController != nil else {
return
}
let alert = createAlert(viewController:viewController,title:title,msg:msg,actions:actions,showOnlyDismissBtn:showOnlyDismissBtn,dismissBtnTitle:dismissBtnTitle)
viewController!.present(alert, animated: true, completion: nil)
}//showError
static func createAlert(viewController:UIViewController?,title:String? = nil,msg:String? = nil,actions:[UIAlertAction]? = nil,showOnlyDismissBtn:Bool=true, dismissBtnTitle: String) -> UIAlertController {
let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
//dismiss button check
if showOnlyDismissBtn {
let actionDismiss = UIAlertAction(title: dismissBtnTitle, style: .cancel, handler: nil)
alert.addAction(actionDismiss)
return alert
}
if actions != nil{
for action in actions!{
alert.addAction(action)
}
}//if
return alert
}
static public func showImagePickerAlert(viewController:UIViewController,actionPhotoLibrary:UIAlertAction,actionCamera:UIAlertAction,actionRemove:UIAlertAction? = nil, cancelTitle: String, title: String) {
let actionCancel = UIAlertAction(title: cancelTitle, style: .cancel, handler: nil)
let alert = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet)
alert.addAction(actionCancel)
alert.addAction(actionCamera)
alert.addAction(actionPhotoLibrary)
if actionRemove != nil{
alert.addAction(actionRemove!)
}
viewController.present(alert, animated: true, completion: nil)
}
}
| mit |
studyYF/YueShiJia | YueShiJia/YueShiJia/Classes/Main/YFNavigationController.swift | 1 | 1369 | //
// YFNavigationController.swift
// YueShiJia
//
// Created by YangFan on 2017/5/10.
// Copyright © 2017年 YangFan. All rights reserved.
//
import UIKit
class YFNavigationController: UINavigationController {
//MARK: 定义属性
//MARK: 生命周期函数
override func viewDidLoad() {
super.viewDidLoad()
// navigationBar.isTranslucent = false
// navigationBar.setBackgroundImage(UIImage.imageWithColor(color: UIColor.white), for: .default)
navigationBar.barTintColor = UIColor.white
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
navigationItem.hidesBackButton = true
if viewControllers.count > 0 {
viewController.hidesBottomBarWhenPushed = true
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
button.setImage(UIImage(named: "nav_return_normal"), for: .normal)
button.addTarget(self, action: #selector(YFNavigationController.back), for: .touchUpInside)
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
}
super.pushViewController(viewController, animated: animated)
}
@objc private func back() {
popViewController(animated: true)
}
}
| apache-2.0 |
nifty-swift/Nifty | Sources/ndims.swift | 2 | 1177 | /***************************************************************************************************
* ndims.swift
*
* This file provides functionality for finding the dimensionality of a matrix.
*
* Author: Philip Erickson
* Creation Date: 1 May 2016
*
* 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.
*
* Copyright 2016 Philip Erickson
**************************************************************************************************/
/// Provide the number of matrix dimensions.
///
/// - Parameters
/// - A: given matrix
/// - Returns: dimensionality of the given matrix
public func ndims<T>(_ A: Matrix<T>) -> Int
{
return A.size.count
} | apache-2.0 |
suragch/MongolAppDevelopment-iOS | Mongol App ComponantsTests/ScalarStringTests.swift | 1 | 9088 |
import XCTest
@testable import Mongol_App_Componants
class ScalarStringTests: XCTestCase {
// MARK: - indexOf
func testIndexOf_zeroLength_nil() {
// Arrange
let string = ScalarString("abc")
let emptyString = ScalarString()
// Assert
XCTAssertEqual(string.indexOf(emptyString), nil)
XCTAssertEqual(emptyString.indexOf(string), nil)
XCTAssertEqual(emptyString.indexOf(emptyString), nil)
}
func testIndexOf_singleInLongStringWithManyMatches_firstMatch() {
// Arrange
let single = ScalarString("c")
let longString = ScalarString("abcabcabc")
// Act
let index = longString.indexOf(single)
// Assert
XCTAssertEqual(index, 2)
}
func testIndexOf_longInLongStringWithManyMatches_firstMatch() {
// Arrange
let long = ScalarString("abc")
let longString = ScalarString("...abc..abc,,,abc")
// Act
let index = longString.indexOf(long)
// Assert
XCTAssertEqual(index, 3)
}
func testIndexOf_longStringinShortString_nil() {
// Arrange
let longString = ScalarString("abcabcabc")
let shortString = ScalarString("abc")
// Act
let index = shortString.indexOf(longString)
// Assert
XCTAssertEqual(index, nil)
}
func testIndexOf_noMatchSingle_nil() {
// Arrange
let string = ScalarString("123456789qwerty")
let single = ScalarString("a")
// Act
let index = string.indexOf(single)
// Assert
XCTAssertEqual(index, nil)
}
func testIndexOf_noMatchString_nil() {
// Arrange
let longstring = ScalarString("123456789qwerty")
let short = ScalarString("abc")
// Act
let index = longstring.indexOf(short)
// Assert
XCTAssertEqual(index, nil)
}
func testIndexOf_equalStrings_zero() {
// Arrange
let longstring = ScalarString("abc")
let short = ScalarString("abc")
// Act
let index = longstring.indexOf(short)
// Assert
XCTAssertEqual(index, 0)
}
// MARK: - insert
func testInsertString_normalConditions_stringWithInsertAtIndex() {
// Arrange
let originalCopy = ScalarString("0123")
var mutatingCopy = originalCopy
let stringToInsert = "abc"
let index = 2
// Act
mutatingCopy.insert(stringToInsert, atIndex: index)
// Assert
XCTAssertEqual(mutatingCopy.toString(), "01abc23")
}
// MARK: - remove
func testRemoveRange_rangeOutOfBounts_nil() {
// Arrange
let string = ScalarString("abc")
let range = 4..<9
// Act
let newString = string.removeRange(range)
// Assert
XCTAssertEqual(newString, nil)
}
func testRemoveRange_normalRange_shortenedString() {
// Arrange
let string = ScalarString("This is a test.")
let range = 4..<9
// Act
let newString = string.removeRange(range)?.toString()
let expected = "This test."
// Assert
XCTAssertEqual(newString, expected)
}
// FIXME: how to me CountableClosedRange supported? Is it needed?
/*func testRemoveRange_wholeRange_zeroLengthString() {
// Arrange
let string = ScalarString("abc")
let range = 0...2
// Act
let newString = string.removeRange(range)
let expected = ScalarString()
// Assert
XCTAssertEqual(newString, expected)
}*/
// MARK: - replace
func testReplaceRange_normalRange_newString() {
// Arrange
let string = ScalarString("aabbcc")
let replacementString = ScalarString("123")
let range = 2..<4
// Act
let newString = string.replaceRange(range, withString: replacementString)
let expected = ScalarString("aa123cc")
// Assert
XCTAssertEqual(newString, expected)
}
func testReplaceRange_beginningRange_newString() {
// Arrange
let string = ScalarString("aabbcc")
let replacementString = ScalarString("123")
let range = 0..<4
// Act
let newString = string.replaceRange(range, withString: replacementString)
let expected = ScalarString("123cc")
// Assert
XCTAssertEqual(newString, expected)
}
func testReplaceRange_endRange_newString() {
// Arrange
let string = ScalarString("aabbcc")
let replacementString = ScalarString("123")
let range = 2..<6
// Act
let newString = string.replaceRange(range, withString: replacementString)
let expected = ScalarString("aa123")
// Assert
XCTAssertEqual(newString, expected)
}
func testReplaceRange_fullRange_newString() {
// Arrange
let string = ScalarString("aabbcc")
let replacementString = ScalarString("123")
let range = 0..<6
// Act
let newString = string.replaceRange(range, withString: replacementString)
let expected = ScalarString("123")
// Assert
XCTAssertEqual(newString, expected)
}
func testReplaceRange_emptyRange_oldString() {
// Arrange
let string = ScalarString("aabbcc")
let replacementString = ScalarString("123")
let range = 3..<3
// Act
let newString = string.replaceRange(range, withString: replacementString)
let expected = ScalarString("aabbcc")
// Assert
XCTAssertEqual(newString, expected)
}
func testReplaceRange_singleValueRange_newString() {
// Arrange
let string = ScalarString("aabbcc")
let replacementString = ScalarString("123")
let range = 3..<4
// Act
let newString = string.replaceRange(range, withString: replacementString)
let expected = ScalarString("aab123cc")
// Assert
XCTAssertEqual(newString, expected)
}
// MARK: - split
func testSplit_emptyString_emptyArray() {
// Arrange
let string = ScalarString("")
let space = ScalarString(" ").charAt(0)
// Act
let newString = string.split(atChar: space)
let expected: [ScalarString] = []
// Assert
XCTAssertEqual(newString, expected)
}
func testSplit_normalString_arrayOfParts() {
// Arrange
let string = ScalarString("a test.")
let space = ScalarString(" ").charAt(0)
// Act
let newString = string.split(atChar: space)
let expected = [ScalarString("a"), ScalarString("test.")]
// Assert
XCTAssertEqual(newString, expected)
}
func testSplit_noMatch_arrayOfOne() {
// Arrange
let string = ScalarString("aTest.")
let space = ScalarString(" ").charAt(0)
// Act
let newString = string.split(atChar: space)
let expected = [ScalarString("aTest.")]
// Assert
XCTAssertEqual(newString, expected)
}
// MARK: - trim
func testTrim_allWhiteSpace_emptyString() {
// Arrange
let myString = ScalarString(" \n \t ")
// Act
let newString = myString.trim()
// Assert
XCTAssertEqual(newString, ScalarString())
}
func testTrim_emptyString_emptyString() {
// Arrange
let myString = ScalarString("")
// Act
let newString = myString.trim()
// Assert
XCTAssertEqual(newString, ScalarString())
}
func testTrim_normalCase_substring() {
// Arrange
let myString = ScalarString(" \thello hi \n")
// Act
let newString = myString.trim()
// Assert
XCTAssertEqual(newString, ScalarString("hello hi"))
}
func testTrim_singleChar_singleChar() {
// Arrange
let myString = ScalarString("a")
// Act
let newString = myString.trim()
// Assert
XCTAssertEqual(newString, ScalarString("a"))
}
}
| mit |
JGiola/swift | test/SILOptimizer/devirt_protocol_method_invocations.swift | 1 | 10450 |
// RUN: %target-swift-frontend -module-name devirt_protocol_method_invocations -enable-spec-devirt -O -Xllvm -sil-disable-pass=ExistentialSpecializer -emit-sil %s | %FileCheck %s
protocol PPP {
func f()
}
protocol QQQ : PPP {
}
protocol RRR : QQQ {
}
struct S : RRR {}
extension QQQ {
@_optimize(none)
func f() {}
}
// Test that all witness_method instructions are devirtualized.
// This test used to crash the compiler because it uses inherited conformances.
// CHECK-LABEL: sil @$s34devirt_protocol_method_invocations24testInheritedConformanceyyF : $@convention(thin) () -> ()
// CHECK-NOT: witness_method
// CHECK-NOT: class_method
// CHECK: apply
// CHECK: // end sil function '$s34devirt_protocol_method_invocations24testInheritedConformanceyyF'
public func testInheritedConformance() {
(S() as QQQ).f()
}
// Test that a witness_method instruction using an indirectly-inherited conformance
// is devirtualized.
//
// This test used to crash the compiler because it uses inherited conformances.
// CHECK-LABEL: sil @$s34devirt_protocol_method_invocations34testIndirectlyInheritedConformanceyyF : $@convention(thin) () -> ()
// CHECK-NOT: witness_method
// CHECK: apply
// CHECK: // end sil function '$s34devirt_protocol_method_invocations34testIndirectlyInheritedConformanceyyF'
public func testIndirectlyInheritedConformance() {
(S() as RRR).f()
}
public protocol Foo {
func foo(_ x:Int) -> Int
}
public extension Foo {
func boo(_ x:Int) -> Int32 {
return 2222 + Int32(x)
}
func getSelf() -> Self {
return self
}
}
var gg = 1111
open class C : Foo {
@inline(never)
open func foo(_ x:Int) -> Int {
gg += 1
return gg + x
}
}
@_transparent
func callfoo(_ f: Foo) -> Int {
return f.foo(2) + f.foo(2)
}
@_transparent
func callboo(_ f: Foo) -> Int32 {
return f.boo(2) + f.boo(2)
}
@_transparent
func callGetSelf(_ f: Foo) -> Foo {
return f.getSelf()
}
// Check that methods returning Self are not devirtualized and do not crash the compiler.
// CHECK-LABEL: sil [noinline] {{.*}}@$s34devirt_protocol_method_invocations05test_a1_b11_extension_C33_invocation_with_self_return_typeyAA3Foo_pAA1CCF
// CHECK: init_existential_addr
// CHECK: open_existential_addr
// CHECK: return
@inline(never)
public func test_devirt_protocol_extension_method_invocation_with_self_return_type(_ c: C) -> Foo {
return callGetSelf(c)
}
// Check that calls to f.foo() get devirtualized and are not invoked
// via the expensive witness_method instruction.
// To achieve that the information about a concrete type C should
// be propagated from init_existential_addr into witness_method and
// apply instructions.
// CHECK-LABEL: sil [noinline] @$s34devirt_protocol_method_invocations05test_a1_b1_C11_invocationySiAA1CCF
// CHECK-NOT: witness_method
// CHECK: checked_cast
// CHECK-NOT: checked_cast
// CHECK: bb1(
// CHECK-NOT: checked_cast
// CHECK: return
// CHECK: bb2(
// CHECK-NOT: checked_cast
// CHECK: function_ref
// CHECK: apply
// CHECK: apply
// CHECK: br bb1(
// CHECK: bb3
// CHECK-NOT: checked_cast
// CHECK: apply
// CHECK: apply
// CHECK: br bb1(
// Check that calls of a method boo() from the protocol extension
// get devirtualized and are not invoked via the expensive witness_method instruction
// or by passing an existential as a parameter.
// To achieve that the information about a concrete type C should
// be propagated from init_existential_addr into apply instructions.
// In fact, the call is expected to be inlined and then constant-folded
// into a single integer constant.
// CHECK-LABEL: sil [noinline] {{.*}}@$s34devirt_protocol_method_invocations05test_a1_b11_extension_C11_invocationys5Int32VAA1CCF
// CHECK-NOT: checked_cast
// CHECK-NOT: open_existential
// CHECK-NOT: witness_method
// CHECK-NOT: apply
// CHECK: integer_literal
// CHECK: return
// CHECK: sil @$s34devirt_protocol_method_invocations12test24114020SiyF
// CHECK: [[T0:%.*]] = integer_literal $Builtin.Int{{.*}}, 1
// CHECK: [[T1:%.*]] = struct $Int ([[T0]] : $Builtin.Int{{.*}})
// CHECK: return [[T1]]
// CHECK: sil @$s34devirt_protocol_method_invocations14testExMetatypeSiyF
// CHECK: [[T0:%.*]] = integer_literal
// CHECK: [[T2:%.*]] = struct $Int ([[T0]] : {{.*}})
// CHECK: return [[T2]] : $Int
@inline(never)
public func test_devirt_protocol_method_invocation(_ c: C) -> Int {
return callfoo(c)
}
@inline(never)
public func test_devirt_protocol_extension_method_invocation(_ c: C) -> Int32 {
return callboo(c)
}
// Make sure that we are not crashing with an assertion due to specialization
// of methods with the Self return type as an argument.
// rdar://20868966
protocol Proto {
func f() -> Self
}
class CC : Proto {
func f() -> Self { return self }
}
func callDynamicSelfExistential(_ p: Proto) {
p.f()
}
public func testSelfReturnType() {
callDynamicSelfExistential(CC())
}
// Make sure that we are not crashing with an assertion due to specialization
// of methods with the Self return type.
// rdar://20955745.
protocol CP : class { func f() -> Self }
func callDynamicSelfClassExistential(_ cp: CP) { cp.f() }
class PP : CP {
func f() -> Self { return self }
}
callDynamicSelfClassExistential(PP())
// Make sure we handle indirect conformances.
// rdar://24114020
protocol Base {
var x: Int { get }
}
protocol Derived : Base {
}
struct SimpleBase : Derived {
var x: Int
}
public func test24114020() -> Int {
let base: Derived = SimpleBase(x: 1)
return base.x
}
protocol StaticP {
static var size: Int { get }
}
struct HasStatic<T> : StaticP {
static var size: Int { return MemoryLayout<T>.size }
}
public func testExMetatype() -> Int {
let type: StaticP.Type = HasStatic<Int>.self
return type.size
}
// rdar://32288618
public func testExMetatypeVar() -> Int {
var type: StaticP.Type = HasStatic<Int>.self
return type.size
}
// IRGen used to crash on the testPropagationOfConcreteTypeIntoExistential method.
// rdar://26286278
protocol MathP {
var sum: Int32 { get nonmutating set }
func done()
}
extension MathP {
@inline(never)
func plus() -> Self {
sum += 1
return self
}
@inline(never)
func minus() {
sum -= 1
if sum == 0 {
done()
}
}
}
protocol MathA : MathP {}
public final class V {
var a: MathA
init(a: MathA) {
self.a = a
}
}
// Check that all witness_method invocations are devirtualized.
// CHECK-LABEL: sil [noinline] {{.*}}@$s34devirt_protocol_method_invocations44testPropagationOfConcreteTypeIntoExistential1v1xyAA1VC_s5Int32VtF
// CHECK-NOT: witness_method
// CHECK-NOT: class_method
// CHECK: return
@inline(never)
public func testPropagationOfConcreteTypeIntoExistential(v: V, x: Int32) {
let y = v.a.plus()
defer {
y.minus()
}
}
// Check that we don't attempt to cast an opened type to a concrete
// type inferred via ProtocolConformanceAnalysis if the type requires
// reabstraction when erased by an existential.
protocol ReabstractedP {
func f()
}
extension Optional : ReabstractedP {
func f() {}
}
// CHECK-LABEL: sil hidden [noinline] {{.*}}@$s34devirt_protocol_method_invocations23testReabstractedWitnessyyAA0F1P_pF : $@convention(thin) (@in_guaranteed ReabstractedP) -> () {
// CHECK: bb0(%0 : $*ReabstractedP):
// CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access %0 : $*ReabstractedP to $*@opened([[ID:.*]], ReabstractedP) Self
// CHECK: [[WM:%.*]] = witness_method $@opened([[ID]], ReabstractedP) Self, #ReabstractedP.f : <Self where Self : ReabstractedP> (Self) -> () -> (), [[OPEN]] : $*@opened([[ID]], ReabstractedP) Self : $@convention(witness_method: ReabstractedP) <τ_0_0 where τ_0_0 : ReabstractedP> (@in_guaranteed τ_0_0) -> ()
// CHECK: apply [[WM]]<@opened([[ID]], ReabstractedP) Self>([[OPEN]]) : $@convention(witness_method: ReabstractedP) <τ_0_0 where τ_0_0 : ReabstractedP> (@in_guaranteed τ_0_0) -> ()
// CHECK-LABEL: } // end sil function '$s34devirt_protocol_method_invocations23testReabstractedWitnessyyAA0F1P_pF'
@inline(never)
func testReabstractedWitness(_ f: ReabstractedP) {
f.f()
}
public func testReabstracted(f: Optional<()->()>) {
testReabstractedWitness(f)
}
// Test that we don't devirtualize calls to protocol requirements with
// covariant `Self`-rooted type parameters nested inside a collection type;
// the devirtualizer doesn't know how to handle these yet.
protocol CovariantSelfInCollection {
associatedtype Assoc
func self1() -> Array<Self>
func self2() -> Dictionary<String, Self>
func self3(_: (Self...) -> Void)
func self4(_: (Array<(Dictionary<String, String>, Self)>) -> Void)
func assoc1() -> Array<Assoc>
func assoc2() -> Dictionary<String, Assoc>
func assoc3(_: (Assoc...) -> Void)
func assoc4(_: (Array<(Dictionary<String, String>, Assoc)>) -> Void)
}
struct CovariantSelfInCollectionImpl: CovariantSelfInCollection {
typealias Assoc = Bool
func self1() -> Array<Self> { [self] }
func self2() -> Dictionary<String, Self> { [#file : self] }
func self3(_: (Self...) -> Void) {}
func self4(_: (Array<(Dictionary<String, String>, Self)>) -> Void) {}
func assoc1() -> Array<Assoc> { [true] }
func assoc2() -> Dictionary<String, Assoc> { [#file : true] }
func assoc3(_: (Assoc...) -> Void) {}
func assoc4(_: (Array<(Dictionary<String, String>, Assoc)>) -> Void) {}
}
// CHECK-LABEL: sil @$s34devirt_protocol_method_invocations12testNoDevirtyyF
//
// CHECK: witness_method $CovariantSelfInCollectionImpl, #CovariantSelfInCollection.self1
// CHECK: witness_method $CovariantSelfInCollectionImpl, #CovariantSelfInCollection.self2
// CHECK: witness_method $CovariantSelfInCollectionImpl, #CovariantSelfInCollection.self3
// CHECK: witness_method $CovariantSelfInCollectionImpl, #CovariantSelfInCollection.self4
// CHECK: witness_method $CovariantSelfInCollectionImpl, #CovariantSelfInCollection.assoc1
// CHECK: witness_method $CovariantSelfInCollectionImpl, #CovariantSelfInCollection.assoc2
// CHECK: witness_method $CovariantSelfInCollectionImpl, #CovariantSelfInCollection.assoc3
// CHECK: witness_method $CovariantSelfInCollectionImpl, #CovariantSelfInCollection.assoc4
// CHECK: end sil function '$s34devirt_protocol_method_invocations12testNoDevirtyyF'
public func testNoDevirt() {
let p: any CovariantSelfInCollection = CovariantSelfInCollectionImpl()
_ = p.self1()
_ = p.self2()
p.self3 { _ in }
p.self4 { _ in }
_ = p.assoc1()
_ = p.assoc2()
p.assoc3 { _ in }
p.assoc4 { _ in }
}
| apache-2.0 |
makezwl/zhao | NimbleTests/Matchers/BeginWithTest.swift | 80 | 1447 | import XCTest
import Nimble
class BeginWithTest: XCTestCase {
func testPositiveMatches() {
expect([1, 2, 3]).to(beginWith(1))
expect([1, 2, 3]).toNot(beginWith(2))
expect("foobar").to(beginWith("foo"))
expect("foobar").toNot(beginWith("oo"))
expect(NSString(string: "foobar")).to(beginWith("foo"))
expect(NSString(string: "foobar")).toNot(beginWith("oo"))
expect(NSArray(array: ["a", "b"])).to(beginWith("a"))
expect(NSArray(array: ["a", "b"])).toNot(beginWith("b"))
}
func testNegativeMatches() {
failsWithErrorMessageForNil("expected to begin with <b>, got <nil>") {
expect(nil as NSArray?).to(beginWith("b"))
}
failsWithErrorMessageForNil("expected to not begin with <b>, got <nil>") {
expect(nil as NSArray?).toNot(beginWith("b"))
}
failsWithErrorMessage("expected to begin with <2>, got <[1, 2, 3]>") {
expect([1, 2, 3]).to(beginWith(2))
}
failsWithErrorMessage("expected to not begin with <1>, got <[1, 2, 3]>") {
expect([1, 2, 3]).toNot(beginWith(1))
}
failsWithErrorMessage("expected to begin with <atm>, got <batman>") {
expect("batman").to(beginWith("atm"))
}
failsWithErrorMessage("expected to not begin with <bat>, got <batman>") {
expect("batman").toNot(beginWith("bat"))
}
}
}
| apache-2.0 |
arvedviehweger/swift | test/decl/ext/protocol.swift | 1 | 22275 | // RUN: %target-typecheck-verify-swift
// ----------------------------------------------------------------------------
// Using protocol requirements from inside protocol extensions
// ----------------------------------------------------------------------------
protocol P1 {
@discardableResult
func reqP1a() -> Bool
}
extension P1 {
func extP1a() -> Bool { return !reqP1a() }
var extP1b: Bool {
return self.reqP1a()
}
var extP1c: Bool {
return extP1b && self.extP1a()
}
}
protocol P2 {
associatedtype AssocP2 : P1
func reqP2a() -> AssocP2
}
extension P2 {
func extP2a() -> AssocP2? { return reqP2a() }
func extP2b() {
self.reqP2a().reqP1a()
}
func extP2c() -> Self.AssocP2 { return extP2a()! }
}
protocol P3 {
associatedtype AssocP3 : P2
func reqP3a() -> AssocP3
}
extension P3 {
func extP3a() -> AssocP3.AssocP2 {
return reqP3a().reqP2a()
}
}
protocol P4 {
associatedtype AssocP4
func reqP4a() -> AssocP4
}
// ----------------------------------------------------------------------------
// Using generics from inside protocol extensions
// ----------------------------------------------------------------------------
func acceptsP1<T : P1>(_ t: T) { }
extension P1 {
func extP1d() { acceptsP1(self) }
}
func acceptsP2<T : P2>(_ t: T) { }
extension P2 {
func extP2acceptsP1() { acceptsP1(reqP2a()) }
func extP2acceptsP2() { acceptsP2(self) }
}
// Use of 'Self' as a return type within a protocol extension.
protocol SelfP1 {
associatedtype AssocType
}
protocol SelfP2 {
}
func acceptSelfP1<T, U : SelfP1>(_ t: T, _ u: U) -> T where U.AssocType == T {
return t
}
extension SelfP1 {
func tryAcceptSelfP1<Z : SelfP1>(_ z: Z)-> Self where Z.AssocType == Self {
return acceptSelfP1(self, z)
}
}
// ----------------------------------------------------------------------------
// Initializers in protocol extensions
// ----------------------------------------------------------------------------
protocol InitP1 {
init(string: String)
}
extension InitP1 {
init(int: Int) { self.init(string: "integer") }
}
struct InitS1 : InitP1 {
init(string: String) { }
}
class InitC1 : InitP1 {
required init(string: String) { }
}
func testInitP1() {
var is1 = InitS1(int: 5)
is1 = InitS1(string: "blah") // check type
_ = is1
var ic1 = InitC1(int: 5)
ic1 = InitC1(string: "blah") // check type
_ = ic1
}
// ----------------------------------------------------------------------------
// Subscript in protocol extensions
// ----------------------------------------------------------------------------
protocol SubscriptP1 {
func readAt(_ i: Int) -> String
func writeAt(_ i: Int, string: String)
}
extension SubscriptP1 {
subscript(i: Int) -> String {
get { return readAt(i) }
set(newValue) { writeAt(i, string: newValue) }
}
}
struct SubscriptS1 : SubscriptP1 {
func readAt(_ i: Int) -> String { return "hello" }
func writeAt(_ i: Int, string: String) { }
}
struct SubscriptC1 : SubscriptP1 {
func readAt(_ i: Int) -> String { return "hello" }
func writeAt(_ i: Int, string: String) { }
}
func testSubscriptP1(_ ss1: SubscriptS1, sc1: SubscriptC1,
i: Int, s: String) {
var ss1 = ss1
var sc1 = sc1
_ = ss1[i]
ss1[i] = s
_ = sc1[i]
sc1[i] = s
}
// ----------------------------------------------------------------------------
// Using protocol extensions on types that conform to the protocols.
// ----------------------------------------------------------------------------
struct S1 : P1 {
@discardableResult
func reqP1a() -> Bool { return true }
func once() -> Bool {
return extP1a() && extP1b
}
}
func useS1(_ s1: S1) -> Bool {
s1.reqP1a()
return s1.extP1a() && s1.extP1b
}
extension S1 {
func twice() -> Bool {
return extP1a() && extP1b
}
}
// ----------------------------------------------------------------------------
// Protocol extensions with additional requirements
// ----------------------------------------------------------------------------
extension P4 where Self.AssocP4 : P1 {
func extP4a() { // expected-note 2 {{found this candidate}}
acceptsP1(reqP4a())
}
}
struct S4aHelper { }
struct S4bHelper : P1 {
func reqP1a() -> Bool { return true }
}
struct S4a : P4 {
func reqP4a() -> S4aHelper { return S4aHelper() }
}
struct S4b : P4 {
func reqP4a() -> S4bHelper { return S4bHelper() }
}
struct S4c : P4 {
func reqP4a() -> Int { return 0 }
}
struct S4d : P4 {
func reqP4a() -> Bool { return false }
}
extension P4 where Self.AssocP4 == Int {
func extP4Int() { }
}
extension P4 where Self.AssocP4 == Bool {
func extP4a() -> Bool { return reqP4a() } // expected-note 2 {{found this candidate}}
}
func testP4(_ s4a: S4a, s4b: S4b, s4c: S4c, s4d: S4d) {
s4a.extP4a() // expected-error{{ambiguous reference to member 'extP4a()'}}
s4b.extP4a() // ok
s4c.extP4a() // expected-error{{ambiguous reference to member 'extP4a()'}}
s4c.extP4Int() // okay
var b1 = s4d.extP4a() // okay, "Bool" version
b1 = true // checks type above
s4d.extP4Int() // expected-error{{'Bool' is not convertible to 'Int'}}
_ = b1
}
// ----------------------------------------------------------------------------
// Protocol extensions with a superclass constraint on Self
// ----------------------------------------------------------------------------
protocol ConformedProtocol {
typealias ConcreteConformanceAlias = Self
}
class BaseWithAlias<T> : ConformedProtocol {
typealias ConcreteAlias = T
func baseMethod(_: T) {}
}
class DerivedWithAlias : BaseWithAlias<Int> {}
protocol ExtendedProtocol {
typealias AbstractConformanceAlias = Self
}
extension ExtendedProtocol where Self : DerivedWithAlias {
func f0(x: T) {} // expected-error {{use of undeclared type 'T'}}
func f1(x: ConcreteAlias) {
let _: Int = x
baseMethod(x)
}
func f2(x: ConcreteConformanceAlias) {
let _: DerivedWithAlias = x
}
func f3(x: AbstractConformanceAlias) {
let _: DerivedWithAlias = x
}
}
// ----------------------------------------------------------------------------
// Using protocol extensions to satisfy requirements
// ----------------------------------------------------------------------------
protocol P5 {
func reqP5a()
}
// extension of P5 provides a witness for P6
extension P5 {
func reqP6a() { reqP5a() }
}
protocol P6 {
func reqP6a()
}
// S6a uses P5.reqP6a
struct S6a : P5 {
func reqP5a() { }
}
extension S6a : P6 { }
// S6b uses P5.reqP6a
struct S6b : P5, P6 {
func reqP5a() { }
}
// S6c uses P5.reqP6a
struct S6c : P6 {
}
extension S6c : P5 {
func reqP5a() { }
}
// S6d does not use P5.reqP6a
struct S6d : P6 {
func reqP6a() { }
}
extension S6d : P5 {
func reqP5a() { }
}
protocol P7 {
associatedtype P7Assoc
func getP7Assoc() -> P7Assoc
}
struct P7FromP8<T> { }
protocol P8 {
associatedtype P8Assoc
func getP8Assoc() -> P8Assoc
}
// extension of P8 provides conformance to P7Assoc
extension P8 {
func getP7Assoc() -> P7FromP8<P8Assoc> { return P7FromP8() }
}
// Okay, P7 requirements satisfied by P8
struct P8a : P8, P7 {
func getP8Assoc() -> Bool { return true }
}
func testP8a(_ p8a: P8a) {
var p7 = p8a.getP7Assoc()
p7 = P7FromP8<Bool>() // okay, check type of above
_ = p7
}
// Okay, P7 requirements explicitly specified
struct P8b : P8, P7 {
func getP7Assoc() -> Int { return 5 }
func getP8Assoc() -> Bool { return true }
}
func testP8b(_ p8b: P8b) {
var p7 = p8b.getP7Assoc()
p7 = 17 // check type of above
_ = p7
}
protocol PConforms1 {
}
extension PConforms1 {
func pc2() { } // expected-note{{candidate exactly matches}}
}
protocol PConforms2 : PConforms1, MakePC2Ambiguous {
func pc2() // expected-note{{multiple matching functions named 'pc2()' with type '() -> ()'}}
}
protocol MakePC2Ambiguous {
}
extension MakePC2Ambiguous {
func pc2() { } // expected-note{{candidate exactly matches}}
}
struct SConforms2a : PConforms2 { } // expected-error{{type 'SConforms2a' does not conform to protocol 'PConforms2'}}
struct SConforms2b : PConforms2 {
func pc2() { }
}
// Satisfying requirements via protocol extensions for fun and profit
protocol _MySeq { }
protocol MySeq : _MySeq {
associatedtype Generator : IteratorProtocol
func myGenerate() -> Generator
}
protocol _MyCollection : _MySeq {
associatedtype Index : Strideable
var myStartIndex : Index { get }
var myEndIndex : Index { get }
associatedtype _Element
subscript (i: Index) -> _Element { get }
}
protocol MyCollection : _MyCollection {
}
struct MyIndexedIterator<C : _MyCollection> : IteratorProtocol {
var container: C
var index: C.Index
mutating func next() -> C._Element? {
if index == container.myEndIndex { return nil }
let result = container[index]
index = index.advanced(by: 1)
return result
}
}
struct OtherIndexedIterator<C : _MyCollection> : IteratorProtocol {
var container: C
var index: C.Index
mutating func next() -> C._Element? {
if index == container.myEndIndex { return nil }
let result = container[index]
index = index.advanced(by: 1)
return result
}
}
extension _MyCollection {
func myGenerate() -> MyIndexedIterator<Self> {
return MyIndexedIterator(container: self, index: self.myEndIndex)
}
}
struct SomeCollection1 : MyCollection {
var myStartIndex: Int { return 0 }
var myEndIndex: Int { return 10 }
subscript (i: Int) -> String {
return "blah"
}
}
struct SomeCollection2 : MyCollection {
var myStartIndex: Int { return 0 }
var myEndIndex: Int { return 10 }
subscript (i: Int) -> String {
return "blah"
}
func myGenerate() -> OtherIndexedIterator<SomeCollection2> {
return OtherIndexedIterator(container: self, index: self.myEndIndex)
}
}
func testSomeCollections(_ sc1: SomeCollection1, sc2: SomeCollection2) {
var mig = sc1.myGenerate()
mig = MyIndexedIterator(container: sc1, index: sc1.myStartIndex)
_ = mig
var ig = sc2.myGenerate()
ig = MyIndexedIterator(container: sc2, index: sc2.myStartIndex) // expected-error {{cannot assign value of type 'MyIndexedIterator<SomeCollection2>' to type 'OtherIndexedIterator<SomeCollection2>'}}
_ = ig
}
public protocol PConforms3 {}
extension PConforms3 {
public var z: Int {
return 0
}
}
public protocol PConforms4 : PConforms3 {
var z: Int { get }
}
struct PConforms4Impl : PConforms4 {}
let pc4z = PConforms4Impl().z
// rdar://problem/20608438
protocol PConforms5 {
func f() -> Int
}
protocol PConforms6 : PConforms5 {}
extension PConforms6 {
func f() -> Int { return 42 }
}
func test<T: PConforms6>(_ x: T) -> Int { return x.f() }
struct PConforms6Impl : PConforms6 { }
// Extensions of a protocol that directly satisfy requirements (i.e.,
// default implementations hack N+1).
protocol PConforms7 {
func method()
var property: Int { get }
subscript (i: Int) -> Int { get }
}
extension PConforms7 {
func method() { }
var property: Int { return 5 }
subscript (i: Int) -> Int { return i }
}
struct SConforms7a : PConforms7 { }
protocol PConforms8 {
associatedtype Assoc
func method() -> Assoc
var property: Assoc { get }
subscript (i: Assoc) -> Assoc { get }
}
extension PConforms8 {
func method() -> Int { return 5 }
var property: Int { return 5 }
subscript (i: Int) -> Int { return i }
}
struct SConforms8a : PConforms8 { }
struct SConforms8b : PConforms8 {
func method() -> String { return "" }
var property: String { return "" }
subscript (i: String) -> String { return i }
}
func testSConforms8b() {
let s: SConforms8b.Assoc = "hello"
_ = s
}
struct SConforms8c : PConforms8 {
func method() -> String { return "" }
}
func testSConforms8c() {
let s: SConforms8c.Assoc = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'SConforms8c.Assoc' (aka 'Int')}}
_ = s
let i: SConforms8c.Assoc = 5
_ = i
}
protocol DefaultInitializable {
init()
}
extension String : DefaultInitializable { }
extension Int : DefaultInitializable { }
protocol PConforms9 {
associatedtype Assoc : DefaultInitializable // expected-note{{protocol requires nested type 'Assoc'}}
func method() -> Assoc
var property: Assoc { get }
subscript (i: Assoc) -> Assoc { get }
}
extension PConforms9 {
func method() -> Self.Assoc { return Assoc() }
var property: Self.Assoc { return Assoc() }
subscript (i: Self.Assoc) -> Self.Assoc { return Assoc() }
}
struct SConforms9a : PConforms9 { // expected-error{{type 'SConforms9a' does not conform to protocol 'PConforms9'}}
}
struct SConforms9b : PConforms9 {
typealias Assoc = Int
}
func testSConforms9b(_ s9b: SConforms9b) {
var p = s9b.property
p = 5
_ = p
}
struct SConforms9c : PConforms9 {
typealias Assoc = String
}
func testSConforms9c(_ s9c: SConforms9c) {
var p = s9c.property
p = "hello"
_ = p
}
struct SConforms9d : PConforms9 {
func method() -> Int { return 5 }
}
func testSConforms9d(_ s9d: SConforms9d) {
var p = s9d.property
p = 6
_ = p
}
protocol PConforms10 {}
extension PConforms10 {
func f() {}
}
protocol PConforms11 {
func f()
}
struct SConforms11 : PConforms10, PConforms11 {}
// ----------------------------------------------------------------------------
// Typealiases in protocol extensions.
// ----------------------------------------------------------------------------
// Basic support
protocol PTypeAlias1 {
associatedtype AssocType1
}
extension PTypeAlias1 {
typealias ArrayOfAssocType1 = [AssocType1]
}
struct STypeAlias1a: PTypeAlias1 {
typealias AssocType1 = Int
}
struct STypeAlias1b<T>: PTypeAlias1 {
typealias AssocType1 = T
}
func testPTypeAlias1() {
var a: STypeAlias1a.ArrayOfAssocType1 = []
a.append(1)
var b: STypeAlias1b<String>.ArrayOfAssocType1 = []
b.append("hello")
}
// Defaulted implementations to satisfy a requirement.
struct TypeAliasHelper<T> { }
protocol PTypeAliasSuper2 {
}
extension PTypeAliasSuper2 {
func foo() -> TypeAliasHelper<Self> { return TypeAliasHelper() }
}
protocol PTypeAliasSub2 : PTypeAliasSuper2 {
associatedtype Helper
func foo() -> Helper
}
struct STypeAliasSub2a : PTypeAliasSub2 { }
struct STypeAliasSub2b<T, U> : PTypeAliasSub2 { }
// ----------------------------------------------------------------------------
// Partial ordering of protocol extension members
// ----------------------------------------------------------------------------
// Partial ordering between members of protocol extensions and members
// of concrete types.
struct S1b : P1 {
func reqP1a() -> Bool { return true }
func extP1a() -> Int { return 0 }
}
func useS1b(_ s1b: S1b) {
var x = s1b.extP1a() // uses S1b.extP1a due to partial ordering
x = 5 // checks that "x" deduced to "Int" above
_ = x
var _: Bool = s1b.extP1a() // still uses P1.ext1Pa due to type annotation
}
// Partial ordering between members of protocol extensions for
// different protocols.
protocol PInherit1 { }
protocol PInherit2 : PInherit1 { }
protocol PInherit3 : PInherit2 { }
protocol PInherit4 : PInherit2 { }
extension PInherit1 {
func order1() -> Int { return 0 }
}
extension PInherit2 {
func order1() -> Bool { return true }
}
extension PInherit3 {
func order1() -> Double { return 1.0 }
}
extension PInherit4 {
func order1() -> String { return "hello" }
}
struct SInherit1 : PInherit1 { }
struct SInherit2 : PInherit2 { }
struct SInherit3 : PInherit3 { }
struct SInherit4 : PInherit4 { }
func testPInherit(_ si2 : SInherit2, si3: SInherit3, si4: SInherit4) {
var b1 = si2.order1() // PInherit2.order1
b1 = true // check that the above returned Bool
_ = b1
var d1 = si3.order1() // PInherit3.order1
d1 = 3.14159 // check that the above returned Double
_ = d1
var s1 = si4.order1() // PInherit4.order1
s1 = "hello" // check that the above returned String
_ = s1
// Other versions are still visible, since they may have different
// types.
b1 = si3.order1() // PInherit2.order1
var _: Int = si3.order1() // PInherit1.order1
}
protocol PConstrained1 {
associatedtype AssocTypePC1
}
extension PConstrained1 {
func pc1() -> Int { return 0 }
}
extension PConstrained1 where AssocTypePC1 : PInherit2 {
func pc1() -> Bool { return true }
}
extension PConstrained1 where Self.AssocTypePC1 : PInherit3 {
func pc1() -> String { return "hello" }
}
struct SConstrained1 : PConstrained1 {
typealias AssocTypePC1 = SInherit1
}
struct SConstrained2 : PConstrained1 {
typealias AssocTypePC1 = SInherit2
}
struct SConstrained3 : PConstrained1 {
typealias AssocTypePC1 = SInherit3
}
func testPConstrained1(_ sc1: SConstrained1, sc2: SConstrained2,
sc3: SConstrained3) {
var i = sc1.pc1() // PConstrained1.pc1
i = 17 // checks type of above
_ = i
var b = sc2.pc1() // PConstrained1 (with PInherit2).pc1
b = true // checks type of above
_ = b
var s = sc3.pc1() // PConstrained1 (with PInherit3).pc1
s = "hello" // checks type of above
_ = s
}
protocol PConstrained2 {
associatedtype AssocTypePC2
}
protocol PConstrained3 : PConstrained2 {
}
extension PConstrained2 where Self.AssocTypePC2 : PInherit1 {
func pc2() -> Bool { return true }
}
extension PConstrained3 {
func pc2() -> String { return "hello" }
}
struct SConstrained3a : PConstrained3 {
typealias AssocTypePC2 = Int
}
struct SConstrained3b : PConstrained3 {
typealias AssocTypePC2 = SInherit3
}
func testSConstrained3(_ sc3a: SConstrained3a, sc3b: SConstrained3b) {
var s = sc3a.pc2() // PConstrained3.pc2
s = "hello"
_ = s
_ = sc3b.pc2()
s = sc3b.pc2()
var _: Bool = sc3b.pc2()
}
extension PConstrained3 where AssocTypePC2 : PInherit1 { }
// Extending via a superclass constraint.
class Superclass {
func foo() { }
static func bar() { }
typealias Foo = Int
}
protocol PConstrained4 { }
extension PConstrained4 where Self : Superclass {
func testFoo() -> Foo {
foo()
self.foo()
return Foo(5)
}
static func testBar() {
bar()
self.bar()
}
}
protocol PConstrained5 { }
protocol PConstrained6 {
associatedtype Assoc
func foo()
}
protocol PConstrained7 { }
extension PConstrained6 {
var prop1: Int { return 0 }
var prop2: Int { return 0 } // expected-note{{'prop2' previously declared here}}
subscript (key: Int) -> Int { return key }
subscript (key: Double) -> Double { return key } // expected-note{{'subscript' previously declared here}}
}
extension PConstrained6 {
var prop2: Int { return 0 } // expected-error{{invalid redeclaration of 'prop2'}}
subscript (key: Double) -> Double { return key } // expected-error{{invalid redeclaration of 'subscript'}}
}
extension PConstrained6 where Assoc : PConstrained5 {
var prop1: Int { return 0 } // okay
var prop3: Int { return 0 } // expected-note{{'prop3' previously declared here}}
subscript (key: Int) -> Int { return key } // ok
subscript (key: String) -> String { return key } // expected-note{{'subscript' previously declared here}}
func foo() { } // expected-note{{'foo()' previously declared here}}
}
extension PConstrained6 where Assoc : PConstrained5 {
var prop3: Int { return 0 } // expected-error{{invalid redeclaration of 'prop3'}}
subscript (key: String) -> String { return key } // expected-error{{invalid redeclaration of 'subscript'}}
func foo() { } // expected-error{{invalid redeclaration of 'foo()'}}
}
extension PConstrained6 where Assoc : PConstrained7 {
var prop1: Int { return 0 } // okay
subscript (key: Int) -> Int { return key } // okay
func foo() { } // okay
}
extension PConstrained6 where Assoc == Int {
var prop4: Int { return 0 }
subscript (key: Character) -> Character { return key }
func foo() { } // okay
}
extension PConstrained6 where Assoc == Double {
var prop4: Int { return 0 } // okay
subscript (key: Character) -> Character { return key } // okay
func foo() { } // okay
}
// Interaction between RawRepresentable and protocol extensions.
public protocol ReallyRaw : RawRepresentable {
}
public extension ReallyRaw where RawValue: SignedInteger {
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
}
enum Foo : Int, ReallyRaw {
case a = 0
}
// ----------------------------------------------------------------------------
// Semantic restrictions
// ----------------------------------------------------------------------------
// Extension cannot have an inheritance clause.
protocol BadProto1 { }
protocol BadProto2 { }
extension BadProto1 : BadProto2 { } // expected-error{{extension of protocol 'BadProto1' cannot have an inheritance clause}}
extension BadProto2 {
struct S { } // expected-error{{type 'S' cannot be nested in protocol extension of 'BadProto2'}}
class C { } // expected-error{{type 'C' cannot be nested in protocol extension of 'BadProto2'}}
enum E { } // expected-error{{type 'E' cannot be nested in protocol extension of 'BadProto2'}}
}
extension BadProto1 {
func foo() { }
var prop: Int { return 0 }
subscript (i: Int) -> String {
return "hello"
}
}
protocol BadProto3 { }
typealias BadProto4 = BadProto3
extension BadProto4 { } // expected-error{{protocol 'BadProto3' in the module being compiled cannot be extended via a type alias}}{{11-20=BadProto3}}
typealias RawRepresentableAlias = RawRepresentable
extension RawRepresentableAlias { } // okay
extension AnyObject { } // expected-error{{'AnyObject' protocol cannot be extended}}
// Members of protocol extensions cannot be overridden.
// rdar://problem/21075287
class BadClass1 : BadProto1 {
func foo() { }
override var prop: Int { return 5 } // expected-error{{property does not override any property from its superclass}}
}
protocol BadProto5 {
associatedtype T1 // expected-note{{protocol requires nested type 'T1'}}
associatedtype T2 // expected-note{{protocol requires nested type 'T2'}}
associatedtype T3 // expected-note{{protocol requires nested type 'T3'}}
}
class BadClass5 : BadProto5 {} // expected-error{{type 'BadClass5' does not conform to protocol 'BadProto5'}}
typealias A = BadProto1
typealias B = BadProto1
extension A & B { // expected-error{{protocol 'BadProto1' in the module being compiled cannot be extended via a type alias}}
}
| apache-2.0 |
austinzheng/swift-compiler-crashes | crashes-duplicates/07881-swift-typebase-getdesugaredtype.swift | 11 | 355 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b: CollectionType where B : e)"
protocol A : a {
typealias e : BooleanType, A : c: e)
protocol A : a {
protocol A {
extension NSData {
}
}
typealias B<A> {
println("
func a
extensi
| mit |
zachmokahn/SUV | Sources/SUV/libUV/Type/UVFSCallback.swift | 1 | 56 | import libUV
public typealias UVFSCallback = uv_fs_cb!
| mit |
CoderLala/DouYZBTest | DouYZB/DouYZB/Classes/Home/Controller/RecommendViewController.swift | 1 | 6127 | //
// RecommendViewController.swift
// DouYZB
//
// Created by 黄金英 on 17/2/4.
// Copyright © 2017年 黄金英. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kItemW = (kScreenWidth - 3 * kItemMargin) / 2
private let kNormalItemH = kItemW * 3 / 4
private let kPrettyItemH = kItemW * 4 / 3
private let kHeaderViewH : CGFloat = 50
private let kCycleViewH = kScreenWidth * 3 / 8
private let kGameViewH : CGFloat = 90
private let kNormalCellID = "kNormalCellID"
private let kPrettyCellID = "kPrettyCellID"
private let kHeaderViewID = "kHeaderViewID"
class RecommendViewController: UIViewController {
//MARK:- 懒加载属性
fileprivate lazy var recommendVM = RecommendViewModel()
fileprivate lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -kCycleViewH - kGameViewH, width: kScreenWidth, height: kCycleViewH)
return cycleView
}()
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenWidth, height: kGameViewH)
return gameView
}()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
//1.创建布局
let layout = UICollectionViewFlowLayout()
// layout.itemSize = CGSize(width: kItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin)
layout.headerReferenceSize = CGSize(width: kScreenWidth, height: kHeaderViewH)
//2.创建UICollectionVi
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionView.register(UINib(nibName: "HomeCollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
//MARK:- 系统回调函数
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLoad() {
super.viewDidLoad()
//1. 设置UI界面
setupUI()
//2. 请求数据
loadData()
}
}
//MARK:- 请求数据
extension RecommendViewController {
fileprivate func loadData() {
//请求推荐数据
recommendVM.requestData {
self.collectionView.reloadData()
//将数据传递给gameView
self.gameView.groups = self.recommendVM.anchorGroups
}
//请求轮播数据
recommendVM.requestCycleData {
self.cycleView.cycleModels = self.recommendVM.cycleModel
}
}
}
//MARK:- 设置UI界面
extension RecommendViewController {
fileprivate func setupUI(){
view.addSubview(collectionView)
collectionView.addSubview(cycleView)
collectionView.addSubview(gameView)
//设置collectionView的内边距
collectionView.contentInset = UIEdgeInsetsMake(kCycleViewH + kGameViewH, 0, 0, 0)
}
}
//MARK:- 遵守UICollectionViewDataSource
extension RecommendViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return recommendVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let group = recommendVM.anchorGroups[section]
return group.anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//0. 取出模型
let group = recommendVM.anchorGroups[indexPath.section]
let anchors = group.anchors[indexPath.item]
//1. 定义cell
var cell : CollectionBaseCell!
//2. 取出cell
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell
}
else {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
}
//3. 将模型赋值给cell
cell.anchor = anchors
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//1. 取出sectionHeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! HomeCollectionHeaderView
//2. 取出模型
headerView.group = recommendVM.anchorGroups[indexPath.section]
return headerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kPrettyItemH)
}
return CGSize(width: kItemW, height: kNormalItemH)
}
}
| mit |
mightydeveloper/swift | test/Constraints/dictionary_literal.swift | 10 | 2741 | // RUN: %target-parse-verify-swift
final class DictStringInt : DictionaryLiteralConvertible {
typealias Key = String
typealias Value = Int
init(dictionaryLiteral elements: (String, Int)...) { }
}
final class Dictionary<K, V> : DictionaryLiteralConvertible {
typealias Key = K
typealias Value = V
init(dictionaryLiteral elements: (K, V)...) { }
}
func useDictStringInt(d: DictStringInt) {}
func useDict<K, V>(d: Dictionary<K,V>) {}
// Concrete dictionary literals.
useDictStringInt([ "Hello" : 1 ])
useDictStringInt([ "Hello" : 1, "World" : 2])
useDictStringInt([ "Hello" : 1, "World" : 2.5]) // expected-error{{cannot convert value of type 'Double' to expected dictionary value type 'Int'}}
useDictStringInt([ 4.5 : 2]) // expected-error{{cannot convert value of type 'Double' to expected dictionary key type 'String'}}
useDictStringInt([ nil : 2]) // expected-error{{nil is not compatible with expected dictionary key type 'String'}}
useDictStringInt([ 7 : 1, "World" : 2]) // expected-error{{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
// Generic dictionary literals.
useDict(["Hello" : 1])
useDict(["Hello" : 1, "World" : 2])
useDict(["Hello" : 1.5, "World" : 2])
useDict([1 : 1.5, 3 : 2.5])
// Fall back to Dictionary<K, V> if no context is otherwise available.
var a = ["Hello" : 1, "World" : 2]
var a2 : Dictionary<String, Int> = a
var a3 = ["Hello" : 1]
var b = [ 1 : 2, 1.5 : 2.5 ]
var b2 : Dictionary<Double, Double> = b
var b3 = [1 : 2.5]
// <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error
// expected-note @+1 {{did you mean to use a dictionary literal instead?}}
var _: Dictionary<String, (Int) -> Int>? = [ // expected-error {{contextual type 'Dictionary<String, (Int) -> Int>' (aka 'Dictionary<String, Int -> Int>') cannot be used with array literal}}
"closure_1" as String, {(Int) -> Int in 0},
"closure_2", {(Int) -> Int in 0}]
var _: Dictionary<String, Int>? = ["foo", 1] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}}
// expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}}
var _: Dictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}}
// expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{41-42=:}} {{51-52=:}}
var _: Dictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{contextual type 'Dictionary<String, Int>' cannot be used with array literal}}
var _: Dictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'Int'}}
| apache-2.0 |
congncif/PagingDataController | Example/PagingDataController/ViewController2.swift | 1 | 972 | //
// ViewController2.swift
// PagingDataController
//
// Created by FOLY on 5/29/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import PagingDataController
import SiFUtilities
class ViewController2: SiFViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.statusBarStyle = .LightContent
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
huonw/swift | validation-test/compiler_crashers_fixed/00187-swift-lowering-typeconverter-getfunctiontypewithcaptures.swift | 65 | 445 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func f<m>() -> (m, m -> m) -> m {
({})
}
| apache-2.0 |
pepibumur/SoundCloudSwift | SoundCloudSwift/Source/Core/Errors/RequestError.swift | 2 | 140 | import Foundation
public enum RequestError: ErrorType {
case HTTPError(NSError)
case MappingError(ErrorType)
case InvalidType
} | mit |
noppoMan/aws-sdk-swift | Sources/Soto/Services/CloudWatchLogs/CloudWatchLogs_Error.swift | 1 | 4318 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for CloudWatchLogs
public struct CloudWatchLogsErrorType: AWSErrorType {
enum Code: String {
case dataAlreadyAcceptedException = "DataAlreadyAcceptedException"
case invalidOperationException = "InvalidOperationException"
case invalidParameterException = "InvalidParameterException"
case invalidSequenceTokenException = "InvalidSequenceTokenException"
case limitExceededException = "LimitExceededException"
case malformedQueryException = "MalformedQueryException"
case operationAbortedException = "OperationAbortedException"
case resourceAlreadyExistsException = "ResourceAlreadyExistsException"
case resourceNotFoundException = "ResourceNotFoundException"
case serviceUnavailableException = "ServiceUnavailableException"
case unrecognizedClientException = "UnrecognizedClientException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize CloudWatchLogs
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// The event was already logged.
public static var dataAlreadyAcceptedException: Self { .init(.dataAlreadyAcceptedException) }
/// The operation is not valid on the specified resource.
public static var invalidOperationException: Self { .init(.invalidOperationException) }
/// A parameter is specified incorrectly.
public static var invalidParameterException: Self { .init(.invalidParameterException) }
/// The sequence token is not valid. You can get the correct sequence token in the expectedSequenceToken field in the InvalidSequenceTokenException message.
public static var invalidSequenceTokenException: Self { .init(.invalidSequenceTokenException) }
/// You have reached the maximum number of resources that can be created.
public static var limitExceededException: Self { .init(.limitExceededException) }
/// The query string is not valid. Details about this error are displayed in a QueryCompileError object. For more information, see QueryCompileError. For more information about valid query syntax, see CloudWatch Logs Insights Query Syntax.
public static var malformedQueryException: Self { .init(.malformedQueryException) }
/// Multiple requests to update the same resource were in conflict.
public static var operationAbortedException: Self { .init(.operationAbortedException) }
/// The specified resource already exists.
public static var resourceAlreadyExistsException: Self { .init(.resourceAlreadyExistsException) }
/// The specified resource does not exist.
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
/// The service cannot complete the request.
public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) }
/// The most likely cause is an invalid AWS access key ID or secret key.
public static var unrecognizedClientException: Self { .init(.unrecognizedClientException) }
}
extension CloudWatchLogsErrorType: Equatable {
public static func == (lhs: CloudWatchLogsErrorType, rhs: CloudWatchLogsErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension CloudWatchLogsErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 |
mtviewdave/PhotoPicker | PhotoPicker/AppDelegate.swift | 1 | 2698 | //
// AppDelegate.swift
// PhotoPicker
//
// Created by Metebelis Labs LLC on 6/29/15.
//
// Copyright 2015 Metebelis Labs LLC
//
// 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 UIKit
@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:.
}
}
| apache-2.0 |
qingcai518/MenuReader | MenuReader/ResultController.swift | 1 | 9217 | //
// ResultController.swift
// MenuReader
//
// Created by RN-079 on 2017/01/04.
// Copyright © 2017年 RN-079. All rights reserved.
//
import UIKit
import RxSwift
class ResultController: ViewController {
@IBOutlet weak var tableView1 : UITableView!
@IBOutlet weak var tableView2 : UITableView!
@IBOutlet weak var indicator: UIActivityIndicatorView!
@IBOutlet weak var selectBtn: UIButton!
var bottomView = UIView()
var translatePartBtn = UIButton()
var translateAllBtn = UIButton()
let model = ResultModel()
let bottomHeight = CGFloat(118)
var results = [ResultInfo]()
var sources = [Int: String]()
var isSelectable = Variable(false)
var isTranslateAll = false
// params.
var image : UIImage!
@IBAction func doSelect() {
isSelectable.value = !isSelectable.value
if (!isSelectable.value) {
for result in results {
result.isSelected.value = false
}
hideBottomView()
} else {
// 選択ボタンが押下されたら、sourcesの内容をクリアする.
sources.removeAll()
showBottomView()
}
}
override func viewDidLoad() {
super.viewDidLoad()
setTableView()
setBottomView()
// データを取得する.
getData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func getData() {
indicator.startAnimating()
model.createRequest(image: image)
}
private func setTableView() {
tableView1.tableFooterView = UIView()
tableView1.delegate = self
tableView1.dataSource = self
tableView2.tableFooterView = UIView()
tableView2.delegate = self
tableView2.dataSource = self
model.delegate = self
}
private func setBottomView() {
bottomView.frame = CGRect(x: 0, y : screenHeight, width: screenWidth, height : bottomHeight)
bottomView.backgroundColor = UIColor.init(white: 0, alpha: 0.8)
self.view.addSubview(bottomView)
translatePartBtn.frame = CGRect(x: 30, y: 12, width: screenWidth - 2 * 30, height: 40)
translatePartBtn.rx.tap.asObservable().bindNext { [weak self] in
self?.isTranslateAll = false
self?.performSegue(withIdentifier: "ToTranslate", sender: nil)
}.addDisposableTo(disposeBag)
translatePartBtn.setBackgroundImage(UIImage(named: "btn_light_blue"), for: .normal)
translatePartBtn.setTitle("選択したレコードを翻訳", for: .normal)
translatePartBtn.setTitleColor(UIColor.white, for: .normal)
translatePartBtn.titleLabel?.font = UIFont.HelveticaBold16()
translatePartBtn.isEnabled = false
bottomView.addSubview(translatePartBtn)
translateAllBtn.frame = CGRect(x: 30, y: 64, width: screenWidth - 2 * 30, height: 40)
translateAllBtn.rx.tap.asObservable().bindNext { [unowned self] in
self.isTranslateAll = true
self.performSegue(withIdentifier: "ToTranslate", sender: nil)
}.addDisposableTo(disposeBag)
translateAllBtn.setBackgroundImage(UIImage(named: "btn_light_blue"), for: .normal)
translateAllBtn.setTitle("全件翻訳", for: .normal)
translateAllBtn.setTitleColor(UIColor.white, for: .normal)
translateAllBtn.titleLabel?.font = UIFont.HelveticaBold16()
bottomView.addSubview(translateAllBtn)
}
func showBottomView() {
UIView.animate(withDuration: 0.5, animations: { [unowned self] in
self.bottomView.frame = CGRect(x: 0, y: screenHeight - self.bottomHeight, width: screenWidth, height: self.bottomHeight)
}) { isFinished in
}
}
func hideBottomView() {
UIView.animate(withDuration: 0.5, animations: { [unowned self] in
self.bottomView.frame = CGRect(x: 0, y: screenHeight, width: screenWidth, height: self.bottomHeight)
}) { isFinished in
}
}
}
extension ResultController : ResultModelDelegate {
func complete(result: String?) {
indicator.stopAnimating()
guard let contentArray = result?.components(separatedBy: "\n") else {return}
for content in contentArray {
if (content.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) == "") {
continue
}
let info = ResultInfo(result: content)
results.append(info)
}
print("results = \(results)")
tableView1.reloadData()
}
func failed(error: NSError) {
indicator.stopAnimating()
print("error = \(error.localizedDescription)")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "ToTranslate") {
guard let next = segue.destination as? TranslateController else {return}
if (isTranslateAll) {
for result in results {
next.sources.append(result.result)
}
} else {
for (_, value) in sources {
next.sources.append(value)
}
}
}
}
}
extension ResultController : UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if (tableView === tableView1) {
let info = results[indexPath.row]
if (isSelectable.value) {
info.isSelected.value = !info.isSelected.value
if (info.isSelected.value) {
sources[indexPath.row] = info.result
} else {
sources.removeValue(forKey: indexPath.row)
}
var flag = false
for result in results {
if (result.isSelected.value) {
flag = true
break
}
}
self.translatePartBtn.isEnabled = flag
} else {
isTranslateAll = false
let info = results[indexPath.row]
sources.removeAll()
sources[indexPath.row] = info.result
performSegue(withIdentifier: "ToTranslate", sender: nil)
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (tableView === tableView1) {
return 44
} else {
let width = screenWidth - 2 * 12
let height = (width / image.size.width ) * image.size.height
return height + 12
}
}
}
extension ResultController : UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (tableView === tableView1) {
return results.count
} else {
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if (tableView == tableView1) {
let info = results[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ResultCell", for: indexPath) as! ResultCell
cell.resultTf.text = info.result
cell.editBtn.rx.tap.asObservable().bindNext { [weak self] in
if (cell.editBtn.currentImage == UIImage(named: "ok_green")) {
cell.editBtn.setImage(UIImage(named: "edit"), for: .normal)
self?.results[indexPath.row].result = cell.resultTf.text!
cell.resultTf.isEnabled = false
} else {
cell.editBtn.setImage(UIImage(named: "ok_green"), for: .normal)
cell.resultTf.isEnabled = true
cell.resultTf.becomeFirstResponder()
}
}.addDisposableTo(cell.disposeBag)
info.isSelected.asDriver().drive(onNext: { value in
cell.checkboxView.image = value ? UIImage(named: "checkbox") : UIImage(named: "checkbox_uncheck")
}, onCompleted: nil, onDisposed: nil).addDisposableTo(cell.disposeBag)
isSelectable.asDriver().drive(onNext: { [weak self] value in
self?.selectBtn.setTitle(value ? "キャンセル" : "選択", for: .normal)
cell.checkboxView.isHidden = !value
}, onCompleted: nil, onDisposed: nil).addDisposableTo(cell.disposeBag)
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell", for: indexPath) as! ImageCell
cell.pictureView.image = self.image
return cell
}
}
}
| mit |
rhx/SwiftGObject | Sources/GLibObject/GLibType.swift | 1 | 4456 | //
// GLibType.swift
// GLibObject
//
// Created by Rene Hexel on 17/4/17.
// Copyright © 2017, 2018, 2020 Rene Hexel. All rights reserved.
//
import CGLib
import GLib
//
// Unfortunately, the G_TYPE_* macros are not imported into Swift
// Therefore, rewe create them manually here
//
public extension GType {
static let invalid = GType( 0 << TYPE_FUNDAMENTAL_SHIFT)
static let none = GType( 1 << TYPE_FUNDAMENTAL_SHIFT)
static let interface = GType( 2 << TYPE_FUNDAMENTAL_SHIFT)
static let char = GType( 3 << TYPE_FUNDAMENTAL_SHIFT)
static let uchar = GType( 4 << TYPE_FUNDAMENTAL_SHIFT)
static let boolean = GType( 5 << TYPE_FUNDAMENTAL_SHIFT)
static let int = GType( 6 << TYPE_FUNDAMENTAL_SHIFT)
static let uint = GType( 7 << TYPE_FUNDAMENTAL_SHIFT)
static let long = GType( 8 << TYPE_FUNDAMENTAL_SHIFT)
static let ulong = GType( 9 << TYPE_FUNDAMENTAL_SHIFT)
static let int64 = GType(10 << TYPE_FUNDAMENTAL_SHIFT)
static let uint64 = GType(11 << TYPE_FUNDAMENTAL_SHIFT)
static let `enum` = GType(12 << TYPE_FUNDAMENTAL_SHIFT)
static let flags = GType(13 << TYPE_FUNDAMENTAL_SHIFT)
static let float = GType(14 << TYPE_FUNDAMENTAL_SHIFT)
static let double = GType(15 << TYPE_FUNDAMENTAL_SHIFT)
static let string = GType(16 << TYPE_FUNDAMENTAL_SHIFT)
static let pointer = GType(17 << TYPE_FUNDAMENTAL_SHIFT)
static let boxed = GType(18 << TYPE_FUNDAMENTAL_SHIFT)
static let param = GType(19 << TYPE_FUNDAMENTAL_SHIFT)
static let object = GType(20 << TYPE_FUNDAMENTAL_SHIFT)
static let variant = GType(21 << TYPE_FUNDAMENTAL_SHIFT)
static let max = GType(TYPE_FUNDAMENTAL_MAX)
}
public extension GType {
@inlinable func test(flags: TypeFundamentalFlags) -> Bool {
return g_type_test_flags(self, flags.rawValue) != 0
}
@inlinable func test(flags: TypeFlags) -> Bool {
return g_type_test_flags(self, flags.rawValue) != 0
}
/// Return the fundamental type which is the ancestor of `self`.
@inlinable var fundamental: GType { return g_type_fundamental(self) }
/// Return `true` iff `self` is a fundamental type.
@inlinable var isFundamental: Bool { return self <= GType.max }
/// Return `true` iff `self` is a derived type.
@inlinable var isDerived: Bool { return !self.isFundamental }
/// Return `true` iff `self` is an interface type.
@inlinable var isInterface: Bool { return self.fundamental == .interface }
/// Return `true` iff `self` is a classed type.
@inlinable var isClassed: Bool { return test(flags: .classed) }
/// Return `true` iff `self` is a derivable type.
@inlinable var isDerivable: Bool { return test(flags: .derivable) }
/// Return `true` iff `self` is a deep derivable type.
@inlinable var isDeepDerivable: Bool { return test(flags: .deepDerivable) }
/// Return `true` iff `self` is an instantiatable type.
@inlinable var isInstantiable: Bool { return test(flags: .instantiatable) }
/// Return `true` iff `self` is an abstract type.
@inlinable var isAbstract: Bool { return test(flags: .abstract) }
/// Return `true` iff `self` is an abstract value type.
@inlinable var isAbstractValue: Bool { return test(flags: .valueAbstract) }
/// Return `true` iff `self` is a value type.
@inlinable var isValueType: Bool { return g_type_check_is_value_type(self) != 0 }
/// Return `true` iff `self` has a value table.
@inlinable var hasValueTable: Bool { return g_type_value_table_peek(self) != nil }
/// Return `true` iff `a` is transformable into `b`
@inlinable static func transformable(from a: GType, to b: GType) -> Bool {
return g_value_type_transformable(a, b) != 0
}
}
//fileprivate struct _GTypeClass { let g_type: GType }
//fileprivate struct _GTypeInstance { let g_class: UnsafeMutablePointer<_GTypeClass>? }
/// Convenience extensions for Object types
public extension ObjectProtocol {
/// Underlying type
@inlinable var type: GType {
let typeInstance = ptr.assumingMemoryBound(to: Optional<UnsafeMutablePointer<GType>>.self)
guard let cls = typeInstance.pointee else { return .invalid }
return cls.pointee
}
/// Name of the underlying type
@inlinable var typeName: String {
return String(cString: g_type_name(type))
}
}
| bsd-2-clause |
mpclarkson/vapor | Sources/Vapor/Hash/HashDriver.swift | 1 | 343 | /**
Classes that conform to `HashDriver` may be set
as the `Hash` classes hashing engine.
*/
public protocol HashDriver {
/**
Given a string, this function will
return the hashed string according
to whatever algorithm it chooses to implement.
*/
func hash(message: String, key: String) -> String
}
| mit |
avito-tech/Marshroute | Example/NavigationDemo/VIPER/SearchResults/View/SearchResultsViewInput.swift | 1 | 400 | import Foundation
struct SearchResultsViewData {
let title: String
let rgb: (red: Double, green: Double, blue: Double)
let onTap: () -> ()
}
protocol SearchResultsViewInput: class, ViewLifecycleObservable {
func setSearchResults(_ searchResults: [SearchResultsViewData])
func setTitle(_ title: String?)
var onRecursionButtonTap: ((_ sender: AnyObject) -> ())? { get set }
}
| mit |
kesun421/firefox-ios | Client/Frontend/Widgets/ChevronView.swift | 3 | 4414 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
enum ChevronDirection {
case left
case up
case right
case down
}
enum ChevronStyle {
case angular
case rounded
}
class ChevronView: UIView {
fileprivate let Padding: CGFloat = 2.5
fileprivate var direction = ChevronDirection.right
fileprivate var lineCapStyle = CGLineCap.round
fileprivate var lineJoinStyle = CGLineJoin.round
var lineWidth: CGFloat = 3.0
var style: ChevronStyle = .rounded {
didSet {
switch style {
case .rounded:
lineCapStyle = CGLineCap.round
lineJoinStyle = CGLineJoin.round
case .angular:
lineCapStyle = CGLineCap.butt
lineJoinStyle = CGLineJoin.miter
}
}
}
init(direction: ChevronDirection) {
super.init(frame: CGRect.zero)
self.direction = direction
if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft {
if direction == .left {
self.direction = .right
} else if direction == .right {
self.direction = .left
}
}
self.backgroundColor = UIColor.clear
self.contentMode = UIViewContentMode.redraw
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let strokeLength = (rect.size.height / 2) - Padding
let path: UIBezierPath
switch direction {
case .left:
path = drawLeftChevronAt(CGPoint(x: rect.size.width - (strokeLength + Padding), y: strokeLength + Padding), strokeLength: strokeLength)
case .up:
path = drawUpChevronAt(CGPoint(x: (rect.size.width - Padding) - strokeLength, y: (strokeLength / 2) + Padding), strokeLength: strokeLength)
case .right:
path = drawRightChevronAt(CGPoint(x: rect.size.width - Padding, y: strokeLength + Padding), strokeLength: strokeLength)
case .down:
path = drawDownChevronAt(CGPoint(x: (rect.size.width - Padding) - strokeLength, y: (strokeLength * 1.5) + Padding), strokeLength: strokeLength)
}
tintColor.set()
// The line thickness needs to be proportional to the distance from the arrow head to the tips. Making it half seems about right.
path.lineCapStyle = lineCapStyle
path.lineJoinStyle = lineJoinStyle
path.lineWidth = lineWidth
path.stroke()
}
fileprivate func drawUpChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath {
return drawChevron(CGPoint(x: origin.x-strokeLength, y: origin.y+strokeLength),
head: CGPoint(x: origin.x, y: origin.y),
rightTip: CGPoint(x: origin.x+strokeLength, y: origin.y+strokeLength))
}
fileprivate func drawDownChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath {
return drawChevron(CGPoint(x: origin.x-strokeLength, y: origin.y-strokeLength),
head: CGPoint(x: origin.x, y: origin.y),
rightTip: CGPoint(x: origin.x+strokeLength, y: origin.y-strokeLength))
}
fileprivate func drawLeftChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath {
return drawChevron(CGPoint(x: origin.x+strokeLength, y: origin.y-strokeLength),
head: CGPoint(x: origin.x, y: origin.y),
rightTip: CGPoint(x: origin.x+strokeLength, y: origin.y+strokeLength))
}
fileprivate func drawRightChevronAt(_ origin: CGPoint, strokeLength: CGFloat) -> UIBezierPath {
return drawChevron(CGPoint(x: origin.x-strokeLength, y: origin.y+strokeLength),
head: CGPoint(x: origin.x, y: origin.y),
rightTip: CGPoint(x: origin.x-strokeLength, y: origin.y-strokeLength))
}
fileprivate func drawChevron(_ leftTip: CGPoint, head: CGPoint, rightTip: CGPoint) -> UIBezierPath {
let path = UIBezierPath()
// Left tip
path.move(to: leftTip)
// Arrow head
path.addLine(to: head)
// Right tip
path.addLine(to: rightTip)
return path
}
}
| mpl-2.0 |
tardieu/swift | test/IRGen/autolink-coff-force-link.swift | 17 | 840 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %swift -target i686--windows-msvc -parse-as-library -parse-stdlib -module-name autolink -module-link-name autolink -autolink-force-load -emit-ir -o - %s | %FileCheck %s
// RUN: %swift -target i686--windows-itanium -parse-as-library -parse-stdlib -module-name autolink -module-link-name autolink -autolink-force-load -S -o - %s | %FileCheck %s -check-prefix CHECK-ASM-GNU
// RUN: %swift -target i686--windows-msvc -parse-as-library -parse-stdlib -module-name autolink -module-link-name autolink -autolink-force-load -S -o - %s | %FileCheck %s -check-prefix CHECK-ASM-MSC
// CHECK: @"_swift_FORCE_LOAD_$_autolink" = common dllexport global i1 false
// CHECK-ASM-GNU: .ascii " -export:__swift_FORCE_LOAD_$_autolink,data"
// CHECK-ASM-MSC: .ascii " /EXPORT:__swift_FORCE_LOAD_$_autolink,DATA"
| apache-2.0 |
iandd0824/ri-ios | dsm5/MasterViewController.swift | 1 | 10948 | //
// MasterViewController.swift
// dsm5
//
// Created by Djanny on 10/5/15.
// Copyright © 2015 ptsd.ri.ucla. All rights reserved.
//
import UIKit
import CoreData
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var detailViewController: DetailViewController? = nil
var managedObjectContext: NSManagedObjectContext? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
//let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
//self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
@IBAction func tapCreateClient(sender: AnyObject) {
/*let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context)
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(NSDate(), forKey: "timeStamp")
// Save the context.
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}*/
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context)
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.setValue(NSDate(), forKey: "timeStamp")
// Save the context.
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath)
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
print(object)
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject)
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
if(editingStyle == .Delete) {
}
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath)
//cell.textLabel!.text = object.valueForKey("timeStamp")!.description
cell.textLabel!.text = object.valueForKey("name")!.description
cell.detailTextLabel!.text = object.valueForKey("id")!.description
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
//let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)
let entity = NSEntityDescription.entityForName("Client", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
//let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
//let predicate = NSPredicate(format: "name == %@", "bbb")
// Set the predicate on the fetch request
//fetchRequest.predicate = predicate
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
do {
try _fetchedResultsController!.performFetch()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//print("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/
}
| mit |
miracle-as/BasicComponents | BasicComponents/UIViewController+Alert.swift | 1 | 3231 | //
// UIViewController+Alert.swift
// Metronome
//
// Created by Lasse Løvdahl on 05/02/2016.
// Copyright © 2016 Miracle A/S. All rights reserved.
//
import Foundation
import UIKit
import Whisper
import DynamicColor
public func statusBarNotify(_ message: String, color: UIColor = .clear) {
let murmur = Murmur(title: message, backgroundColor: color, titleColor: color.isLight() ? .black : .white)
show(whistle: murmur, action: .show(2))
}
public extension UIViewController {
public func askUserFor(_ title: String, message: String, whenAsked: @escaping (_ ok: Bool) -> Void) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Annuller", style: .cancel) { _ in
whenAsked(false)
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .default) { _ in
whenAsked(true)
}
alertController.addAction(OKAction)
self.present(alertController, animated: true) {
}
}
public func alert(_ title: String = "Error", message: String, whenAcknowledge: @escaping () -> Void) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default) { _ in
whenAcknowledge()
}
alertController.addAction(OKAction)
self.present(alertController, animated: true) {
}
}
public func close(animate animated: Bool) {
if let navigationController = navigationController {
navigationController.popViewController(animated: animated)
} else {
dismiss(animated: animated, completion: .none)
}
}
public var isVisible: Bool {
if isViewLoaded {
return view.window != nil
}
return false
}
public var contentViewController: UIViewController {
if let vc = self as? UINavigationController {
return vc.topViewController ?? self
} else {
return self
}
}
public var isTopViewController: Bool {
if self.navigationController != nil {
return self.navigationController?.visibleViewController === self
} else if self.tabBarController != nil {
return self.tabBarController?.selectedViewController == self && self.presentedViewController == nil
} else {
return self.presentedViewController == nil && self.isVisible
}
}
public var isRunningInFullScreen: Bool {
if let
delegate = UIApplication.shared.delegate,
let window = delegate.window,
let win = window {
return win.frame.equalTo(win.screen.bounds)
}
return true
}
class var className: String {
get {
return NSStringFromClass(self).components(separatedBy: ".").last!
}
}
fileprivate class func instanceFromMainStoryboardHelper<T>() -> T? {
if let
appDelegate = UIApplication.shared.delegate,
let rvc = appDelegate.window??.rootViewController,
let controller = rvc.storyboard?.instantiateViewController(withIdentifier: className) as? T {
return controller
}
return .none
}
public class func instanceFromMainStoryboard() -> Self? {
return instanceFromMainStoryboardHelper()
}
}
| mit |
RamiAsia/Swift-Sorting | Sorting Algorithms/Insertion-Sort/Tests/LinuxMain.swift | 1 | 114 | import XCTest
@testable import Insertion_SortTestSuite
XCTMain([
testCase(Insertion_SortTests.allTests),
])
| mit |
milseman/swift | test/Sema/availability_nonoverlapping.swift | 23 | 11306 | // RUN: not %target-swift-frontend -typecheck %s -swift-version 3 2> %t.3.txt
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-3 %s < %t.3.txt
// RUN: %FileCheck -check-prefix=NEGATIVE -check-prefix=NEGATIVE-3 %s < %t.3.txt
// RUN: not %target-swift-frontend -typecheck %s -swift-version 4 2> %t.4.txt
// RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-4 %s < %t.4.txt
// RUN: %FileCheck -check-prefix=NEGATIVE -check-prefix=NEGATIVE-4 %s < %t.4.txt
class NonOptToOpt {
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = NonOptToOpt()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class NonOptToOptReversed {
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = NonOptToOptReversed()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class OptToNonOpt {
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init!() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = OptToNonOpt()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class OptToNonOptReversed {
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init!() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = OptToNonOptReversed()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class NoChange {
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() {}
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()'
}
class NoChangeReversed {
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() {}
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()'
}
class OptToOpt {
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init!() {}
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init?() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()'
}
class OptToOptReversed {
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init?() {}
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init!() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()'
}
class ThreeWayA {
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 4.0, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 5.0)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class ThreeWayB {
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 5.0)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 4.0, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class ThreeWayC {
@available(swift, introduced: 5.0)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 4.0, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class ThreeWayD {
@available(swift, introduced: 5.0)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 4.0, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class ThreeWayE {
@available(swift, introduced: 4.0, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 5.0)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class ThreeWayF {
@available(swift, introduced: 4.0, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 5.0)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class DisjointThreeWay {
@available(swift, obsoleted: 4.0)
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 4.1, obsoleted: 5.0)
public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, introduced: 5.1)
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
class OverlappingVersions {
@available(swift, obsoleted: 5.0)
public init(a: ()) {}
@available(swift 4.0)
public init?(a: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(a:)'
@available(swift 4.0)
public init?(b: ()) {}
@available(swift, obsoleted: 4.1)
public init(b: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(b:)'
public init(c: ()) {}
@available(swift 4.0)
public init?(c: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(c:)'
@available(swift 4.0)
public init(c2: ()) {}
public init?(c2: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(c2:)'
@available(swift, obsoleted: 4.0)
public init(d: ()) {}
public init?(d: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(d:)'
public init(d2: ()) {}
@available(swift, obsoleted: 4.0)
public init?(d2: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(d2:)'
@available(swift, obsoleted: 4.0)
public init(e: ()) {}
@available(swift 4.0)
public init?(e: ()) {}
@available(swift 4.0)
public init!(e: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(e:)'
@available(swift, obsoleted: 4.0)
public init(f: ()) {}
@available(swift 4.0)
public init?(f: ()) {}
@available(swift, obsoleted: 4.0)
public init!(f: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(f:)'
}
class NonThrowingToThrowing {
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = NonThrowingToThrowing()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
_ = NonThrowingToThrowing.foo()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class NonThrowingToThrowingReversed {
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = NonThrowingToThrowingReversed()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
_ = NonThrowingToThrowingReversed.foo()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class ThrowingToNonThrowing {
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = ThrowingToNonThrowing()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
_ = ThrowingToNonThrowing.foo()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class ThrowingToNonThrowingReversed {
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = ThrowingToNonThrowingReversed()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
_ = ThrowingToNonThrowingReversed.foo()
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
class ChangePropertyType {
// We don't allow this for stored properties.
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public var stored: Int16 = 0
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public var stored: Int8 = 0 // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'stored'
// OK for computed properties.
@available(swift 4.0)
@available(*, deprecated, message: "yes 4.0")
public var computed: Int16 { get { } set { } }
@available(swift, obsoleted: 4.0)
@available(*, deprecated, message: "not 4.0")
public var computed: Int8 { get { } set { } } // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error
}
_ = ChangePropertyType().computed
// CHECK-3: :[[@LINE-1]]:{{.+}} not 4.0
// CHECK-4: :[[@LINE-2]]:{{.+}} yes 4.0
| apache-2.0 |
pixeldock/PXDToolkit | Pod/Classes/ApplicationExtensions.swift | 1 | 823 | //
// ApplicationExtensions.swift
// PXDToolbox
//
// Created by Jörn Schoppe on 19.01.16.
//
//
import Foundation
// Functions to access app version and build number
public extension UIApplication {
/**
Gets the current app version
- Returns: A String with the app version
*/
static func appVersion() -> String {
guard let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String else { return "" }
return version
}
/**
Gets the current build number
- Returns: A String with the current build number
*/
static func appBuild() -> String {
guard let build = Bundle.main.object(forInfoDictionaryKey: String(kCFBundleVersionKey)) as? String else { return "" }
return build
}
}
| mit |
talk2junior/iOSND-Beginning-iOS-Swift-3.0 | Playground Collection/Part 2 - Robot Maze 2/Boolean Expressions/Boolean Expressions.playground/Pages/The _ _ Operator.xcplaygroundpage/Contents.swift | 1 | 602 | //: [Previous](@previous)
import Foundation
// The || Operator
//: let compoundBool = <first boolean expression> | | <second boolean expression>
// If Jessica finishes her homework OR it's not a school night ...
let finishedHomework = true
let noSchoolTomorrow = false
let allowedToPlayVideoGames = finishedHomework || noSchoolTomorrow
// The || operator can also be used to combine multiple comparison operators
let audienceRating = 85
let criticsRating = 75
let recommendedByAFriend = true
let goWatchMovie = (audienceRating > 90 && criticsRating > 80) || recommendedByAFriend
//: [Next](@next)
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.