repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
twostraws/HackingWithSwift | SwiftUI/project19/SnowSeeker/ResortView.swift | 1 | 2921 | //
// ResortView.swift
// SnowSeeker
//
// Created by Paul Hudson on 23/01/2022.
//
import SwiftUI
struct ResortView: View {
let resort: Resort
@Environment(\.horizontalSizeClass) var sizeClass
@Environment(\.dynamicTypeSize) var typeSize
@EnvironmentObject var favorites: Favorites
@State private var selectedFacility: Facility?
@State private var showingFacility = false
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
Image(decorative: resort.id)
.resizable()
.scaledToFit()
HStack {
if sizeClass == .compact && typeSize > .large {
VStack(spacing: 10) { ResortDetailsView(resort: resort) }
VStack(spacing: 10) { SkiDetailsView(resort: resort) }
} else {
ResortDetailsView(resort: resort)
SkiDetailsView(resort: resort)
}
}
.padding(.vertical)
.background(Color.primary.opacity(0.1))
.dynamicTypeSize(...DynamicTypeSize.xxxLarge)
Group {
Text(resort.description)
.padding(.vertical)
Text("Facilities")
.font(.headline)
HStack {
ForEach(resort.facilityTypes) { facility in
Button {
selectedFacility = facility
showingFacility = true
} label: {
facility.icon
.font(.title)
}
}
}
Button(favorites.contains(resort) ? "Remove from Favorites" : "Add to Favorites") {
if favorites.contains(resort) {
favorites.remove(resort)
} else {
favorites.add(resort)
}
}
.buttonStyle(.borderedProminent)
.padding()
}
.padding(.horizontal)
}
}
.navigationTitle("\(resort.name), \(resort.country)")
.navigationBarTitleDisplayMode(.inline)
.alert(selectedFacility?.name ?? "More information", isPresented: $showingFacility, presenting: selectedFacility) { _ in
} message: { facility in
Text(facility.description)
}
}
}
struct ResortView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
ResortView(resort: Resort.example)
}
.environmentObject(Favorites())
}
}
| unlicense | 09c4726f8ca00194d7abb6dab31a8c54 | 31.820225 | 128 | 0.466279 | 5.693957 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/SettingsViewController.swift | 1 | 46085 | //
// SettingsViewController.swift
// Slide for Reddit
//
// Created by Carlos Crane on 1/10/17.
// Copyright © 2017 Haptic Apps. All rights reserved.
//
import Anchorage
import BiometricAuthentication
import LicensesViewController
import MessageUI
import RealmSwift
import RLBAlertsPickers
import SDWebImage
import UIKit
class SettingsViewController: MediaTableViewController, MFMailComposeViewControllerDelegate {
var goPro: UITableViewCell = InsetCell()
var general: UITableViewCell = InsetCell(style: .subtitle, reuseIdentifier: "general")
var manageSubs: UITableViewCell = InsetCell(style: .subtitle, reuseIdentifier: "managesubs")
var mainTheme: UITableViewCell = InsetCell()
var postLayout: UITableViewCell = InsetCell()
var icon: UITableViewCell = InsetCell()
var subThemes: UITableViewCell = InsetCell()
var font: UITableViewCell = InsetCell()
var comments: UITableViewCell = InsetCell()
var linkHandling: UITableViewCell = InsetCell()
var history: UITableViewCell = InsetCell(style: .subtitle, reuseIdentifier: "history")
var dataSaving: UITableViewCell = InsetCell()
var filters: UITableViewCell = InsetCell()
var content: UITableViewCell = InsetCell()
var lockCell: UITableViewCell = InsetCell()
var subIconsCell: UITableViewCell = InsetCell()
var subCell: UITableViewCell = InsetCell()
var licenseCell: UITableViewCell = InsetCell()
var contributorsCell: UITableViewCell = InsetCell()
var aboutCell: UITableViewCell = InsetCell()
var githubCell: UITableViewCell = InsetCell()
var clearCell: UITableViewCell = InsetCell(style: .subtitle, reuseIdentifier: "cache")
var cacheCell: UITableViewCell = InsetCell()
var backupCell: UITableViewCell = InsetCell()
var gestureCell: UITableViewCell = InsetCell(style: .subtitle, reuseIdentifier: "gestures")
var widgetsCell: UITableViewCell = InsetCell(style: .subtitle, reuseIdentifier: "widgets")
var autoPlayCell: UITableViewCell = InsetCell(style: .subtitle, reuseIdentifier: "autoplay")
var tagsCell: UITableViewCell = InsetCell()
var audioSettings = InsetCell()
var postActionCell: UITableViewCell = InsetCell()
var shortcutCell: UITableViewCell = InsetCell()
var coffeeCell: UITableViewCell = InsetCell()
var viewModeCell: UITableViewCell = InsetCell(style: .subtitle, reuseIdentifier: "viewmode")
var lock = UISwitch().then {
$0.onTintColor = ColorUtil.baseAccent
}
var subIcons = UISwitch().then {
$0.onTintColor = ColorUtil.baseAccent
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if ColorUtil.theme.isLight && SettingValues.reduceColor {
if #available(iOS 13, *) {
return .darkContent
} else {
return .default
}
} else {
return .lightContent
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
lock.onTintColor = ColorUtil.baseAccent
if SettingsPro.changed {
doPro()
}
let button = UIButtonWithContext.init(type: .custom)
button.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
button.setImage(UIImage(sfString: SFSymbol.xmark, overrideString: "close")!.navIcon(), for: UIControl.State.normal)
button.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25)
button.addTarget(self, action: #selector(handleBackButton), for: .touchUpInside)
let barButton = UIBarButtonItem.init(customView: button)
navigationItem.leftBarButtonItem = barButton
}
func doPro() {
self.tableView.reloadData()
let menuB = UIBarButtonItem(image: UIImage(sfString: SFSymbol.heartCircleFill, overrideString: "support")?.toolbarIcon().getCopy(withColor: GMColor.red500Color()), style: .plain, target: self, action: #selector(SettingsViewController.didPro(_:)))
navigationItem.rightBarButtonItem = menuB
}
@objc public func handleBackButton() {
if self.navigationController?.viewControllers.count == 1 {
self.dismiss(animated: true, completion: nil)
} else {
self.navigationController?.popViewController(animated: true)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: false)
setupBaseBarColors()
self.history.detailTextLabel?.text = "\(History.seenTimes.allKeys.count) visited post" + (History.seenTimes.allKeys.count != 1 ? "s" : "")
navigationController?.setToolbarHidden(true, animated: false)
self.icon.imageView?.image = Bundle.main.icon?.getCopy(withSize: CGSize(width: 25, height: 25))
if (oldAppMode == .MULTI_COLUMN || oldAppMode == .SINGLE) && SettingValues.appMode == .SPLIT {
let alert = UIAlertController(title: "Switching to Split Content mode requires an app restart", message: "Would you like to close Slide now, or have changes applied next time you open Slide?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Close Slide now", style: UIAlertAction.Style.destructive, handler: { (_) in
UserDefaults.standard.synchronize()
exit(0)
}))
alert.addAction(UIAlertAction(title: "Apply later", style: UIAlertAction.Style.cancel, handler: { (_) in
self.oldAppMode = SettingValues.appMode
}))
self.present(alert, animated: true, completion: nil)
} else if (SettingValues.appMode == .MULTI_COLUMN || SettingValues.appMode == .SINGLE) && oldAppMode == .SPLIT {
let alert = UIAlertController(title: "Switching to Columned mode requires an app restart", message: "Would you like to close Slide now, or have changes applied next time you open Slide?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Close Slide now", style: UIAlertAction.Style.destructive, handler: { (_) in
UserDefaults.standard.synchronize()
exit(0)
}))
alert.addAction(UIAlertAction(title: "Apply later", style: UIAlertAction.Style.cancel, handler: { (_) in
self.oldAppMode = SettingValues.appMode
}))
self.present(alert, animated: true, completion: nil)
}
}
var oldAppMode = SettingValues.appMode
override func loadView() {
super.loadView()
if SettingValues.isPro {
let menuB = UIBarButtonItem(image: UIImage(sfString: SFSymbol.heartCircleFill, overrideString: "support")?.toolbarIcon().getCopy(withColor: GMColor.red500Color()), style: .plain, target: self, action: #selector(SettingsViewController.didPro(_:)))
navigationItem.rightBarButtonItem = menuB
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = UIRectEdge.all
self.extendedLayoutIncludesOpaqueBars = true
doCells()
self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
}
@objc func didPro(_ sender: AnyObject) {
let alert = UIAlertController.init(title: "Pro Supporter", message: "Thank you for supporting my work and going Pro 😊\n\nIf you need any assistance with pro features, feel free to send me a message!", preferredStyle: .alert)
/*alert.addAction(UIAlertAction.init(title: "Tip jar", style: .default, handler: { (_) in
VCPresenter.donateDialog(self)
}))*/
alert.addAction(UIAlertAction.init(title: "Email", style: .default, handler: { (_) in
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients(["[email protected]"])
mail.setSubject("Slide Pro Purchase Support")
self.present(mail, animated: true)
}
}))
alert.addAction(UIAlertAction.init(title: "Private Message", style: .default, handler: { (_) in
let base = TapBehindModalViewController(rootViewController: ReplyViewController.init(name: "ccrama", completion: { (_) in
BannerUtil.makeBanner(text: "Message sent!", color: GMColor.green500Color(), seconds: 3, context: self, top: true, callback: nil)
}))
VCPresenter.presentAlert(base, parentVC: self)
}))
alert.addAction(UIAlertAction.init(title: "Close", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
func doCells(_ reset: Bool = true) {
self.view.backgroundColor = ColorUtil.theme.backgroundColor
// set the title
self.title = "Settings"
self.tableView.separatorStyle = .none
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = 200
self.general.textLabel?.text = "General"
self.general.accessoryType = .disclosureIndicator
self.general.backgroundColor = ColorUtil.theme.foregroundColor
self.general.textLabel?.textColor = ColorUtil.theme.fontColor
self.general.imageView?.image = UIImage(sfString: SFSymbol.gear, overrideString: "settings")?.toolbarIcon()
self.general.imageView?.tintColor = ColorUtil.theme.fontColor
self.general.detailTextLabel?.textColor = ColorUtil.theme.fontColor
self.general.detailTextLabel?.text = "Display settings, haptic feedback and default sorting"
self.general.detailTextLabel?.numberOfLines = 0
self.general.detailTextLabel?.lineBreakMode = .byWordWrapping
self.manageSubs.textLabel?.text = "Subscriptions"
self.manageSubs.accessoryType = .disclosureIndicator
self.manageSubs.backgroundColor = ColorUtil.theme.foregroundColor
self.manageSubs.textLabel?.textColor = ColorUtil.theme.fontColor
self.manageSubs.imageView?.image = UIImage(sfString: .rCircleFill, overrideString: "subs")?.toolbarIcon()
self.manageSubs.imageView?.tintColor = ColorUtil.theme.fontColor
self.manageSubs.detailTextLabel?.textColor = ColorUtil.theme.fontColor
self.manageSubs.detailTextLabel?.text = "Manage your subscriptions and rearrange the sidebar"
self.manageSubs.detailTextLabel?.numberOfLines = 0
self.postActionCell.textLabel?.text = "Reorder post actions"
self.postActionCell.accessoryType = .disclosureIndicator
self.postActionCell.backgroundColor = ColorUtil.theme.foregroundColor
self.postActionCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.postActionCell.imageView?.image = UIImage(sfString: SFSymbol.arrowUpArrowDownCircleFill, overrideString: "compact")?.toolbarIcon()
self.postActionCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.shortcutCell.textLabel?.text = "Reorder homepage shortcuts"
self.shortcutCell.accessoryType = .disclosureIndicator
self.shortcutCell.backgroundColor = ColorUtil.theme.foregroundColor
self.shortcutCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.shortcutCell.imageView?.image = UIImage(sfString: SFSymbol.boltFill, overrideString: "compact")?.toolbarIcon()
self.shortcutCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.mainTheme.textLabel?.text = "App theme"
self.mainTheme.accessoryType = .disclosureIndicator
self.mainTheme.backgroundColor = ColorUtil.theme.foregroundColor
self.mainTheme.textLabel?.textColor = ColorUtil.theme.fontColor
self.mainTheme.imageView?.image = UIImage(named: "palette")?.toolbarIcon()
self.mainTheme.imageView?.tintColor = ColorUtil.theme.fontColor
self.icon.textLabel?.text = "App icon"
self.icon.accessoryType = .disclosureIndicator
self.icon.backgroundColor = ColorUtil.theme.foregroundColor
self.icon.textLabel?.textColor = ColorUtil.theme.fontColor
self.icon.imageView?.image = Bundle.main.icon?.getCopy(withSize: CGSize(width: 25, height: 25))
self.icon.imageView?.layer.cornerRadius = 5
self.icon.imageView?.clipsToBounds = true
self.tagsCell.textLabel?.text = "User Tags Management"
self.tagsCell.accessoryType = .disclosureIndicator
self.tagsCell.backgroundColor = ColorUtil.theme.foregroundColor
self.tagsCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.tagsCell.imageView?.image = UIImage(sfString: SFSymbol.tagFill, overrideString: "user")?.toolbarIcon()
self.tagsCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.goPro.textLabel?.text = "Support Slide, go Pro!"
self.goPro.accessoryType = .disclosureIndicator
self.goPro.backgroundColor = ColorUtil.theme.foregroundColor
self.goPro.textLabel?.textColor = ColorUtil.theme.fontColor
self.goPro.imageView?.image = UIImage(sfString: SFSymbol.heartCircleFill, overrideString: "support")?.toolbarIcon().getCopy(withColor: GMColor.red500Color())
self.goPro.imageView?.tintColor = ColorUtil.theme.fontColor
self.coffeeCell.textLabel?.text = "Tip Jar"
self.coffeeCell.accessoryType = .disclosureIndicator
self.coffeeCell.backgroundColor = ColorUtil.theme.foregroundColor
self.coffeeCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.coffeeCell.imageView?.image = UIImage(sfString: SFSymbol.heartCircleFill, overrideString: "support")?.toolbarIcon().getCopy(withColor: GMColor.lightGreen500Color())
self.coffeeCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.clearCell.textLabel?.text = "Clear cache"
self.clearCell.accessoryType = .none
self.clearCell.backgroundColor = ColorUtil.theme.foregroundColor
self.clearCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.clearCell.imageView?.image = UIImage(sfString: SFSymbol.trashFill, overrideString: "multis")?.toolbarIcon()
self.clearCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.clearCell.detailTextLabel?.textColor = ColorUtil.theme.fontColor
let countBytes = ByteCountFormatter()
countBytes.allowedUnits = [.useMB]
countBytes.countStyle = .file
let fileSize = countBytes.string(fromByteCount: Int64(SDImageCache.shared.totalDiskSize() + UInt(checkRealmFileSize())))
self.clearCell.detailTextLabel?.text = fileSize
self.clearCell.detailTextLabel?.numberOfLines = 0
self.backupCell.textLabel?.text = "Backup and Restore"
self.backupCell.accessoryType = .disclosureIndicator
self.backupCell.backgroundColor = ColorUtil.theme.foregroundColor
self.backupCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.backupCell.imageView?.image = UIImage(sfString: SFSymbol.arrowCounterclockwise, overrideString: "restore")?.toolbarIcon()
self.backupCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.gestureCell.textLabel?.text = "Gestures"
self.gestureCell.accessoryType = .disclosureIndicator
self.gestureCell.backgroundColor = ColorUtil.theme.foregroundColor
self.gestureCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.gestureCell.imageView?.image = UIImage(sfString: .scribble, overrideString: "gestures")?.toolbarIcon()
self.gestureCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.gestureCell.detailTextLabel?.textColor = ColorUtil.theme.fontColor
self.gestureCell.detailTextLabel?.text = "Swipe and tap gestures for submissions and comments"
self.gestureCell.detailTextLabel?.numberOfLines = 0
self.widgetsCell.textLabel?.text = "Widgets"
self.widgetsCell.accessoryType = .disclosureIndicator
self.widgetsCell.backgroundColor = ColorUtil.theme.foregroundColor
self.widgetsCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.widgetsCell.imageView?.image = UIImage(sfString: .squareGrid2x2, overrideString: "gestures")?.toolbarIcon()
self.widgetsCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.widgetsCell.detailTextLabel?.textColor = ColorUtil.theme.fontColor
self.widgetsCell.detailTextLabel?.text = "Create subreddit lists for Slide widgets"
self.widgetsCell.detailTextLabel?.numberOfLines = 0
self.cacheCell.textLabel?.text = "Offline caching"
self.cacheCell.accessoryType = .disclosureIndicator
self.cacheCell.backgroundColor = ColorUtil.theme.foregroundColor
self.cacheCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.cacheCell.imageView?.image = UIImage(sfString: SFSymbol.arrow2Circlepath, overrideString: "save-1")?.toolbarIcon()
self.cacheCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.postLayout.textLabel?.text = "Card layout"
self.postLayout.accessoryType = .disclosureIndicator
self.postLayout.backgroundColor = ColorUtil.theme.foregroundColor
self.postLayout.textLabel?.textColor = ColorUtil.theme.fontColor
self.postLayout.imageView?.image = UIImage(sfString: SFSymbol.squareStack3dUpFill, overrideString: "layout")?.toolbarIcon()
self.postLayout.imageView?.tintColor = ColorUtil.theme.fontColor
self.subThemes.textLabel?.text = "Subreddit themes"
self.subThemes.accessoryType = .disclosureIndicator
self.subThemes.backgroundColor = ColorUtil.theme.foregroundColor
self.subThemes.textLabel?.textColor = ColorUtil.theme.fontColor
self.subThemes.imageView?.image = UIImage(sfString: .eyedropperHalffull, overrideString: "subs")?.toolbarIcon()
self.subThemes.imageView?.tintColor = ColorUtil.theme.fontColor
self.font.textLabel?.text = "Font and Links"
self.font.accessoryType = .disclosureIndicator
self.font.backgroundColor = ColorUtil.theme.foregroundColor
self.font.textLabel?.textColor = ColorUtil.theme.fontColor
self.font.imageView?.image = UIImage(sfString: SFSymbol.textformat, overrideString: "size")?.toolbarIcon()
self.font.imageView?.tintColor = ColorUtil.theme.fontColor
self.comments.textLabel?.text = "Comments"
self.comments.accessoryType = .disclosureIndicator
self.comments.backgroundColor = ColorUtil.theme.foregroundColor
self.comments.textLabel?.textColor = ColorUtil.theme.fontColor
self.comments.imageView?.image = UIImage(sfString: SFSymbol.bubbleLeftAndBubbleRightFill, overrideString: "comments")?.toolbarIcon()
self.comments.imageView?.tintColor = ColorUtil.theme.fontColor
self.linkHandling.textLabel?.text = "Link handling"
self.linkHandling.accessoryType = .disclosureIndicator
self.linkHandling.backgroundColor = ColorUtil.theme.foregroundColor
self.linkHandling.textLabel?.textColor = ColorUtil.theme.fontColor
self.linkHandling.imageView?.image = UIImage(sfString: SFSymbol.link, overrideString: "link")?.toolbarIcon()
self.linkHandling.imageView?.tintColor = ColorUtil.theme.fontColor
self.history.textLabel?.text = "History"
self.history.accessoryType = .disclosureIndicator
self.history.backgroundColor = ColorUtil.theme.foregroundColor
self.history.textLabel?.textColor = ColorUtil.theme.fontColor
self.history.imageView?.image = UIImage(sfString: SFSymbol.clockFill, overrideString: "history")?.toolbarIcon()
self.history.imageView?.tintColor = ColorUtil.theme.fontColor
self.history.detailTextLabel?.textColor = ColorUtil.theme.fontColor
self.history.detailTextLabel?.text = "\(History.seenTimes.allKeys.count) visited posts"
self.history.detailTextLabel?.numberOfLines = 0
self.dataSaving.textLabel?.text = "Data saving"
self.dataSaving.accessoryType = .disclosureIndicator
self.dataSaving.backgroundColor = ColorUtil.theme.foregroundColor
self.dataSaving.textLabel?.textColor = ColorUtil.theme.fontColor
self.dataSaving.imageView?.image = UIImage(sfString: SFSymbol.wifiExclamationmark, overrideString: "data")?.toolbarIcon()
self.dataSaving.imageView?.tintColor = ColorUtil.theme.fontColor
self.content.textLabel?.text = "NSFW Content"
self.content.accessoryType = .disclosureIndicator
self.content.backgroundColor = ColorUtil.theme.foregroundColor
self.content.textLabel?.textColor = ColorUtil.theme.fontColor
self.content.imageView?.image = UIImage(sfString: SFSymbol.eyeSlashFill, overrideString: "image")?.toolbarIcon()
self.content.imageView?.tintColor = ColorUtil.theme.fontColor
self.subCell.textLabel?.text = "Visit the Slide subreddit!"
self.subCell.accessoryType = .disclosureIndicator
self.subCell.backgroundColor = ColorUtil.theme.foregroundColor
self.subCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.subCell.imageView?.image = UIImage(sfString: .rCircleFill, overrideString: "subs")?.toolbarIcon()
self.subCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.filters.textLabel?.text = "Filters"
self.filters.accessoryType = .disclosureIndicator
self.filters.backgroundColor = ColorUtil.theme.foregroundColor
self.filters.textLabel?.textColor = ColorUtil.theme.fontColor
self.filters.imageView?.image = UIImage(named: "filter")?.toolbarIcon()
self.filters.imageView?.tintColor = ColorUtil.theme.fontColor
self.aboutCell.textLabel?.text = "Version: \(getVersion())"
self.aboutCell.accessoryType = .disclosureIndicator
self.aboutCell.backgroundColor = ColorUtil.theme.foregroundColor
self.aboutCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.aboutCell.imageView?.image = UIImage(sfString: SFSymbol.infoCircleFill, overrideString: "info")?.toolbarIcon()
self.aboutCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.githubCell.textLabel?.text = "Github"
self.githubCell.accessoryType = .disclosureIndicator
self.githubCell.backgroundColor = ColorUtil.theme.foregroundColor
self.githubCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.githubCell.imageView?.image = UIImage(named: "github")?.toolbarIcon()
self.githubCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.licenseCell.textLabel?.text = "Open source licenses"
self.licenseCell.accessoryType = .disclosureIndicator
self.licenseCell.backgroundColor = ColorUtil.theme.foregroundColor
self.licenseCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.licenseCell.imageView?.image = UIImage(sfString: SFSymbol.chevronLeftSlashChevronRight, overrideString: "code")?.toolbarIcon()
self.licenseCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.contributorsCell.textLabel?.text = "Slide project contributors"
self.contributorsCell.accessoryType = .disclosureIndicator
self.contributorsCell.backgroundColor = ColorUtil.theme.foregroundColor
self.contributorsCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.contributorsCell.imageView?.image = UIImage(sfString: SFSymbol.smileyFill, overrideString: "happy")?.toolbarIcon()
self.contributorsCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.autoPlayCell.textLabel?.text = "Autoplay videos and gifs"
self.autoPlayCell.accessoryType = .none
self.autoPlayCell.backgroundColor = ColorUtil.theme.foregroundColor
self.autoPlayCell.textLabel?.textColor = ColorUtil.theme.fontColor
self.autoPlayCell.imageView?.image = UIImage(sfString: SFSymbol.playFill, overrideString: "play")?.toolbarIcon()
self.autoPlayCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.autoPlayCell.detailTextLabel?.textColor = ColorUtil.theme.fontColor
self.autoPlayCell.detailTextLabel?.text = SettingValues.autoPlayMode.description() + "\nAutoplaying videos can lead to more data use"
self.autoPlayCell.detailTextLabel?.numberOfLines = 0
self.autoPlayCell.detailTextLabel?.lineBreakMode = .byWordWrapping
viewModeCell.textLabel?.text = "Multi-Column and app behavior"
viewModeCell.accessoryType = .disclosureIndicator
viewModeCell.backgroundColor = ColorUtil.theme.foregroundColor
viewModeCell.textLabel?.textColor = ColorUtil.theme.fontColor
viewModeCell.selectionStyle = UITableViewCell.SelectionStyle.none
self.viewModeCell.imageView?.image = UIImage(sfString: SFSymbol.sidebarLeft, overrideString: "multicolumn")?.toolbarIcon()
self.viewModeCell.imageView?.tintColor = ColorUtil.theme.fontColor
self.viewModeCell.detailTextLabel?.textColor = ColorUtil.theme.fontColor
self.viewModeCell.detailTextLabel?.text = "Multi-Column mode, Split UI, and subreddit bar settings"
self.viewModeCell.detailTextLabel?.numberOfLines = 0
lock = UISwitch().then {
$0.onTintColor = ColorUtil.baseAccent
}
lock.isOn = SettingValues.biometrics
lock.isEnabled = BioMetricAuthenticator.canAuthenticate()
lock.addTarget(self, action: #selector(SettingsViewController.switchIsChanged(_:)), for: UIControl.Event.valueChanged)
lockCell.textLabel?.text = "Biometric app lock"
lockCell.accessoryView = lock
lockCell.backgroundColor = ColorUtil.theme.foregroundColor
lockCell.textLabel?.textColor = ColorUtil.theme.fontColor
lockCell.selectionStyle = UITableViewCell.SelectionStyle.none
self.lockCell.imageView?.image = UIImage(sfString: SFSymbol.lockFill, overrideString: "lockapp")?.toolbarIcon()
self.lockCell.imageView?.tintColor = ColorUtil.theme.fontColor
subIcons = UISwitch().then {
$0.onTintColor = ColorUtil.baseAccent
}
subIcons.isOn = SettingValues.subredditIcons
subIcons.addTarget(self, action: #selector(SettingsViewController.switchIsChanged(_:)), for: UIControl.Event.valueChanged)
subIconsCell.textLabel?.text = "Subreddit Icons on posts"
subIconsCell.accessoryView = subIcons
subIconsCell.backgroundColor = ColorUtil.theme.foregroundColor
subIconsCell.textLabel?.textColor = ColorUtil.theme.fontColor
subIconsCell.selectionStyle = UITableViewCell.SelectionStyle.none
self.subIconsCell.imageView?.image = UIImage(named: "icon")?.getCopy(withSize: CGSize(width: 25, height: 25))
self.subIconsCell.imageView?.layer.cornerRadius = 12.5
self.subIconsCell.imageView?.clipsToBounds = true
audioSettings.textLabel?.text = "Audio"
audioSettings.accessoryType = .disclosureIndicator
audioSettings.backgroundColor = ColorUtil.theme.foregroundColor
audioSettings.textLabel?.textColor = ColorUtil.theme.fontColor
audioSettings.imageView?.image = UIImage(sfString: SFSymbol.speaker3Fill, overrideString: "audio")?.toolbarIcon()
audioSettings.imageView?.tintColor = ColorUtil.theme.fontColor
if reset {
self.tableView.reloadData()
}
}
@objc func switchIsChanged(_ changed: UISwitch) {
if changed == lock {
if !VCPresenter.proDialogShown(feature: true, self) {
SettingValues.biometrics = changed.isOn
UserDefaults.standard.set(changed.isOn, forKey: SettingValues.pref_biometrics)
} else {
changed.isOn = false
}
} else if changed == subIcons {
SingleSubredditViewController.cellVersion += 1
MainViewController.needsReTheme = true
SettingValues.subredditIcons = changed.isOn
UserDefaults.standard.set(changed.isOn, forKey: SettingValues.pref_subredditIcons)
}
UserDefaults.standard.synchronize()
}
func checkRealmFileSize() -> Double {
if let realmPath = Realm.Configuration.defaultConfiguration.fileURL?.relativePath {
do {
let attributes = try FileManager.default.attributesOfItem(atPath: realmPath)
if let fileSize = attributes[FileAttributeKey.size] as? Double {
return fileSize
}
} catch let error {
print(error)
}
}
return 0
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 4
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView()
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 30
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell
switch indexPath.section {
case 0:
if SettingValues.isPro {
switch indexPath.row {
case 0: cell = self.general
case 1: cell = self.manageSubs
case 2: cell = self.viewModeCell
case 3: cell = self.lockCell
case 4: cell = self.subIconsCell
case 5: cell = self.gestureCell
case 6: cell = self.widgetsCell
default: fatalError("Unknown row in section 0")
}
} else {
switch indexPath.row {
case 0: cell = self.general
case 1: cell = self.manageSubs
case 2: cell = self.goPro
case 3: cell = self.viewModeCell
case 4: cell = self.lockCell
case 5: cell = self.subIconsCell
case 6: cell = self.gestureCell
case 7: cell = self.widgetsCell
default: fatalError("Unknown row in section 0")
}
}
case 1:
switch indexPath.row {
case 0: cell = self.mainTheme
case 1: cell = self.icon
case 2: cell = self.postLayout
case 3: cell = self.autoPlayCell
case 4: cell = self.audioSettings
case 5: cell = self.subThemes
case 6: cell = self.font
case 7: cell = self.comments
case 8: cell = self.postActionCell
case 9: cell = self.shortcutCell
default: fatalError("Unknown row in section 1")
}
case 2:
switch indexPath.row {
case 0: cell = self.linkHandling
case 1: cell = self.history
case 2: cell = self.dataSaving
case 3: cell = self.content
case 4: cell = self.filters
case 5: cell = self.cacheCell
case 6: cell = self.clearCell
case 7: cell = self.backupCell
case 8: cell = self.tagsCell
default: fatalError("Unknown row in section 2")
}
case 3:
switch indexPath.row {
case 0: cell = self.aboutCell
case 1: cell = self.subCell
case 2: cell = self.contributorsCell
//case 4: return self.coffeeCell
case 3: cell = self.githubCell
case 4: cell = self.licenseCell
default: fatalError("Unknown row in section 3")
}
default: fatalError("Unknown section")
}
return cell
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let cell = cell as? InsetCell {
if indexPath.row == 0 {
cell.top = true
} else {
cell.top = false
}
if indexPath.row == tableView.numberOfRows(inSection: indexPath.section) - 1 {
cell.bottom = true
} else {
cell.bottom = false
}
}
}
// func showMultiColumn() {
// if !VCPresenter.proDialogShown(feature: true, self) {
// let actionSheetController: UIAlertController = UIAlertController(title: "Multi Column Mode", message: "", preferredStyle: .actionSheet)
//
// let cancelActionButton: UIAlertAction = UIAlertAction(title: "Close", style: .cancel) { _ -> Void in
// }
// actionSheetController.addAction(cancelActionButton)
//
// multiColumn = UISwitch.init(frame: CGRect.init(x: 20, y: 20, width: 75, height: 50))
// multiColumn.isOn = SettingValues.multiColumn
// multiColumn.addTarget(self, action: #selector(SettingsViewController.switchIsChanged(_:)), for: UIControlEvents.valueChanged)
// actionSheetController.view.addSubview(multiColumn)
//
// let values = [["1", "2", "3", "4", "5"]]
// actionSheetController.addPickerView(values: values, initialSelection: [(0, SettingValues.multiColumnCount - 1)]) { (_, _, chosen, _) in
// SettingValues.multiColumnCount = chosen.row + 1
// UserDefaults.standard.set(chosen.row + 1, forKey: SettingValues.pref_multiColumnCount)
// UserDefaults.standard.synchronize()
// SubredditReorderViewController.changed = true
// }
//
// actionSheetController.modalPresentationStyle = .popover
//
// if let presenter = actionSheetController.popoverPresentationController {
// presenter.sourceView = multiColumnCell
// presenter.sourceRect = multiColumnCell.bounds
// }
//
// self.present(actionSheetController, animated: true, completion: nil)
// }
// }
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
var ch: UIViewController?
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
ch = SettingsGeneral()
case 1:
ch = SubredditReorderViewController()
case 2:
if !SettingValues.isPro {
VCPresenter.proDialogShown(feature: true, self)
} else {
ch = SettingsViewMode()
}
case 3:
if !SettingValues.isPro {
ch = SettingsViewMode()
}
case 5:
if SettingValues.isPro {
ch = SettingsGestures()
}
case 6:
if !SettingValues.isPro {
ch = SettingsGestures()
} else {
ch = SettingsWidget()
}
case 7:
ch = SettingsWidget()
default:
break
}
case 1:
switch indexPath.row {
case 0:
ch = SettingsTheme()
(ch as! SettingsTheme).tochange = self
case 1:
if #available(iOS 10.3, *) {
ch = SettingsIcon()
} else {
let alert = UIAlertController(title: "Can't access alternate icons", message: "Alternate icons require iOS 10.3 or above", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil))
VCPresenter.presentAlert(alert, parentVC: self)
}
case 2:
ch = SettingsLayout()
case 3:
let alertController = DragDownAlertMenu(title: "AutoPlay Settings", subtitle: "AutoPlay can lead to higher data use", icon: nil)
for item in SettingValues.AutoPlay.cases {
alertController.addAction(title: item.description(), icon: UIImage()) {
UserDefaults.standard.set(item.rawValue, forKey: SettingValues.pref_autoPlayMode)
SettingValues.autoPlayMode = item
UserDefaults.standard.synchronize()
self.autoPlayCell.detailTextLabel?.text = SettingValues.autoPlayMode.description() + "\nAutoPlaying videos can lead to more data use"
SingleSubredditViewController.cellVersion += 1
SubredditReorderViewController.changed = true
}
}
alertController.show(self)
case 4:
ch = SettingsAudio()
case 5:
ch = SubredditThemeViewController()
case 6:
ch = SettingsFont()
case 7:
ch = SettingsComments()
case 8:
ch = SettingsPostMenu()
case 9:
ch = SettingsShortcutMenu()
default:
break
}
case 2:
switch indexPath.row {
case 0:
ch = SettingsLinkHandling()
case 1:
ch = SettingsHistory()
case 2:
ch = SettingsData()
case 3:
ch = SettingsContent()
case 4:
ch = FiltersViewController()
case 5:
ch = CacheSettings()
case 6:
do {
let realm = try Realm()
try! realm.write {
realm.deleteAll()
}
if let path = Realm.Configuration.defaultConfiguration.fileURL?.relativePath {
do {
try FileManager().removeItem(atPath: path)
} catch {
}
} else {
print("Realm file not found")
}
} catch let error as NSError {
print("error - \(error.localizedDescription)")
}
let activity = UIActivityIndicatorView()
activity.color = ColorUtil.theme.navIconColor
activity.hidesWhenStopped = true
activity.backgroundColor = ColorUtil.theme.foregroundColor
clearCell.addSubview(activity)
activity.startAnimating()
activity.rightAnchor == clearCell.rightAnchor - 16
activity.centerYAnchor == clearCell.centerYAnchor
DispatchQueue.global(qos: .background).async { [weak self] in
guard let self = self else { return }
SDImageCache.shared.clearMemory()
SDImageCache.shared.clearDisk()
do {
var cache_path = SDImageCache.shared.diskCachePath
cache_path += cache_path.endsWith("/") ? "" : "/"
let files = try FileManager.default.contentsOfDirectory(atPath: cache_path)
for file in files {
if file.endsWith(".mp4") {
try FileManager.default.removeItem(atPath: cache_path + file)
}
}
} catch {
print(error)
}
let defaultURL = Realm.Configuration.defaultConfiguration.fileURL!
let defaultParentURL = defaultURL.deletingLastPathComponent()
let compactedURL = defaultParentURL.appendingPathComponent("default-compact.realm")
let countBytes = ByteCountFormatter()
countBytes.allowedUnits = [.useMB]
countBytes.countStyle = .file
let fileSize = countBytes.string(fromByteCount: Int64(SDImageCache.shared.totalDiskSize() + UInt(self.checkRealmFileSize())))
DispatchQueue.main.async {
self.clearCell.accessoryType = .disclosureIndicator
BannerUtil.makeBanner(text: "All caches cleared!", color: GMColor.green500Color(), seconds: 3, context: self)
self.clearCell.detailTextLabel?.text = fileSize
activity.stopAnimating()
}
}
case 7:
if !SettingValues.isPro {
ch = SettingsPro()
} else {
ch = SettingsBackup()
}
case 8:
ch = SettingsUserTags()
default:
break
}
case 3:
switch indexPath.row {
case 0:
var url = UserDefaults.standard.string(forKey: "vlink") ?? ""
if url.isEmpty {
url = "https://www.reddit.com/r/slide_ios"
} else {
VCPresenter.openRedditLink(url, self.navigationController, self)
}
case 1:
ch = SingleSubredditViewController.init(subName: "slide_ios", single: true)
case 2:
let url = URL.init(string: "https://github.com/ccrama/Slide-ios/graphs/contributors")!
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
case 3:
let url = URL.init(string: "https://github.com/ccrama/Slide-ios")!
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
case 4:
ch = LicensesViewController()
let file = Bundle.main.path(forResource: "Credits", ofType: "plist")!
(ch as! LicensesViewController).loadPlist(NSDictionary(contentsOfFile: file)!)
default:
break
}
default:
break
}
if let n = ch {
VCPresenter.showVC(viewController: n, popupIfPossible: false, parentNavigationController: navigationController, parentViewController: self)
}
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label: UILabel = UILabel()
label.textColor = ColorUtil.baseAccent
label.font = FontGenerator.boldFontOfSize(size: 14, submission: true)
let toReturn = label.withPadding(padding: UIEdgeInsets.init(top: 0, left: 24, bottom: 0, right: 0))
toReturn.backgroundColor = ColorUtil.theme.backgroundColor
switch section {
case 0: label.text = "General"
case 1: label.text = "Appearance"
case 2: label.text = "Content"
case 3: label.text = "About"
default: label.text = ""
}
return toReturn
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var iOS14 = false
if #available(iOS 14.0, *) {
iOS14 = true
}
switch section {
case 0: return ((SettingValues.isPro) ? 6 : 7) + (iOS14 ? 1 : 0)
case 1: return 10
case 2: return 9
case 3: return 5
default: fatalError("Unknown number of sections")
}
}
func getVersion() -> String {
let dictionary = Bundle.main.infoDictionary!
let version = dictionary["CFBundleShortVersionString"] as! String
let build = dictionary["CFBundleVersion"] as! String
return "\(version) build \(build)"
}
}
extension Bundle {
public var icon: UIImage? {
if #available(iOS 10.3, *) {
if let alt = UIApplication.shared.alternateIconName {
return UIImage(named: "ic_" + alt)
}
}
if let icons = infoDictionary?["CFBundleIcons"] as? [String: Any],
let primaryIcon = icons["CFBundlePrimaryIcon"] as? [String: Any],
let iconFiles = primaryIcon["CFBundleIconFiles"] as? [String],
let lastIcon = iconFiles.last {
return UIImage(named: lastIcon)
}
return nil
}
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value) })
}
| apache-2.0 | 1a3d0ec3da7c32e8f4623dac4f71ea2a | 48.65625 | 258 | 0.642347 | 5.070533 | false | false | false | false |
parkboo/ios-charts | Charts/Classes/Charts/CombinedChartView.swift | 1 | 7656 | //
// CombinedChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
/// This chart class allows the combination of lines, bars, scatter and candle data all displayed in one chart area.
public class CombinedChartView: BarLineChartViewBase, LineChartDataProvider, BarChartDataProvider, ScatterChartDataProvider, CandleChartDataProvider, BubbleChartDataProvider, CubicLineChartDataProvider, CustomBar1ChartDataProvider
{
/// the fill-formatter used for determining the position of the fill-line
internal var _fillFormatter: ChartFillFormatter!
/// enum that allows to specify the order in which the different data objects for the combined-chart are drawn
@objc
public enum CombinedChartDrawOrder: Int
{
case Bar
case Bubble
case Line
case Candle
case Scatter
case Cubic
case CustomBar1
}
public override func initialize()
{
super.initialize()
_highlighter = CombinedHighlighter(chart: self)
/// WORKAROUND: Swift 2.0 compiler malfunctions when optimizations are enabled, and assigning directly to _fillFormatter causes a crash with a EXC_BAD_ACCESS. See https://github.com/danielgindi/ios-charts/issues/406
let workaroundFormatter = BarLineChartFillFormatter()
_fillFormatter = workaroundFormatter
renderer = CombinedChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
}
override func calcMinMax()
{
super.calcMinMax()
if (self.barData !== nil || self.candleData !== nil || self.bubbleData !== nil)
{
_chartXMin = -0.5
_chartXMax = Double(_data.xVals.count) - 0.5
if (self.bubbleData !== nil)
{
for set in self.bubbleData?.dataSets as! [BubbleChartDataSet]
{
let xmin = set.xMin
let xmax = set.xMax
if (xmin < chartXMin)
{
_chartXMin = xmin
}
if (xmax > chartXMax)
{
_chartXMax = xmax
}
}
}
}
_deltaX = CGFloat(abs(_chartXMax - _chartXMin))
if (_deltaX == 0.0 && self.lineData?.yValCount > 0)
{
_deltaX = 1.0
}
if (_deltaX == 0.0 && self.cubicData?.yValCount > 0)
{
_deltaX = 1.0
}
}
public override var data: ChartData?
{
get
{
return super.data
}
set
{
super.data = newValue
(renderer as! CombinedChartRenderer?)!.createRenderers()
}
}
public var fillFormatter: ChartFillFormatter
{
get
{
return _fillFormatter
}
set
{
_fillFormatter = newValue
if (_fillFormatter == nil)
{
_fillFormatter = BarLineChartFillFormatter()
}
}
}
// MARK: - LineChartDataProvider
public var lineData: LineChartData?
{
get
{
if (_data === nil)
{
return nil
}
return (_data as! CombinedChartData!).lineData
}
}
// MARK: - BarChartDataProvider
public var barData: BarChartData?
{
get
{
if (_data === nil)
{
return nil
}
return (_data as! CombinedChartData!).barData
}
}
// MARK: - ScatterChartDataProvider
public var scatterData: ScatterChartData?
{
get
{
if (_data === nil)
{
return nil
}
return (_data as! CombinedChartData!).scatterData
}
}
// MARK: - CandleChartDataProvider
public var candleData: CandleChartData?
{
get
{
if (_data === nil)
{
return nil
}
return (_data as! CombinedChartData!).candleData
}
}
// MARK: - BubbleChartDataProvider
public var bubbleData: BubbleChartData?
{
get
{
if (_data === nil)
{
return nil
}
return (_data as! CombinedChartData!).bubbleData
}
}
// MARK: - CubicLineChartDataProvider
public var cubicData: CubicLineChartData?
{
get
{
if (_data === nil)
{
return nil
}
return (_data as! CombinedChartData!).cubicData
}
}
// MARK: - CustomBar1ChartDataProvider
public var customBar1Data: CustomBar1ChartData?
{
get
{
if (_data === nil)
{
return nil
}
return (_data as! CombinedChartData!).customBar1Data
}
}
// MARK: - Accessors
/// flag that enables or disables the highlighting arrow
public var drawHighlightArrowEnabled: Bool
{
get { return (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled }
set { (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled = newValue }
}
/// if set to true, all values are drawn above their bars, instead of below their top
public var drawValueAboveBarEnabled: Bool
{
get { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled }
set { (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled = newValue }
}
/// if set to true, a grey area is darawn behind each bar that indicates the maximum value
public var drawBarShadowEnabled: Bool
{
get { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled }
set { (renderer as! CombinedChartRenderer!).drawBarShadowEnabled = newValue }
}
/// - returns: true if drawing the highlighting arrow is enabled, false if not
public var isDrawHighlightArrowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawHighlightArrowEnabled; }
/// - returns: true if drawing values above bars is enabled, false if not
public var isDrawValueAboveBarEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawValueAboveBarEnabled; }
/// - returns: true if drawing shadows (maxvalue) for each bar is enabled, false if not
public var isDrawBarShadowEnabled: Bool { return (renderer as! CombinedChartRenderer!).drawBarShadowEnabled; }
/// the order in which the provided data objects should be drawn.
/// The earlier you place them in the provided array, the further they will be in the background.
/// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines.
public var drawOrder: [Int]
{
get
{
return (renderer as! CombinedChartRenderer!).drawOrder.map { $0.rawValue }
}
set
{
(renderer as! CombinedChartRenderer!).drawOrder = newValue.map { CombinedChartDrawOrder(rawValue: $0)! }
}
}
} | apache-2.0 | 19421a690ffc52cb9f55aa38fa122047 | 28.114068 | 230 | 0.556818 | 5.44911 | false | false | false | false |
ikesyo/Quick | Sources/Quick/Configuration/Configuration.swift | 40 | 5985 | import Foundation
/**
A closure that temporarily exposes a Configuration object within
the scope of the closure.
*/
public typealias QuickConfigurer = (_ configuration: Configuration) -> ()
/**
A closure that, given metadata about an example, returns a boolean value
indicating whether that example should be run.
*/
public typealias ExampleFilter = (_ example: Example) -> Bool
/**
A configuration encapsulates various options you can use
to configure Quick's behavior.
*/
final public class Configuration: NSObject {
internal let exampleHooks = ExampleHooks()
internal let suiteHooks = SuiteHooks()
internal var exclusionFilters: [ExampleFilter] = [{ example in
if let pending = example.filterFlags[Filter.pending] {
return pending
} else {
return false
}
}]
internal var inclusionFilters: [ExampleFilter] = [{ example in
if let focused = example.filterFlags[Filter.focused] {
return focused
} else {
return false
}
}]
/**
Run all examples if none match the configured filters. True by default.
*/
public var runAllWhenEverythingFiltered = true
/**
Registers an inclusion filter.
All examples are filtered using all inclusion filters.
The remaining examples are run. If no examples remain, all examples are run.
- parameter filter: A filter that, given an example, returns a value indicating
whether that example should be included in the examples
that are run.
*/
public func include(_ filter: @escaping ExampleFilter) {
inclusionFilters.append(filter)
}
/**
Registers an exclusion filter.
All examples that remain after being filtered by the inclusion filters are
then filtered via all exclusion filters.
- parameter filter: A filter that, given an example, returns a value indicating
whether that example should be excluded from the examples
that are run.
*/
public func exclude(_ filter: @escaping ExampleFilter) {
exclusionFilters.append(filter)
}
/**
Identical to Quick.Configuration.beforeEach, except the closure is
provided with metadata on the example that the closure is being run
prior to.
*/
#if _runtime(_ObjC)
@objc(beforeEachWithMetadata:)
public func beforeEach(_ closure: @escaping BeforeExampleWithMetadataClosure) {
exampleHooks.appendBefore(closure)
}
#else
public func beforeEach(_ closure: @escaping BeforeExampleWithMetadataClosure) {
exampleHooks.appendBefore(closure)
}
#endif
/**
Like Quick.DSL.beforeEach, this configures Quick to execute the
given closure before each example that is run. The closure
passed to this method is executed before each example Quick runs,
globally across the test suite. You may call this method multiple
times across mulitple +[QuickConfigure configure:] methods in order
to define several closures to run before each example.
Note that, since Quick makes no guarantee as to the order in which
+[QuickConfiguration configure:] methods are evaluated, there is no
guarantee as to the order in which beforeEach closures are evaluated
either. Mulitple beforeEach defined on a single configuration, however,
will be executed in the order they're defined.
- parameter closure: The closure to be executed before each example
in the test suite.
*/
public func beforeEach(_ closure: @escaping BeforeExampleClosure) {
exampleHooks.appendBefore(closure)
}
/**
Identical to Quick.Configuration.afterEach, except the closure
is provided with metadata on the example that the closure is being
run after.
*/
#if _runtime(_ObjC)
@objc(afterEachWithMetadata:)
public func afterEach(_ closure: @escaping AfterExampleWithMetadataClosure) {
exampleHooks.appendAfter(closure)
}
#else
public func afterEach(_ closure: @escaping AfterExampleWithMetadataClosure) {
exampleHooks.appendAfter(closure)
}
#endif
/**
Like Quick.DSL.afterEach, this configures Quick to execute the
given closure after each example that is run. The closure
passed to this method is executed after each example Quick runs,
globally across the test suite. You may call this method multiple
times across mulitple +[QuickConfigure configure:] methods in order
to define several closures to run after each example.
Note that, since Quick makes no guarantee as to the order in which
+[QuickConfiguration configure:] methods are evaluated, there is no
guarantee as to the order in which afterEach closures are evaluated
either. Mulitple afterEach defined on a single configuration, however,
will be executed in the order they're defined.
- parameter closure: The closure to be executed before each example
in the test suite.
*/
public func afterEach(_ closure: @escaping AfterExampleClosure) {
exampleHooks.appendAfter(closure)
}
/**
Like Quick.DSL.beforeSuite, this configures Quick to execute
the given closure prior to any and all examples that are run.
The two methods are functionally equivalent.
*/
public func beforeSuite(_ closure: @escaping BeforeSuiteClosure) {
suiteHooks.appendBefore(closure)
}
/**
Like Quick.DSL.afterSuite, this configures Quick to execute
the given closure after all examples have been run.
The two methods are functionally equivalent.
*/
public func afterSuite(_ closure: @escaping AfterSuiteClosure) {
suiteHooks.appendAfter(closure)
}
}
| apache-2.0 | 0322d51da08f2a947c0fa99e95a8e75e | 36.173913 | 87 | 0.676023 | 5.372531 | false | true | false | false |
Ming-Lau/DouyuTV | DouyuTV/DouyuTV/Classes/Home/View/HomeCycleView.swift | 1 | 1521 | //
// HomeCycleView.swift
// DouyuTV
//
// Created by 刘明 on 16/11/10.
// Copyright © 2016年 刘明. All rights reserved.
//
import UIKit
private let kCycleCell = "kCycleCell"
class HomeCycleView: UIView {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = UIViewAutoresizing()
//注册cell
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCycleCell)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
extension HomeCycleView{
class func homeCycleView() ->HomeCycleView{
return Bundle.main.loadNibNamed("HomeCycleView", owner: nil, options: nil)?.first as! HomeCycleView
}
}
extension HomeCycleView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCell, for: indexPath)
cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.blue : UIColor.red
return cell
}
}
| mit | 1ed775342da22060b17a47f2db335427 | 32.466667 | 121 | 0.705179 | 5.284211 | false | false | false | false |
danieltskv/swift-memory-game | MemoryGame/MemoryGame/Model/Card.swift | 1 | 775 | //
// Card.swift
// MemoryGame
//
// Created by Daniel Tsirulnikov on 19.3.2016.
// Copyright © 2016 Daniel Tsirulnikov. All rights reserved.
//
import Foundation
import UIKit.UIImage
class Card : CustomStringConvertible {
// MARK: - Properties
var id:NSUUID = NSUUID.init()
var shown:Bool = false
var image:UIImage
// MARK: - Lifecycle
init(image:UIImage) {
self.image = image
}
init(card:Card) {
self.id = card.id.copy() as! NSUUID
self.shown = card.shown
self.image = card.image.copy() as! UIImage
}
// MARK: - Methods
var description: String {
return "\(id.UUIDString)"
}
func equals(card: Card) -> Bool {
return card.id.isEqual(id)
}
} | apache-2.0 | 1d15825078a0e11d971e2cd09164e84e | 17.902439 | 61 | 0.586563 | 3.757282 | false | false | false | false |
stephentyrone/swift | test/decl/var/property_wrappers.swift | 1 | 56634 | // RUN: %target-typecheck-verify-swift -swift-version 5
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct Wrapper<T> {
private var _stored: T
init(stored: T) {
self._stored = stored
}
var wrappedValue: T {
get { _stored }
set { _stored = newValue }
}
}
@propertyWrapper
struct WrapperWithInitialValue<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperWithDefaultInit<T> {
private var stored: T?
var wrappedValue: T {
get { stored! }
set { stored = newValue }
}
init() {
self.stored = nil
}
}
@propertyWrapper
struct WrapperAcceptingAutoclosure<T> {
private let fn: () -> T
var wrappedValue: T {
return fn()
}
init(wrappedValue fn: @autoclosure @escaping () -> T) {
self.fn = fn
}
init(body fn: @escaping () -> T) {
self.fn = fn
}
}
@propertyWrapper
struct MissingValue<T> { }
// expected-error@-1{{property wrapper type 'MissingValue' does not contain a non-static property named 'wrappedValue'}} {{educational-notes=property-wrapper-requirements}}
@propertyWrapper
struct StaticValue {
static var wrappedValue: Int = 17
}
// expected-error@-3{{property wrapper type 'StaticValue' does not contain a non-static property named 'wrappedValue'}}
// expected-error@+1{{'@propertyWrapper' attribute cannot be applied to this declaration}}
@propertyWrapper
protocol CannotBeAWrapper {
associatedtype Value
var wrappedValue: Value { get set }
}
@propertyWrapper
struct NonVisibleValueWrapper<Value> {
private var wrappedValue: Value // expected-error{{private property 'wrappedValue' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleValueWrapper' (which is internal)}} {{educational-notes=property-wrapper-requirements}}
}
@propertyWrapper
struct NonVisibleInitWrapper<Value> {
var wrappedValue: Value
private init(wrappedValue initialValue: Value) { // expected-error{{private initializer 'init(wrappedValue:)' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleInitWrapper' (which is internal)}}
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct InitialValueTypeMismatch<Value> {
var wrappedValue: Value // expected-note{{'wrappedValue' declared here}}
init(wrappedValue initialValue: Value?) { // expected-error{{'init(wrappedValue:)' parameter type ('Value?') must be the same as its 'wrappedValue' property type ('Value') or an @autoclosure thereof}} {{educational-notes=property-wrapper-requirements}}
self.wrappedValue = initialValue!
}
}
@propertyWrapper
struct MultipleInitialValues<Value> {
var wrappedValue: Value? = nil // expected-note 2{{'wrappedValue' declared here}}
init(wrappedValue initialValue: Int) { // expected-error{{'init(wrappedValue:)' parameter type ('Int') must be the same as its 'wrappedValue' property type ('Value?') or an @autoclosure thereof}}
}
init(wrappedValue initialValue: Double) { // expected-error{{'init(wrappedValue:)' parameter type ('Double') must be the same as its 'wrappedValue' property type ('Value?') or an @autoclosure thereof}}
}
}
@propertyWrapper
struct InitialValueFailable<Value> {
var wrappedValue: Value
init?(wrappedValue initialValue: Value) { // expected-error{{property wrapper initializer 'init(wrappedValue:)' cannot be failable}} {{educational-notes=property-wrapper-requirements}}
return nil
}
}
@propertyWrapper
struct InitialValueFailableIUO<Value> {
var wrappedValue: Value
init!(wrappedValue initialValue: Value) { // expected-error{{property wrapper initializer 'init(wrappedValue:)' cannot be failable}}
return nil
}
}
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct _lowercaseWrapper<T> {
var wrappedValue: T
}
@propertyWrapper
struct _UppercaseWrapper<T> {
var wrappedValue: T
}
// ---------------------------------------------------------------------------
// Limitations on where property wrappers can be used
// ---------------------------------------------------------------------------
func testLocalContext() {
@WrapperWithInitialValue // expected-error{{property wrappers are not yet supported on local properties}}
var x = 17
x = 42
_ = x
}
enum SomeEnum {
case foo
@Wrapper(stored: 17)
var bar: Int // expected-error{{property 'bar' declared inside an enum cannot have a wrapper}}
// expected-error@-1{{enums must not contain stored properties}}
@Wrapper(stored: 17)
static var x: Int
}
protocol SomeProtocol {
@Wrapper(stored: 17)
var bar: Int // expected-error{{property 'bar' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
@Wrapper(stored: 17)
static var x: Int // expected-error{{property 'x' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
}
struct HasWrapper { }
extension HasWrapper {
@Wrapper(stored: 17)
var inExt: Int // expected-error{{property 'inExt' declared inside an extension cannot have a wrapper}}
// expected-error@-1{{extensions must not contain stored properties}}
@Wrapper(stored: 17)
static var x: Int
}
class ClassWithWrappers {
@Wrapper(stored: 17)
var x: Int
}
class Superclass {
var x: Int = 0
}
class SubclassOfClassWithWrappers: ClassWithWrappers {
override var x: Int {
get { return super.x }
set { super.x = newValue }
}
}
class SubclassWithWrapper: Superclass {
@Wrapper(stored: 17)
override var x: Int { get { return 0 } set { } } // expected-error{{property 'x' with attached wrapper cannot override another property}}
}
class C { }
struct BadCombinations {
@WrapperWithInitialValue
lazy var x: C = C() // expected-error{{property 'x' with a wrapper cannot also be lazy}}
@Wrapper
weak var y: C? // expected-error{{property 'y' with a wrapper cannot also be weak}}
@Wrapper
unowned var z: C // expected-error{{property 'z' with a wrapper cannot also be unowned}}
}
struct MultipleWrappers {
// FIXME: The diagnostics here aren't great. The problem is that we're
// attempting to splice a 'wrappedValue:' argument into the call to Wrapper's
// init, but it doesn't have a matching init. We're then attempting to access
// the nested 'wrappedValue', but Wrapper's 'wrappedValue' is Int.
@Wrapper(stored: 17) // expected-error{{cannot convert value of type 'Int' to expected argument type 'WrapperWithInitialValue<Int>'}}
@WrapperWithInitialValue // expected-error{{extra argument 'wrappedValue' in call}}
var x: Int = 17
@WrapperWithInitialValue // expected-error 2{{property wrapper can only apply to a single variable}}
var (y, z) = (1, 2)
}
// ---------------------------------------------------------------------------
// Initialization
// ---------------------------------------------------------------------------
struct Initialization {
@Wrapper(stored: 17)
var x: Int
@Wrapper(stored: 17)
var x2: Double
@Wrapper(stored: 17)
var x3 = 42 // expected-error {{extra argument 'wrappedValue' in call}}
@Wrapper(stored: 17)
var x4
@WrapperWithInitialValue
var y = true
@WrapperWithInitialValue<Int>
var y2 = true // expected-error{{cannot convert value of type 'Bool' to specified type 'Int'}}
mutating func checkTypes(s: String) {
x2 = s // expected-error{{cannot assign value of type 'String' to type 'Double'}}
x4 = s // expected-error{{cannot assign value of type 'String' to type 'Int'}}
y = s // expected-error{{cannot assign value of type 'String' to type 'Bool'}}
}
}
@propertyWrapper
struct Clamping<V: Comparable> {
var value: V
let min: V
let max: V
init(wrappedValue initialValue: V, min: V, max: V) {
value = initialValue
self.min = min
self.max = max
assert(value >= min && value <= max)
}
var wrappedValue: V {
get { return value }
set {
if newValue < min {
value = min
} else if newValue > max {
value = max
} else {
value = newValue
}
}
}
}
struct Color {
@Clamping(min: 0, max: 255) var red: Int = 127
@Clamping(min: 0, max: 255) var green: Int = 127
@Clamping(min: 0, max: 255) var blue: Int = 127
@Clamping(min: 0, max: 255) var alpha: Int = 255
}
func testColor() {
_ = Color(green: 17)
}
// ---------------------------------------------------------------------------
// Wrapper type formation
// ---------------------------------------------------------------------------
@propertyWrapper
struct IntWrapper {
var wrappedValue: Int
}
@propertyWrapper
struct WrapperForHashable<T: Hashable> { // expected-note{{property wrapper type 'WrapperForHashable' declared here}}
var wrappedValue: T
}
@propertyWrapper
struct WrapperWithTwoParams<T, U> {
var wrappedValue: (T, U)
}
struct NotHashable { }
struct UseWrappersWithDifferentForm {
@IntWrapper
var x: Int
// FIXME: Diagnostic should be better here
@WrapperForHashable
var y: NotHashable // expected-error{{property type 'NotHashable' does not match that of the 'wrappedValue' property of its wrapper type 'WrapperForHashable'}}
@WrapperForHashable
var yOkay: Int
@WrapperWithTwoParams
var zOkay: (Int, Float)
// FIXME: Need a better diagnostic here
@HasNestedWrapper.NestedWrapper
var w: Int // expected-error{{property type 'Int' does not match that of the 'wrappedValue' property of its wrapper type 'HasNestedWrapper.NestedWrapper'}}
@HasNestedWrapper<Double>.NestedWrapper
var wOkay: Int
@HasNestedWrapper.ConcreteNestedWrapper
var wOkay2: Int
}
@propertyWrapper
struct Function<T, U> { // expected-note{{property wrapper type 'Function' declared here}}
var wrappedValue: (T) -> U?
}
struct TestFunction {
@Function var f: (Int) -> Float?
@Function var f2: (Int) -> Float // expected-error{{property type '(Int) -> Float' does not match that of the 'wrappedValue' property of its wrapper type 'Function'}}
func test() {
let _: Int = _f // expected-error{{cannot convert value of type 'Function<Int, Float>' to specified type 'Int'}}
}
}
// ---------------------------------------------------------------------------
// Nested wrappers
// ---------------------------------------------------------------------------
struct HasNestedWrapper<T> {
@propertyWrapper
struct NestedWrapper<U> { // expected-note{{property wrapper type 'NestedWrapper' declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct ConcreteNestedWrapper {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
@NestedWrapper
var y: [T] = []
}
struct UsesNestedWrapper<V> {
@HasNestedWrapper<V>.NestedWrapper
var y: [V]
}
// ---------------------------------------------------------------------------
// Referencing the backing store
// ---------------------------------------------------------------------------
struct BackingStore<T> {
@Wrapper
var x: T
@WrapperWithInitialValue
private var y = true // expected-note{{'y' declared here}}
func getXStorage() -> Wrapper<T> {
return _x
}
func getYStorage() -> WrapperWithInitialValue<Bool> {
return self._y
}
}
func testBackingStore<T>(bs: BackingStore<T>) {
_ = bs.x
_ = bs.y // expected-error{{'y' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Explicitly-specified accessors
// ---------------------------------------------------------------------------
struct WrapperWithAccessors {
@Wrapper // expected-error{{property wrapper cannot be applied to a computed property}}
var x: Int {
return 17
}
}
struct UseWillSetDidSet {
@Wrapper
var x: Int {
willSet {
print(newValue)
}
}
@Wrapper
var y: Int {
didSet {
print(oldValue)
}
}
@Wrapper
var z: Int {
willSet {
print(newValue)
}
didSet {
print(oldValue)
}
}
}
// ---------------------------------------------------------------------------
// Mutating/nonmutating
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithNonMutatingSetter<Value> {
class Box {
var wrappedValue: Value
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
}
var box: Box
init(wrappedValue initialValue: Value) {
self.box = Box(wrappedValue: initialValue)
}
var wrappedValue: Value {
get { return box.wrappedValue }
nonmutating set { box.wrappedValue = newValue }
}
}
@propertyWrapper
struct WrapperWithMutatingGetter<Value> {
var readCount = 0
var writeCount = 0
var stored: Value
init(wrappedValue initialValue: Value) {
self.stored = initialValue
}
var wrappedValue: Value {
mutating get {
readCount += 1
return stored
}
set {
writeCount += 1
stored = newValue
}
}
}
@propertyWrapper
class ClassWrapper<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseMutatingnessWrappers {
@WrapperWithNonMutatingSetter
var x = true
@WrapperWithMutatingGetter
var y = 17
@WrapperWithNonMutatingSetter // expected-error{{property wrapper can only be applied to a 'var'}}
let z = 3.14159 // expected-note 2{{change 'let' to 'var' to make it mutable}}
@ClassWrapper
var w = "Hello"
}
func testMutatingness() {
var mutable = UseMutatingnessWrappers()
_ = mutable.x
mutable.x = false
_ = mutable.y
mutable.y = 42
_ = mutable.z
mutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
_ = mutable.w
mutable.w = "Goodbye"
let nonmutable = UseMutatingnessWrappers() // expected-note 2{{change 'let' to 'var' to make it mutable}}
// Okay due to nonmutating setter
_ = nonmutable.x
nonmutable.x = false
_ = nonmutable.y // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
nonmutable.y = 42 // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
_ = nonmutable.z
nonmutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
// Okay due to implicitly nonmutating setter
_ = nonmutable.w
nonmutable.w = "World"
}
// ---------------------------------------------------------------------------
// Access control
// ---------------------------------------------------------------------------
struct HasPrivateWrapper<T> {
@propertyWrapper
private struct PrivateWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@PrivateWrapper
var y: [T] = []
// expected-error@-1{{property must be declared private because its property wrapper type uses a private type}}
// Okay to reference private entities from a private property
@PrivateWrapper
private var z: [T]
}
public struct HasUsableFromInlineWrapper<T> {
@propertyWrapper
struct InternalWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@InternalWrapper
@usableFromInline
var y: [T] = []
// expected-error@-1{{property wrapper type referenced from a '@usableFromInline' property must be '@usableFromInline' or public}}
}
@propertyWrapper
class Box<Value> {
private(set) var wrappedValue: Value
init(wrappedValue initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseBox {
@Box
var x = 17 // expected-note{{'_x' declared here}}
}
func testBox(ub: UseBox) {
_ = ub.x
ub.x = 5 // expected-error{{cannot assign to property: 'x' is a get-only property}}
var mutableUB = ub
mutableUB = ub
}
func backingVarIsPrivate(ub: UseBox) {
_ = ub._x // expected-error{{'_x' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Memberwise initializers
// ---------------------------------------------------------------------------
struct MemberwiseInits<T> {
@Wrapper
var x: Bool
@WrapperWithInitialValue
var y: T
}
func testMemberwiseInits() {
// expected-error@+1{{type '(Wrapper<Bool>, Double) -> MemberwiseInits<Double>'}}
let _: Int = MemberwiseInits<Double>.init
_ = MemberwiseInits(x: Wrapper(stored: true), y: 17)
}
struct DefaultedMemberwiseInits {
@Wrapper(stored: true)
var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(wrappedValue: 17)
var z: Int
@WrapperWithDefaultInit
var w: Int
@WrapperWithDefaultInit
var optViaDefaultInit: Int?
@WrapperWithInitialValue
var optViaInitialValue: Int?
}
struct CannotDefaultMemberwiseOptionalInit { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Int?
}
func testDefaultedMemberwiseInits() {
_ = DefaultedMemberwiseInits()
_ = DefaultedMemberwiseInits(
x: Wrapper(stored: false),
y: 42,
z: WrapperWithInitialValue(wrappedValue: 42))
_ = DefaultedMemberwiseInits(y: 42)
_ = DefaultedMemberwiseInits(x: Wrapper(stored: false))
_ = DefaultedMemberwiseInits(z: WrapperWithInitialValue(wrappedValue: 42))
_ = DefaultedMemberwiseInits(w: WrapperWithDefaultInit())
_ = DefaultedMemberwiseInits(optViaDefaultInit: WrapperWithDefaultInit())
_ = DefaultedMemberwiseInits(optViaInitialValue: nil)
_ = DefaultedMemberwiseInits(optViaInitialValue: 42)
_ = CannotDefaultMemberwiseOptionalInit() // expected-error{{missing argument for parameter 'x' in call}}
_ = CannotDefaultMemberwiseOptionalInit(x: Wrapper(stored: nil))
}
// ---------------------------------------------------------------------------
// Default initializers
// ---------------------------------------------------------------------------
struct DefaultInitializerStruct {
@Wrapper(stored: true)
var x
@WrapperWithInitialValue
var y: Int = 10
}
struct NoDefaultInitializerStruct { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Bool
}
class DefaultInitializerClass {
@Wrapper(stored: true)
var x
@WrapperWithInitialValue
final var y: Int = 10
}
class NoDefaultInitializerClass { // expected-error{{class 'NoDefaultInitializerClass' has no initializers}}
@Wrapper
final var x: Bool // expected-note{{stored property 'x' without initial value prevents synthesized initializers}}
}
func testDefaultInitializers() {
_ = DefaultInitializerStruct()
_ = DefaultInitializerClass()
_ = NoDefaultInitializerStruct() // expected-error{{missing argument for parameter 'x' in call}}
}
struct DefaultedPrivateMemberwiseLets {
@Wrapper(stored: true)
private var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(wrappedValue: 17)
private var z: Int
}
func testDefaultedPrivateMemberwiseLets() {
_ = DefaultedPrivateMemberwiseLets()
_ = DefaultedPrivateMemberwiseLets(y: 42)
_ = DefaultedPrivateMemberwiseLets(x: Wrapper(stored: false)) // expected-error{{argument passed to call that takes no arguments}}
}
// ---------------------------------------------------------------------------
// Storage references
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithStorageRef<T> {
var wrappedValue: T
var projectedValue: Wrapper<T> {
return Wrapper(stored: wrappedValue)
}
}
extension Wrapper {
var wrapperOnlyAPI: Int { return 17 }
}
struct TestStorageRef {
@WrapperWithStorageRef var x: Int // expected-note{{'_x' declared here}}
init(x: Int) {
self._x = WrapperWithStorageRef(wrappedValue: x)
}
mutating func test() {
let _: Wrapper = $x
let i = $x.wrapperOnlyAPI
let _: Int = i
// x is mutable, $x is not
x = 17
$x = Wrapper(stored: 42) // expected-error{{cannot assign to property: '$x' is immutable}}
}
}
func testStorageRef(tsr: TestStorageRef) {
let _: Wrapper = tsr.$x
_ = tsr._x // expected-error{{'_x' is inaccessible due to 'private' protection level}}
}
struct TestStorageRefPrivate {
@WrapperWithStorageRef private(set) var x: Int
init() {
self._x = WrapperWithStorageRef(wrappedValue: 5)
}
}
func testStorageRefPrivate() {
var tsr = TestStorageRefPrivate()
let a = tsr.$x // okay, getter is internal
tsr.$x = a // expected-error{{cannot assign to property: '$x' is immutable}}
}
// rdar://problem/50873275 - crash when using wrapper with projectedValue in
// generic type.
@propertyWrapper
struct InitialValueWrapperWithStorageRef<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
wrappedValue = initialValue
}
var projectedValue: Wrapper<T> {
return Wrapper(stored: wrappedValue)
}
}
struct TestGenericStorageRef<T> {
struct Inner { }
@InitialValueWrapperWithStorageRef var inner: Inner = Inner()
}
// Wiring up the _projectedValueProperty attribute.
struct TestProjectionValuePropertyAttr {
@_projectedValueProperty(wrapperA)
@WrapperWithStorageRef var a: String
var wrapperA: Wrapper<String> {
Wrapper(stored: "blah")
}
@_projectedValueProperty(wrapperB) // expected-error{{could not find projection value property 'wrapperB'}}
@WrapperWithStorageRef var b: String
}
// ---------------------------------------------------------------------------
// Misc. semantic issues
// ---------------------------------------------------------------------------
@propertyWrapper
struct BrokenLazy { }
// expected-error@-1{{property wrapper type 'BrokenLazy' does not contain a non-static property named 'wrappedValue'}}
struct S {
@BrokenLazy
var wrappedValue: Int
}
@propertyWrapper
struct DynamicSelfStruct {
var wrappedValue: Self { self } // okay
var projectedValue: Self { self } // okay
}
@propertyWrapper
class DynamicSelf {
var wrappedValue: Self { self } // expected-error {{property wrapper wrapped value cannot have dynamic Self type}}
var projectedValue: Self? { self } // expected-error {{property wrapper projected value cannot have dynamic Self type}}
}
struct UseDynamicSelfWrapper {
@DynamicSelf() var value
}
// ---------------------------------------------------------------------------
// Invalid redeclaration
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithProjectedValue<T> {
var wrappedValue: T
var projectedValue: T { return wrappedValue }
}
class TestInvalidRedeclaration1 {
@WrapperWithProjectedValue var i = 17
// expected-note@-1 {{'i' previously declared here}}
// expected-note@-2 {{'$i' synthesized for property wrapper projected value}}
// expected-note@-3 {{'_i' synthesized for property wrapper backing storage}}
@WrapperWithProjectedValue var i = 39
// expected-error@-1 {{invalid redeclaration of 'i'}}
// expected-error@-2 {{invalid redeclaration of synthesized property '$i'}}
// expected-error@-3 {{invalid redeclaration of synthesized property '_i'}}
}
// SR-12839
struct TestInvalidRedeclaration2 {
var _foo1 = 123 // expected-error {{invalid redeclaration of synthesized property '_foo1'}}
@WrapperWithInitialValue var foo1 = 123 // expected-note {{'_foo1' synthesized for property wrapper backing storage}}
}
struct TestInvalidRedeclaration3 {
@WrapperWithInitialValue var foo1 = 123 // expected-note {{'_foo1' synthesized for property wrapper backing storage}}
var _foo1 = 123 // expected-error {{invalid redeclaration of synthesized property '_foo1'}}
}
// ---------------------------------------------------------------------------
// Closures in initializers
// ---------------------------------------------------------------------------
struct UsesExplicitClosures {
@WrapperAcceptingAutoclosure(body: { 42 })
var x: Int
@WrapperAcceptingAutoclosure(body: { return 42 })
var y: Int
}
// ---------------------------------------------------------------------------
// Enclosing instance diagnostics
// ---------------------------------------------------------------------------
@propertyWrapper
struct Observable<Value> {
private var stored: Value
init(wrappedValue: Value) {
self.stored = wrappedValue
}
@available(*, unavailable, message: "must be in a class")
var wrappedValue: Value { // expected-note{{'wrappedValue' has been explicitly marked unavailable here}}
get { fatalError("called wrappedValue getter") }
set { fatalError("called wrappedValue setter") }
}
static subscript<EnclosingSelf>(
_enclosingInstance observed: EnclosingSelf,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Self>
) -> Value {
get {
observed[keyPath: storageKeyPath].stored
}
set {
observed[keyPath: storageKeyPath].stored = newValue
}
}
}
struct MyObservedValueType {
@Observable // expected-error{{'wrappedValue' is unavailable: must be in a class}}
var observedProperty = 17
}
// ---------------------------------------------------------------------------
// Miscellaneous bugs
// ---------------------------------------------------------------------------
// rdar://problem/50822051 - compiler assertion / hang
@propertyWrapper
struct PD<Value> {
var wrappedValue: Value
init<A>(wrappedValue initialValue: Value, a: A) {
self.wrappedValue = initialValue
}
}
struct TestPD {
@PD(a: "foo") var foo: Int = 42
}
protocol P { }
@propertyWrapper
struct WrapperRequiresP<T: P> {
var wrappedValue: T
var projectedValue: T { return wrappedValue }
}
struct UsesWrapperRequiringP {
// expected-note@-1{{in declaration of}}
@WrapperRequiresP var x.: UsesWrapperRequiringP
// expected-error@-1{{expected member name following '.'}}
// expected-error@-2{{expected declaration}}
// expected-error@-3{{type annotation missing in pattern}}
}
// SR-10899 / rdar://problem/51588022
@propertyWrapper
struct SR_10899_Wrapper { // expected-note{{property wrapper type 'SR_10899_Wrapper' declared here}}
var wrappedValue: String { "hi" }
}
struct SR_10899_Usage {
@SR_10899_Wrapper var thing: Bool // expected-error{{property type 'Bool' does not match that of the 'wrappedValue' property of its wrapper type 'SR_10899_Wrapper'}}
}
// SR-11061 / rdar://problem/52593304 assertion with DeclContext mismatches
class SomeValue {
@SomeA(closure: { $0 }) var some: Int = 100
}
@propertyWrapper
struct SomeA<T> {
var wrappedValue: T
let closure: (T) -> (T)
init(wrappedValue initialValue: T, closure: @escaping (T) -> (T)) {
self.wrappedValue = initialValue
self.closure = closure
}
}
// rdar://problem/51989272 - crash when the property wrapper is a generic type
// alias
typealias Alias<T> = WrapperWithInitialValue<T>
struct TestAlias {
@Alias var foo = 17
}
// rdar://problem/52969503 - crash due to invalid source ranges in ill-formed
// code.
@propertyWrapper
struct Wrap52969503<T> {
var wrappedValue: T
init(blah: Int, wrappedValue: T) { }
}
struct Test52969503 {
@Wrap52969503(blah: 5) var foo: Int = 1 // expected-error{{argument 'blah' must precede argument 'wrappedValue'}}
}
//
// ---------------------------------------------------------------------------
// Property wrapper composition
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperA<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperB<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperC<Value> {
var wrappedValue: Value?
init(wrappedValue initialValue: Value?) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperD<Value, X, Y> { // expected-note{{property wrapper type 'WrapperD' declared here}}
var wrappedValue: Value
}
@propertyWrapper
struct WrapperE<Value> {
var wrappedValue: Value
}
struct TestComposition {
@WrapperA @WrapperB @WrapperC var p1: Int?
@WrapperA @WrapperB @WrapperC var p2 = "Hello"
@WrapperD<WrapperE, Int, String> @WrapperE var p3: Int?
@WrapperD<WrapperC, Int, String> @WrapperC var p4: Int?
@WrapperD<WrapperC, Int, String> @WrapperE var p5: Int // expected-error{{property type 'Int' does not match that of the 'wrappedValue' property of its wrapper type 'WrapperD<WrapperC, Int, String>'}}
func triggerErrors(d: Double) { // expected-note 6 {{mark method 'mutating' to make 'self' mutable}} {{2-2=mutating }}
p1 = d // expected-error{{cannot assign value of type 'Double' to type 'Int'}} {{8-8=Int(}} {{9-9=)}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
p2 = d // expected-error{{cannot assign value of type 'Double' to type 'String'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
// TODO(diagnostics): Looks like source range for 'd' here is reported as starting at 10, but it should be 8
p3 = d // expected-error{{cannot assign value of type 'Double' to type 'Int'}} {{10-10=Int(}} {{11-11=)}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
_p1 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<Int>>>'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
_p2 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<String>>>'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
_p3 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperD<WrapperE<Int?>, Int, String>'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
}
}
// ---------------------------------------------------------------------------
// Property wrapper composition type inference
// ---------------------------------------------------------------------------
protocol DefaultValue {
static var defaultValue: Self { get }
}
extension Int: DefaultValue {
static var defaultValue: Int { 0 }
}
struct TestCompositionTypeInference {
@propertyWrapper
struct A<Value: DefaultValue> {
var wrappedValue: Value
init(wrappedValue: Value = .defaultValue, key: String) {
self.wrappedValue = wrappedValue
}
}
@propertyWrapper
struct B<Value: DefaultValue>: DefaultValue {
var wrappedValue: Value
init(wrappedValue: Value = .defaultValue) {
self.wrappedValue = wrappedValue
}
static var defaultValue: B<Value> { B() }
}
// All of these are okay
@A(key: "b") @B
var a: Int = 0
@A(key: "b") @B
var b: Int
@A(key: "c") @B @B
var c: Int
}
// ---------------------------------------------------------------------------
// Missing Property Wrapper Unwrap Diagnostics
// ---------------------------------------------------------------------------
@propertyWrapper
struct Foo<T> { // expected-note {{arguments to generic parameter 'T' ('W' and 'Int') are expected to be equal}}
var wrappedValue: T {
get {
fatalError("boom")
}
set {
}
}
var prop: Int = 42
func foo() {}
func bar(x: Int) {}
subscript(q: String) -> Int {
get { return 42 }
set { }
}
subscript(x x: Int) -> Int {
get { return 42 }
set { }
}
subscript(q q: String, a: Int) -> Bool {
get { return false }
set { }
}
}
extension Foo : Equatable where T : Equatable {
static func == (lhs: Foo, rhs: Foo) -> Bool {
lhs.wrappedValue == rhs.wrappedValue
}
}
extension Foo : Hashable where T : Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(wrappedValue)
}
}
@propertyWrapper
struct Bar<T, V> {
var wrappedValue: T
func bar() {}
// TODO(diagnostics): We need to figure out what to do about subscripts.
// The problem standing in our way - keypath application choice
// is always added to results even if it's not applicable.
}
@propertyWrapper
struct Baz<T> {
var wrappedValue: T
func onPropertyWrapper() {}
var projectedValue: V {
return V()
}
}
extension Bar where V == String { // expected-note {{where 'V' = 'Bool'}}
func barWhereVIsString() {}
}
struct V {
func onProjectedValue() {}
}
struct W {
func onWrapped() {}
}
struct MissingPropertyWrapperUnwrap {
@Foo var w: W
@Foo var x: Int
@Bar<Int, Bool> var y: Int
@Bar<Int, String> var z: Int
@Baz var usesProjectedValue: W
func a<T>(_: Foo<T>) {}
func a<T>(named: Foo<T>) {}
func b(_: Foo<Int>) {}
func c(_: V) {}
func d(_: W) {}
func e(_: Foo<W>) {}
subscript<T : Hashable>(takesFoo x: Foo<T>) -> Foo<T> { x }
func baz() {
self.x.foo() // expected-error {{referencing instance method 'foo()' requires wrapper 'Foo<Int>'}}{{10-10=_}}
self.x.prop // expected-error {{referencing property 'prop' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x.bar(x: 42) // expected-error {{referencing instance method 'bar(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.y.bar() // expected-error {{referencing instance method 'bar()' requires wrapper 'Bar<Int, Bool>'}}{{10-10=_}}
self.y.barWhereVIsString() // expected-error {{referencing instance method 'barWhereVIsString()' requires wrapper 'Bar<Int, Bool>'}}{{10-10=_}}
// expected-error@-1 {{referencing instance method 'barWhereVIsString()' on 'Bar' requires the types 'Bool' and 'String' be equivalent}}
self.z.barWhereVIsString() // expected-error {{referencing instance method 'barWhereVIsString()' requires wrapper 'Bar<Int, String>'}}{{10-10=_}}
self.usesProjectedValue.onPropertyWrapper() // expected-error {{referencing instance method 'onPropertyWrapper()' requires wrapper 'Baz<W>'}}{{10-10=_}}
self._w.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
self.usesProjectedValue.onProjectedValue() // expected-error {{referencing instance method 'onProjectedValue()' requires wrapper 'V'}}{{10-10=$}}
self.$usesProjectedValue.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
self._usesProjectedValue.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
a(self.w) // expected-error {{cannot convert value 'w' of type 'W' to expected type 'Foo<W>', use wrapper instead}}{{12-12=_}}
b(self.x) // expected-error {{cannot convert value 'x' of type 'Int' to expected type 'Foo<Int>', use wrapper instead}}{{12-12=_}}
b(self.w) // expected-error {{cannot convert value of type 'W' to expected argument type 'Foo<Int>'}}
e(self.w) // expected-error {{cannot convert value 'w' of type 'W' to expected type 'Foo<W>', use wrapper instead}}{{12-12=_}}
b(self._w) // expected-error {{cannot convert value of type 'Foo<W>' to expected argument type 'Foo<Int>'}}
c(self.usesProjectedValue) // expected-error {{cannot convert value 'usesProjectedValue' of type 'W' to expected type 'V', use wrapper instead}}{{12-12=$}}
d(self.$usesProjectedValue) // expected-error {{cannot convert value '$usesProjectedValue' of type 'V' to expected type 'W', use wrapped value instead}}{{12-13=}}
d(self._usesProjectedValue) // expected-error {{cannot convert value '_usesProjectedValue' of type 'Baz<W>' to expected type 'W', use wrapped value instead}}{{12-13=}}
self.x["ultimate question"] // expected-error {{referencing subscript 'subscript(_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x["ultimate question"] = 42 // expected-error {{referencing subscript 'subscript(_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[x: 42] // expected-error {{referencing subscript 'subscript(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[x: 42] = 0 // expected-error {{referencing subscript 'subscript(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[q: "ultimate question", 42] // expected-error {{referencing subscript 'subscript(q:_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[q: "ultimate question", 42] = true // expected-error {{referencing subscript 'subscript(q:_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
// SR-11476
_ = \Self.[takesFoo: self.x] // expected-error {{cannot convert value 'x' of type 'Int' to expected type 'Foo<Int>', use wrapper instead}}{{31-31=_}}
_ = \Foo<W>.[x: self._x] // expected-error {{cannot convert value '_x' of type 'Foo<Int>' to expected type 'Int', use wrapped value instead}} {{26-27=}}
}
}
struct InvalidPropertyDelegateUse {
// TODO(diagnostics): We need to a tailored diagnostic for extraneous arguments in property delegate initialization
@Foo var x: Int = 42 // expected-error@:21 {{argument passed to call that takes no arguments}}
func test() {
self.x.foo() // expected-error {{value of type 'Int' has no member 'foo'}}
}
}
// SR-11060
class SR_11060_Class {
@SR_11060_Wrapper var property: Int = 1234 // expected-error {{missing argument for parameter 'string' in property wrapper initializer; add 'wrappedValue' and 'string' arguments in '@SR_11060_Wrapper(...)'}}
}
@propertyWrapper
struct SR_11060_Wrapper {
var wrappedValue: Int
init(wrappedValue: Int, string: String) { // expected-note {{'init(wrappedValue:string:)' declared here}}
self.wrappedValue = wrappedValue
}
}
// SR-11138
// Check that all possible compositions of nonmutating/mutating accessors
// on wrappers produce wrapped properties with the correct settability and
// mutatiness in all compositions.
@propertyWrapper
struct NonmutatingGetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
}
}
@propertyWrapper
struct MutatingGetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
}
}
@propertyWrapper
struct NonmutatingGetNonmutatingSetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
nonmutating set { fatalError() }
}
}
@propertyWrapper
struct MutatingGetNonmutatingSetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
nonmutating set { fatalError() }
}
}
@propertyWrapper
struct NonmutatingGetMutatingSetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
mutating set { fatalError() }
}
}
@propertyWrapper
struct MutatingGetMutatingSetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
mutating set { fatalError() }
}
}
struct AllCompositionsStruct {
// Should have nonmutating getter, undefined setter
@NonmutatingGetWrapper @NonmutatingGetWrapper
var ngxs_ngxs: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetWrapper // expected-error{{cannot be composed}}
var ngxs_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngxs_ngns: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetNonmutatingSetWrapper // expected-error{{cannot be composed}}
var ngxs_mgns: Int
// Should have nonmutating getter, undefined setter
@NonmutatingGetWrapper @NonmutatingGetMutatingSetWrapper
var ngxs_ngms: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetMutatingSetWrapper // expected-error{{cannot be composed}}
var ngxs_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetWrapper @NonmutatingGetWrapper
var mgxs_ngxs: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetWrapper // expected-error{{cannot be composed}}
var mgxs_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgxs_ngns: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetNonmutatingSetWrapper // expected-error{{cannot be composed}}
var mgxs_mgns: Int
// Should have mutating getter, undefined setter
@MutatingGetWrapper @NonmutatingGetMutatingSetWrapper
var mgxs_ngms: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetMutatingSetWrapper // expected-error{{cannot be composed}}
var mgxs_mgms: Int
////
// Should have nonmutating getter, undefined setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetWrapper
var ngns_ngxs: Int
// Should have nonmutating getter, undefined setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetWrapper
var ngns_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngns_ngns: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var ngns_mgns: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var ngns_ngms: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetMutatingSetWrapper
var ngns_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetWrapper
var mgns_ngxs: Int
// Should have mutating getter, undefined setter
@MutatingGetNonmutatingSetWrapper @MutatingGetWrapper
var mgns_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgns_ngns: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var mgns_mgns: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var mgns_ngms: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @MutatingGetMutatingSetWrapper
var mgns_mgms: Int
////
// Should have nonmutating getter, undefined setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetWrapper
var ngms_ngxs: Int
// Should have mutating getter, undefined setter
@NonmutatingGetMutatingSetWrapper @MutatingGetWrapper
var ngms_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngms_ngns: Int
// Should have mutating getter, nonmutating setter
@NonmutatingGetMutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var ngms_mgns: Int
// Should have nonmutating getter, mutating setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var ngms_ngms: Int
// Should have mutating getter, mutating setter
@NonmutatingGetMutatingSetWrapper @MutatingGetMutatingSetWrapper
var ngms_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetMutatingSetWrapper @NonmutatingGetWrapper
var mgms_ngxs: Int
// Should have mutating getter, undefined setter
@MutatingGetMutatingSetWrapper @MutatingGetWrapper
var mgms_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgms_ngns: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var mgms_mgns: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var mgms_ngms: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @MutatingGetMutatingSetWrapper
var mgms_mgms: Int
func readonlyContext(x: Int) { // expected-note *{{}}
_ = ngxs_ngxs
// _ = ngxs_mgxs
_ = ngxs_ngns
// _ = ngxs_mgns
_ = ngxs_ngms
// _ = ngxs_mgms
_ = mgxs_ngxs // expected-error{{}}
// _ = mgxs_mgxs
_ = mgxs_ngns // expected-error{{}}
// _ = mgxs_mgns
_ = mgxs_ngms // expected-error{{}}
// _ = mgxs_mgms
_ = ngns_ngxs
_ = ngns_mgxs
_ = ngns_ngns
_ = ngns_mgns
_ = ngns_ngms
_ = ngns_mgms
_ = mgns_ngxs // expected-error{{}}
_ = mgns_mgxs // expected-error{{}}
_ = mgns_ngns // expected-error{{}}
_ = mgns_mgns // expected-error{{}}
_ = mgns_ngms // expected-error{{}}
_ = mgns_mgms // expected-error{{}}
_ = ngms_ngxs
_ = ngms_mgxs // expected-error{{}}
_ = ngms_ngns
_ = ngms_mgns // expected-error{{}}
_ = ngms_ngms
_ = ngms_mgms // expected-error{{}}
_ = mgms_ngxs // expected-error{{}}
_ = mgms_mgxs // expected-error{{}}
_ = mgms_ngns // expected-error{{}}
_ = mgms_mgns // expected-error{{}}
_ = mgms_ngms // expected-error{{}}
_ = mgms_mgms // expected-error{{}}
////
ngxs_ngxs = x // expected-error{{}}
// ngxs_mgxs = x
ngxs_ngns = x
// ngxs_mgns = x
ngxs_ngms = x // expected-error{{}}
// ngxs_mgms = x
mgxs_ngxs = x // expected-error{{}}
// mgxs_mgxs = x
mgxs_ngns = x // expected-error{{}}
// mgxs_mgns = x
mgxs_ngms = x // expected-error{{}}
// mgxs_mgms = x
ngns_ngxs = x // expected-error{{}}
ngns_mgxs = x // expected-error{{}}
ngns_ngns = x
ngns_mgns = x
ngns_ngms = x
ngns_mgms = x
mgns_ngxs = x // expected-error{{}}
mgns_mgxs = x // expected-error{{}}
mgns_ngns = x // expected-error{{}}
mgns_mgns = x // expected-error{{}}
mgns_ngms = x // expected-error{{}}
mgns_mgms = x // expected-error{{}}
ngms_ngxs = x // expected-error{{}}
ngms_mgxs = x // expected-error{{}}
ngms_ngns = x
// FIXME: This ought to be allowed because it's a pure set, so the mutating
// get should not come into play.
ngms_mgns = x // expected-error{{cannot use mutating getter}}
ngms_ngms = x // expected-error{{}}
ngms_mgms = x // expected-error{{}}
mgms_ngxs = x // expected-error{{}}
mgms_mgxs = x // expected-error{{}}
mgms_ngns = x // expected-error{{}}
mgms_mgns = x // expected-error{{}}
mgms_ngms = x // expected-error{{}}
mgms_mgms = x // expected-error{{}}
}
mutating func mutatingContext(x: Int) {
_ = ngxs_ngxs
// _ = ngxs_mgxs
_ = ngxs_ngns
// _ = ngxs_mgns
_ = ngxs_ngms
// _ = ngxs_mgms
_ = mgxs_ngxs
// _ = mgxs_mgxs
_ = mgxs_ngns
// _ = mgxs_mgns
_ = mgxs_ngms
// _ = mgxs_mgms
_ = ngns_ngxs
_ = ngns_mgxs
_ = ngns_ngns
_ = ngns_mgns
_ = ngns_ngms
_ = ngns_mgms
_ = mgns_ngxs
_ = mgns_mgxs
_ = mgns_ngns
_ = mgns_mgns
_ = mgns_ngms
_ = mgns_mgms
_ = ngms_ngxs
_ = ngms_mgxs
_ = ngms_ngns
_ = ngms_mgns
_ = ngms_ngms
_ = ngms_mgms
_ = mgms_ngxs
_ = mgms_mgxs
_ = mgms_ngns
_ = mgms_mgns
_ = mgms_ngms
_ = mgms_mgms
////
ngxs_ngxs = x // expected-error{{}}
// ngxs_mgxs = x
ngxs_ngns = x
// ngxs_mgns = x
ngxs_ngms = x // expected-error{{}}
// ngxs_mgms = x
mgxs_ngxs = x // expected-error{{}}
// mgxs_mgxs = x
mgxs_ngns = x
// mgxs_mgns = x
mgxs_ngms = x // expected-error{{}}
// mgxs_mgms = x
ngns_ngxs = x // expected-error{{}}
ngns_mgxs = x // expected-error{{}}
ngns_ngns = x
ngns_mgns = x
ngns_ngms = x
ngns_mgms = x
mgns_ngxs = x // expected-error{{}}
mgns_mgxs = x // expected-error{{}}
mgns_ngns = x
mgns_mgns = x
mgns_ngms = x
mgns_mgms = x
ngms_ngxs = x // expected-error{{}}
ngms_mgxs = x // expected-error{{}}
ngms_ngns = x
ngms_mgns = x
ngms_ngms = x
ngms_mgms = x
mgms_ngxs = x // expected-error{{}}
mgms_mgxs = x // expected-error{{}}
mgms_ngns = x
mgms_mgns = x
mgms_ngms = x
mgms_mgms = x
}
}
// rdar://problem/54184846 - crash while trying to retrieve wrapper info on l-value base type
func test_missing_method_with_lvalue_base() {
@propertyWrapper
struct Ref<T> {
var wrappedValue: T
}
struct S<T> where T: RandomAccessCollection, T.Element: Equatable {
@Ref var v: T.Element
init(items: T, v: Ref<T.Element>) {
self.v.binding = v // expected-error {{value of type 'T.Element' has no member 'binding'}}
}
}
}
// SR-11288
// Look into the protocols that the type conforms to
// typealias as propertyWrapper //
@propertyWrapper
struct SR_11288_S0 {
var wrappedValue: Int
}
protocol SR_11288_P1 {
typealias SR_11288_Wrapper1 = SR_11288_S0
}
struct SR_11288_S1: SR_11288_P1 {
@SR_11288_Wrapper1 var answer = 42 // Okay
}
// associatedtype as propertyWrapper //
protocol SR_11288_P2 {
associatedtype SR_11288_Wrapper2 = SR_11288_S0
}
struct SR_11288_S2: SR_11288_P2 {
@SR_11288_Wrapper2 var answer = 42 // expected-error {{unknown attribute 'SR_11288_Wrapper2'}}
}
protocol SR_11288_P3 {
associatedtype SR_11288_Wrapper3
}
struct SR_11288_S3: SR_11288_P3 {
typealias SR_11288_Wrapper3 = SR_11288_S0
@SR_11288_Wrapper3 var answer = 42 // Okay
}
// typealias as propertyWrapper in a constrained protocol extension //
protocol SR_11288_P4 {}
extension SR_11288_P4 where Self: AnyObject { // expected-note {{requirement specified as 'Self' : 'AnyObject' [with Self = SR_11288_S4]}}
typealias SR_11288_Wrapper4 = SR_11288_S0
}
struct SR_11288_S4: SR_11288_P4 {
@SR_11288_Wrapper4 var answer = 42 // expected-error {{'SR_11288_S4.SR_11288_Wrapper4' (aka 'SR_11288_S0') requires that 'SR_11288_S4' be a class type}}
}
class SR_11288_C0: SR_11288_P4 {
@SR_11288_Wrapper4 var answer = 42 // Okay
}
// typealias as propertyWrapper in a generic type //
protocol SR_11288_P5 {
typealias SR_11288_Wrapper5 = SR_11288_S0
}
struct SR_11288_S5<T>: SR_11288_P5 {
@SR_11288_Wrapper5 var answer = 42 // Okay
}
// SR-11393
protocol Copyable: AnyObject {
func copy() -> Self
}
@propertyWrapper
struct CopyOnWrite<Value: Copyable> {
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
var wrappedValue: Value
var projectedValue: Value {
mutating get {
if !isKnownUniquelyReferenced(&wrappedValue) {
wrappedValue = wrappedValue.copy()
}
return wrappedValue
}
set {
wrappedValue = newValue
}
}
}
final class CopyOnWriteTest: Copyable {
let a: Int
init(a: Int) {
self.a = a
}
func copy() -> Self {
Self.init(a: a)
}
}
struct CopyOnWriteDemo1 {
@CopyOnWrite var a = CopyOnWriteTest(a: 3)
func foo() { // expected-note{{mark method 'mutating' to make 'self' mutable}}
_ = $a // expected-error{{cannot use mutating getter on immutable value: 'self' is immutable}}
}
}
@propertyWrapper
struct NonMutatingProjectedValueSetWrapper<Value> {
var wrappedValue: Value
var projectedValue: Value {
get { wrappedValue }
nonmutating set { }
}
}
struct UseNonMutatingProjectedValueSet {
@NonMutatingProjectedValueSetWrapper var x = 17
func test() { // expected-note{{mark method 'mutating' to make 'self' mutable}}
$x = 42 // okay
x = 42 // expected-error{{cannot assign to property: 'self' is immutable}}
}
}
// SR-11478
@propertyWrapper
struct SR_11478_W<Value> {
var wrappedValue: Value
}
class SR_11478_C1 {
@SR_11478_W static var bool1: Bool = true // Ok
@SR_11478_W class var bool2: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
@SR_11478_W class final var bool3: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
final class SR_11478_C2 {
@SR_11478_W static var bool1: Bool = true // Ok
@SR_11478_W class var bool2: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
@SR_11478_W class final var bool3: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
// SR-11381
@propertyWrapper
struct SR_11381_W<T> {
init(wrappedValue: T) {}
var wrappedValue: T {
fatalError()
}
}
struct SR_11381_S {
@SR_11381_W var foo: Int = nil // expected-error {{'nil' is not compatible with expected argument type 'Int'}}
}
// rdar://problem/53349209 - regression in property wrapper inference
struct Concrete1: P {}
@propertyWrapper struct ConcreteWrapper {
var wrappedValue: Concrete1 { get { fatalError() } }
}
struct TestConcrete1 {
@ConcreteWrapper() var s1
func f() {
// Good:
let _: P = self.s1
// Bad:
self.g(s1: self.s1)
// Ugly:
self.g(s1: self.s1 as P)
}
func g(s1: P) {
// ...
}
}
// SR-11477
// Two initializers that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W1 { // Okay
let name: String
init() {
self.name = "Init"
}
init(name: String = "DefaultParamInit") {
self.name = name
}
var wrappedValue: Int {
get { return 0 }
}
}
// Two initializers with default arguments that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W2 { // Okay
let name: String
init(anotherName: String = "DefaultParamInit1") {
self.name = anotherName
}
init(name: String = "DefaultParamInit2") {
self.name = name
}
var wrappedValue: Int {
get { return 0 }
}
}
// Single initializer that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W3 { // Okay
let name: String
init() {
self.name = "Init"
}
var wrappedValue: Int {
get { return 0 }
}
}
// rdar://problem/56213175 - backward compatibility issue with Swift 5.1,
// which unconditionally skipped protocol members.
protocol ProtocolWithWrapper {
associatedtype Wrapper = Float // expected-note{{associated type 'Wrapper' declared here}}
}
struct UsesProtocolWithWrapper: ProtocolWithWrapper {
@Wrapper var foo: Int // expected-warning{{ignoring associated type 'Wrapper' in favor of module-scoped property wrapper 'Wrapper'; please qualify the reference with 'property_wrappers'}}{{4-4=property_wrappers.}}
}
// rdar://problem/56350060 - [Dynamic key path member lookup] Assertion when subscripting with a key path
func test_rdar56350060() {
@propertyWrapper
@dynamicMemberLookup
struct DynamicWrapper<Value> {
var wrappedValue: Value { fatalError() }
subscript<T>(keyPath keyPath: KeyPath<Value, T>) -> DynamicWrapper<T> {
fatalError()
}
subscript<T>(dynamicMember keyPath: KeyPath<Value, T>) -> DynamicWrapper<T> {
return self[keyPath: keyPath] // Ok
}
}
}
// rdar://problem/57411331 - crash due to incorrectly synthesized "nil" default
// argument.
@propertyWrapper
struct Blah<Value> {
init(blah _: Int) { }
var wrappedValue: Value {
let val: Value? = nil
return val!
}
}
struct UseRdar57411331 {
let x = Rdar57411331(other: 5)
}
struct Rdar57411331 {
@Blah(blah: 17) var something: Int?
var other: Int
}
// SR-11994
@propertyWrapper
open class OpenPropertyWrapperWithPublicInit {
public init(wrappedValue: String) { // Okay
self.wrappedValue = wrappedValue
}
open var wrappedValue: String = "Hello, world"
}
// SR-11654
struct SR_11654_S {}
class SR_11654_C {
@Foo var property: SR_11654_S?
}
func sr_11654_generic_func<T>(_ argument: T?) -> T? {
return argument
}
let sr_11654_c = SR_11654_C()
_ = sr_11654_generic_func(sr_11654_c.property) // Okay
// rdar://problem/59471019 - property wrapper initializer requires empty parens
// for default init
@propertyWrapper
struct DefaultableIntWrapper {
var wrappedValue: Int
init() {
self.wrappedValue = 0
}
}
struct TestDefaultableIntWrapper {
@DefaultableIntWrapper var x
@DefaultableIntWrapper() var y
@DefaultableIntWrapper var z: Int
mutating func test() {
x = y
y = z
}
}
@propertyWrapper
public struct NonVisibleImplicitInit {
// expected-error@-1 {{internal initializer 'init()' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleImplicitInit' (which is public)}}
public var wrappedValue: Bool {
return false
}
}
| apache-2.0 | 7f4709f3cde79483445b4cab58bf6800 | 27.036634 | 260 | 0.649839 | 4.196354 | false | false | false | false |
lorentey/swift | test/SILGen/keypath_property_descriptors.swift | 30 | 5278 | // RUN: %target-swift-emit-silgen %s | %FileCheck --check-prefix=CHECK --check-prefix=NONRESILIENT %s
// RUN: %target-swift-emit-silgen -enable-library-evolution %s | %FileCheck --check-prefix=CHECK --check-prefix=RESILIENT %s
// RUN: %target-swift-emit-silgen -enable-private-imports %s | %FileCheck --check-prefix=PRIVATEIMPORTS %s
// TODO: globals should get descriptors
public var a: Int = 0
@inlinable
public var b: Int { return 0 }
@usableFromInline
internal var c: Int = 0
// no descriptor
// CHECK-NOT: sil_property #d
// PRIVATEIMPORTS-NOT: sil_property #d
internal var d: Int = 0
// CHECK-NOT: sil_property #e
// PRIVATEIMPORTS-NOT: sil_property #e
private var e: Int = 0
public struct A {
// NONRESILIENT-LABEL: sil_property #A.a ()
// RESILIENT-LABEL: sil_property #A.a (stored_property
// PRIVATEIMPORTS-LABEL: sil_property #A.a ()
public var a: Int = 0
// CHECK-LABEL: sil_property #A.b ()
// PRIVATEIMPORTS-LABEL: sil_property #A.b ()
@inlinable
public var b: Int { return 0 }
// NONRESILIENT-LABEL: sil_property #A.c ()
// RESILIENT-LABEL: sil_property #A.c (stored_property
// PRIVATEIMPORTS-LABEL: sil_property #A.c ()
@usableFromInline
internal var c: Int = 0
// no descriptor
// CHECK-NOT: sil_property #A.d
// PRIVATEIMPORTS-LABEL: sil_property #A.d ()
internal var d: Int = 0
// CHECK-NOT: sil_property #A.e
// PRIVATEIMPORTS-LABEL: sil_property #A.e ()
fileprivate var e: Int = 0
// CHECK-NOT: sil_property #A.f
// PRIVATEIMPORTS-LABEL: sil_property #A.f ()
private var f: Int = 0
// TODO: static vars should get descriptors
public static var a: Int = 0
@inlinable
public static var b: Int { return 0 }
@usableFromInline
internal static var c: Int = 0
// no descriptor
// CHECK-NOT: sil_property #A.d
internal static var d: Int = 0
// CHECK-NOT: sil_property #A.e
fileprivate static var e: Int = 0
// CHECK-NOT: sil_property #A.f
private static var f: Int = 0
// CHECK-LABEL: sil_property #A.subscript{{.*}} (){{$}}
public subscript(a x: Int) -> Int { return x }
// CHECK-LABEL: sil_property #A.subscript{{.*}} (){{$}}
@inlinable
public subscript(b x: Int) -> Int { return x }
// CHECK-LABEL: sil_property #A.subscript{{.*}} (){{$}}
@usableFromInline
internal subscript(c x: Int) -> Int { return x }
// no descriptor
// CHECK-NOT: sil_property #A.subscript
internal subscript(d x: Int) -> Int { return x }
fileprivate subscript(e x: Int) -> Int { return x }
private subscript(f x: Int) -> Int { return x }
// CHECK-LABEL: sil_property #A.subscript{{.*}} (){{$}}
public subscript<T>(a x: T) -> T { return x }
// CHECK-LABEL: sil_property #A.subscript{{.*}} (){{$}}
@inlinable
public subscript<T>(b x: T) -> T { return x }
// CHECK-LABEL: sil_property #A.subscript{{.*}} (){{$}}
@usableFromInline
internal subscript<T>(c x: T) -> T { return x }
// no descriptor
// CHECK-NOT: sil_property #A.subscript
internal subscript<T>(d x: T) -> T { return x }
fileprivate subscript<T>(e x: T) -> T { return x }
private subscript<T>(f x: T) -> T { return x }
// no descriptor
// CHECK-NOT: sil_property #A.count
public var count: Int {
mutating get {
_count += 1
return _count
}
set {
_count = newValue
}
}
// CHECK-NOT: sil_property #A._count
private var _count: Int = 0
// NONRESILIENT-LABEL: sil_property #A.getSet ()
// PRIVATEIMPORTS-LABEL: sil_property #A.getSet ()
// RESILIENT-LABEL: sil_property #A.getSet (settable_property
public var getSet: Int {
get { return 0 }
set { }
}
// CHECK-LABEL: sil_property #A.hiddenSetter (settable_property
// PRIVATEIMPORTS-LABEL: sil_property #A.hiddenSetter (settable_property
public internal(set) var hiddenSetter: Int {
get { return 0 }
set { }
}
// PRIVATEIMPORTS-LABEL: sil_property #A.privateSetter (settable_property
public private(set) var privateSetter: Int {
get { return 0 }
set { }
}
// PRIVATEIMPORTS-LABEL: sil_property #A.fileprivateSetter (settable_property
public fileprivate(set) var fileprivateSetter: Int {
get { return 0 }
set { }
}
// NONRESILIENT-LABEL: sil_property #A.usableFromInlineSetter ()
// PRIVATEIMPORTS-LABEL: sil_property #A.usableFromInlineSetter ()
// RESILIENT-LABEL: sil_property #A.usableFromInlineSetter (settable_property
public internal(set) var usableFromInlineSetter: Int {
get { return 0 }
@usableFromInline set { }
}
}
@_fixed_layout
public struct FixedLayout {
// NONRESILIENT-LABEL: sil_property #FixedLayout.a ()
// RESILIENT-LABEL: sil_property #FixedLayout.a (stored_property
public var a: Int
// NONRESILIENT-LABEL: sil_property #FixedLayout.b ()
// RESILIENT-LABEL: sil_property #FixedLayout.b (stored_property
public var b: Int
// NONRESILIENT-LABEL: sil_property #FixedLayout.c ()
// RESILIENT-LABEL: sil_property #FixedLayout.c (stored_property
public var c: Int
}
public class Foo {}
extension Array where Element == Foo {
public class Bar {
// NONRESILIENT-LABEL: sil_property #Array.Bar.dontCrash<τ_0_0 where τ_0_0 == Foo> (settable_property $Int
public private(set) var dontCrash : Int {
get {
return 10
}
set {
}
}
}
}
| apache-2.0 | 0aae07b0c9a3158595ae192b922bf6ba | 30.035294 | 124 | 0.6558 | 3.461942 | false | false | false | false |
thedistance/TheDistanceCore | TDCore/Extensions/UIViewController-OpenURLs.swift | 1 | 3551 | //
// UIViewController-OpenURLs.swift
// TDCore
//
// Created by Josh Campion on 13/04/2016.
// Copyright © 2016 The Distance. All rights reserved.
//
import UIKit
import TheDistanceCore
import SafariServices
public extension UIApplication {
/// - returns: The response of `canOpenURL(_:)` as an `NSNumber` so the result can be accessed from the result of a `performSelector(...)`.
public func number_canOpenURL(url:URL) -> NSNumber {
return NSNumber(value: canOpenURL(url))
}
}
extension UIViewController {
/**
Convenience method for opening an `NSURL` in a browser, giving the user a choice of opening either Google Chrome or Safari. If Safari is chosen, this calls `openInSafari(_:)`.
- note: As of iOS 9, `googlechrome` and `googlechromes` should be added to the `LSApplicationQueriesSchemes` key in `info.plist` in order to open in Chrome to work.
- parameter url: The `NSURL` to open in a browser.
- parameter item: Either the `UIView` or `UIBarButtonItem` that the `ActionSheet` style `UIAlertController` will be presented from on Regular-Regular size class devices.
- paramter inViewController: The `UIViewController` that will present the `UIAlertController`. If `nil`, `self` is used to present the `UIAlertController`. The default value is `nil`.
-seealso: `openInSafari(_:)`
-seealso: `presentViewController(_:fromSourceItem:inViewController:animated:completion)`.
*/
public func openURL(url:URL, fromSourceItem item:UIPopoverSourceType, inViewController:UIViewController? = nil) {
if let chromeURL = url.googleChromeURL(), self.canOpenURL(url: URL(string: "googlechrome://")! as NSURL) {
let alert = UIAlertController(title: nil, message: "Open with...", preferredStyle: UIAlertController.Style.actionSheet)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Safari", style: .default, handler: { (action) -> Void in
self.openInSafari(url:url)
}))
alert.addAction(UIAlertAction(title: "Google Chrome", style: .default, handler: { (action) -> Void in
self.openURL(url: chromeURL as NSURL)
}))
self.presentViewController(alert, fromSourceItem: item)
} else {
openInSafari(url:url)
}
}
/**
Opens the specified `NSURL` in Safari, or presents an `SFSafariViewController` if called on iOS 9. The presented `SFSafariViewController` has `self` as its delegate and is dismissed on the `SFSafariViewControllerDelegate` method, `safariViewControllerDidFinish(_:)`.
- parameter url: The `NSURL` to open.
*/
public func openInSafari(url:URL) {
// if #available(iOS 9, *) {
// let vc = SFSafariViewController(url: url)
// vc.delegate = self
// self.present(vc, animated: true, completion: nil)
// return
// }
if self.canOpenURL(url:url as NSURL) {
self.openURL(url:url as NSURL)
}
}
/// Simple `SFSafariViewControllerDelegate` implementation that dismisses a presented `SFSafariViewController`.
// @available(iOS 9.0, *)
// public func safariViewControllerDidFinish(controller: SFSafariViewController) {
// controller.dismiss(animated:true, completion: nil)
// }
}
| mit | 9dfdbbd8b1d92c49a5aba7aebe2c09fb | 40.764706 | 271 | 0.646197 | 4.652687 | false | false | false | false |
tinrobots/Mechanica | Sources/AVFoundation/AVAsset+Utils.swift | 1 | 1343 | #if canImport(AVAsset)
import AVFoundation
extension AVAsset {
/// **Mechanica**
///
/// Generates a thumbnail image.
///
///
/// Example:
///
/// let url = URL(string: "https://link/to/video.mp4")!
/// let asset = AVAsset(url: url)
/// let thumbnail = asset.thumbnail(fromTime: 5)
///
/// - Parameter time: Seconds into the video where the image should be generated.
/// - Returns: A thumbnail image.
/// - Throws: Throws an error if no thumbnail could be created.
/// - Note: This function may take some time to complete: it's recommended to dispatch the call on another queue if the thumbnail is not generated from a local resource.
public func thumbnail(fromTime time: Float64 = 0) throws -> Image {
let imageGenerator = AVAssetImageGenerator(asset: self)
imageGenerator.appliesPreferredTrackTransform = true
imageGenerator.requestedTimeToleranceAfter = .zero
imageGenerator.requestedTimeToleranceBefore = .zero
let time = CMTime(seconds: time, preferredTimescale: 1)
var actualTime = CMTime(value: 0, timescale: 0)
let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: &actualTime)
#if canImport(UIKit)
return Image(cgImage: cgImage)
#elseif canImport(AppKit)
return Image(cgImage: cgImage, size: .zero)
#endif
}
}
#endif
| mit | 0d9ba6957c292d757896eac9e774d1ca | 33.435897 | 171 | 0.690246 | 4.332258 | false | false | false | false |
yangxiaodongcn/iOSAppBase | iOSAppBase/iOSAppBase/Tools/Device/Size.swift | 1 | 384 | //
// Size.swift
// Device
//
// Created by Lucas Ortis on 30/10/2015.
// Copyright © 2015 Ekhoo. All rights reserved.
//
public enum Size: Float {
case unknown = 0.0
case screen3_5Inch = 3.5
case screen4_0Inch = 4.0
case screen4_7Inch = 4.7
case screen5_5Inch = 5.5
case screen7_9Inch = 7.9
case screen9_7Inch = 9.7
case screen12_9Inch = 12.9
}
| mit | a1d1c132ff6c4ae5cc51ae32211279c8 | 20.277778 | 48 | 0.624021 | 2.755396 | false | false | false | false |
mshhmzh/firefox-ios | ThirdParty/SQLite.swift/Tests/SchemaTests.swift | 9 | 41948 | import XCTest
import SQLite
class SchemaTests : XCTestCase {
func test_drop_compilesDropTableExpression() {
XCTAssertEqual("DROP TABLE \"table\"", table.drop())
XCTAssertEqual("DROP TABLE IF EXISTS \"table\"", table.drop(ifExists: true))
}
func test_drop_compilesDropVirtualTableExpression() {
XCTAssertEqual("DROP VIRTUAL TABLE \"virtual_table\"", virtualTable.drop())
XCTAssertEqual("DROP VIRTUAL TABLE IF EXISTS \"virtual_table\"", virtualTable.drop(ifExists: true))
}
func test_drop_compilesDropViewExpression() {
XCTAssertEqual("DROP VIEW \"view\"", _view.drop())
XCTAssertEqual("DROP VIEW IF EXISTS \"view\"", _view.drop(ifExists: true))
}
func test_create_withBuilder_compilesCreateTableExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (" +
"\"blob\" BLOB NOT NULL, " +
"\"blobOptional\" BLOB, " +
"\"double\" REAL NOT NULL, " +
"\"doubleOptional\" REAL, " +
"\"int64\" INTEGER NOT NULL, " +
"\"int64Optional\" INTEGER, " +
"\"string\" TEXT NOT NULL, " +
"\"stringOptional\" TEXT" +
")",
table.create { t in
t.column(data)
t.column(dataOptional)
t.column(double)
t.column(doubleOptional)
t.column(int64)
t.column(int64Optional)
t.column(string)
t.column(stringOptional)
}
)
XCTAssertEqual(
"CREATE TEMPORARY TABLE \"table\" (\"int64\" INTEGER NOT NULL)",
table.create(temporary: true) { $0.column(int64) }
)
XCTAssertEqual(
"CREATE TABLE IF NOT EXISTS \"table\" (\"int64\" INTEGER NOT NULL)",
table.create(ifNotExists: true) { $0.column(int64) }
)
XCTAssertEqual(
"CREATE TEMPORARY TABLE IF NOT EXISTS \"table\" (\"int64\" INTEGER NOT NULL)",
table.create(temporary: true, ifNotExists: true) { $0.column(int64) }
)
}
func test_create_withQuery_compilesCreateTableExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" AS SELECT \"int64\" FROM \"view\"",
table.create(_view.select(int64))
)
}
// thoroughness test for ambiguity
func test_column_compilesColumnDefinitionExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL)",
table.create { t in t.column(int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE)",
table.create { t in t.column(int64, unique: true) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL DEFAULT (\"int64\"))",
table.create { t in t.column(int64, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL DEFAULT (0))",
table.create { t in t.column(int64, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, unique: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE DEFAULT (\"int64\"))",
table.create { t in t.column(int64, unique: true, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE DEFAULT (0))",
table.create { t in t.column(int64, unique: true, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, unique: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, unique: true, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) DEFAULT (0))",
table.create { t in t.column(int64, unique: true, check: int64 > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (0))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) DEFAULT (0))",
table.create { t in t.column(int64, check: int64 > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (0))",
table.create { t in t.column(int64, check: int64Optional > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, primaryKey: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, primaryKey: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL DEFAULT (\"int64\"))",
table.create { t in t.column(int64, primaryKey: true, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, primaryKey: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, primaryKey: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, primaryKey: true, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64, primaryKey: true, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER)",
table.create { t in t.column(int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE)",
table.create { t in t.column(int64Optional, unique: true) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0))",
table.create { t in t.column(int64Optional, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64Optional, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER DEFAULT (0))",
table.create { t in t.column(int64Optional, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, unique: true, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE DEFAULT (0))",
table.create { t in t.column(int64Optional, unique: true, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) DEFAULT (0))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) DEFAULT (0))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, check: int64 > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (\"int64\"))",
table.create { t in t.column(int64Optional, check: int64Optional > 0, defaultValue: int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, check: int64 > 0, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (\"int64Optional\"))",
table.create { t in t.column(int64Optional, check: int64Optional > 0, defaultValue: int64Optional) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (0))",
table.create { t in t.column(int64Optional, check: int64 > 0, defaultValue: 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (0))",
table.create { t in t.column(int64Optional, check: int64Optional > 0, defaultValue: 0) }
)
}
func test_column_withIntegerExpression_compilesPrimaryKeyAutoincrementColumnDefinitionExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)",
table.create { t in t.column(int64, primaryKey: .Autoincrement) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (\"int64\" > 0))",
table.create { t in t.column(int64, primaryKey: .Autoincrement, check: int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL CHECK (\"int64Optional\" > 0))",
table.create { t in t.column(int64, primaryKey: .Autoincrement, check: int64Optional > 0) }
)
}
func test_column_withIntegerExpression_compilesReferentialColumnDefinitionExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, unique: true, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, check: int64 > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, check: int64Optional > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, unique: true, check: int64 > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64, unique: true, check: int64Optional > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, check: int64 > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, check: int64Optional > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64 > 0, references: table, int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\"))",
table.create { t in t.column(int64Optional, unique: true, check: int64Optional > 0, references: table, int64) }
)
}
func test_column_withStringExpression_compilesCollatedColumnDefinitionExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL COLLATE RTRIM)",
table.create { t in t.column(string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"string\" != '') COLLATE RTRIM)",
table.create { t in t.column(string, check: string != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') COLLATE RTRIM)",
table.create { t in t.column(string, check: stringOptional != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: string != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: stringOptional != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: string != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: stringOptional != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: string != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, unique: true, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, check: string != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(string, check: stringOptional != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, check: string != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(string, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL COLLATE RTRIM)",
table.create { t in t.column(stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: string != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: stringOptional != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: string != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: string != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL UNIQUE CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, unique: true, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: string != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT (\"string\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: string, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: string != "", defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT (\"stringOptional\") COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: stringOptional, collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: string != "", defaultValue: "string", collate: .Rtrim) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (\"stringOptional\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM)",
table.create { t in t.column(stringOptional, check: stringOptional != "", defaultValue: "string", collate: .Rtrim) }
)
}
func test_primaryKey_compilesPrimaryKeyExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (PRIMARY KEY (\"int64\"))",
table.create { t in t.primaryKey(int64) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (PRIMARY KEY (\"int64\", \"string\"))",
table.create { t in t.primaryKey(int64, string) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (PRIMARY KEY (\"int64\", \"string\", \"double\"))",
table.create { t in t.primaryKey(int64, string, double) }
)
}
func test_unique_compilesUniqueExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (UNIQUE (\"int64\"))",
table.create { t in t.unique(int64) }
)
}
func test_check_compilesCheckExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (CHECK ((\"int64\" > 0)))",
table.create { t in t.check(int64 > 0) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (CHECK ((\"int64Optional\" > 0)))",
table.create { t in t.check(int64Optional > 0) }
)
}
func test_foreignKey_compilesForeignKeyExpression() {
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"string\") REFERENCES \"table\" (\"string\"))",
table.create { t in t.foreignKey(string, references: table, string) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"stringOptional\") REFERENCES \"table\" (\"string\"))",
table.create { t in t.foreignKey(stringOptional, references: table, string) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"string\") REFERENCES \"table\" (\"string\") ON UPDATE CASCADE ON DELETE SET NULL)",
table.create { t in t.foreignKey(string, references: table, string, update: .Cascade, delete: .SetNull) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"string\", \"string\") REFERENCES \"table\" (\"string\", \"string\"))",
table.create { t in t.foreignKey((string, string), references: table, (string, string)) }
)
XCTAssertEqual(
"CREATE TABLE \"table\" (FOREIGN KEY (\"string\", \"string\", \"string\") REFERENCES \"table\" (\"string\", \"string\", \"string\"))",
table.create { t in t.foreignKey((string, string, string), references: table, (string, string, string)) }
)
}
func test_addColumn_compilesAlterTableExpression() {
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL DEFAULT (1)",
table.addColumn(int64, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) DEFAULT (1)",
table.addColumn(int64, check: int64 > 0, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) DEFAULT (1)",
table.addColumn(int64, check: int64Optional > 0, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER",
table.addColumn(int64Optional)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64\" > 0)",
table.addColumn(int64Optional, check: int64 > 0)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0)",
table.addColumn(int64Optional, check: int64Optional > 0)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER DEFAULT (1)",
table.addColumn(int64Optional, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64\" > 0) DEFAULT (1)",
table.addColumn(int64Optional, check: int64 > 0, defaultValue: 1)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) DEFAULT (1)",
table.addColumn(int64Optional, check: int64Optional > 0, defaultValue: 1)
)
}
func test_addColumn_withIntegerExpression_compilesReferentialAlterTableExpression() {
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL UNIQUE REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, unique: true, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, check: int64 > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, check: int64Optional > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, unique: true, check: int64 > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64\" INTEGER NOT NULL UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64, unique: true, check: int64Optional > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER UNIQUE REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, unique: true, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, check: int64 > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, check: int64Optional > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER UNIQUE CHECK (\"int64\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, unique: true, check: int64 > 0, references: table, int64)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"int64Optional\" INTEGER UNIQUE CHECK (\"int64Optional\" > 0) REFERENCES \"table\" (\"int64\")",
table.addColumn(int64Optional, unique: true, check: int64Optional > 0, references: table, int64)
)
}
func test_addColumn_withStringExpression_compilesCollatedAlterTableExpression() {
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"string\" TEXT NOT NULL DEFAULT ('string') COLLATE RTRIM",
table.addColumn(string, defaultValue: "string", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"string\" TEXT NOT NULL CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM",
table.addColumn(string, check: string != "", defaultValue: "string", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"string\" TEXT NOT NULL CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM",
table.addColumn(string, check: stringOptional != "", defaultValue: "string", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT COLLATE RTRIM",
table.addColumn(stringOptional, collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"string\" != '') COLLATE RTRIM",
table.addColumn(stringOptional, check: string != "", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"stringOptional\" != '') COLLATE RTRIM",
table.addColumn(stringOptional, check: stringOptional != "", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"string\" != '') DEFAULT ('string') COLLATE RTRIM",
table.addColumn(stringOptional, check: string != "", defaultValue: "string", collate: .Rtrim)
)
XCTAssertEqual(
"ALTER TABLE \"table\" ADD COLUMN \"stringOptional\" TEXT CHECK (\"stringOptional\" != '') DEFAULT ('string') COLLATE RTRIM",
table.addColumn(stringOptional, check: stringOptional != "", defaultValue: "string", collate: .Rtrim)
)
}
func test_rename_compilesAlterTableRenameToExpression() {
XCTAssertEqual("ALTER TABLE \"old\" RENAME TO \"table\"", Table("old").rename(table))
}
func test_createIndex_compilesCreateIndexExpression() {
XCTAssertEqual("CREATE INDEX \"index_table_on_int64\" ON \"table\" (\"int64\")", table.createIndex(int64))
XCTAssertEqual(
"CREATE UNIQUE INDEX \"index_table_on_int64\" ON \"table\" (\"int64\")",
table.createIndex([int64], unique: true)
)
XCTAssertEqual(
"CREATE INDEX IF NOT EXISTS \"index_table_on_int64\" ON \"table\" (\"int64\")",
table.createIndex([int64], ifNotExists: true)
)
XCTAssertEqual(
"CREATE UNIQUE INDEX IF NOT EXISTS \"index_table_on_int64\" ON \"table\" (\"int64\")",
table.createIndex([int64], unique: true, ifNotExists: true)
)
}
func test_dropIndex_compilesCreateIndexExpression() {
XCTAssertEqual("DROP INDEX \"index_table_on_int64\"", table.dropIndex(int64))
XCTAssertEqual("DROP INDEX IF EXISTS \"index_table_on_int64\"", table.dropIndex([int64], ifExists: true))
}
func test_create_onView_compilesCreateViewExpression() {
XCTAssertEqual(
"CREATE VIEW \"view\" AS SELECT \"int64\" FROM \"table\"",
_view.create(table.select(int64))
)
XCTAssertEqual(
"CREATE TEMPORARY VIEW \"view\" AS SELECT \"int64\" FROM \"table\"",
_view.create(table.select(int64), temporary: true)
)
XCTAssertEqual(
"CREATE VIEW IF NOT EXISTS \"view\" AS SELECT \"int64\" FROM \"table\"",
_view.create(table.select(int64), ifNotExists: true)
)
XCTAssertEqual(
"CREATE TEMPORARY VIEW IF NOT EXISTS \"view\" AS SELECT \"int64\" FROM \"table\"",
_view.create(table.select(int64), temporary: true, ifNotExists: true)
)
}
func test_create_onVirtualTable_compilesCreateVirtualTableExpression() {
XCTAssertEqual(
"CREATE VIRTUAL TABLE \"virtual_table\" USING \"custom\"('foo', 'bar')",
virtualTable.create(Module("custom", ["foo", "bar"]))
)
}
func test_rename_onVirtualTable_compilesAlterTableRenameToExpression() {
XCTAssertEqual(
"ALTER TABLE \"old\" RENAME TO \"virtual_table\"",
VirtualTable("old").rename(virtualTable)
)
}
}
| mpl-2.0 | 0428189f3bfae4746fd6ea37b5c539f0 | 53.691004 | 155 | 0.582793 | 4.344692 | false | false | false | false |
wireapp/wire-ios-sync-engine | Tests/Source/MockSessionManager.swift | 1 | 2867 | //
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
@testable import WireSyncEngine
class MockSessionManager: NSObject, WireSyncEngine.SessionManagerType {
static let accountManagerURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("MockSessionManager.accounts")
var foregroundNotificationResponder: ForegroundNotificationResponder?
var callKitManager: WireSyncEngine.CallKitManager?
var callNotificationStyle: CallNotificationStyle = .pushNotifications
var accountManager: AccountManager = AccountManager(sharedDirectory: accountManagerURL)
var backgroundUserSessions: [UUID: ZMUserSession] = [:]
var mockUserSession: ZMUserSession?
var lastRequestToShowMessage: (ZMUserSession, ZMConversation, ZMConversationMessage)?
var lastRequestToShowConversation: (ZMUserSession, ZMConversation)?
var lastRequestToShowConversationsList: ZMUserSession?
var lastRequestToShowUserProfile: UserType?
var lastRequestToShowConnectionRequest: UUID?
func showConversation(_ conversation: ZMConversation, at message: ZMConversationMessage?, in session: ZMUserSession) {
if let message = message {
lastRequestToShowMessage = (session, conversation, message)
} else {
lastRequestToShowConversation = (session, conversation)
}
}
func showConversationList(in session: ZMUserSession) {
lastRequestToShowConversationsList = session
}
func showUserProfile(user: UserType) {
lastRequestToShowUserProfile = user
}
func showConnectionRequest(userId: UUID) {
lastRequestToShowConnectionRequest = userId
}
@objc public var updatePushTokenCalled = false
func updatePushToken(for session: ZMUserSession) {
updatePushTokenCalled = true
}
func updateAppIconBadge(accountID: UUID, unreadCount: Int) {
// no-op
}
func configureUserNotifications() {
// no-op
}
func update(credentials: ZMCredentials) -> Bool {
return false
}
func checkJailbreakIfNeeded() -> Bool {
return false
}
func passwordVerificationDidFail(with failCount: Int) {
// no-op
}
}
| gpl-3.0 | 168fb3328d15c6f07e94f5999a32e4ac | 33.130952 | 133 | 0.732473 | 5.156475 | false | false | false | false |
parkera/swift-corelibs-foundation | Foundation/Bundle.swift | 1 | 15594 | // 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
open class Bundle: NSObject {
private var _bundle : CFBundle!
public static var _supportsFHSBundles: Bool {
#if DEPLOYMENT_RUNTIME_OBJC
return false
#else
return _CFBundleSupportsFHSBundles()
#endif
}
public static var _supportsFreestandingBundles: Bool {
#if DEPLOYMENT_RUNTIME_OBJC
return false
#else
return _CFBundleSupportsFreestandingBundles()
#endif
}
private static var _mainBundle : Bundle = {
return Bundle(cfBundle: CFBundleGetMainBundle())
}()
open class var main: Bundle {
get {
return _mainBundle
}
}
private class var allBundlesRegardlessOfType: [Bundle] {
// FIXME: This doesn't return bundles that weren't loaded using CFBundle or class Bundle. https://bugs.swift.org/browse/SR-10433
guard let bundles = CFBundleGetAllBundles()?._swiftObject as? [CFBundle] else { return [] }
return bundles.map(Bundle.init(cfBundle:))
}
private var isFramework: Bool {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
return bundleURL.pathExtension == "framework"
#else
#if os(Windows)
if let name = _CFBundleCopyExecutablePath(_bundle)?._nsObject {
return name.pathExtension.lowercased == "dll"
}
#else
// We're assuming this is an OS like Linux or BSD that uses FHS-style library names (lib….so or lib….so.2.3.4)
if let name = _CFBundleCopyExecutablePath(_bundle)?._nsObject {
return name.hasPrefix("lib") && (name.pathExtension == "so" || name.range(of: ".so.").location != NSNotFound)
}
#endif
return false
#endif
}
open class var allBundles: [Bundle] {
return allBundlesRegardlessOfType.filter { !$0.isFramework }
}
open class var allFrameworks: [Bundle] {
return allBundlesRegardlessOfType.filter { $0.isFramework }
}
internal init(cfBundle: CFBundle) {
super.init()
_bundle = cfBundle
}
public init?(path: String) {
super.init()
// TODO: We do not yet resolve symlinks, but we must for compatibility
// let resolvedPath = path._nsObject.stringByResolvingSymlinksInPath
let resolvedPath = path
guard resolvedPath.length > 0 else {
return nil
}
let url = URL(fileURLWithPath: resolvedPath)
_bundle = CFBundleCreate(kCFAllocatorSystemDefault, unsafeBitCast(url, to: CFURL.self))
if (_bundle == nil) {
return nil
}
}
public convenience init?(url: URL) {
self.init(path: url.path)
}
public init(for aClass: AnyClass) {
NSUnimplemented()
}
public init?(identifier: String) {
super.init()
guard let result = CFBundleGetBundleWithIdentifier(identifier._cfObject) else {
return nil
}
_bundle = result
}
public convenience init?(_executableURL: URL) {
guard let bundleURL = _CFBundleCopyBundleURLForExecutableURL(_executableURL._cfObject)?.takeRetainedValue() else {
return nil
}
self.init(url: bundleURL._swiftObject)
}
override open var description: String {
return "\(String(describing: Bundle.self)) <\(bundleURL.path)> (\(isLoaded ? "loaded" : "not yet loaded"))"
}
/* Methods for loading and unloading bundles. */
open func load() -> Bool {
return CFBundleLoadExecutable(_bundle)
}
open var isLoaded: Bool {
return CFBundleIsExecutableLoaded(_bundle)
}
@available(*,deprecated,message:"Not available on non-Darwin platforms")
open func unload() -> Bool { NSUnsupported() }
open func preflight() throws {
var unmanagedError:Unmanaged<CFError>? = nil
try withUnsafeMutablePointer(to: &unmanagedError) { (unmanagedCFError: UnsafeMutablePointer<Unmanaged<CFError>?>) in
CFBundlePreflightExecutable(_bundle, unmanagedCFError)
if let error = unmanagedCFError.pointee {
throw error.takeRetainedValue()._nsObject
}
}
}
open func loadAndReturnError() throws {
var unmanagedError:Unmanaged<CFError>? = nil
try withUnsafeMutablePointer(to: &unmanagedError) { (unmanagedCFError: UnsafeMutablePointer<Unmanaged<CFError>?>) in
CFBundleLoadExecutableAndReturnError(_bundle, unmanagedCFError)
if let error = unmanagedCFError.pointee {
let retainedValue = error.takeRetainedValue()
throw retainedValue._nsObject
}
}
}
/* Methods for locating various components of a bundle. */
open var bundleURL: URL {
return CFBundleCopyBundleURL(_bundle)._swiftObject
}
open var resourceURL: URL? {
return CFBundleCopyResourcesDirectoryURL(_bundle)?._swiftObject
}
open var executableURL: URL? {
return CFBundleCopyExecutableURL(_bundle)?._swiftObject
}
open func url(forAuxiliaryExecutable executableName: String) -> URL? {
return CFBundleCopyAuxiliaryExecutableURL(_bundle, executableName._cfObject)?._swiftObject
}
open var privateFrameworksURL: URL? {
return CFBundleCopyPrivateFrameworksURL(_bundle)?._swiftObject
}
open var sharedFrameworksURL: URL? {
return CFBundleCopySharedFrameworksURL(_bundle)?._swiftObject
}
open var sharedSupportURL: URL? {
return CFBundleCopySharedSupportURL(_bundle)?._swiftObject
}
open var builtInPlugInsURL: URL? {
return CFBundleCopyBuiltInPlugInsURL(_bundle)?._swiftObject
}
open var appStoreReceiptURL: URL? {
// Always nil on this platform
return nil
}
open var bundlePath: String {
return bundleURL.path
}
open var resourcePath: String? {
return resourceURL?.path
}
open var executablePath: String? {
return executableURL?.path
}
open func path(forAuxiliaryExecutable executableName: String) -> String? {
return url(forAuxiliaryExecutable: executableName)?.path
}
open var privateFrameworksPath: String? {
return privateFrameworksURL?.path
}
open var sharedFrameworksPath: String? {
return sharedFrameworksURL?.path
}
open var sharedSupportPath: String? {
return sharedSupportURL?.path
}
open var builtInPlugInsPath: String? {
return builtInPlugInsURL?.path
}
// -----------------------------------------------------------------------------------
// MARK: - URL Resource Lookup - Class
open class func url(forResource name: String?, withExtension ext: String?, subdirectory subpath: String?, in bundleURL: URL) -> URL? {
// If both name and ext are nil/zero-length, return nil
if (name == nil || name!.isEmpty) && (ext == nil || ext!.isEmpty) {
return nil
}
return CFBundleCopyResourceURLInDirectory(bundleURL._cfObject, name?._cfObject, ext?._cfObject, subpath?._cfObject)._swiftObject
}
open class func urls(forResourcesWithExtension ext: String?, subdirectory subpath: String?, in bundleURL: NSURL) -> [NSURL]? {
return CFBundleCopyResourceURLsOfTypeInDirectory(bundleURL._cfObject, ext?._cfObject, subpath?._cfObject)?._unsafeTypedBridge()
}
// -----------------------------------------------------------------------------------
// MARK: - URL Resource Lookup - Instance
open func url(forResource name: String?, withExtension ext: String?) -> URL? {
return self.url(forResource: name, withExtension: ext, subdirectory: nil)
}
open func url(forResource name: String?, withExtension ext: String?, subdirectory subpath: String?) -> URL? {
// If both name and ext are nil/zero-length, return nil
if (name == nil || name!.isEmpty) && (ext == nil || ext!.isEmpty) {
return nil
}
return CFBundleCopyResourceURL(_bundle, name?._cfObject, ext?._cfObject, subpath?._cfObject)?._swiftObject
}
open func url(forResource name: String?, withExtension ext: String?, subdirectory subpath: String?, localization localizationName: String?) -> URL? {
// If both name and ext are nil/zero-length, return nil
if (name == nil || name!.isEmpty) && (ext == nil || ext!.isEmpty) {
return nil
}
return CFBundleCopyResourceURLForLocalization(_bundle, name?._cfObject, ext?._cfObject, subpath?._cfObject, localizationName?._cfObject)?._swiftObject
}
open func urls(forResourcesWithExtension ext: String?, subdirectory subpath: String?) -> [NSURL]? {
return CFBundleCopyResourceURLsOfType(_bundle, ext?._cfObject, subpath?._cfObject)?._unsafeTypedBridge()
}
open func urls(forResourcesWithExtension ext: String?, subdirectory subpath: String?, localization localizationName: String?) -> [NSURL]? {
return CFBundleCopyResourceURLsOfTypeForLocalization(_bundle, ext?._cfObject, subpath?._cfObject, localizationName?._cfObject)?._unsafeTypedBridge()
}
// -----------------------------------------------------------------------------------
// MARK: - Path Resource Lookup - Class
open class func path(forResource name: String?, ofType ext: String?, inDirectory bundlePath: String) -> String? {
return Bundle.url(forResource: name, withExtension: ext, subdirectory: bundlePath, in: URL(fileURLWithPath: bundlePath))?.path
}
open class func paths(forResourcesOfType ext: String?, inDirectory bundlePath: String) -> [String] {
// Force-unwrap path, because if the URL can't be turned into a path then something is wrong anyway
return urls(forResourcesWithExtension: ext, subdirectory: bundlePath, in: NSURL(fileURLWithPath: bundlePath))?.map { $0.path! } ?? []
}
// -----------------------------------------------------------------------------------
// MARK: - Path Resource Lookup - Instance
open func path(forResource name: String?, ofType ext: String?) -> String? {
return self.url(forResource: name, withExtension: ext, subdirectory: nil)?.path
}
open func path(forResource name: String?, ofType ext: String?, inDirectory subpath: String?) -> String? {
return self.url(forResource: name, withExtension: ext, subdirectory: subpath)?.path
}
open func path(forResource name: String?, ofType ext: String?, inDirectory subpath: String?, forLocalization localizationName: String?) -> String? {
return self.url(forResource: name, withExtension: ext, subdirectory: subpath, localization: localizationName)?.path
}
open func paths(forResourcesOfType ext: String?, inDirectory subpath: String?) -> [String] {
// Force-unwrap path, because if the URL can't be turned into a path then something is wrong anyway
return self.urls(forResourcesWithExtension: ext, subdirectory: subpath)?.map { $0.path! } ?? []
}
open func paths(forResourcesOfType ext: String?, inDirectory subpath: String?, forLocalization localizationName: String?) -> [String] {
// Force-unwrap path, because if the URL can't be turned into a path then something is wrong anyway
return self.urls(forResourcesWithExtension: ext, subdirectory: subpath, localization: localizationName)?.map { $0.path! } ?? []
}
// -----------------------------------------------------------------------------------
// MARK: - Localized Strings
open func localizedString(forKey key: String, value: String?, table tableName: String?) -> String {
let localizedString = CFBundleCopyLocalizedString(_bundle, key._cfObject, value?._cfObject, tableName?._cfObject)!
return localizedString._swiftObject
}
// -----------------------------------------------------------------------------------
// MARK: - Other
open var bundleIdentifier: String? {
return CFBundleGetIdentifier(_bundle)?._swiftObject
}
open var infoDictionary: [String : Any]? {
let cfDict: CFDictionary? = CFBundleGetInfoDictionary(_bundle)
return __SwiftValue.fetch(cfDict) as? [String : Any]
}
open var localizedInfoDictionary: [String : Any]? {
let cfDict: CFDictionary? = CFBundleGetLocalInfoDictionary(_bundle)
return __SwiftValue.fetch(cfDict) as? [String : Any]
}
open func object(forInfoDictionaryKey key: String) -> Any? {
if let localizedInfoDictionary = localizedInfoDictionary {
return localizedInfoDictionary[key]
} else {
return infoDictionary?[key]
}
}
open func classNamed(_ className: String) -> AnyClass? {
// FIXME: This will return a class that may not be associated with the receiver. https://bugs.swift.org/browse/SR-10347.
guard isLoaded || load() else { return nil }
return NSClassFromString(className)
}
open var principalClass: AnyClass? {
// NB: Cross-platform Swift doesn't have a notion of 'the first class in the ObjC segment' that ObjC platforms have. For swift-corelibs-foundation, if a bundle doesn't have a principal class named, the principal class is nil.
guard let name = infoDictionary?["NSPrincipalClass"] as? String else { return nil }
return classNamed(name)
}
open var preferredLocalizations: [String] {
return Bundle.preferredLocalizations(from: localizations)
}
open var localizations: [String] {
let cfLocalizations: CFArray? = CFBundleCopyBundleLocalizations(_bundle)
let nsLocalizations = __SwiftValue.fetch(cfLocalizations) as? [Any]
return nsLocalizations?.map { $0 as! String } ?? []
}
open var developmentLocalization: String? {
let region = CFBundleGetDevelopmentRegion(_bundle)!
return region._swiftObject
}
open class func preferredLocalizations(from localizationsArray: [String]) -> [String] {
let cfLocalizations: CFArray? = CFBundleCopyPreferredLocalizationsFromArray(localizationsArray._cfObject)
let nsLocalizations = __SwiftValue.fetch(cfLocalizations) as? [Any]
return nsLocalizations?.map { $0 as! String } ?? []
}
open class func preferredLocalizations(from localizationsArray: [String], forPreferences preferencesArray: [String]?) -> [String] {
let localizations = CFBundleCopyLocalizationsForPreferences(localizationsArray._cfObject, preferencesArray?._cfObject)!
return localizations._swiftObject.map { return ($0 as! NSString)._swiftObject }
}
open var executableArchitectures: [NSNumber]? {
let architectures = CFBundleCopyExecutableArchitectures(_bundle)!
return architectures._swiftObject.map() { $0 as! NSNumber }
}
}
| apache-2.0 | 7830ca3f7bd21349690410a7d196798b | 38.770408 | 233 | 0.627518 | 4.985609 | false | false | false | false |
mortenjust/androidtool-mac | AndroidTool/scriptsPopoverViewController.swift | 1 | 4049 | //
// scriptsPopoverViewController.swift
// AndroidTool
//
// Created by Morten Just Petersen on 4/26/15.
// Copyright (c) 2015 Morten Just Petersen. All rights reserved.
//
import Cocoa
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
@objc protocol UserScriptDelegate : class {
func userScriptStarted()
func userScriptEnded()
func userScriptWantsSerial() -> String
}
class scriptsPopoverViewController: NSViewController {
let buttonHeight:CGFloat = 30
// accepted answer here http://stackoverflow.com/questions/26180268/interface-builder-iboutlet-and-protocols-for-delegate-and-datasource-in-swift
@IBOutlet var delegate : UserScriptDelegate!
let fileM = FileManager.default
func setup(){
let folder = Util().getSupportFolderScriptPath()
let allScripts = Util().getFilesInScriptFolder(folder)
if allScripts?.count > 0 {
addScriptsToView(allScripts!, view: self.view)
}
}
func addScriptsToView(_ scripts:[String], view:NSView){
var i:CGFloat = 1
view.frame.size.height = CGFloat(scripts.count) * (buttonHeight+3) + buttonHeight
let folderButton = NSButton(frame: NSRect(x: 10.0, y: 3,
width: view.bounds.width-15.0,
height: buttonHeight))
folderButton.image = NSImage(named: "revealFolder")
folderButton.isBordered = false
folderButton.action = #selector(revealScriptFolderClicked)
folderButton.target = self
view.addSubview(folderButton)
for script in scripts {
let scriptButton = NSButton(frame: NSRect(x: 10.0, y: (i*buttonHeight+3),
width: view.bounds.width-15.0,
height: buttonHeight))
let friendlyScriptName = script.replacingOccurrences(of: ".sh", with: "")
scriptButton.title = friendlyScriptName
if #available(OSX 10.10.3, *) {
scriptButton.setButtonType(NSButtonType.accelerator)
} else {
// Fallback on earlier versions
}
scriptButton.bezelStyle = NSBezelStyle.rounded
scriptButton.action = #selector(runScriptClicked)
scriptButton.target = self
view.addSubview(scriptButton)
i += 1
}
}
func runScript(_ scriptPath:String){
delegate.userScriptStarted()
let serial:String = delegate.userScriptWantsSerial()
print("ready to run on \(serial)")
ShellTasker(scriptFile: scriptPath).run(arguments: ["\(serial)"], isUserScript: true) { (output) -> Void in
self.delegate.userScriptEnded()
}
}
func runScriptClicked(_ sender:NSButton){
let scriptName = "\(sender.title).sh"
let scriptPath = "\(Util().getSupportFolderScriptPath())/\(scriptName)"
print("ready to run \(scriptPath)")
runScript(scriptPath)
}
func revealScriptFolderClicked(_ sender:NSButton) {
Util().revealScriptsFolder()
}
override func viewDidLoad() {
if #available(OSX 10.10, *) {
super.viewDidLoad()
} else {
// Fallback on earlier versions
}
// Do view setup here.
}
override func awakeFromNib() {
setup()
}
}
| apache-2.0 | 719dfeb1e9200c8e365b3c7a55c5006b | 30.632813 | 149 | 0.610027 | 4.63803 | false | false | false | false |
nofelmahmood/Seam | Source/Core/Token.swift | 3 | 2196 | // Token.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Nofel Mahmood ( https://twitter.com/NofelMahmood )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import CloudKit
class Token {
static let Key = "com.seam.syncToken.key"
private var newToken: CKServerChangeToken?
static let sharedToken = Token()
func rawToken() -> CKServerChangeToken? {
guard let rawToken = UserDefaults.standard.object(forKey: Token.Key) as? NSData else {
return nil
}
return NSKeyedUnarchiver.unarchiveObject(with: rawToken as Data) as? CKServerChangeToken
}
func save(token: CKServerChangeToken) {
newToken = token
}
func discard() {
newToken = nil
}
func unCommittedToken() -> CKServerChangeToken? {
return newToken
}
func commit() {
guard let newToken = newToken else {
return
}
let archivedToken = NSKeyedArchiver.archivedData(withRootObject: newToken)
UserDefaults.standard.set(archivedToken, forKey: Token.Key)
}
func reset() {
discard()
UserDefaults.standard.set(nil, forKey: Token.Key)
}
}
| mit | ef1bd2a7b2ad430b992eea799fd0b3ed | 33.3125 | 92 | 0.709472 | 4.400802 | false | false | false | false |
jphacks/KB_01 | jphacks/ViewController/MapViewController/MapViewController.swift | 1 | 12661 | //
// MapViewController.swift
// jphacks
//
// Created by 山口智生 on 2015/11/28.
// Copyright © 2015年 at. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
import Social
class MapViewController: BaseViewController {
private let mapView = MKMapView()
let dismissButton: UIButton! = UIButton()
// pinを立てるやつたち
var spots: [Spot] = []
// 経路として通る点
var viaLocations: [CLLocationCoordinate2D] = []
var totalTime: Int! = nil
var totalDist: Int! = nil
var routes: [MKRoute] = [] {
didSet {
var time: Double = 0
var dist: Double = 0
for route in self.routes {
time += Double(route.expectedTravelTime)
dist += Double(route.distance)
}
if !routes.isEmpty {
self.totalTime = Int(time/60)
self.totalDist = Int(dist)
self.distanceLabel?.text = "(\(self.totalDist) m)"
self.needTimeLabel?.text = "\(self.totalTime) 分"
} else {
self.distanceLabel?.text = ""
self.needTimeLabel?.text = "計算中…"
}
}
}
// 詳細を上に表示
var spotDetailView: SpotDetailView! = nil
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var needTimeLabel: UILabel!
@IBOutlet weak var postTweetButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let statusBarHeight = Util.getStatusBarHeight()
mapView.frame = CGRectMake(0, statusBarHeight, self.view.bounds.width, self.view.bounds.height - statusBarHeight - 65)
if !self.view.subviews.contains(mapView) {
self.view.addSubview(mapView)
}
mapView.delegate = self
// mapの表示範囲
fitMapWithSpots(viaLocations.first!, toLocation: viaLocations.last!)
addPin(viaLocations.first!)
addPin(viaLocations.last!)
// 渡されたspotsについてピンを立てる
spots.forEach { spot in
addSpotPin(spot)
}
// 経路を表示
redrawRoutes()
// mapをタップしたら詳細が消えるようにrecognizerを追加
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tappedMap:")
mapView.addGestureRecognizer(tapGestureRecognizer)
// 閉じるボタン
dismissButton.frame = CGRectMake(30,50, 50,50)
dismissButton.layer.cornerRadius = 25
dismissButton.setTitle("✕", forState: .Normal)
dismissButton.titleLabel?.font = UIFont.systemFontOfSize(30)
dismissButton.setTitleColor(Constants.COLOR_DISABLED, forState: .Normal)
dismissButton.setTitleColor(Constants.COLOR_WHITE, forState: .Highlighted)
dismissButton.backgroundColor = Constants.COLOR_WHITE
dismissButton.addTarget(self, action: "dismiss", forControlEvents: .TouchUpInside)
self.view.addSubview(dismissButton)
if spotDetailView == nil {
spotDetailView = SpotDetailView.create(self)
spotDetailView.mapViewController = self
self.view.addSubview(spotDetailView)
}
spotDetailView.setUp(self.spots.first ?? Spot(name: "大阪", address: "0-0-0", detail: "fdさいfjdしお", latitude: 135, longitude: 35))
spotDetailView.hidden = true
/*let tweetButton: UIButton = UIButton(frame: CGRectMake(300,100,100,100))
tweetButton.backgroundColor = UIColor.whiteColor()
tweetButton.addTarget(self, action: "PostTweet", forControlEvents: .TouchUpInside)
tweetButton.setTitle("Tweet", forState: .Normal)
self.view.addSubview(tweetButton)*/
postTweetButton.addTarget(self, action: "PostTweet", forControlEvents: .TouchUpInside)
}
func getDist(fromLocation: CLLocationCoordinate2D, toLocation: CLLocationCoordinate2D) -> Double {
return pow(fromLocation.latitude - toLocation.latitude, 2) + pow(fromLocation.longitude - toLocation.longitude, 2)
}
// 適切な位置にinsertする
func insertViaLocation(location: CLLocationCoordinate2D) {
var index = 0
var minDistDiff:Double = 100000000
var prel: CLLocationCoordinate2D! = nil
for (i,l) in self.viaLocations.enumerate() {
if let unwrappedPrel = prel {
let distDiff = getDist(unwrappedPrel, toLocation: location) + getDist(location, toLocation: l) - getDist(unwrappedPrel, toLocation: l)
// 最小の更新
if distDiff < minDistDiff {
index = i
minDistDiff = distDiff
}
}
// はじめだけ
prel = l
}
viaLocations.insert(location, atIndex: index)
redrawRoutes()
}
func fitMapWithSpots(fromLocation: CLLocationCoordinate2D, toLocation: CLLocationCoordinate2D) {
// fromLocation, toLocationに基いてmapの表示範囲を設定
// 現在地と目的地を含む矩形を計算
let maxLat: Double
let minLat: Double
let maxLon: Double
let minLon: Double
if fromLocation.latitude > toLocation.latitude {
maxLat = fromLocation.latitude
minLat = toLocation.latitude
} else {
maxLat = toLocation.latitude
minLat = fromLocation.latitude
}
if fromLocation.longitude > toLocation.longitude {
maxLon = fromLocation.longitude
minLon = toLocation.longitude
} else {
maxLon = toLocation.longitude
minLon = fromLocation.longitude
}
let center = CLLocationCoordinate2DMake((maxLat + minLat) / 2, (maxLon + minLon) / 2)
let mapMargin:Double = 1.5; // 経路が入る幅(1.0)+余白(0.5)
let leastCoordSpan:Double = 0.005; // 拡大表示したときの最大値
let span = MKCoordinateSpanMake(fmax(leastCoordSpan, fabs(maxLat - minLat) * mapMargin), fmax(leastCoordSpan, fabs(maxLon - minLon) * mapMargin))
mapView.setRegion(mapView.regionThatFits(MKCoordinateRegionMake(center, span)), animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tappedMap(sender: UIGestureRecognizer?) {
// タップした位置にpinをおく&ルートとしてよる
/*let location = getLocationFromTap(sender!)
self.insertViaLocation(location)
self.addPin(location)*/
}
func dismiss() {
self.dismissViewControllerAnimated(true, completion: nil)
}
// 一旦削除してルートを再描画
func redrawRoutes() {
self.mapView.removeOverlays(self.mapView.overlays)
self.routes = []
var prel: CLLocationCoordinate2D! = nil
for l in self.viaLocations {
if let unwrappedPrel = prel {
addRoute(unwrappedPrel, toCoordinate: l)
}
prel = l
}
}
func addSpotPin(spot: Spot) {
let pin = SpotPinAnnotation()
pin.title = spot.name
pin.subtitle = spot.detail
pin.spot = spot
pin.coordinate = CLLocationCoordinate2DMake(CLLocationDegrees(spot.latitude), CLLocationDegrees(spot.longitude))
mapView.addAnnotation(pin)
}
func addPin(location: CLLocationCoordinate2D) {
let pin = SpotPinAnnotation()
pin.coordinate = location
pin.title = "title"
pin.subtitle = "sub title"
pin.pinColor = UIColor.blueColor()
mapView.addAnnotation(pin)
}
func addRoute(fromCoordinate: CLLocationCoordinate2D, toCoordinate: CLLocationCoordinate2D) {
let fromItem: MKMapItem = MKMapItem(placemark: MKPlacemark(coordinate: fromCoordinate, addressDictionary: nil))
let toItem: MKMapItem = MKMapItem(placemark: MKPlacemark(coordinate: toCoordinate, addressDictionary: nil))
// MKDirectionsRequestを生成.
let myRequest: MKDirectionsRequest = MKDirectionsRequest()
// 出発&目的地
myRequest.source = fromItem
myRequest.destination = toItem
myRequest.requestsAlternateRoutes = false
// 徒歩
myRequest.transportType = MKDirectionsTransportType.Walking
// MKDirectionsを生成してRequestをセット.
let myDirections: MKDirections = MKDirections(request: myRequest)
// 経路探索.
myDirections.calculateDirectionsWithCompletionHandler { (response: MKDirectionsResponse?, error: NSError?) -> Void in
if error != nil {
print(error)
return
}
if let route = response?.routes.first as MKRoute? {
print("目的地まで \(route.distance)m")
print("所要時間 \(Int(route.expectedTravelTime/60))分")
self.routes.append(route)
// mapViewにルートを描画.
self.mapView.addOverlay(route.polyline)
}
}
}
// tapをおいたとき用
func getLocationFromTap(sender: UIGestureRecognizer) -> CLLocationCoordinate2D {
return self.mapView.convertPoint(sender.locationInView(mapView), toCoordinateFromView: mapView)
}
}
extension MapViewController: MKMapViewDelegate {
// マップが移動した時
func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
self.spotDetailView?.hidden = true
}
// 経路を描画するときの色や線の太さを指定
func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 3
return polylineRenderer
} else {
// ダミー
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 5
return polylineRenderer
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation === mapView.userLocation { // 現在地を示すアノテーションの場合はデフォルトのまま
return nil
} else {
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView?.animatesDrop = true
}
else {
pinView?.annotation = annotation
}
if annotation.isKindOfClass(SpotPinAnnotation.self) {
if let color = (annotation as! SpotPinAnnotation).pinColor {
pinView?.pinTintColor = color
}
}
return pinView
}
}
//
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
guard let annotation = view.annotation else {
return
}
print(annotation.title)
if annotation.isKindOfClass(SpotPinAnnotation) {
if let spot = (annotation as! SpotPinAnnotation).spot {
spotDetailView.setUp(spot)
spotDetailView.hidden = false
}
}
}
func PostTweet() {
let tweetView = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
tweetView.setInitialText("寄り道しました! \n#droppin")
//tweetView.addImage(self.view.GetImage() as UIImage)
tweetView.addImage(self.mapView.GetImage() as UIImage)
self.presentViewController(tweetView, animated: true, completion: nil)
}
}
| mit | 1f2a8be05112a61c6ba9313589533050 | 34.662722 | 153 | 0.606106 | 4.758784 | false | false | false | false |
Rain-dew/YLTextView | YLTextViewDemo/YLTextView_SwitDemo/YLTextView_Swit/ViewController.swift | 1 | 760 | //
// ViewController.swift
// YLTextView_Swit
//
// Created by 张雨露 on 2017/6/9.
// Copyright © 2017年 张雨露. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .lightGray
let textview = UITextView(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
// textview.text = "如果你想对textView.text直接赋值。请在设置属性之前进行,否则影响计算"
textview.placeholder = "喜欢请Star"
textview.limitLength = 200
// textview.limitLines = 2
textview.autoHeight = true
textview.center = self.view.center
view.addSubview(textview)
}
}
| mit | e1c8a6b30c1ba824bf6aad190d277c8a | 24.37037 | 88 | 0.648175 | 3.663102 | false | false | false | false |
lixiangzhou/ZZSwiftTool | ZZSwiftTool/ZZSwiftTool/ZZExtension/ZZUIExtension/UIColor+ZZExtension.swift | 1 | 5772 | //
// UIColor+ZZExtension.swift
// ZZSwiftTool
//
// Created by lixiangzhou on 17/3/12.
// Copyright © 2017年 lixiangzhou. All rights reserved.
//
import UIKit
public extension UIColor {
/// 快速创建颜色
///
/// - parameter red: 红
/// - parameter green: 绿
/// - parameter blue: 蓝
/// - parameter alpha: 透明度
convenience init(red: Int, green: Int, blue: Int, alphaValue: CGFloat = 1.0) {
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alphaValue)
}
/// 16进制rgb颜色值生成对应UIColor
///
/// - parameter stringHexValue: 16进制颜色值, 可包含前缀0x,#,颜色值可以是 RGB RGBA RRGGBB RRGGBBAA
convenience init?(stringHexValue: String) {
var hexValue = stringHexValue.zz_trim.uppercased()
if hexValue.hasPrefix("#") {
hexValue = hexValue.substring(from: hexValue.index(hexValue.startIndex, offsetBy: 1))
} else if hexValue.hasPrefix("0X") {
hexValue = hexValue.substring(from: hexValue.index(hexValue.startIndex, offsetBy: 2))
}
let len = hexValue.characters.count
// RGB RGBA RRGGBB RRGGBBAA
if len != 3 && len != 4 && len != 6 && len != 8 {
return nil
}
var resultHexValue: UInt32 = 0
guard Scanner(string: hexValue).scanHexInt32(&resultHexValue) else {
return nil
}
var divisor: CGFloat = 255
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if len == 3 {
divisor = 15
r = CGFloat((resultHexValue & 0xF00) >> 8) / divisor
g = CGFloat((resultHexValue & 0x0F0) >> 4) / divisor
b = CGFloat( resultHexValue & 0x00F) / divisor
a = 1
} else if len == 4 {
divisor = 15
r = CGFloat((resultHexValue & 0xF000) >> 12) / divisor
g = CGFloat((resultHexValue & 0x0F00) >> 8) / divisor
b = CGFloat((resultHexValue & 0x00F0) >> 4) / divisor
a = CGFloat(resultHexValue & 0x000F) / divisor
} else if len == 6 {
r = CGFloat((resultHexValue & 0xFF0000) >> 16) / divisor
g = CGFloat((resultHexValue & 0x00FF00) >> 8) / divisor
b = CGFloat(resultHexValue & 0x0000FF) / divisor
a = 1
} else if len == 8 {
r = CGFloat((resultHexValue & 0xFF000000) >> 24) / divisor
g = CGFloat((resultHexValue & 0x00FF0000) >> 16) / divisor
b = CGFloat((resultHexValue & 0x0000FF00) >> 8) / divisor
a = CGFloat(resultHexValue & 0x000000FF) / divisor
}
self.init(red: r, green: g, blue: b, alpha: a)
}
/// 随机色
static var zz_random: UIColor {
let red = arc4random() % 256
let green = arc4random() % 256
let blue = arc4random() % 256
return UIColor(red: Int(red), green: Int(green), blue: Int(blue))
}
/// 返回颜色的rgba值
var rgbaValue: String? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
let red = Int(r * 255)
let green = Int(g * 255)
let blue = Int(b * 255)
let alpha = Int(a * 255)
/* 进制转换
String(value: T, radix: Int) value的radix表现形式
Int(String, radix: Int) Int(value, radix:radix) value 是 radix 进制,转成10进制
*/
let value = (red << 24) + (green << 16) + (blue << 8) + alpha
return String(value, radix: 16)
}
return nil
}
var rgbValue: String? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: nil) {
let red = Int(r * 255)
let green = Int(g * 255)
let blue = Int(b * 255)
/* 进制转换
String(value: T, radix: Int) value的radix表现形式
Int(String, radix: Int) Int(value, radix:radix) value 是 radix 进制,转成10进制
*/
let value = (red << 16) + (green << 8) + blue
return String(value, radix: 16)
}
return nil
}
/// 返回颜色的rgba值
var rgbaHexStringValue: (red: String, green: String, blue: String, alpha: String)? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
let red = String(Int(r * 255), radix: 16)
let green = String(Int(g * 255), radix: 16)
let blue = String(Int(b * 255), radix: 16)
let alpha = String(Int(a * 255), radix: 16)
return (red: red, green: green, blue: blue, alpha: alpha)
}
return nil
}
/// 返回颜色的rgba值,0-255
var rgbaIntValue: (red: Int, green: Int, blue: Int, alpha: Int)? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
if getRed(&r, green: &g, blue: &b, alpha: &a) {
let red = Int(r * 255)
let green = Int(g * 255)
let blue = Int(b * 255)
let alpha = Int(a * 255)
return (red: red, green: green, blue: blue, alpha: alpha)
}
return nil
}
}
| mit | a13e4ef554662498cc1167a38acd7faf | 31.637427 | 123 | 0.499015 | 3.783729 | false | false | false | false |
4jchc/4jchc-BaiSiBuDeJie | 4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Other-其他/View/XMGTopWindow.swift | 1 | 2176 | //
// XMGTopWindow.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/3/2.
// Copyright © 2016年 蒋进. All rights reserved.
//
import UIKit
class XMGTopWindow: NSObject {
/** 全局的窗口 */
static var window_:UIWindow?
/// 显示窗口
static func show(){
window_!.hidden = false
}
static func hide(){
window_!.hidden = true
}
// 当第一次使用这个类的时候会调用一次
override class func initialize(){
// frame数据
let frame:CGRect = CGRectMake(0, 0, XMGScreenW, 20);
// 显示窗口
window_ = UIWindow()
window_?.backgroundColor = UIColor.redColor()
window_!.windowLevel = UIWindowLevelAlert;
window_!.frame = frame;
window_?.rootViewController = UiwindViewController()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "windowClick")
self.window_!.addGestureRecognizer(tap)
window_!.makeKeyAndVisible()
let window:UIWindow = UIApplication.sharedApplication().keyWindow!
printLog("superview11-\(window.superview?.subviews)")
}
/// 监听窗口点击
static func windowClick() {
let window:UIWindow = UIApplication.sharedApplication().keyWindow!
searchScrollViewInView(window)
}
static func searchScrollViewInView(superview:UIView){
for subview in superview.subviews{
//CGRectIntersectsRect(UIApplication.sharedApplication().keyWindow!.bounds, subview.frame)
//let subview = subview as? UIScrollView
// 如果是scrollview, 滚动最顶部
if subview.isKindOfClass(UIScrollView.self){
let subview = subview as! UIScrollView
var offset:CGPoint = subview.contentOffset
offset.y = -subview.contentInset.top;
subview.setContentOffset(offset, animated: true)
}
// 继续查找子控件
self.searchScrollViewInView(subview)
}
}
} | apache-2.0 | 9b853ed6c6b9a5a677205a0a2b60d0e8 | 26.466667 | 102 | 0.587664 | 5.009732 | false | false | false | false |
jcsla/MusicoAudioPlayer | MusicoAudioPlayer/Classes/Reachability.swift | 2 | 7522 | /*
Copyright (c) 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import SystemConfiguration
import Foundation
extension NSNotification.Name {
static let ReachabilityChanged = NSNotification.Name(rawValue: "ReachabilityChanged")
}
func callback(reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
guard let info = info else { return }
let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
DispatchQueue.main.async {
reachability.reachabilityChanged(flags: flags)
}
}
class Reachability: NSObject {
enum NetworkStatus {
case notReachable, reachableViaWiFi, reachableViaWWAN
}
// MARK: - *** properties ***
var reachableOnWWAN: Bool
var notificationCenter = NotificationCenter.default
var currentReachabilityStatus: NetworkStatus {
if isReachable() {
if isReachableViaWiFi() {
return .reachableViaWiFi
}
if isRunningOnDevice {
return .reachableViaWWAN
}
}
return .notReachable
}
// MARK: - *** Initialisation methods ***
required init(reachabilityRef: SCNetworkReachability?) {
reachableOnWWAN = true
self.reachabilityRef = reachabilityRef
}
convenience override init() {
var zeroAddress = sockaddr()
zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
zeroAddress.sa_family = sa_family_t(AF_INET)
let ref = withUnsafePointer(to: &zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
self.init(reachabilityRef: ref)
}
// MARK: - *** Notifier methods ***
@discardableResult
func startNotifier() -> Bool {
if notifierRunning {
return true
}
guard let reachabilityRef = reachabilityRef else { return false }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil,
copyDescription: nil)
context.info = UnsafeMutableRawPointer(
Unmanaged<Reachability>.passUnretained(self).toOpaque())
if SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
if SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
notifierRunning = true
return true
}
}
stopNotifier()
return false
}
func stopNotifier() {
if let reachabilityRef = reachabilityRef {
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
}
notifierRunning = false
}
// MARK: - *** Connection test methods ***
func isReachable() -> Bool {
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
return self.isReachable(with: flags)
})
}
func isReachableViaWiFi() -> Bool {
return isReachableWithTest() { flags -> Bool in
// Check we're reachable
if self.isReachable(flags: flags) {
if self.isRunningOnDevice {
// Check we're NOT on WWAN
if self.isOnWWAN(flags: flags) {
return false
}
}
return true
}
return false
}
}
// MARK: - *** Private methods ***
#if (arch(i386) || arch(x86_64)) && os(iOS)
private let isRunningOnDevice = false
#else
private let isRunningOnDevice = true
#endif
private var notifierRunning = false
private var reachabilityRef: SCNetworkReachability?
private let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability")
fileprivate func reachabilityChanged(flags: SCNetworkReachabilityFlags) {
notificationCenter.post(name: .ReachabilityChanged, object: self)
}
private func isReachable(with flags: SCNetworkReachabilityFlags) -> Bool {
let reachable = isReachable(flags: flags)
if !reachable {
return false
}
if isConnectionRequiredOrTransient(flags: flags) {
return false
}
if isRunningOnDevice {
if isOnWWAN(flags: flags) && !reachableOnWWAN {
// We don't want to connect when on 3G.
return false
}
}
return true
}
private func isReachableWithTest(_ test: (SCNetworkReachabilityFlags) -> (Bool)) -> Bool {
if let reachabilityRef = reachabilityRef {
var flags = SCNetworkReachabilityFlags(rawValue: 0)
let gotFlags = withUnsafeMutablePointer(to: &flags) {
SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0))
}
if gotFlags {
return test(flags)
}
}
return false
}
// WWAN may be available, but not active until a connection has been established.
// WiFi may require a connection for VPN on Demand.
private func isOnWWAN(flags: SCNetworkReachabilityFlags) -> Bool {
#if os(iOS)
return flags.contains(.isWWAN)
#else
return false
#endif
}
private func isReachable(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.reachable)
}
private func isConnectionRequiredOrTransient(flags: SCNetworkReachabilityFlags) -> Bool {
let testcase: SCNetworkReachabilityFlags = [.connectionRequired, .transientConnection]
return flags.intersection(testcase) == testcase
}
private var reachabilityFlags: SCNetworkReachabilityFlags {
if let reachabilityRef = reachabilityRef {
var flags = SCNetworkReachabilityFlags(rawValue: 0)
let gotFlags = withUnsafeMutablePointer(to: &flags) {
SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0))
}
if gotFlags {
return flags
}
}
return []
}
deinit {
stopNotifier()
reachabilityRef = nil
}
}
| mit | 499494cf4d7c35dc29be4c6340f50e99 | 31.562771 | 119 | 0.644642 | 5.795069 | false | false | false | false |
DigitalExegete/RokuRemoteMac | RokuRemote/RemoteController/RemoteViewController.swift | 1 | 4996 | //
// RemoteViewController.swift
// RokuRemote
//
// Created by William Jones on 4/23/17.
// Copyright © 2017 Treblotto Music & Music Technology. All rights reserved.
//
import Cocoa
@objc class RemoteViewController: NSViewController, URLSessionDelegate, NSTableViewDelegate, NSTableViewDataSource, NSPopoverDelegate, RokuRemoteNetworkInterfaceDelegate {
let collapsedViewWidth: CGFloat = 289
let expandedViewWidth: CGFloat = 530
var deviceModel: RokuDeviceModel?
@IBOutlet var channelButton: NSButton?
@IBOutlet var channelPopover: NSPopover?
@IBOutlet var currentChannelImageView: NSImageView?
@IBOutlet var deviceTableView: NSTableView?
@IBOutlet var rokuRemoteViewWidth: NSLayoutConstraint?
var currentChannelImage: NSImage?
var moreButtonImage: NSImage?
@IBOutlet var expandButton: NSButton?
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func awakeFromNib() {
}
override func viewDidAppear() {
super.viewDidAppear()
}
override func viewDidLoad() {
super.viewDidLoad()
self.expandButton?.image = UserDefaults.standard.bool(forKey: "remoteExpanded") ? NSImage(named: NSImageNameGoRightTemplate) : NSImage(named: NSImageNameGoRightTemplate)
rokuRemoteViewWidth?.animator().constant = UserDefaults.standard.bool(forKey: "remoteExpanded") ? self.expandedViewWidth : self.collapsedViewWidth
self.expandButton?.animator().frameCenterRotation = UserDefaults.standard.bool(forKey: "remoteExpanded") ? 180 : 0
NotificationCenter.default.addObserver(forName: Notification.Name.NSTableViewSelectionDidChange, object: self.deviceTableView, queue: nil) { (note: Notification) in
if let deviceTableCellView: RokuTableCellView = self.deviceTableView?.view(atColumn: 0, row: (self.deviceTableView?.selectedRow)!, makeIfNecessary: false) as? RokuTableCellView {
self.deviceModel = deviceTableCellView.objectValue
}
}
if (self.deviceTableView?.numberOfRows as Int!) > 0 && self.deviceTableView?.selectedRow != -1 {
if let deviceTableCellView: RokuTableCellView = self.deviceTableView?.view(atColumn: 0, row: (self.deviceTableView?.selectedRow)!, makeIfNecessary: false) as? RokuTableCellView {
self.deviceModel = deviceTableCellView.objectValue
}
}
}
@IBAction func expandButtonClicked(sender: NSButton?) {
rokuRemoteViewWidth?.animator().constant = (sender?.state==NSOnState) ? self.expandedViewWidth : self.collapsedViewWidth
self.expandButton?.animator().image = (sender?.state==NSOnState) ? NSImage(named: NSImageNameGoRightTemplate) : NSImage(named: NSImageNameGoRightTemplate)
self.expandButton?.animator().frameCenterRotation = (sender?.state==NSOnState) ? 180 : 0
}
@IBAction func remoteButtonClicked(sender: RokuPushButton?) {
let realAction: RokuRemoteControlActions = RokuRemoteControlActions.init(rawValue: (sender?.buttonAction)!)!
let currentDevice = self.deviceModel
currentDevice?.sendRokuKeypressCommand(realAction)
}
@IBAction func remoteTransportClick(sender: NSSegmentedControl? ) {
let segCell: NSSegmentedCell? = sender?.cell as! NSSegmentedCell?
//(forSegment:UInt((sender?.selectedSegment))
let realAction: RokuRemoteControlActions = RokuRemoteControlActions.init(rawValue: UInt((segCell?.tag(forSegment: (sender?.selectedSegment)!))!))!
if self.deviceModel == nil {
if let deviceTableCellView: RokuTableCellView = self.deviceTableView?.view(atColumn: 0, row: (self.deviceTableView?.selectedRow)!, makeIfNecessary: false) as? RokuTableCellView {
self.deviceModel = deviceTableCellView.objectValue
}
}
let currentDevice = self.deviceModel
currentDevice?.sendRokuKeypressCommand(realAction)
}
@IBAction func channelButtonClicked(sender: NSButton?) {
self.channelPopover?.delegate = self
self.channelPopover?.show(relativeTo: (self.channelButton?.bounds)!, of: sender!, preferredEdge: NSRectEdge.maxY)
}
override func mouseDown(with event: NSEvent) {
var clickPoint = event.locationInWindow
clickPoint = self.view.convert(clickPoint, from: nil)
let clickedLayer = self.view.layer?.hitTest(clickPoint)
if let controlAction = clickedLayer?.value(forKey: "rokuAction") as! NSNumber?
{
let realAction: RokuRemoteControlActions = RokuRemoteControlActions.init(rawValue: (controlAction.uintValue))!
let currentDevice = self.deviceModel
currentDevice?.sendRokuKeypressCommand(realAction)
}
}
class override func exposedBindings() -> [String] {
return ["deviceModel"]
}
func networkInterface(_ networkInterface: RokuRemoteNetworkInterface!, receivedData data: Data!, forChannel rokuChannelID: UInt) {
CATransaction.begin()
self.currentChannelImage = NSImage(data: data)
self.currentChannelImageView?.image = self.currentChannelImage
CATransaction.commit()
}
}
| mit | 21f23dfd71a17d2136f974a6fc260a54 | 31.019231 | 190 | 0.741341 | 4.3172 | false | false | false | false |
makomori/Dots | Example/Dots/ViewController.swift | 1 | 1220 | //
// ViewController.swift
// Dots
//
// Created by makomori on 05/11/2017.
// Copyright (c) 2017 makomori. All rights reserved.
//
import UIKit
import Dots
class ViewController: UIViewController {
var loadingView: DotsLoadingView?
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func showGoogleProgress(_ sender: Any) {
self.stop(self)
self.loadingView = DotsLoadingView(colors: nil)
self.loadingView?.show()
}
@IBAction func showCustomProgress(_ sender: Any) {
self.stop(self)
let firstColor = UIColor(red: 1.0, green: 0.631, blue: 0.761, alpha: 1.0)
let secondColor = UIColor(red: 1.0, green: 0.431, blue: 0.631, alpha: 1.0)
let thirdColor = UIColor(red: 1.0, green: 0.259, blue: 0.522, alpha: 1.0)
let fourthColor = UIColor(red: 1.0, green: 0.082, blue: 0.408, alpha: 1.0)
self.loadingView = DotsLoadingView(colors: [firstColor, secondColor, thirdColor, fourthColor])
self.loadingView?.show()
}
@IBAction func stop(_ sender: Any) {
if let _ = self.loadingView {
self.loadingView?.stop()
self.loadingView = nil
}
}
}
| mit | 8d438a60353c0ed26db1450c06794574 | 28.756098 | 102 | 0.614754 | 3.674699 | false | false | false | false |
divadretlaw/very | Sources/very/Extensions/URLSessionExtensions.swift | 1 | 2073 | //
// URLSessionExtensions.swift
// very
//
// Created by David Walter on 05.07.20.
//
import Foundation
extension URLSession {
func synchronousDataTask(with url: URL) -> (Data?, URLResponse?, Error?) {
var data: Data?
var response: URLResponse?
var error: Error?
let semaphore = DispatchSemaphore(value: 0)
let dataTask = dataTask(with: url) {
data = $0
response = $1
error = $2
semaphore.signal()
}
dataTask.resume()
_ = semaphore.wait(timeout: .distantFuture)
return (data, response, error)
}
func synchronousDataTask(with url: URL, completion: (Data?, URLResponse?, Error?) -> Void) {
let (data, response, error) = synchronousDataTask(with: url)
completion(data, response, error)
}
}
extension Optional where Wrapped == URLResponse {
var isSuccess: Bool {
(self as? HTTPURLResponse)?.isSuccess ?? false
}
var isRedirection: Bool {
(self as? HTTPURLResponse)?.isRedirection ?? false
}
var isClientError: Bool {
(self as? HTTPURLResponse)?.isClientError ?? false
}
var isServerError: Bool {
(self as? HTTPURLResponse)?.isServerError ?? false
}
func isHttpStatus(range: Int) -> Bool {
guard let http = self as? HTTPURLResponse else {
return false
}
return http.isHttpStatus(range: range)
}
}
extension URLResponse {
var isSuccess: Bool {
isHttpStatus(range: 200)
}
var isRedirection: Bool {
isHttpStatus(range: 300)
}
var isClientError: Bool {
isHttpStatus(range: 400)
}
var isServerError: Bool {
isHttpStatus(range: 400)
}
func isHttpStatus(range: Int) -> Bool {
guard let http = self as? HTTPURLResponse else {
return false
}
return http.statusCode / 100 == range / 100
}
}
| apache-2.0 | 12755c6c264fccf4d93d61eb300209bf | 22.292135 | 96 | 0.557646 | 4.566079 | false | false | false | false |
benlangmuir/swift | test/Interpreter/SDK/objc_mangling.swift | 20 | 2292 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -module-name MangleTest %s -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// rdar://problem/56959761
// UNSUPPORTED: OS=watchos
import Foundation
/* FIXME: SwiftObject doesn't support -description
class Foo { }
var anyFoo: AnyObject = Foo()
print(anyFoo.description())
@objc class Bar { }
var anyBar: AnyObject = Bar()
print(anyBar.description())
*/
func checkClassName(_ cls: AnyClass, _ name: String, _ mangled: String)
{
// Class's name should appear unmangled.
assert(NSStringFromClass(cls) == name)
assert(NSStringFromClass(object_getClass(cls)!) == name)
// Look up by unmangled name should work.
// Look up by mangled name should also work.
for query in [name, mangled] {
let cls2 = NSClassFromString(query)!
assert(cls === cls2)
assert(object_getClass(cls) === object_getClass(cls2))
}
}
func checkProtocolName(_ proto: Protocol, _ name: String, _ mangled: String)
{
// Protocol's name should appear unmangled.
assert(NSStringFromProtocol(proto) == name)
// Look up by unmangled name should work.
// Look up by mangled name should also work.
for query in [name, mangled] {
let proto2 = NSProtocolFromString(query)
assert(protocol_isEqual(proto, proto2))
}
}
func checkIvarName(_ cls: AnyClass, _ name: String)
{
let ivarName = ivar_getName(class_getInstanceVariable(cls, name)!)
let s = ivarName != nil ? String(cString: ivarName!) : Optional.none
assert(name == s)
}
@objc class Wibble : NSObject { }
checkClassName(Wibble.self, "MangleTest.Wibble", "_TtC10MangleTest6Wibble")
// Check whether the class name comes out properly in the instance description
var anyWibble: AnyObject = Wibble()
print(anyWibble.description)
// CHECK: MangleTest.Wibble
// ObjC metadata is not punycoded.
@objc protocol RadicalHeart⺖ { }
checkProtocolName(RadicalHeart⺖.self, "MangleTest.RadicalHeart⺖", "_TtP10MangleTest15RadicalHeart⺖_")
@objc class RadicalSheep⽺ : NSObject, RadicalHeart⺖ {
var ⽺x: Int = 0
}
checkClassName(RadicalSheep⽺.self,
"MangleTest.RadicalSheep⽺", "_TtC10MangleTest15RadicalSheep⽺")
checkIvarName(RadicalSheep⽺.self, "⽺x")
| apache-2.0 | e9783f19acfe62430b671852d263cf5a | 27.708861 | 101 | 0.715608 | 3.320644 | false | true | false | false |
saasquatch/mobile-sdk-ios-sample | SampleApp/ShareLinksViewController.swift | 1 | 6124 | //
// ShareLinksViewController.swift
// SampleApp
//
// Created by Trevor Lee on 2017-06-06.
//
import Foundation
import UIKit
import saasquatch
import JWT
class ShareLinksViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
let user = User.sharedUser
// engagementMedium array
let engagementMediumPickerData = ["ALL", "HOSTED", "EMAIL", "POPUP", "MOBILE", "EMBED", "UNKNOWN"]
// shareMedium array
let shareMediumPickerData = ["ALL", "EMAIL", "SMS", "WHATSAPP", "LINKEDIN", "TWITTER", "FBMESSENGER", "UNKNOWN", "DIRECT", "FACEBOOK"]
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelSelectAnEngagementMedium: UILabel!
@IBOutlet weak var labelShowEngagementMedium: UILabel!
@IBOutlet weak var labelSelectAShareMedium: UILabel!
@IBOutlet weak var labelShowShareMedium: UILabel!
@IBOutlet weak var pickerEngagement: UIPickerView!
@IBOutlet weak var buttonEngagementMediumText: UIButton!
@IBOutlet weak var textOut: UITextView!
@IBOutlet weak var buttonGetLinks: UIButton!
var buttonCount = -1;
@IBAction func buttonEngagementMedium(_ sender: UIButton) {
buttonCount = buttonCount + 1
if(buttonCount % 2 != 0){
pickerEngagement.isHidden = true;
buttonGetLinks.isHidden = false;
buttonEngagementMediumText.setTitle("Click Here", for: .normal)
}else{
pickerEngagement.isHidden = false;
buttonGetLinks.isHidden = true;
buttonEngagementMediumText.setTitle("Done", for: .normal)
}
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(ShareLinksViewController.dismissKeyboard), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
let tap = UITapGestureRecognizer(target: self, action: #selector(ShareLinksViewController.dismissKeyboard))
self.view.addGestureRecognizer(tap)
pickerEngagement.isHidden = true
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2;
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if (component == 0) {
return engagementMediumPickerData[row]
}
else if (component == 1) {
return shareMediumPickerData[row]
}
return nil;
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if (component == 0) {
return engagementMediumPickerData.count
}
else {
return shareMediumPickerData.count
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if (component == 0) {
labelShowEngagementMedium.text = engagementMediumPickerData[row]
}
else {
labelShowShareMedium.text = shareMediumPickerData[row]
}
}
@objc func dismissKeyboard() {
self.view.endEditing(true)
}
@IBAction func getLinks(_ sender: UIButton) {
var engagementMedium = labelShowEngagementMedium.text
var shareMedium = labelShowShareMedium.text
if(engagementMedium == "ALL") {
engagementMedium = nil
}
if(shareMedium == "ALL") {
shareMedium = nil
}
Saasquatch.getSharelinks(user.tenant, forReferringAccountID: user.accountId, forReferringUserID: user.id, withEngagementMedium: engagementMedium, withShareMedium: shareMedium, withToken: user.token, completionHandler: {(userInfo: AnyObject?, error: NSError?) in
if error != nil {
// Show an alert describing the error
DispatchQueue.main.async(execute: {
self.showErrorAlert("shareLinks Error", message: error!.localizedDescription)
})
return
}
guard let shareLinks = userInfo!["shareLinks"] as? [String: AnyObject] else {
DispatchQueue.main.async(execute: {
self.showErrorAlert("shareLinks", message: "Something went wrong retrieving your links")
})
return
}
var engagementMediumKeys = Array(shareLinks.keys)
for (keys) in engagementMediumKeys {
print(keys)
}
let shareLinksKeys = shareLinks[engagementMediumKeys[0]] as? [String: String]
let shareMedium = Array(shareLinksKeys!.keys)
for (keys2) in shareMedium {
print(keys2)
}
var output = ""
for(value) in engagementMediumKeys {
for (value2) in shareMedium {
var link = shareLinks[value] as? [String: String]
let links = link![value2]
print(value)
print(value2)
print(links!)
output = output.appending(value + " + " + value2)
output = output.appending(" = " + links! + "\n")
}
output = output.appending("\n")
}
print(output)
DispatchQueue.main.async() {
self.textOut.text = output
}
}
)}
func showErrorAlert(_ title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
| mit | 3ee1614252884e15893a6868d822a0fa | 31.231579 | 269 | 0.576094 | 5.159225 | false | false | false | false |
feedhenry-templates/sync-ios-swift | sync-ios-app/DetailledViewController.swift | 1 | 3083 | /*
* Copyright Red Hat, Inc., and individual contributors
*
* 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
import FeedHenry
open class DetailledViewController: UIViewController {
var item: ShoppingItem!
var action: String!
var dataManager: DataManager!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var createdTextField: UITextField!
@IBOutlet weak var createdLabel: UILabel!
// public var isUpdate: Bool {
// if let uid = item.uid where uid != "" {
// print("UID \(uid)")
// return true
// }
// return false
// }
open override func viewDidLoad() {
if let item = item {
self.nameTextField.text = item.name
self.createdLabel.isHidden = false
self.createdTextField.isHidden = false
if let created = item.created {
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.long
formatter.timeStyle = .medium
self.createdTextField.text = formatter.string(from: created as Date)
}
} else {// create
self.createdLabel.isHidden = true
self.createdTextField.isHidden = true
}
}
@IBAction func saveItem(_ sender: AnyObject) {
if let name = self.nameTextField.text, name != "" {
if let item = item {
item.name = name
item.created = Date()
dataManager.updateItem(item)
print("HIT CREATE > UPDATE BUTTON:: \(item)")
} else {
item = dataManager.getItem()
item.name = name
item.created = Date()
dataManager.createItem(item)
print("HIT CREATE > SAVE BUTTON:: \(item)")
}
} else {
displayError("Name is required")
}
let parent = self.parent as! UINavigationController
parent.popViewController(animated: true)
}
@IBAction func cancel(_ sender: AnyObject) {
if let parent = self.parent as? UINavigationController {
parent.popViewController(animated: true)
}
}
func displayError(_ error: String) {
let alert = UIAlertController(title: error, message: nil, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
| apache-2.0 | 3f831568b1c6b77cfd44868e1e7ed4f6 | 34.436782 | 89 | 0.600065 | 4.802181 | false | false | false | false |
HabitRPG/habitrpg-ios | Habitica API Client/Habitica API Client/Models/User/APIPurchased.swift | 1 | 2448 | //
// APIPurchased.swift
// Habitica API Client
//
// Created by Phillip Thelen on 23.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
class APIPurchased: PurchasedProtocol, Decodable {
var hair: [OwnedCustomizationProtocol]
var skin: [OwnedCustomizationProtocol]
var shirt: [OwnedCustomizationProtocol]
var background: [OwnedCustomizationProtocol]
var subscriptionPlan: SubscriptionPlanProtocol?
enum CodingKeys: String, CodingKey {
case hair
case skin
case shirt
case background
case subscriptionPlan = "plan"
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
let hairDict = try?values.decode([String: [String: Bool]].self, forKey: .hair)
hair = (hairDict?.map({ (hairGroup) -> [OwnedCustomizationProtocol] in
return hairGroup.value.map({ (key, isOwned) -> OwnedCustomizationProtocol in
return APIOwnedCustomization(key: key, type: "hair", group: hairGroup.key, isOwned: isOwned)
})
})).map({ (ownedHair) -> [OwnedCustomizationProtocol] in
var ownedList = [OwnedCustomizationProtocol]()
ownedHair.forEach({ (group) in
ownedList.append(contentsOf: group)
})
return ownedList
}) ?? []
let skinDict = try?values.decode([String: Bool].self, forKey: .skin)
skin = (skinDict?.map({ (skinItem) -> OwnedCustomizationProtocol in
return APIOwnedCustomization(key: skinItem.key, type: "skin", group: nil, isOwned: skinItem.value)
})) ?? []
let shirtDict = try?values.decode([String: Bool].self, forKey: .shirt)
shirt = (shirtDict?.map({ shirtItem -> OwnedCustomizationProtocol in
return APIOwnedCustomization(key: shirtItem.key, type: "shirt", group: nil, isOwned: shirtItem.value)
})) ?? []
let backgroundDict = try?values.decode([String: Bool].self, forKey: .background)
background = (backgroundDict?.map({ backgroundItem -> OwnedCustomizationProtocol in
return APIOwnedCustomization(key: backgroundItem.key, type: "background", group: nil, isOwned: backgroundItem.value)
})) ?? []
subscriptionPlan = try? values.decode(APISubscriptionPlan.self, forKey: .subscriptionPlan)
}
}
| gpl-3.0 | a3b1aa24eaa239e8e52f86558c973128 | 42.696429 | 128 | 0.652227 | 4.354093 | false | false | false | false |
davidjupijnsping/patient-zero-ios | Patient Ø/ViewControllers/GameViewController.swift | 1 | 2739 | //
// ViewController.swift
// Patient Ø
//
// Created by David Jupijn on 10/06/16.
// Copyright © 2016 Sping. All rights reserved.
//
import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON
class GameViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var startGameButton: UIButton!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupLocationManager()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didTapStartGame(sender: UIButton) {
sendStartGameRequest()
}
private func sendStartGameRequest() {
Alamofire.request(.GET, "\(apiURL)games.json", parameters: nil)
.responseJSON { response in
if response.result.value != nil {
let json = JSON(response.result.value!)
// debugPrint("JSON: \(json)")
GameManager.sharedInstance.startGame(GameInfo(json:json))
self.startGameButton.hidden = true
self.locationManager.startUpdatingLocation()
}
}
}
func setupLocationManager() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedAlways {
}
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
if newLocation.coordinate != oldLocation.coordinate {
// debugPrint("GOT A NEW LOCATION BRUH! \(newLocation)")
postUserLocation(newLocation)
GameManager.sharedInstance.userLocation = newLocation
}
}
func postUserLocation(location: CLLocation) {
if GameManager.sharedInstance.started && GameManager.sharedInstance.gameInfo != nil && GameManager.sharedInstance.userLocation != nil {
let params = ["location": ["game_id": GameManager.sharedInstance.gameInfo!.id, "lat": GameManager.sharedInstance.userLocation!.coordinate.latitude, "long": GameManager.sharedInstance.userLocation!.coordinate.longitude]]
Alamofire.request(.POST, "\(apiURL)locations.json", parameters: params)
.responseJSON { response in
debugPrint("posted userlocation")
}
}
}
}
| apache-2.0 | e96941db3cbcd0fd00abdb21e4372cd8 | 31.2 | 231 | 0.659847 | 5.551724 | false | false | false | false |
gogozs/Pulley | Pulley/PrimaryContentViewController.swift | 1 | 2828 | //
// ViewController.swift
// Pulley
//
// Created by Brendan Lee on 7/6/16.
// Copyright © 2016 52inc. All rights reserved.
//
import UIKit
import MapKit
class PrimaryContentViewController: UIViewController, PulleyPrimaryContentControllerDelegate {
@IBOutlet var mapView: MKMapView!
@IBOutlet var controlsContainer: UIView!
@IBOutlet var temperatureLabel: UILabel!
@IBOutlet var temperatureLabelBottomConstraint: NSLayoutConstraint!
private let temperatureLabelBottomDistance: CGFloat = 8.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
controlsContainer.layer.cornerRadius = 10.0
temperatureLabel.layer.cornerRadius = 7.0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Uncomment if you want to change the visual effect style to dark. Note: The rest of the sample app's UI isn't made for dark theme. This just shows you how to do it.
// if let drawer = self.parent as? PulleyViewController
// {
// drawer.drawerBackgroundVisualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func makeUIAdjustmentsForFullscreen(progress: CGFloat)
{
controlsContainer.alpha = 1.0 - progress
}
func drawerChangedDistanceFromBottom(drawer: PulleyViewController, distance: CGFloat)
{
if distance <= 268.0
{
temperatureLabelBottomConstraint.constant = distance + temperatureLabelBottomDistance
}
else
{
temperatureLabelBottomConstraint.constant = 268.0 + temperatureLabelBottomDistance
}
}
@IBAction func runPrimaryContentTransitionWithoutAnimation(sender: AnyObject) {
if let drawer = self.parent as? PulleyViewController
{
let primaryContent = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PrimaryTransitionTargetViewController")
drawer.setPrimaryContentViewController(controller: primaryContent, animated: false)
}
}
@IBAction func runPrimaryContentTransition(sender: AnyObject) {
if let drawer = self.parent as? PulleyViewController
{
let primaryContent = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PrimaryTransitionTargetViewController")
drawer.setPrimaryContentViewController(controller: primaryContent, animated: true)
}
}
}
| mit | 48225351e702f81d270e756b7d3dfed5 | 33.47561 | 173 | 0.676689 | 5.30394 | false | false | false | false |
AlesTsurko/DNMKit | DNM_iOS/DNM_iOS/Tremolo.swift | 1 | 1740 | //
// Tremolo.swift
// denm_view
//
// Created by James Bean on 9/24/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
public class Tremolo: CAShapeLayer, BuildPattern {
public var x: CGFloat = 0
public var barHeight: CGFloat { get { return 0.5 * width } }
public var top: CGFloat = 0
public var width: CGFloat = 0
public var amountBars: Int = 3
public var hasBeenBuilt: Bool = false
public init(x: CGFloat, top: CGFloat, width: CGFloat, amountBars: Int = 3) {
super.init()
self.x = x
self.top = top
self.width = width
self.amountBars = amountBars
build()
}
public override init() { super.init() }
public override init(layer: AnyObject) { super.init(layer: layer) }
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
public func build() {
path = makePath()
setFrame()
setVisualAttributes()
hasBeenBuilt = true
}
internal func makePath() -> CGPath {
let path = UIBezierPath()
var accumHeight: CGFloat = 0.5 * barHeight
for _ in 0..<amountBars {
let bar = ParallelogramVertical(
x: 0.5 * width, y: accumHeight, width: 0.309 * width, length: width, slope: 0.25
)
accumHeight += barHeight
path.appendPath(bar)
}
return path.CGPath
}
public func setVisualAttributes() {
fillColor = UIColor.grayscaleColorWithDepthOfField(.MiddleForeground).CGColor
}
public func setFrame() {
// something
frame = CGPathGetBoundingBox(path)
position.x = x // hack?
}
}
| gpl-2.0 | 40b403bc8ef7f52b410dc90f3f2c20f5 | 26.603175 | 96 | 0.583669 | 4.210654 | false | false | false | false |
truhoada/iWeatherSwift | iWeather99/ViewController.swift | 1 | 2674 | //
// ViewController.swift
// iWeather99
//
// Created by hoangdangtrung on 12/22/15.
// Copyright © 2015 hoangdangtrung. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var labelLocation: UILabel!
@IBOutlet weak var labelButtonTemperature: UIButton!
@IBOutlet weak var labelCDegree: UILabel!
@IBOutlet weak var imageStatusWeather: UIImageView!
@IBOutlet weak var labelQuote: UILabel!
let arrayQuotes = ["1111111111", "22222222222", "333333333333", "4444444444444"]
let arrayLocations = ["New York", "Tokyo", "Hanoi", "Ho Chi Minh City"]
let arrayImageStatusWeathers = ["cloud", "rain", "light", "sun"]
var isCTemp = true
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func btnRefresh(sender: AnyObject) {
// self.labelCDegree.text = "C"
let locationIndex = arc4random_uniform(UInt32(arrayLocations.count))
self.labelLocation.text = arrayLocations[Int(locationIndex)]
let quoteIndex = arc4random_uniform(UInt32(arrayQuotes.count))
self.labelQuote.text = arrayQuotes[Int(quoteIndex)]
let imageStatusIndex = arc4random_uniform(UInt32(arrayImageStatusWeathers.count))
self.imageStatusWeather.image = UIImage(named: arrayImageStatusWeathers[Int(imageStatusIndex)])
self.labelButtonTemperature.setTitle(NSString(format: "%2.1f", getTemperature()) as String, forState: UIControlState.Normal)
}
@IBAction func btnTemperatureChanged(sender: UIButton) {
let stringCurrentTemp = self.labelButtonTemperature.titleLabel?.text
let floatCurrentTemp = (stringCurrentTemp! as NSString).floatValue
// if self.labelCDegree.text == "C" {
if isCTemp == true {
self.labelCDegree.text = "F"
let floatFTemp = (floatCurrentTemp * 1.8) + 32
self.labelButtonTemperature.setTitle(NSString(format: "%2.1f", floatFTemp) as String, forState: UIControlState.Normal)
isCTemp = false
} else {
self.labelCDegree.text = "C"
let floatCTemp = (floatCurrentTemp - 32)/1.8
self.labelButtonTemperature.setTitle(NSString(format: "%2.1f", floatCTemp) as String, forState: UIControlState.Normal)
isCTemp = true
}
}
func getTemperature() -> Float {
var num = Float(14) + Float(arc4random_uniform(18)) + Float(arc4random()) / Float(UINT32_MAX)
if isCTemp == true {
return num
} else {
num = num * 1.8 + 32
}
return num
}
}
| mit | 71eaedebf829820f8536d586d41985d4 | 35.121622 | 132 | 0.643846 | 4.037764 | false | false | false | false |
epv44/TwitchAPIWrapper | Sources/TwitchAPIWrapper/Network/Authorization/TwitchAuthorizationManager.swift | 1 | 7848 | //
// TwitchAuthorizationManager
// TwitchAPIWrapper
//
// Created by Eric Vennaro on 10/11/16.
//
// Note that the Twitch API never has tokens expire, so if a token exists it is valid indefinitely
import Foundation
import KeychainAccess
import UIKit
import AuthenticationServices
///Error for authentication requests.
public enum AuthorizationError: Error {
/**
Specifies that the url response from the server does not contain `queryItems`.
- parameter url: The url that does not contain query items.
*/
case invalidURLResponse(url: URL)
/**
Specifies that the JSON response could not be properly parsed.
- parameter JSON: The JSON that could not be parsed.
*/
case unableToParseJSON(json: String)
/**
Specifies that an unknown error has occured.
- parameter Error: the error that was thrown.
*/
case unknownError(Error)
/**
Specifies that the parameters included in the url request are not properly defined.
- parameter desc: Description of what parameters must be defined.
*/
case invalidQueryParameters(desc: String)
/**
Specifies that the authorization url is invalid.
- parameter desc: Description of what makes a valid authorization url.
- parameter url: The provided, invalid, url.
*/
case invalidAuthURL(desc: String, url: String)
/**
Specifies that the authorization code returned is invalid, or missing.
- parameter desc: Description of the missing code.
*/
case noCode(desc: String)
}
/**
The `TwitchAuthorizationManager` is responsible for managing the oauth2 bearer token flow with the Twitch server.
*/
@available(iOS 13.0, *)
public class TwitchAuthorizationManager {
//MARK: - Properties
///Singleton instance of the Authorization manager.
public static let sharedInstance = TwitchAuthorizationManager()
///The Client Id used for authorization.
public var clientID: String?
///The Client Secret used for authorization.
public var clientSecret: String?
///The Redirect URI used for authorization.
public var redirectURI: String?
///The scopes the user is authorized.
public var scopes: String?
///Authorization token **Read Only**.
public var authToken: String? {
get {
guard let token = ((try? keychain.get(twitchAccessToken)) as String??) else {
EVLog(text: "Bad retrieval of access token", line: #line, fileName: #file)
return nil
}
return token
}
}
///Scopes authorized from server **Read Only**.
public var authorizedScopes: [String]? {
get {
guard let data = (((try? keychain.getData(twitchScopes)) as Data??)),
let scopesData = data,
let scopes = (try? JSONSerialization.jsonObject(with: scopesData, options: [])) as? [String] else {
EVLog(text: "Bad retrieval of scope", line: #line, fileName: #file)
return nil
}
return scopes
}
}
///View controller that will present the webview for authorization, the "app context"
public var contextProvider: UIViewController?
///Credentials from the server, contains authorized scopes and the auth token this can be used to set the auth token without going through
///the built in authorization flow
public var credentials: Credentials? {
get {
guard let authToken = authToken, let scopes = authorizedScopes else { return nil }
return Credentials(accessToken: authToken, scopes: scopes)
}
set {
if let valueToSave = newValue {
guard let accessToken = valueToSave.accessToken,
let scopes = valueToSave.scopes else {
EVLog(text: "Error occured saving value to the keychain, credentials object is incomplete", line: #line, fileName: #file)
return
}
guard let scopesData = try? JSONSerialization.data(withJSONObject: scopes, options: []) else {
EVLog(text: "Error occured saving value to the keychain, credentials object is incomplete", line: #line, fileName: #file)
return
}
// try to remove first, this may fail that should be ok
do {
try keychain.remove(twitchAccessToken)
try keychain.remove(twitchScopes)
} catch {
EVLog(text: "Warn: removing keychain objects failed", line: #line, fileName: #file)
}
do{
try keychain.set(accessToken, key: twitchAccessToken)
try keychain.set(scopesData, key: twitchScopes)
} catch {
EVLog(text: "Unknown error occured saving value to the keychain", line: #line, fileName: #file)
}
} else {
EVLog(text: "Bad value: \(String(describing: newValue))", line: #line, fileName: #file)
}
}
}
private let userAccount = "twitch"
private let loadingAuthTokenKey = "loadingOauthToken"
private let keychain = Keychain(service: "com.vennaro.TwitchAPIWrapper")
private let twitchAccessToken = "twitchAccessToken"
private let twitchScopes = "twitchScopes"
private var authenticationSession: ASWebAuthenticationSession?
//MARK: - Initializer
///Others should not initialize the Singleton.
private init(){}
//MARK: - Public Functions
///Returns true if a valid authorization token exists.
public func hasOAuthToken() -> Bool {
return authToken != nil && !authToken!.isEmpty
}
/**
Starts the Twitch authorization flow with the Server.
- throws `AuthorizationError`.
*/
public func login() throws {
if authToken == nil {
let state = NSUUID().uuidString
guard let clientID = clientID, let redirectURI = redirectURI, let scopes = scopes else {
throw AuthorizationError.invalidQueryParameters(desc: "Must define values for the Client Id, Redirect URI, and scopes")
}
let authPath = "\(TwitchEndpoints.authentication.construct()?.absoluteString ?? "")?response_type=token&client_id=\(clientID)&redirect_uri=\(redirectURI)&scope=\(scopes)&state=\(state)&force_verify=true"
guard let authURL = URL(string: authPath) else {
EVLog(text: "Invalid auth url: \(authPath)", line: #line, fileName: #file)
throw AuthorizationError.invalidAuthURL(desc: "Authorization url is invalid, please check your values for the Redirect URI, Client Id, and scopes", url: authPath)
}
contextProvider?.present(TWAuthWebViewController(delegate: self, redirectURI: redirectURI, authURL: authURL, state: state), animated: true, completion: nil)
} else {
EVLog(text: "Authorization token exits no need to authorization again", line: #line, fileName: #file)
}
}
/**
Removes users credentials from the app forcing re-authentication with Twitch
- throws: `Error` see: https://github.com/kishikawakatsumi/KeychainAccess
*/
public func logout() throws {
try keychain.remove(twitchAccessToken)
try keychain.remove(twitchScopes)
}
}
//MARK: - TWAuthWebViewDelegate
extension TwitchAuthorizationManager: TWAuthWebViewDelegate {
func completeAuthentication(_ vc: UIViewController, token: String, scopes: [String]) {
credentials = Credentials(accessToken: token, scopes: scopes)
}
}
| mit | 229341d2218483199b4e47fd9c119a15 | 37.851485 | 215 | 0.628186 | 5.069767 | false | false | false | false |
stowy/LayoutKit | LayoutKit.playground/Pages/Label.xcplaygroundpage/Contents.swift | 6 | 791 | import UIKit
import PlaygroundSupport
import LayoutKit
let rootView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
rootView.backgroundColor = .white
func labelLayout(_ text: String) -> LabelLayout<UILabel> {
return LabelLayout<UILabel>(
text: text,
font: .systemFont(ofSize: 18),
numberOfLines: 0,
alignment: .center,
flexibility: .high,
viewReuseId: "label",
config: { _ in }
)
}
//let arrangement = labelLayout("Hello World").arrangement(width: 100, height: 150)
let arrangement = labelLayout("Hello World").arrangement()
print(arrangement)
arrangement.makeViews(in: rootView)
Debug.addBorderColorsRecursively(rootView)
Debug.printRecursiveDescription(rootView)
PlaygroundPage.current.liveView = rootView
| apache-2.0 | a9d3c07f6245efb2d594caeef9198693 | 26.275862 | 83 | 0.707965 | 4.05641 | false | false | false | false |
syncloud/ios | Syncloud/Discovery.swift | 1 | 3160 | import Foundation
protocol EndpointListener {
func found(_ endpoint: Endpoint)
func error(_ error: Error)
}
func ipv4Enpoint(_ data: Data) -> Endpoint? {
var address = sockaddr()
(data as NSData).getBytes(&address, length: MemoryLayout<sockaddr>.size)
if address.sa_family == sa_family_t(AF_INET) {
var addressIPv4 = sockaddr_in()
(data as NSData).getBytes(&addressIPv4, length: MemoryLayout<sockaddr>.size)
let host = String(cString: inet_ntoa(addressIPv4.sin_addr))
let port = Int(CFSwapInt16(addressIPv4.sin_port))
return Endpoint(host: host, port: port)
}
return nil
}
class BrowserDelegate : NSObject, NetServiceBrowserDelegate, NetServiceDelegate {
var resolving = [NetService]()
var listener: EndpointListener
init(listener: EndpointListener) {
self.listener = listener
}
func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser, didFindDomain domainName: String, moreComing moreDomainsComing: Bool) {
NSLog("BrowserDelegate.netServiceBrowser.didFindDomain")
}
func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser, didRemoveDomain domainName: String, moreComing moreDomainsComing: Bool) {
NSLog("BrowserDelegate.netServiceBrowser.didRemoveDomain")
}
func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser, didFind netService: NetService, moreComing moreServicesComing: Bool) {
NSLog("BrowserDelegate.netServiceBrowser.didFindService")
netService.delegate = self
resolving.append(netService)
netService.resolve(withTimeout: 0.0)
}
func netServiceDidResolveAddress(_ sender: NetService) {
for addressData in sender.addresses! {
let endpoint = ipv4Enpoint(addressData)
if let theEndpoint = endpoint {
self.listener.found(theEndpoint)
}
}
}
func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser, didRemove netService: NetService, moreComing moreServicesComing: Bool) {
NSLog("BrowserDelegate.netServiceBrowser.didRemoveService")
}
func netServiceBrowserWillSearch(_ aNetServiceBrowser: NetServiceBrowser){
NSLog("BrowserDelegate.netServiceBrowserWillSearch")
}
func netServiceBrowser(_ netServiceBrowser: NetServiceBrowser, didNotSearch errorInfo: [String : NSNumber]) {
NSLog("BrowserDelegate.netServiceBrowser.didNotSearch")
}
func netServiceBrowserDidStopSearch(_ netServiceBrowser: NetServiceBrowser) {
NSLog("BrowserDelegate.netServiceBrowserDidStopSearch")
}
}
class Discovery {
let BM_DOMAIN = "local."
let BM_TYPE = "_ssh._tcp."
var nsb: NetServiceBrowser
var nsbdel: BrowserDelegate?
init() {
self.nsb = NetServiceBrowser()
}
func start(_ serviceName: String, listener: EndpointListener) {
self.nsbdel = BrowserDelegate(listener: listener)
nsb.delegate = nsbdel
nsb.searchForServices(ofType: BM_TYPE, inDomain: BM_DOMAIN)
}
func stop() {
nsb.stop()
}
}
| gpl-3.0 | f32337f348c95b34385b1fe239919b84 | 32.263158 | 140 | 0.686076 | 4.869029 | false | false | false | false |
dasdom/UIStackViewPlayground | UIStackView.playground/Pages/Timeline.xcplaygroundpage/Contents.swift | 1 | 3286 | //: [Previous](@previous)
import UIKit
import PlaygroundSupport
//: First we need a `hostView` to put the different elements on.
let hostView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 130))
hostView.backgroundColor = .white
PlaygroundPage.current.liveView = hostView
let avatarImageView = UIImageView(image: UIImage(named: "IMG_0345.jpg"))
avatarImageView.clipsToBounds = true
avatarImageView.backgroundColor = .yellow
avatarImageView.contentMode = .scaleAspectFill
avatarImageView.layer.cornerRadius = 5
let handleLabel = UILabel(frame: .zero)
handleLabel.text = "dasdom"
handleLabel.font = UIFont(name: "Avenir-Heavy", size: 13)
//handleLabel.backgroundColor = UIColor.redColor()
let dateLabel = UILabel(frame: .zero)
dateLabel.text = "06/26/2015"
dateLabel.font = UIFont(name: "Avenir-Book", size: 13)
//dateLabel.backgroundColor = UIColor.grayColor()
let textLabel = UILabel(frame: .zero)
let textWithoutLink = "I played a bit with UIStackView. Good stuff!\nExamples: "
let linkString = "https://github.com/dasdom/UIStackViewPlayground"
let tweetString = textWithoutLink + linkString
let attributedString = NSMutableAttributedString(string: tweetString, attributes: [NSAttributedString.Key.font: UIFont(name: "Avenir-Book", size: 14)!])
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor(red: 0.1, green: 0.1, blue: 1.0, alpha: 1.0), range: NSMakeRange(textWithoutLink.count, linkString.count))
textLabel.attributedText = attributedString
textLabel.numberOfLines = 0
//textLabel.backgroundColor = UIColor.yellowColor()
let metaStackView = UIStackView(arrangedSubviews: [handleLabel, dateLabel])
metaStackView.spacing = 10
let textStackView = UIStackView(arrangedSubviews: [metaStackView, textLabel])
textStackView.axis = .vertical
textStackView.spacing = 5
let mainStackView = UIStackView(arrangedSubviews: [avatarImageView, textStackView])
mainStackView.translatesAutoresizingMaskIntoConstraints = false
mainStackView.alignment = .top
mainStackView.spacing = 10
hostView.addSubview(mainStackView)
NSLayoutConstraint.activate(
[
avatarImageView.widthAnchor.constraint(equalToConstant: 60),
avatarImageView.heightAnchor.constraint(equalToConstant: 60),
mainStackView.topAnchor.constraint(equalTo: hostView.topAnchor, constant: 10),
mainStackView.bottomAnchor.constraint(equalTo: hostView.bottomAnchor, constant: -10),
mainStackView.leadingAnchor.constraint(equalTo: hostView.leadingAnchor, constant: 10),
mainStackView.trailingAnchor.constraint(equalTo: hostView.trailingAnchor, constant: -10),
])
var constraints = [NSLayoutConstraint]()
//constraints.append(avatarImageView.widthAnchor.constraint(equalToConstant: 60))
//constraints.append(avatarImageView.heightAnchor.constraint(equalToConstant: 60))
//constraints.append(mainStackView.topAnchor.constraint(equalTo: hostView.topAnchor, constant: 10))
//constraints.append(mainStackView.bottomAnchor.constraint(equalTo: hostView.bottomAnchor, constant: -10))
//constraints.append(mainStackView.leadingAnchor.constraint(equalTo: hostView.leadingAnchor, constant: 10))
//constraints.append(mainStackView.trailingAnchor.constraint(equalTo: hostView.trailingAnchor, constant: -10))
NSLayoutConstraint.activate(constraints)
//: [Next](@next)
| mit | 62a264e9d49d290dd502f7f2470e8bf2 | 43.405405 | 191 | 0.80067 | 4.470748 | false | false | false | false |
cburrows/swift-protobuf | Sources/protoc-gen-swift/StringUtils.swift | 3 | 3801 | // Sources/protoc-gen-swift/StringUtils.swift - String processing utilities
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobufPluginLibrary
func splitPath(pathname: String) -> (dir:String, base:String, suffix:String) {
var dir = ""
var base = ""
var suffix = ""
for c in pathname {
if c == "/" {
dir += base + suffix + String(c)
base = ""
suffix = ""
} else if c == "." {
base += suffix
suffix = String(c)
} else {
suffix += String(c)
}
}
let validSuffix = suffix.isEmpty || suffix.first == "."
if !validSuffix {
base += suffix
suffix = ""
}
return (dir: dir, base: base, suffix: suffix)
}
func partition(string: String, atFirstOccurrenceOf substring: String) -> (String, String) {
guard let index = string.range(of: substring)?.lowerBound else {
return (string, "")
}
return (String(string[..<index]),
String(string[string.index(after: index)...]))
}
func parseParameter(string: String?) -> [(key:String, value:String)] {
guard let string = string, !string.isEmpty else {
return []
}
let parts = string.components(separatedBy: ",")
let asPairs = parts.map { partition(string: $0, atFirstOccurrenceOf: "=") }
let result = asPairs.map { (key:trimWhitespace($0), value:trimWhitespace($1)) }
return result
}
func trimWhitespace(_ s: String) -> String {
return s.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// The protoc parser emits byte literals using an escaped C convention.
/// Fortunately, it uses only a limited subset of the C escapse:
/// \n\r\t\\\'\" and three-digit octal escapes but nothing else.
func escapedToDataLiteral(_ s: String) -> String {
if s.isEmpty {
return "Data()"
}
var out = "Data(["
var separator = ""
var escape = false
var octal = 0
var octalAccumulator = 0
for c in s.utf8 {
if octal > 0 {
precondition(c >= 48 && c < 56)
octalAccumulator <<= 3
octalAccumulator |= (Int(c) - 48)
octal -= 1
if octal == 0 {
out += separator
out += "\(octalAccumulator)"
separator = ", "
}
} else if escape {
switch c {
case 110:
out += separator
out += "10"
separator = ", "
case 114:
out += separator
out += "13"
separator = ", "
case 116:
out += separator
out += "9"
separator = ", "
case 48..<56:
octal = 2 // 2 more digits
octalAccumulator = Int(c) - 48
default:
out += separator
out += "\(c)"
separator = ", "
}
escape = false
} else if c == 92 { // backslash
escape = true
} else {
out += separator
out += "\(c)"
separator = ", "
}
}
out += "])"
return out
}
/// Generate a Swift string literal suitable for including in
/// source code
private let hexdigits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
func stringToEscapedStringLiteral(_ s: String) -> String {
if s.isEmpty {
return "String()"
}
var out = "\""
for c in s.unicodeScalars {
switch c.value {
case 0:
out += "\\0"
case 1..<32:
let n = Int(c.value)
let hex1 = hexdigits[(n >> 4) & 15]
let hex2 = hexdigits[n & 15]
out += "\\u{" + hex1 + hex2 + "}"
case 34:
out += "\\\""
case 92:
out += "\\\\"
default:
out.append(String(c))
}
}
return out + "\""
}
| apache-2.0 | a191f2c157849987fc1bce67ca24a62d | 25.213793 | 104 | 0.550381 | 3.744828 | false | false | false | false |
powerytg/Accented | Accented/Core/API/Requests/DeleteVotePhotoRequest.swift | 1 | 1602 | //
// DeleteVotePhotoRequest.swift
// Accented
//
// Request to delete a vote on photo
//
// Created by Tiangong You on 9/9/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class DeleteVotePhotoRequest: APIRequest {
private var photoId : String
init(photoId : String, success : SuccessAction?, failure : FailureAction?) {
self.photoId = photoId
super.init(success: success, failure: failure)
ignoreCache = true
url = "\(APIRequest.baseUrl)photos/\(photoId)/vote"
// Currently we only support upvote a photo
parameters = [RequestParameters.vote : "1"]
}
override func handleSuccess(data: Data, response: HTTPURLResponse?) {
super.handleSuccess(data: data, response: response)
let userInfo : [String : Any] = [RequestParameters.photoId : photoId,
RequestParameters.response : data]
NotificationCenter.default.post(name: APIEvents.photoDidDeleteVote, object: nil, userInfo: userInfo)
if let success = successAction {
success()
}
}
override func handleFailure(_ error: Error) {
super.handleFailure(error)
let userInfo : [String : String] = [RequestParameters.errorMessage : error.localizedDescription]
NotificationCenter.default.post(name: APIEvents.photoFailedDeleteVote, object: nil, userInfo: userInfo)
if let failure = failureAction {
failure(error.localizedDescription)
}
}
}
| mit | 4e2acb9f86ffbc08a567b05dcc3c327c | 31.02 | 111 | 0.627733 | 4.866261 | false | false | false | false |
ECLabs/CareerUp | LocationHandler.swift | 1 | 1761 | import Parse
var locationInstance: LocationHandler?
class LocationHandler: NSObject {
var locations:[Location] = []
var loadingCount = 0
var reloaded = false
class func sharedInstance() -> LocationHandler {
if !(locationInstance != nil) {
locationInstance = LocationHandler()
}
return locationInstance!
}
func get() {
self.locations.removeAll(keepCapacity: false)
loadingCount = -1
let query = PFQuery(className: "Location")
query.cachePolicy = kPFCachePolicyNetworkElseCache;
query.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
self.loadingCount = objects.count
for object in objects {
let location = self.parseLocation(object as PFObject)
self.locations.append(location)
self.loadingCount--
}
}
})
}
func parseLocation(object:PFObject)->Location {
let location = Location()
location.objectId = object.objectId
location.updatedAt = object.updatedAt
if (object["name"]? != nil) {
location.name = object["name"] as String
}
if (object["address"]? != nil){
location.address = object["address"] as String
}
if (object["state"]? != nil) {
location.state = object["state"] as String
}
if (object["city"]? != nil) {
location.city = object["city"] as String
}
location.jobs = JobHandler.sharedInstance().getAllForLocation(location.objectId)
return location
}
}
| mit | 45e9a3f7f28bab43e571545bf7229a2f | 30.446429 | 100 | 0.558206 | 5.134111 | false | false | false | false |
calkinssean/woodshopBMX | WoodshopBMX/Pods/Charts/Charts/Classes/Data/Implementations/Standard/PieChartDataSet.swift | 7 | 1738 | //
// PieChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 24/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class PieChartDataSet: ChartDataSet, IPieChartDataSet
{
private func initialize()
{
self.valueTextColor = NSUIColor.whiteColor()
self.valueFont = NSUIFont.systemFontOfSize(13.0)
}
public required init()
{
super.init()
initialize()
}
public override init(yVals: [ChartDataEntry]?, label: String?)
{
super.init(yVals: yVals, label: label)
initialize()
}
// MARK: - Styling functions and accessors
private var _sliceSpace = CGFloat(0.0)
/// the space in pixels between the pie-slices
/// **default**: 0
/// **maximum**: 20
public var sliceSpace: CGFloat
{
get
{
return _sliceSpace
}
set
{
var space = newValue
if (space > 20.0)
{
space = 20.0
}
if (space < 0.0)
{
space = 0.0
}
_sliceSpace = space
}
}
/// indicates the selection distance of a pie slice
public var selectionShift = CGFloat(18.0)
// MARK: - NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! PieChartDataSet
copy._sliceSpace = _sliceSpace
copy.selectionShift = selectionShift
return copy
}
} | apache-2.0 | e8e85663c40cfe7373086088b46cad25 | 21.294872 | 66 | 0.558688 | 4.597884 | false | false | false | false |
tjw/swift | test/SILGen/errors.swift | 1 | 48717 | // RUN: %target-swift-frontend -parse-stdlib -enable-sil-ownership -emit-silgen -Xllvm -sil-print-debuginfo -verify -primary-file %s %S/Inputs/errors_other.swift | %FileCheck %s
// TODO: Turn back on ownership verification. I turned off the verification on
// this file since it shows an ownership error that does not affect
// codegen. Specifically when we destroy the temporary array we use for the
// variadic tuple, we try to borrow the temporary array when we pass it to the
// destroy function. This makes the ownership verifier think that the owned
// value we are trying to destroy is not cleaned up. But once ownership is
// stripped out, the destroy array function still does what it needs to do. The
// actual fix for this would require a bunch of surgery in SILGenApply around
// how function types are computed and preserving non-canonical function types
// through SILGenApply. This is something that can be done after +0 is turned
// on.
import Swift
class Cat {}
enum HomeworkError : Error {
case TooHard
case TooMuch
case CatAteIt(Cat)
}
func someValidPointer<T>() -> UnsafePointer<T> { fatalError() }
func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() }
// CHECK: sil hidden @$S6errors10make_a_cat{{.*}}F : $@convention(thin) () -> (@owned Cat, @error Error) {
// CHECK: [[T1:%.*]] = metatype $@thick Cat.Type
// CHECK: [[T0:%.*]] = function_ref @$S6errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat
// CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]])
// CHECK-NEXT: return [[T2]] : $Cat
func make_a_cat() throws -> Cat {
return Cat()
}
// CHECK: sil hidden @$S6errors15dont_make_a_cat{{.*}}F : $@convention(thin) () -> (@owned Cat, @error Error) {
// CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError
// CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error
// CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type
// CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooHard!enumelt
// CHECK-NEXT: store [[T1]] to [init] [[ADDR]]
// CHECK-NEXT: builtin "willThrow"
// CHECK-NEXT: throw [[BOX]]
func dont_make_a_cat() throws -> Cat {
throw HomeworkError.TooHard
}
// CHECK: sil hidden @$S6errors11dont_return{{.*}}F : $@convention(thin) <T> (@in_guaranteed T) -> (@out T, @error Error) {
// CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError
// CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error
// CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type
// CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooMuch!enumelt
// CHECK-NEXT: store [[T1]] to [init] [[ADDR]]
// CHECK-NEXT: builtin "willThrow"
// CHECK-NOT: destroy_addr %1 : $*T
// CHECK-NEXT: throw [[BOX]]
func dont_return<T>(_ argument: T) throws -> T {
throw HomeworkError.TooMuch
}
// CHECK: sil hidden @$S6errors16all_together_nowyAA3CatCSbF : $@convention(thin) (Bool) -> @owned Cat {
// CHECK: bb0(%0 : @trivial $Bool):
// CHECK: [[RET_TEMP:%.*]] = alloc_stack $Cat
// Branch on the flag.
// CHECK: cond_br {{%.*}}, [[FLAG_TRUE:bb[0-9]+]], [[FLAG_FALSE:bb[0-9]+]]
// In the true case, call make_a_cat().
// CHECK: [[FLAG_TRUE]]:
// CHECK: [[MAC_FN:%.*]] = function_ref @$S6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[MAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[MAC_NORMAL:bb[0-9]+]], error [[MAC_ERROR:bb[0-9]+]]
// CHECK: [[MAC_NORMAL]]([[T0:%.*]] : @owned $Cat):
// CHECK-NEXT: br [[TERNARY_CONT:bb[0-9]+]]([[T0]] : $Cat)
// In the false case, call dont_make_a_cat().
// CHECK: [[FLAG_FALSE]]:
// CHECK: [[DMAC_FN:%.*]] = function_ref @$S6errors15dont_make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[DMAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[DMAC_NORMAL:bb[0-9]+]], error [[DMAC_ERROR:bb[0-9]+]]
// CHECK: [[DMAC_NORMAL]]([[T0:%.*]] : @owned $Cat):
// CHECK-NEXT: br [[TERNARY_CONT]]([[T0]] : $Cat)
// Merge point for the ternary operator. Call dont_return with the result.
// CHECK: [[TERNARY_CONT]]([[T0:%.*]] : @owned $Cat):
// CHECK-NEXT: [[ARG_TEMP:%.*]] = alloc_stack $Cat
// CHECK-NEXT: store [[T0]] to [init] [[ARG_TEMP]]
// CHECK: [[DR_FN:%.*]] = function_ref @$S6errors11dont_return{{.*}} :
// CHECK-NEXT: try_apply [[DR_FN]]<Cat>([[RET_TEMP]], [[ARG_TEMP]]) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error), normal [[DR_NORMAL:bb[0-9]+]], error [[DR_ERROR:bb[0-9]+]]
// CHECK: [[DR_NORMAL]]({{%.*}} : @trivial $()):
// CHECK-NEXT: destroy_addr [[ARG_TEMP]]
// CHECK-NEXT: dealloc_stack [[ARG_TEMP]]
// CHECK-NEXT: [[T0:%.*]] = load [take] [[RET_TEMP]] : $*Cat
// CHECK-NEXT: dealloc_stack [[RET_TEMP]]
// CHECK-NEXT: br [[RETURN:bb[0-9]+]]([[T0]] : $Cat)
// Return block.
// CHECK: [[RETURN]]([[T0:%.*]] : @owned $Cat):
// CHECK-NEXT: return [[T0]] : $Cat
// Catch dispatch block.
// CHECK: [[CATCH:bb[0-9]+]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]]
// CHECK-NEXT: [[SRC_TEMP:%.*]] = alloc_stack $Error
// CHECK-NEXT: [[COPIED_BORROWED_ERROR:%.*]] = copy_value [[BORROWED_ERROR]]
// CHECK-NEXT: store [[COPIED_BORROWED_ERROR]] to [init] [[SRC_TEMP]]
// CHECK-NEXT: [[DEST_TEMP:%.*]] = alloc_stack $HomeworkError
// CHECK-NEXT: checked_cast_addr_br copy_on_success Error in [[SRC_TEMP]] : $*Error to HomeworkError in [[DEST_TEMP]] : $*HomeworkError, [[IS_HWE:bb[0-9]+]], [[NOT_HWE:bb[0-9]+]]
// Catch HomeworkError.
// CHECK: [[IS_HWE]]:
// CHECK-NEXT: [[T0_ORIG:%.*]] = load [take] [[DEST_TEMP]] : $*HomeworkError
// CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[T0_ORIG]]
// CHECK-NEXT: switch_enum [[T0_COPY]] : $HomeworkError, case #HomeworkError.CatAteIt!enumelt.1: [[MATCH:bb[0-9]+]], default [[NO_MATCH:bb[0-9]+]]
// Catch HomeworkError.CatAteIt.
// CHECK: [[MATCH]]([[T0:%.*]] : @owned $Cat):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[BORROWED_T0]]
// CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: destroy_value [[T0_ORIG]]
// CHECK-NEXT: dealloc_stack [[DEST_TEMP]]
// CHECK-NEXT: destroy_addr [[SRC_TEMP]]
// CHECK-NEXT: dealloc_stack [[SRC_TEMP]]
// CHECK-NEXT: end_borrow [[BORROWED_ERROR]] from [[ERROR]]
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: br [[RETURN]]([[T0_COPY]] : $Cat)
// Catch other HomeworkErrors.
// CHECK: [[NO_MATCH]]([[CATCHALL_ERROR:%.*]] : @owned $HomeworkError):
// CHECK-NEXT: destroy_value [[CATCHALL_ERROR]]
// CHECK-NEXT: destroy_value [[T0_ORIG]]
// CHECK-NEXT: dealloc_stack [[DEST_TEMP]]
// CHECK-NEXT: destroy_addr [[SRC_TEMP]]
// CHECK-NEXT: dealloc_stack [[SRC_TEMP]]
// CHECK-NEXT: br [[CATCHALL:bb[0-9]+]]
// Catch other types.
// CHECK: [[NOT_HWE]]:
// CHECK-NEXT: dealloc_stack [[DEST_TEMP]]
// CHECK-NEXT: destroy_addr [[SRC_TEMP]]
// CHECK-NEXT: dealloc_stack [[SRC_TEMP]]
// CHECK-NEXT: br [[CATCHALL:bb[0-9]+]]
// Catch all.
// CHECK: [[CATCHALL]]:
// CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type
// CHECK: [[T0:%.*]] = function_ref @$S6errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat
// CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]])
// CHECK-NEXT: end_borrow [[BORROWED_ERROR]] from [[ERROR]]
// CHECK-NEXT: destroy_value [[ERROR]] : $Error
// CHECK-NEXT: br [[RETURN]]([[T2]] : $Cat)
// Landing pad.
// CHECK: [[MAC_ERROR]]([[T0:%.*]] : @owned $Error):
// CHECK-NEXT: dealloc_stack [[RET_TEMP]]
// CHECK-NEXT: br [[CATCH]]([[T0]] : $Error)
// CHECK: [[DMAC_ERROR]]([[T0:%.*]] : @owned $Error):
// CHECK-NEXT: dealloc_stack [[RET_TEMP]]
// CHECK-NEXT: br [[CATCH]]([[T0]] : $Error)
// CHECK: [[DR_ERROR]]([[T0:%.*]] : @owned $Error):
// CHECK-NEXT: destroy_addr [[CAT:%.*]] :
// CHECK-NEXT: dealloc_stack [[CAT]]
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: br [[CATCH]]([[T0]] : $Error)
func all_together_now(_ flag: Bool) -> Cat {
do {
return try dont_return(flag ? make_a_cat() : dont_make_a_cat())
} catch HomeworkError.CatAteIt(let cat) {
return cat
} catch _ {
return Cat()
}
}
// Catch in non-throwing context.
// CHECK-LABEL: sil hidden @$S6errors11catch_a_catAA3CatCyF : $@convention(thin) () -> @owned Cat
// CHECK-NEXT: bb0:
// CHECK-NEXT: [[M:%.*]] = metatype $@thick Cat.Type
// CHECK: [[F:%.*]] = function_ref @$S6errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat
// CHECK-NEXT: [[V:%.*]] = apply [[F]]([[M]])
// CHECK-NEXT: return [[V]] : $Cat
func catch_a_cat() -> Cat {
do {
return Cat()
} catch _ as HomeworkError {} // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}}
}
// Initializers.
class HasThrowingInit {
var field: Int
init(value: Int) throws {
field = value
}
}
// CHECK-LABEL: sil hidden @$S6errors15HasThrowingInit{{.*}} : $@convention(method) (Int, @thick HasThrowingInit.Type) -> (@owned HasThrowingInit, @error Error)
// CHECK: [[SELF:%.*]] = alloc_ref $HasThrowingInit
// CHECK: [[T0:%.*]] = function_ref @$S6errors15HasThrowingInit{{.*}}c : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error)
// CHECK-NEXT: try_apply [[T0]](%0, [[SELF]]) : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error), normal bb1, error bb2
// CHECK: bb1([[SELF:%.*]] : @owned $HasThrowingInit):
// CHECK-NEXT: return [[SELF]]
// CHECK: bb2([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: builtin "willThrow"
// CHECK-NEXT: throw [[ERROR]]
// CHECK-LABEL: sil hidden @$S6errors15HasThrowingInit{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) {
// CHECK: [[T0:%.*]] = mark_uninitialized [rootself] %1 : $HasThrowingInit
// CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[BORROWED_T0]] : $HasThrowingInit
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[T1]] : $*Int
// CHECK-NEXT: assign %0 to [[WRITE]] : $*Int
// CHECK-NEXT: end_access [[WRITE]]
// CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK-NEXT: [[T0_RET:%.*]] = copy_value [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: return [[T0_RET]] : $HasThrowingInit
enum ColorError : Error {
case Red, Green, Blue
}
//CHECK-LABEL: sil hidden @$S6errors6IThrows5Int32VyKF
//CHECK: builtin "willThrow"
//CHECK-NEXT: throw
func IThrow() throws -> Int32 {
throw ColorError.Red
return 0 // expected-warning {{will never be executed}}
}
// Make sure that we are not emitting calls to 'willThrow' on rethrow sites.
//CHECK-LABEL: sil hidden @$S6errors12DoesNotThrows5Int32VyKF
//CHECK-NOT: builtin "willThrow"
//CHECK: return
func DoesNotThrow() throws -> Int32 {
_ = try IThrow()
return 2
}
// rdar://20782111
protocol Doomed {
func check() throws
}
// CHECK-LABEL: sil private [transparent] [thunk] @$S6errors12DoomedStructVAA0B0A2aDP5checkyyKFTW : $@convention(witness_method: Doomed) (@in_guaranteed DoomedStruct) -> @error Error
// CHECK: [[SELF:%.*]] = load [trivial] %0 : $*DoomedStruct
// CHECK: [[T0:%.*]] = function_ref @$S6errors12DoomedStructV5checkyyKF : $@convention(method) (DoomedStruct) -> @error Error
// CHECK-NEXT: try_apply [[T0]]([[SELF]])
// CHECK: bb1([[T0:%.*]] : @trivial $()):
// CHECK: [[T0:%.*]] = tuple ()
// CHECK: return [[T0]] : $()
// CHECK: bb2([[T0:%.*]] : @owned $Error):
// CHECK: builtin "willThrow"([[T0]] : $Error)
// CHECK: throw [[T0]] : $Error
struct DoomedStruct : Doomed {
func check() throws {}
}
// CHECK-LABEL: sil private [transparent] [thunk] @$S6errors11DoomedClassCAA0B0A2aDP5checkyyKFTW : $@convention(witness_method: Doomed) (@in_guaranteed DoomedClass) -> @error Error {
// CHECK: [[BORROWED_SELF:%.*]] = load_borrow %0
// CHECK: [[T0:%.*]] = class_method [[BORROWED_SELF]] : $DoomedClass, #DoomedClass.check!1 : (DoomedClass) -> () throws -> (), $@convention(method) (@guaranteed DoomedClass) -> @error Error
// CHECK-NEXT: try_apply [[T0]]([[BORROWED_SELF]])
// CHECK: bb1([[T0:%.*]] : @trivial $()):
// CHECK: [[T0:%.*]] = tuple ()
// CHECK: end_borrow [[BORROWED_SELF]] from %0
// CHECK: return [[T0]] : $()
// CHECK: bb2([[T0:%.*]] : @owned $Error):
// CHECK: builtin "willThrow"([[T0]] : $Error)
// CHECK: end_borrow [[BORROWED_SELF]] from %0
// CHECK: throw [[T0]] : $Error
class DoomedClass : Doomed {
func check() throws {}
}
// CHECK-LABEL: sil private [transparent] [thunk] @$S6errors11HappyStructVAA6DoomedA2aDP5checkyyKFTW : $@convention(witness_method: Doomed) (@in_guaranteed HappyStruct) -> @error Error
// CHECK: [[T0:%.*]] = function_ref @$S6errors11HappyStructV5checkyyF : $@convention(method) (HappyStruct) -> ()
// CHECK: [[T1:%.*]] = apply [[T0]](%1)
// CHECK: [[T1:%.*]] = tuple ()
// CHECK: return [[T1]] : $()
struct HappyStruct : Doomed {
func check() {}
}
// CHECK-LABEL: sil private [transparent] [thunk] @$S6errors10HappyClassCAA6DoomedA2aDP5checkyyKFTW : $@convention(witness_method: Doomed) (@in_guaranteed HappyClass) -> @error Error
// CHECK: [[SELF:%.*]] = load_borrow %0 : $*HappyClass
// CHECK: [[T0:%.*]] = class_method [[SELF]] : $HappyClass, #HappyClass.check!1 : (HappyClass) -> () -> (), $@convention(method) (@guaranteed HappyClass) -> ()
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: [[T1:%.*]] = tuple ()
// CHECK: end_borrow [[SELF]] from %0
// CHECK: return [[T1]] : $()
class HappyClass : Doomed {
func check() {}
}
func create<T>(_ fn: () throws -> T) throws -> T {
return try fn()
}
func testThunk(_ fn: () throws -> Int) throws -> Int {
return try create(fn)
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$SSis5Error_pIgdzo_SisAA_pIegrzo_TR : $@convention(thin) (@noescape @callee_guaranteed () -> (Int, @error Error)) -> (@out Int, @error Error)
// CHECK: bb0(%0 : @trivial $*Int, %1 : @trivial $@noescape @callee_guaranteed () -> (Int, @error Error)):
// CHECK: try_apply %1()
// CHECK: bb1([[T0:%.*]] : @trivial $Int):
// CHECK: store [[T0]] to [trivial] %0 : $*Int
// CHECK: [[T0:%.*]] = tuple ()
// CHECK: return [[T0]]
// CHECK: bb2([[T0:%.*]] : @owned $Error):
// CHECK: builtin "willThrow"([[T0]] : $Error)
// CHECK: throw [[T0]] : $Error
func createInt(_ fn: () -> Int) throws {}
func testForceTry(_ fn: () -> Int) {
try! createInt(fn)
}
// CHECK-LABEL: sil hidden @$S6errors12testForceTryyySiyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> Int) -> ()
// CHECK: bb0([[ARG:%.*]] : @trivial $@noescape @callee_guaranteed () -> Int):
// CHECK: [[FUNC:%.*]] = function_ref @$S6errors9createIntyySiyXEKF : $@convention(thin) (@noescape @callee_guaranteed () -> Int) -> @error Error
// CHECK: try_apply [[FUNC]]([[ARG]])
// CHECK: return
// CHECK: builtin "unexpectedError"
// CHECK: unreachable
func testForceTryMultiple() {
_ = try! (make_a_cat(), make_a_cat())
}
// CHECK-LABEL: sil hidden @$S6errors20testForceTryMultipleyyF
// CHECK-NEXT: bb0:
// CHECK: [[FN_1:%.+]] = function_ref @$S6errors10make_a_catAA3CatCyKF
// CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]],
// CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : @owned $Cat)
// CHECK: [[FN_2:%.+]] = function_ref @$S6errors10make_a_catAA3CatCyKF
// CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]],
// CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : @owned $Cat)
// CHECK-NEXT: destroy_value [[VALUE_2]] : $Cat
// CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.+]] : @owned $Error):
// CHECK-NEXT: = builtin "unexpectedError"([[ERROR]] : $Error)
// CHECK-NEXT: unreachable
// CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : @owned $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : @owned $Error):
// CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '$S6errors20testForceTryMultipleyyF'
// Make sure we balance scopes correctly inside a switch.
// <rdar://problem/20923654>
enum CatFood {
case Canned
case Dry
}
// Something we can switch on that throws.
func preferredFood() throws -> CatFood {
return CatFood.Canned
}
func feedCat() throws -> Int {
switch try preferredFood() {
case .Canned:
return 0
case .Dry:
return 1
}
}
// CHECK-LABEL: sil hidden @$S6errors7feedCatSiyKF : $@convention(thin) () -> (Int, @error Error)
// CHECK: debug_value undef : $Error, var, name "$error", argno 1
// CHECK: %1 = function_ref @$S6errors13preferredFoodAA03CatC0OyKF : $@convention(thin) () -> (CatFood, @error Error)
// CHECK: try_apply %1() : $@convention(thin) () -> (CatFood, @error Error), normal bb1, error bb5
// CHECK: bb1([[VAL:%.*]] : @trivial $CatFood):
// CHECK: switch_enum [[VAL]] : $CatFood, case #CatFood.Canned!enumelt: bb2, case #CatFood.Dry!enumelt: bb3
// CHECK: bb5([[ERROR:%.*]] : @owned $Error)
// CHECK: throw [[ERROR]] : $Error
// Throwing statements inside cases.
func getHungryCat(_ food: CatFood) throws -> Cat {
switch food {
case .Canned:
return try make_a_cat()
case .Dry:
return try dont_make_a_cat()
}
}
// errors.getHungryCat throws (errors.CatFood) -> errors.Cat
// CHECK-LABEL: sil hidden @$S6errors12getHungryCatyAA0D0CAA0D4FoodOKF : $@convention(thin) (CatFood) -> (@owned Cat, @error Error)
// CHECK: bb0(%0 : @trivial $CatFood):
// CHECK: debug_value undef : $Error, var, name "$error", argno 2
// CHECK: switch_enum %0 : $CatFood, case #CatFood.Canned!enumelt: bb1, case #CatFood.Dry!enumelt: bb3
// CHECK: bb1:
// CHECK: [[FN:%.*]] = function_ref @$S6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb2, error bb6
// CHECK: bb3:
// CHECK: [[FN:%.*]] = function_ref @$S6errors15dont_make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb4, error bb7
// CHECK: bb6([[ERROR:%.*]] : @owned $Error):
// CHECK: br bb8([[ERROR:%.*]] : $Error)
// CHECK: bb7([[ERROR:%.*]] : @owned $Error):
// CHECK: br bb8([[ERROR]] : $Error)
// CHECK: bb8([[ERROR:%.*]] : @owned $Error):
// CHECK: throw [[ERROR]] : $Error
func take_many_cats(_ cats: Cat...) throws {}
func test_variadic(_ cat: Cat) throws {
try take_many_cats(make_a_cat(), cat, make_a_cat(), make_a_cat())
}
// CHECK-LABEL: sil hidden @$S6errors13test_variadicyyAA3CatCKF : $@convention(thin) (@guaranteed Cat) -> @error Error {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Cat):
// CHECK: debug_value undef : $Error, var, name "$error", argno 2
// CHECK: [[N:%.*]] = integer_literal $Builtin.Word, 4
// CHECK: [[T0:%.*]] = function_ref @$Ss27_allocateUninitializedArray{{.*}}F
// CHECK: [[T1:%.*]] = apply [[T0]]<Cat>([[N]])
// CHECK: [[BORROWED_T1:%.*]] = begin_borrow [[T1]]
// CHECK: [[BORROWED_ARRAY:%.*]] = tuple_extract [[BORROWED_T1]] : $(Array<Cat>, Builtin.RawPointer), 0
// CHECK: [[ARRAY:%.*]] = copy_value [[BORROWED_ARRAY]]
// CHECK: [[T2:%.*]] = tuple_extract [[BORROWED_T1]] : $(Array<Cat>, Builtin.RawPointer), 1
// CHECK: end_borrow [[BORROWED_T1]] from [[T1]]
// CHECK: destroy_value [[T1]]
// CHECK: [[ELT0:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Cat
// Element 0.
// CHECK: [[T0:%.*]] = function_ref @$S6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_0:bb[0-9]+]], error [[ERR_0:bb[0-9]+]]
// CHECK: [[NORM_0]]([[CAT0:%.*]] : @owned $Cat):
// CHECK-NEXT: store [[CAT0]] to [init] [[ELT0]]
// Element 1.
// CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 1
// CHECK-NEXT: [[ELT1:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]]
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: store [[ARG_COPY]] to [init] [[ELT1]]
// Element 2.
// CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 2
// CHECK-NEXT: [[ELT2:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$S6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_2:bb[0-9]+]], error [[ERR_2:bb[0-9]+]]
// CHECK: [[NORM_2]]([[CAT2:%.*]] : @owned $Cat):
// CHECK-NEXT: store [[CAT2]] to [init] [[ELT2]]
// Element 3.
// CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 3
// CHECK-NEXT: [[ELT3:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$S6errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_3:bb[0-9]+]], error [[ERR_3:bb[0-9]+]]
// CHECK: [[NORM_3]]([[CAT3:%.*]] : @owned $Cat):
// CHECK-NEXT: store [[CAT3]] to [init] [[ELT3]]
// Complete the call and return.
// CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]]
// CHECK: [[TAKE_FN:%.*]] = function_ref @$S6errors14take_many_catsyyAA3CatCd_tKF : $@convention(thin) (@guaranteed Array<Cat>) -> @error Error
// CHECK-NEXT: try_apply [[TAKE_FN]]([[BORROWED_ARRAY]]) : $@convention(thin) (@guaranteed Array<Cat>) -> @error Error, normal [[NORM_CALL:bb[0-9]+]], error [[ERR_CALL:bb[0-9]+]]
// CHECK: [[NORM_CALL]]([[T0:%.*]] : @trivial $()):
// CHECK-NEXT: end_borrow [[BORROWED_ARRAY]] from [[ARRAY]]
// CHECK-NEXT: destroy_value [[ARRAY]]
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return
// Failure from element 0.
// CHECK: [[ERR_0]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NOT: end_borrow
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$Ss29_deallocateUninitializedArray{{.*}}F
// CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]])
// CHECK-NEXT: br [[RETHROW:.*]]([[ERROR]] : $Error)
// Failure from element 2.
// CHECK: [[ERR_2]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: destroy_addr [[ELT1]]
// CHECK-NEXT: destroy_addr [[ELT0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$Ss29_deallocateUninitializedArray{{.*}}F
// CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]])
// CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error)
// Failure from element 3.
// CHECK: [[ERR_3]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: destroy_addr [[ELT2]]
// CHECK-NEXT: destroy_addr [[ELT1]]
// CHECK-NEXT: destroy_addr [[ELT0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @$Ss29_deallocateUninitializedArray{{.*}}F
// CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]])
// CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error)
// Failure from call.
// CHECK: [[ERR_CALL]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: end_borrow
// CHECK-NEXT: destroy_value [[ARRAY]]
// CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error)
// Rethrow.
// CHECK: [[RETHROW]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '$S6errors13test_variadicyyAA3CatCKF'
// rdar://20861374
// Clear out the self box before delegating.
class BaseThrowingInit : HasThrowingInit {
var subField: Int
init(value: Int, subField: Int) throws {
self.subField = subField
try super.init(value: value)
}
}
// CHECK: sil hidden @$S6errors16BaseThrowingInit{{.*}}c : $@convention(method) (Int, Int, @owned BaseThrowingInit) -> (@owned BaseThrowingInit, @error Error)
// CHECK: [[BOX:%.*]] = alloc_box ${ var BaseThrowingInit }
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[BOX]]
// CHECK: [[PB:%.*]] = project_box [[MARKED_BOX]]
// Initialize subField.
// CHECK: [[T0:%.*]] = load_borrow [[PB]]
// CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $BaseThrowingInit, #BaseThrowingInit.subField
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[T1]] : $*Int
// CHECK-NEXT: assign %1 to [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]]
// CHECK-NEXT: end_borrow [[T0]] from [[PB]]
// Super delegation.
// CHECK-NEXT: [[T0:%.*]] = load [take] [[PB]]
// CHECK-NEXT: [[T2:%.*]] = upcast [[T0]] : $BaseThrowingInit to $HasThrowingInit
// CHECK: [[T3:%[0-9]+]] = function_ref @$S6errors15HasThrowingInitC5valueACSi_tKcfc : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error)
// CHECK-NEXT: apply [[T3]](%0, [[T2]])
// Cleanups for writebacks.
protocol Supportable {
mutating func support() throws
}
protocol Buildable {
associatedtype Structure : Supportable
var firstStructure: Structure { get set }
subscript(name: String) -> Structure { get set }
}
func supportFirstStructure<B: Buildable>(_ b: inout B) throws {
try b.firstStructure.support()
}
// CHECK-LABEL: sil hidden @$S6errors21supportFirstStructure{{.*}}F : $@convention(thin) <B where B : Buildable> (@inout B) -> @error Error {
// CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure
// CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer
// CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.firstStructure!materializeForSet.1 :
// CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[BASE:%[0-9]*]])
// CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0
// CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure
// CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B
// CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 :
// CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error):
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: throw [[ERROR]]
// CHECK: } // end sil function '$S6errors21supportFirstStructure{{.*}}F'
func supportStructure<B: Buildable>(_ b: inout B, name: String) throws {
try b[name].support()
}
// CHECK-LABEL: sil hidden @$S6errors16supportStructure_4nameyxz_SStKAA9BuildableRzlF : $@convention(thin) <B where B : Buildable> (@inout B, @guaranteed String) -> @error Error {
// CHECK: bb0({{.*}}, [[INDEX:%.*]] : @guaranteed $String):
// CHECK: [[INDEX_COPY:%.*]] = copy_value [[INDEX]] : $String
// CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure
// CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer
// CHECK: [[BORROWED_INDEX_COPY:%.*]] = begin_borrow [[INDEX_COPY]]
// CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.subscript!materializeForSet.1 :
// CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[BORROWED_INDEX_COPY]], [[BASE:%[0-9]*]])
// CHECK: end_borrow [[BORROWED_INDEX_COPY]] from [[INDEX_COPY]]
// CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0
// CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure
// CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B
// CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 :
// CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : $@convention(witness_method: Supportable) <τ_0_0 where τ_0_0 : Supportable> (@inout τ_0_0) -> @error Error, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK: switch_enum [[CALLBACK]] : ${{.*}}, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
//
// CHECK: [[SOME_BB]](
// CHECK: apply
//
// CHECK: [[NONE_BB]]:
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: destroy_value [[INDEX_COPY]] : $String
// CHECK: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error):
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: destroy_value [[INDEX_COPY]] : $String
// CHECK: throw [[ERROR]]
// CHECK: } // end sil function '$S6errors16supportStructure{{.*}}F'
struct Pylon {
var name: String
mutating func support() throws {}
}
struct Bridge {
var mainPylon : Pylon
subscript(name: String) -> Pylon {
get {
return mainPylon
}
set {}
}
}
func supportStructure(_ b: inout Bridge, name: String) throws {
try b[name].support()
}
// CHECK: sil hidden @$S6errors16supportStructure_4nameyAA6BridgeVz_SStKF : $@convention(thin) (@inout Bridge, @guaranteed String) -> @error Error {
// CHECK: bb0([[ARG1:%.*]] : @trivial $*Bridge, [[ARG2:%.*]] : @guaranteed $String):
// CHECK: [[INDEX_COPY_1:%.*]] = copy_value [[ARG2]] : $String
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[ARG1]] : $*Bridge
// CHECK-NEXT: [[INDEX_COPY_2:%.*]] = copy_value [[INDEX_COPY_1]] : $String
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Pylon
// CHECK-NEXT: [[BASE:%.*]] = load_borrow [[WRITE]] : $*Bridge
// CHECK-NEXT: [[BORROWED_INDEX_COPY_1:%.*]] = begin_borrow [[INDEX_COPY_1]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[GETTER:%.*]] = function_ref @$S6errors6BridgeVyAA5PylonVSScig :
// CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]([[BORROWED_INDEX_COPY_1]], [[BASE]])
// CHECK-NEXT: end_borrow [[BORROWED_INDEX_COPY_1]]
// CHECK-NEXT: store [[T0]] to [init] [[TEMP]]
// CHECK-NEXT: end_borrow [[BASE]] from [[WRITE]]
// CHECK: [[SUPPORT:%.*]] = function_ref @$S6errors5PylonV7supportyyKF
// CHECK-NEXT: try_apply [[SUPPORT]]([[TEMP]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK-NEXT: [[T0:%.*]] = load [take] [[TEMP]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[SETTER:%.*]] = function_ref @$S6errors6BridgeVyAA5PylonVSScis :
// CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2]], [[WRITE]])
// CHECK-NEXT: end_access [[WRITE]]
// CHECK-NEXT: dealloc_stack [[TEMP]]
// CHECK-NEXT: destroy_value [[INDEX_COPY_1]] : $String
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// We end up with ugly redundancy here because we don't want to
// consume things during cleanup emission. It's questionable.
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: [[T0:%.*]] = load [copy] [[TEMP]]
// CHECK-NEXT: [[INDEX_COPY_2_COPY:%.*]] = copy_value [[INDEX_COPY_2]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[SETTER:%.*]] = function_ref @$S6errors6BridgeVyAA5PylonVSScis :
// CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2_COPY]], [[WRITE]])
// CHECK-NEXT: destroy_addr [[TEMP]]
// CHECK-NEXT: dealloc_stack [[TEMP]]
// ==> SEMANTIC ARC TODO: INDEX_COPY_2 on the next line should be INDEX_COPY_2_COPY
// CHECK-NEXT: destroy_value [[INDEX_COPY_2]] : $String
// CHECK-NEXT: end_access [[WRITE]]
// CHECK-NEXT: destroy_value [[INDEX_COPY_1]] : $String
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '$S6errors16supportStructure_4nameyAA6BridgeVz_SStKF'
struct OwnedBridge {
var owner : AnyObject
subscript(name: String) -> Pylon {
addressWithOwner { return (someValidPointer(), owner) }
mutableAddressWithOwner { return (someValidPointer(), owner) }
}
}
func supportStructure(_ b: inout OwnedBridge, name: String) throws {
try b[name].support()
}
// CHECK: sil hidden @$S6errors16supportStructure_4nameyAA11OwnedBridgeVz_SStKF :
// CHECK: bb0([[ARG1:%.*]] : @trivial $*OwnedBridge, [[ARG2:%.*]] : @guaranteed $String):
// CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $String
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*OwnedBridge
// CHECK: [[BORROWED_ARG2_COPY:%.*]] = begin_borrow [[ARG2_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @$S6errors11OwnedBridgeVyAA5PylonVSSciaO :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[BORROWED_ARG2_COPY]], [[WRITE]])
// CHECK-NEXT: end_borrow [[BORROWED_ARG2_COPY]]
// CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0
// CHECK-NEXT: [[BORROWED_OWNER:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 1
// CHECK-NEXT: [[OWNER:%.*]] = copy_value [[BORROWED_OWNER]]
// CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]]
// CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
// CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]]
// CHECK: [[SUPPORT:%.*]] = function_ref @$S6errors5PylonV7supportyyKF
// CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK-NEXT: end_access [[WRITE]]
// CHECK-NEXT: destroy_value [[OWNER]] : $AnyObject
// CHECK-NEXT: destroy_value [[ARG2_COPY]] : $String
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: destroy_value [[OWNER]] : $AnyObject
// CHECK-NEXT: end_access [[WRITE]]
// CHECK-NEXT: destroy_value [[ARG2_COPY]] : $String
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '$S6errors16supportStructure_4nameyAA11OwnedBridgeVz_SStKF'
struct PinnedBridge {
var owner : Builtin.NativeObject
subscript(name: String) -> Pylon {
addressWithPinnedNativeOwner { return (someValidPointer(), owner) }
mutableAddressWithPinnedNativeOwner { return (someValidPointer(), owner) }
}
}
func supportStructure(_ b: inout PinnedBridge, name: String) throws {
try b[name].support()
}
// CHECK: sil hidden @$S6errors16supportStructure_4nameyAA12PinnedBridgeVz_SStKF :
// CHECK: bb0([[ARG1:%.*]] : @trivial $*PinnedBridge, [[ARG2:%.*]] : @guaranteed $String):
// CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $String
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[ARG1]] : $*PinnedBridge
// CHECK-NEXT: [[BORROWED_ARG2_COPY:%.*]] = begin_borrow [[ARG2_COPY]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @$S6errors12PinnedBridgeVyAA5PylonVSSciaP :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[BORROWED_ARG2_COPY]], [[WRITE]])
// CHECK-NEXT: end_borrow [[BORROWED_ARG2_COPY]]
// CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0
// CHECK-NEXT: [[BORROWED_OWNER:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 1
// CHECK-NEXT: [[OWNER:%.*]] = copy_value [[BORROWED_OWNER]]
// CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]]
// CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
// CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]]
// CHECK: [[SUPPORT:%.*]] = function_ref @$S6errors5PylonV7supportyyKF
// CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK-NEXT: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: end_access [[WRITE]]
// CHECK-NEXT: destroy_value [[ARG2_COPY]] : $String
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: [[OWNER_COPY:%.*]] = copy_value [[OWNER]]
// CHECK-NEXT: strong_unpin [[OWNER_COPY]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: destroy_value [[OWNER]]
// CHECK-NEXT: end_access [[WRITE]]
// CHECK-NEXT: destroy_value [[ARG2_COPY]] : $String
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '$S6errors16supportStructure_4nameyAA12PinnedBridgeVz_SStKF'
// ! peepholes its argument with getSemanticsProvidingExpr().
// Test that that doesn't look through try!.
// rdar://21515402
func testForcePeephole(_ f: () throws -> Int?) -> Int {
let x = (try! f())!
return x
}
// CHECK-LABEL: sil hidden @$S6errors15testOptionalTryyyF
// CHECK-NEXT: bb0:
// CHECK: [[FN:%.+]] = function_ref @$S6errors10make_a_catAA3CatCyKF
// CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]([[VALUE:%.+]] : @owned $Cat)
// CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<Cat>, #Optional.some!enumelt.1, [[VALUE]]
// CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<Cat>)
// CHECK: [[DONE]]([[RESULT:%.+]] : @owned $Optional<Cat>):
// CHECK-NEXT: destroy_value [[RESULT]] : $Optional<Cat>
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: [[NONE:%.+]] = enum $Optional<Cat>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<Cat>)
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : @owned $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '$S6errors15testOptionalTryyyF'
func testOptionalTry() {
_ = try? make_a_cat()
}
func sudo_make_a_cat() {}
// CHECK-LABEL: sil hidden @{{.*}}testOptionalTryThatNeverThrows
func testOptionalTryThatNeverThrows() {
guard let _ = try? sudo_make_a_cat() else { // expected-warning{{no calls to throwing}}
return
}
}
// CHECK-LABEL: sil hidden @$S6errors18testOptionalTryVaryyF
// CHECK-NEXT: bb0:
// CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<Cat> }
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1
// CHECK: [[FN:%.+]] = function_ref @$S6errors10make_a_catAA3CatCyKF
// CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]([[VALUE:%.+]] : @owned $Cat)
// CHECK-NEXT: store [[VALUE]] to [init] [[BOX_DATA]] : $*Cat
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1
// CHECK-NEXT: br [[DONE:[^ ]+]],
// CHECK: [[DONE]]:
// CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<Cat> }
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : @owned $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '$S6errors18testOptionalTryVaryyF'
func testOptionalTryVar() {
var cat = try? make_a_cat() // expected-warning {{initialization of variable 'cat' was never used; consider replacing with assignment to '_' or removing it}}
}
// CHECK-LABEL: sil hidden @$S6errors26testOptionalTryAddressOnly{{.*}}F
// CHECK: bb0(%0 : @trivial $*T):
// CHECK: [[BOX:%.+]] = alloc_stack $Optional<T>
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK: [[FN:%.+]] = function_ref @$S6errors11dont_return{{.*}}F
// CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], %0) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]({{%.+}} : @trivial $()):
// CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: br [[DONE:[^ ]+]],
// CHECK: [[DONE]]:
// CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T>
// CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T>
// CHECK-NOT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : @owned $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '$S6errors26testOptionalTryAddressOnlyyyxlF'
func testOptionalTryAddressOnly<T>(_ obj: T) {
_ = try? dont_return(obj)
}
// CHECK-LABEL: sil hidden @$S6errors29testOptionalTryAddressOnlyVar{{.*}}F
// CHECK: bb0(%0 : @trivial $*T):
// CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK: [[FN:%.+]] = function_ref @$S6errors11dont_return{{.*}}F
// CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], %0) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]({{%.+}} : @trivial $()):
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: br [[DONE:[^ ]+]],
// CHECK: [[DONE]]:
// CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK-NOT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : @owned $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '$S6errors29testOptionalTryAddressOnlyVaryyxlF'
func testOptionalTryAddressOnlyVar<T>(_ obj: T) {
var copy = try? dont_return(obj) // expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}}
}
// CHECK-LABEL: sil hidden @$S6errors23testOptionalTryMultipleyyF
// CHECK: bb0:
// CHECK: [[FN_1:%.+]] = function_ref @$S6errors10make_a_catAA3CatCyKF
// CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]],
// CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : @owned $Cat)
// CHECK: [[FN_2:%.+]] = function_ref @$S6errors10make_a_catAA3CatCyKF
// CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]],
// CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : @owned $Cat)
// CHECK-NEXT: [[TUPLE:%.+]] = tuple ([[VALUE_1]] : $Cat, [[VALUE_2]] : $Cat)
// CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.some!enumelt.1, [[TUPLE]]
// CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<(Cat, Cat)>)
// CHECK: [[DONE]]([[RESULT:%.+]] : @owned $Optional<(Cat, Cat)>):
// CHECK-NEXT: destroy_value [[RESULT]] : $Optional<(Cat, Cat)>
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : @owned $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: [[NONE:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<(Cat, Cat)>)
// CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : @owned $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : @owned $Error):
// CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '$S6errors23testOptionalTryMultipleyyF'
func testOptionalTryMultiple() {
_ = try? (make_a_cat(), make_a_cat())
}
// CHECK-LABEL: sil hidden @$S6errors25testOptionalTryNeverFailsyyF
// CHECK: bb0:
// CHECK-NEXT: [[VALUE:%.+]] = tuple ()
// CHECK-NEXT: = enum $Optional<()>, #Optional.some!enumelt.1, [[VALUE]]
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: } // end sil function '$S6errors25testOptionalTryNeverFailsyyF'
func testOptionalTryNeverFails() {
_ = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}}
}
// CHECK-LABEL: sil hidden @$S6errors28testOptionalTryNeverFailsVaryyF
// CHECK: bb0:
// CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<()> }
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: = init_enum_data_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1
// CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<()> }
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK-NEXT: } // end sil function '$S6errors28testOptionalTryNeverFailsVaryyF'
func testOptionalTryNeverFailsVar() {
var unit: ()? = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{variable 'unit' was never used; consider replacing with '_' or removing it}}
}
// CHECK-LABEL: sil hidden @$S6errors36testOptionalTryNeverFailsAddressOnly{{.*}}F
// CHECK: bb0(%0 : @trivial $*T):
// CHECK: [[BOX:%.+]] = alloc_stack $Optional<T>
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T
// CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T>
// CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T>
// CHECK-NOT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK-NEXT: } // end sil function '$S6errors36testOptionalTryNeverFailsAddressOnlyyyxlF'
func testOptionalTryNeverFailsAddressOnly<T>(_ obj: T) {
_ = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}}
}
// CHECK-LABEL: sil hidden @$S6errors39testOptionalTryNeverFailsAddressOnlyVar{{.*}}F
// CHECK: bb0(%0 : @trivial $*T):
// CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: } // end sil function '$S6errors13OtherErrorSubCACycfC'
func testOptionalTryNeverFailsAddressOnlyVar<T>(_ obj: T) {
var copy = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}}
}
class SomeErrorClass : Error { }
// CHECK-LABEL: sil_vtable SomeErrorClass
// CHECK-NEXT: #SomeErrorClass.init!initializer.1: {{.*}} : @$S6errors14SomeErrorClassCACycfc
// CHECK-NEXT: #SomeErrorClass.deinit!deallocator: @$S6errors14SomeErrorClassCfD
// CHECK-NEXT: }
class OtherErrorSub : OtherError { }
// CHECK-LABEL: sil_vtable OtherErrorSub {
// CHECK-NEXT: #OtherError.init!initializer.1: {{.*}} : @$S6errors13OtherErrorSubCACycfc [override] // OtherErrorSub.init()
// CHECK-NEXT: #OtherErrorSub.deinit!deallocator: @$S6errors13OtherErrorSubCfD // OtherErrorSub.__deallocating_deinit
// CHECK-NEXT:}
| apache-2.0 | 856580b56434ec9290a6c5affa02ad5e | 49.306818 | 234 | 0.610654 | 3.200381 | false | false | false | false |
antonio081014/Stanford-CS193p | Developing iOS 8 Apps with Swift/Happiness/Happiness/FaceView.swift | 1 | 3796 | //
// FaceView.swift
// Happiness
//
// Created by Antonio081014 on 6/3/15.
// Copyright (c) 2015 Antonio081014.com. All rights reserved.
//
import UIKit
protocol FaceViewDataSource: class {
func smilinessForFaceView(sender: FaceView) -> Double?
}
@IBDesignable
class FaceView: UIView {
weak var dataSource: FaceViewDataSource?
func scale(gesture: UIPinchGestureRecognizer) {
if gesture.state == .Changed {
scale *= gesture.scale
gesture.scale = 1
}
}
@IBInspectable
var lineWidth: CGFloat = 3 {
didSet { setNeedsDisplay() }
}
@IBInspectable
var color: UIColor = UIColor.blueColor() {
didSet { setNeedsDisplay() }
}
@IBInspectable
var scale: CGFloat = 0.90 {
didSet { setNeedsDisplay() }
}
var faceCenter: CGPoint {
get { return convertPoint(center, fromView: superview) }
}
var faceRadius: CGFloat {
get { return min(bounds.size.width, bounds.size.height) / 2 * scale }
}
private struct Scaling {
static let FaceRadiusToEyeRadiusRatio: CGFloat = 10
static let FaceRadiusToEyeOffsetRatio: CGFloat = 3
static let FaceRadiusToEyeSeparationRatio: CGFloat = 1.5
static let FaceRadiusToMouthWidthRatio: CGFloat = 1
static let FaceRadiusToMouthHeightRatio: CGFloat = 3
static let FaceRadiusToMouthOffsetRatio: CGFloat = 3
}
private enum Eye {
case Left
case Right
}
private func bezierPathForEye(whichEye: Eye) ->UIBezierPath {
let eyeRadius = faceRadius / Scaling.FaceRadiusToEyeRadiusRatio
let eyeVerticleOffset = faceRadius / Scaling.FaceRadiusToEyeRadiusRatio
let eyeHorizontalSeparation = faceRadius / Scaling.FaceRadiusToEyeSeparationRatio
var eyeCenter = faceCenter
eyeCenter.y -= eyeVerticleOffset
switch whichEye {
case .Left: eyeCenter.x -= eyeHorizontalSeparation / 2
case .Right: eyeCenter.x += eyeHorizontalSeparation / 2
}
let path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: CGFloat(0), endAngle: CGFloat(2 * M_PI), clockwise: true)
path.lineWidth = lineWidth
return path
}
private func bezierPathForSmile(fractionOfMaxSmail: Double) ->UIBezierPath {
let mouthWidth = faceRadius / Scaling.FaceRadiusToMouthWidthRatio
let mouthHeight = faceRadius / Scaling.FaceRadiusToMouthHeightRatio
let mouthVerticleOffset = faceRadius / Scaling.FaceRadiusToMouthOffsetRatio
let smileHeight = CGFloat(max(min(fractionOfMaxSmail, 1), -1)) * mouthHeight
let start = CGPoint(x: faceCenter.x - mouthWidth / 2, y: faceCenter.y + mouthVerticleOffset)
let end = CGPoint(x: faceCenter.x + mouthWidth / 2, y: faceCenter.y + mouthVerticleOffset)
let cp1 = CGPoint(x: start.x + mouthWidth / 3, y: start.y + smileHeight)
let cp2 = CGPoint(x: end.x - mouthWidth / 3, y: cp1.y)
let path = UIBezierPath()
path.moveToPoint(start)
path.addCurveToPoint(end, controlPoint1: cp1, controlPoint2: cp2)
path.lineWidth = lineWidth
return path
}
override func drawRect(rect: CGRect)
{
let facePath = UIBezierPath(arcCenter: faceCenter, radius: faceRadius, startAngle: CGFloat(0), endAngle: CGFloat(2 * M_PI), clockwise: true)
facePath.lineWidth = lineWidth
color.set()
facePath.stroke()
bezierPathForEye(Eye.Left).stroke()
bezierPathForEye(Eye.Right).stroke()
let smiliness = dataSource?.smilinessForFaceView(self) ?? 0.0
bezierPathForSmile(smiliness).stroke()
}
}
| mit | 926774bf630c6f7f088b3966565d3138 | 32.892857 | 148 | 0.648841 | 4.829517 | false | false | false | false |
roambotics/swift | validation-test/compiler_crashers_2_fixed/0087-issue-46601.swift | 2 | 1808 | // RUN: %target-swift-frontend -emit-ir %s
// https://github.com/apple/swift/issues/46601
public enum Event<Element, Error: Swift.Error> {
case next(Element)
case failed(Error)
case completed
}
public typealias Observer<Element, Error: Swift.Error> = (Event<Element, Error>) -> Void
public protocol Disposable {
func dispose()
var isDisposed: Bool { get }
}
public protocol SignalProtocol {
/// The type of elements generated by the signal.
associatedtype Element
/// The type of error that can terminate the signal.
associatedtype Error: Swift.Error
/// Register an observer that will receive events from a signal.
/// This actually triggers event production. Use the returned disposable
/// to unsubscribe and cancel event production.
func observe(with observer: @escaping Observer<Element, Error>) -> Disposable
}
public protocol ObserverProtocol {
/// Type of elements being received.
associatedtype Element
/// Type of error that can be received.
associatedtype Error: Swift.Error
/// Send the event to the observer.
func on(_ event: Event<Element, Error>)
}
/// A type that is both a signal and an observer.
public protocol SubjectProtocol: SignalProtocol, ObserverProtocol {
}
public final class AnySubject<Element, Error: Swift.Error>: SubjectProtocol {
private let baseObserve: (@escaping Observer<Element, Error>) -> Disposable
private let baseOn: Observer<Element, Error>
public init<S: SubjectProtocol>(base: S) where S.Element == Element, S.Error == Error {
baseObserve = base.observe
baseOn = base.on
}
public func on(_ event: Event<Element, Error>) {
return baseOn(event)
}
public func observe(with observer: @escaping Observer<Element, Error>) -> Disposable {
return baseObserve(observer)
}
}
| apache-2.0 | 457baebda8d904051faaaff51f629c4d | 24.828571 | 89 | 0.721792 | 4.244131 | false | false | false | false |
dche/GLMath | Sources/IntExt.swift | 1 | 1438 | //
// GLMath - IntExt.swift
//
// Copyright (c) 2016 The GLMath authors.
// Licensed under MIT License.
extension BaseInt {
public var isPow2: Bool {
return !isZero && !(self & (self - 1)).isZero
}
public var leadingZeros: UInt {
var v = unsafeBitCast(self, to: UInt32.self)
guard !v.isZero else { return 32 }
var c: UInt = 0
if (v & 0xFFFF0000 == 0) { c += 16; v <<= 16 }
if (v & 0xFF000000 == 0) { c += 8; v <<= 8 }
if (v & 0xF0000000 == 0) { c += 4; v <<= 4 }
if (v & 0xC0000000 == 0) { c += 2; v <<= 2 }
if (v & 0x80000000 == 0) { c += 1 }
return c
}
public var trailingZeros: UInt {
var v = unsafeBitCast(self, to: UInt32.self)
guard !v.isZero else { return 32 }
var c: UInt = 0
if (v & 0x0000FFFF == 0) { c += 16; v >>= 16 }
if (v & 0x000000FF == 0) { c += 8; v >>= 8 }
if (v & 0x0000000F == 0) { c += 4; v >>= 4 }
if (v & 0x00000003 == 0) { c += 2; v >>= 2 }
if (v & 0x00000001 == 0) { c += 1 }
return c
}
public var bitCount: UInt {
let v = unsafeBitCast(self, to: UInt32.self)
var c: UInt32 = v - ((v >> 1) & 0x55555555)
c = ((c >> 2) & 0x33333333) + (c & 0x33333333)
c = ((c >> 4) + c) & 0x0F0F0F0F
c = ((c >> 8) + c) & 0x00FF00FF
c = ((c >> 16) + c) & 0x0000FFFF
return UInt(c)
}
}
| mit | 5e0122838528ffe7baf9bfaad437a956 | 30.26087 | 54 | 0.461752 | 3.008368 | false | false | false | false |
iOSDevLog/iOSDevLog | 230. Localizations/230. Localizations/Bundle+localizable.swift | 1 | 766 | //
// Bundle+localizable.swift
// 230. Localizations
//
// Created by iOS Dev Log on 2017/12/20.
// Copyright © 2017年 iOSDevLog. All rights reserved.
//
import Foundation
extension Bundle {
class func loadLocalizableString(languageBundleName: String, key: String) -> String? {
let languageBundlePath = Bundle.main.path(forResource: languageBundleName, ofType: "lproj")
guard languageBundlePath != nil else {
return nil
}
let languageBundle = Bundle.init(path: languageBundlePath!)
guard languageBundle != nil else {
return nil
}
let value = languageBundle?.localizedString(forKey: key, value: "", table: "")
return value
}
}
| mit | a42cf405e9a9c6d4cad53fe480cef26f | 26.25 | 99 | 0.6173 | 4.596386 | false | false | false | false |
payjp/payjp-ios | Sources/Views/CardFormView.swift | 1 | 21915 | //
// CardFormView.swift
// PAYJP
//
// Created by Tadashi Wakayanagi on 2019/10/10.
// Copyright © 2019 PAY, Inc. All rights reserved.
//
import UIKit
/// CardForm style protocol.
public protocol CardFormStylable {
/// Apply card form style.
///
/// - Parameter style: card form style
func apply(style: FormStyle)
/// Set whether to enable card holder form.
///
/// - Parameter required: card holder required
func setCardHolderRequired(_ required: Bool)
}
protocol CardFormProperties {
var brandLogoImage: UIImageView! { get }
var cvcIconImage: UIImageView! { get }
var ocrButton: UIButton! { get }
var cardNumberTextField: FormTextField! { get }
var expirationTextField: FormTextField! { get }
var cvcTextField: FormTextField! { get }
var cardHolderTextField: FormTextField! { get }
var cardNumberErrorLabel: UILabel! { get }
var expirationErrorLabel: UILabel! { get }
var cvcErrorLabel: UILabel! { get }
var cardHolderErrorLabel: UILabel! { get }
var inputTextColor: UIColor { get }
var inputTintColor: UIColor { get }
var inputTextErrorColorEnabled: Bool { get }
var isHolderRequired: Bool { get }
var cardNumberSeparator: String { get }
}
protocol CardFormViewTextFieldDelegate: AnyObject {
func didBeginEditing(textField: UITextField)
func didDeleteBackward(textField: FormTextField)
}
// swiftlint:disable type_body_length file_length
/// Base class of CardFormView.
@objcMembers
public class CardFormView: UIView {
private let expirationFormatter: ExpirationFormatterType = ExpirationFormatter()
private let nsErrorConverter: NSErrorConverterType = NSErrorConverter()
private var cardIOProxy: CardIOProxy!
/// CardFormView delegate.
public weak var delegate: CardFormViewDelegate?
weak var textFieldDelegate: CardFormViewTextFieldDelegate?
var viewModel: CardFormViewViewModelType = CardFormViewViewModel()
var cardFormProperties: CardFormProperties!
var currentCardBrand: CardBrand {
return viewModel.cardBrand
}
var currentCardNumber: CardNumber? {
return viewModel.cardNumber
}
override public init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
cardIOProxy = CardIOProxy(delegate: self)
viewModel.delegate = self
}
/// カード番号の入力フィールドを更新する
///
/// - Parameters:
/// - input: カード番号
/// - forceShowError: エラー表示を強制するか
private func updateCardNumberInput(input: String?, forceShowError: Bool = false, separator: String) {
cardFormProperties.cardNumberTextField.tintColor = .clear
let result = viewModel.update(cardNumber: input, separator: separator)
switch result {
case let .success(cardNumber):
cardFormProperties.cardNumberTextField.text = cardNumber.formatted
if cardFormProperties.inputTextErrorColorEnabled {
cardFormProperties.cardNumberTextField.textColor = cardFormProperties.inputTextColor
}
inputCardNumberSuccess(value: cardNumber)
updateBrandLogo(brand: cardNumber.brand)
updateCvcIcon(brand: cardNumber.brand)
focusNextInputField(currentField: cardFormProperties.cardNumberTextField)
case let .failure(error):
switch error {
case let .cardNumberEmptyError(value, instant),
let .cardNumberInvalidError(value, instant),
let .cardNumberInvalidBrandError(value, instant):
cardFormProperties.cardNumberTextField.text = value?.formatted
if cardFormProperties.inputTextErrorColorEnabled {
cardFormProperties.cardNumberTextField.textColor = forceShowError ||
instant ? Style.Color.red : cardFormProperties.inputTextColor
}
inputCardNumberFailure(value: value, error: error, forceShowError: forceShowError, instant: instant)
updateBrandLogo(brand: value?.brand)
updateCvcIcon(brand: value?.brand)
default:
break
}
}
cardFormProperties.cardNumberErrorLabel.isHidden = cardFormProperties.cardNumberTextField.text == nil
// ブランドが変わったらcvcのチェックを走らせる
if viewModel.isCardBrandChanged || input?.isEmpty == true {
updateCvcInput(input: cardFormProperties.cvcTextField.text)
}
}
/// ブランドロゴの表示を更新する
///
/// - Parameter brand: カードブランド
func updateBrandLogo(brand: CardBrand?) {
guard let brandLogoImage = cardFormProperties.brandLogoImage else { return }
guard let brand = brand else {
brandLogoImage.image = "icon_card".image
return
}
brandLogoImage.image = brand.logoImage
}
/// 有効期限の入力フィールドを更新する
///
/// - Parameters:
/// - input: 有効期限
/// - forceShowError: エラー表示を強制するか
private func updateExpirationInput(input: String?, forceShowError: Bool = false) {
cardFormProperties.expirationTextField.tintColor = .clear
let result = viewModel.update(expiration: input)
switch result {
case let .success(expiration):
cardFormProperties.expirationTextField.text = expiration.formatted
if cardFormProperties.inputTextErrorColorEnabled {
cardFormProperties.expirationTextField.textColor = cardFormProperties.inputTextColor
}
inputExpirationSuccess(value: expiration)
focusNextInputField(currentField: cardFormProperties.expirationTextField)
case let .failure(error):
switch error {
case let .expirationEmptyError(value, instant),
let .expirationInvalidError(value, instant):
cardFormProperties.expirationTextField.text = value?.formatted
if cardFormProperties.inputTextErrorColorEnabled {
cardFormProperties.expirationTextField.textColor = forceShowError ||
instant ? Style.Color.red : cardFormProperties.inputTextColor
}
inputExpirationFailure(value: value, error: error, forceShowError: forceShowError, instant: instant)
default:
break
}
}
cardFormProperties.expirationErrorLabel.isHidden = cardFormProperties.expirationTextField.text == nil
}
/// CVCの入力フィールドを更新する
///
/// - Parameters:
/// - input: CVC
/// - forceShowError: エラー表示を強制するか
private func updateCvcInput(input: String?, forceShowError: Bool = false) {
cardFormProperties.cvcTextField.tintColor = .clear
let result = viewModel.update(cvc: input)
switch result {
case let .success(cvc):
cardFormProperties.cvcTextField.text = cvc
if cardFormProperties.inputTextErrorColorEnabled {
cardFormProperties.cvcTextField.textColor = cardFormProperties.inputTextColor
}
inputCvcSuccess(value: cvc)
focusNextInputField(currentField: cardFormProperties.cvcTextField)
case let .failure(error):
switch error {
case let .cvcEmptyError(value, instant),
let .cvcInvalidError(value, instant):
cardFormProperties.cvcTextField.text = value
if cardFormProperties.inputTextErrorColorEnabled {
cardFormProperties.cvcTextField.textColor = forceShowError ||
instant ? Style.Color.red : cardFormProperties.inputTextColor
}
inputCvcFailure(value: value, error: error, forceShowError: forceShowError, instant: instant)
default:
break
}
}
cardFormProperties.cvcErrorLabel.isHidden = cardFormProperties.cvcTextField.text == nil
}
/// cvcアイコンの表示を更新する
///
/// - Parameter brand: カードブランド
private func updateCvcIcon(brand: CardBrand?) {
guard let cvcIconImage = cardFormProperties.cvcIconImage else { return }
guard let brand = brand else {
cvcIconImage.image = "icon_card_cvc_3".image
return
}
cvcIconImage.image = brand.cvcIconImage
}
/// カード名義の入力フィールドを更新する
///
/// - Parameters:
/// - input: カード名義
/// - forceShowError: エラー表示を強制するか
private func updateCardHolderInput(input: String?, forceShowError: Bool = false) {
let result = viewModel.update(cardHolder: input)
switch result {
case let .success(cardHolder):
cardFormProperties.cardHolderTextField.text = cardHolder
if cardFormProperties.inputTextErrorColorEnabled {
cardFormProperties.cardHolderTextField.textColor = cardFormProperties.inputTextColor
}
inputCardHolderSuccess(value: cardHolder)
case let .failure(error):
switch error {
case let .cardHolderEmptyError(value, instant):
cardFormProperties.cardHolderTextField.text = value
if cardFormProperties.inputTextErrorColorEnabled {
cardFormProperties.cardHolderTextField.textColor = forceShowError ||
instant ? Style.Color.red : cardFormProperties.inputTextColor
}
inputCardHolderFailure(value: value, error: error, forceShowError: forceShowError, instant: instant)
default:
break
}
}
cardFormProperties.cardHolderErrorLabel.isHidden = cardFormProperties.cardHolderTextField.text == nil
}
func inputCardNumberSuccess(value: CardNumber) {
cardFormProperties.cardNumberErrorLabel.text = nil
}
func inputCardNumberFailure(value: CardNumber?, error: Error, forceShowError: Bool, instant: Bool) {
cardFormProperties.cardNumberErrorLabel.text = forceShowError || instant ? error.localizedDescription : nil
}
func inputExpirationSuccess(value: Expiration) {
cardFormProperties.expirationErrorLabel.text = nil
}
func inputExpirationFailure(value: Expiration?, error: Error, forceShowError: Bool, instant: Bool) {
cardFormProperties.expirationErrorLabel.text = forceShowError || instant ? error.localizedDescription : nil
}
func inputCvcSuccess(value: String) {
cardFormProperties.cvcErrorLabel.text = nil
}
func inputCvcFailure(value: String?, error: Error, forceShowError: Bool, instant: Bool) {
cardFormProperties.cvcErrorLabel.text = forceShowError || instant ? error.localizedDescription : nil
}
func inputCardHolderSuccess(value: String) {
cardFormProperties.cardHolderErrorLabel.text = nil
}
func inputCardHolderFailure(value: String?, error: Error, forceShowError: Bool, instant: Bool) {
cardFormProperties.cardHolderErrorLabel.text = forceShowError || instant ? error.localizedDescription : nil
}
func inputCardHolderComplete() {
cardFormProperties.cardHolderErrorLabel.isHidden = cardFormProperties.cardHolderTextField.text == nil
}
/// バリデーションOKの場合、次のTextFieldへフォーカスを移動する
///
/// - Parameter currentField: 現在のTextField
func focusNextInputField(currentField: UITextField) {
switch currentField {
case cardFormProperties.cardNumberTextField:
if cardFormProperties.cardNumberTextField.isFirstResponder {
cardFormProperties.expirationTextField.becomeFirstResponder()
}
case cardFormProperties.expirationTextField:
if cardFormProperties.expirationTextField.isFirstResponder {
cardFormProperties.cvcTextField.becomeFirstResponder()
}
case cardFormProperties.cvcTextField:
if cardFormProperties.cvcTextField.isFirstResponder && cardFormProperties.isHolderRequired {
cardFormProperties.cardHolderTextField.becomeFirstResponder()
}
default:
break
}
}
/// textFieldのtintColorをリセットする
private func resetTintColor() {
cardFormProperties.cardNumberTextField.tintColor = cardFormProperties.inputTintColor
cardFormProperties.expirationTextField.tintColor = cardFormProperties.inputTintColor
cardFormProperties.cvcTextField.tintColor = cardFormProperties.inputTintColor
cardFormProperties.cardHolderTextField.tintColor = cardFormProperties.inputTintColor
}
/// textField入力値を取得する
func cardFormInput(completion: (Result<CardFormInput, Error>) -> Void) {
viewModel.cardFormInput(completion: completion)
}
/// カメラ使用を許可していない場合にアラートを表示する
private func showCameraPermissionAlert() {
let alertController = UIAlertController(title: "payjp_scanner_camera_permission_denied_title".localized,
message: "payjp_scanner_camera_permission_denied_message".localized,
preferredStyle: .alert)
let settingsAction = UIAlertAction(
title: "payjp_common_settings".localized,
style: .default,
handler: { (_) -> Void in
guard let settingsURL = URL(string: UIApplication.openSettingsURLString ) else {
return
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(settingsURL)
}
})
let closeAction = UIAlertAction(title: "payjp_common_ok".localized,
style: .default,
handler: nil)
alertController.addAction(closeAction)
alertController.addAction(settingsAction)
alertController.preferredAction = settingsAction
guard let viewController = UIApplication.topViewController() else {
return
}
viewController.present(alertController, animated: true, completion: nil)
}
func notifyIsValidChanged() {
self.delegate?.formInputValidated(in: self, isValid: isValid)
}
}
// MARK: CardFormAction
extension CardFormView: CardFormAction {
public var isValid: Bool {
return viewModel.isValid
}
@nonobjc public func createToken(tenantId: String? = nil, completion: @escaping (Result<Token, Error>) -> Void) {
viewModel.createToken(with: tenantId, completion: completion)
}
public func createTokenWith(_ tenantId: String?, completion: @escaping (Token?, NSError?) -> Void) {
viewModel.createToken(with: tenantId) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let result):
completion(result, nil)
case .failure(let error):
completion(nil, self.nsErrorConverter.convert(from: error))
}
}
}
@nonobjc public func fetchBrands(tenantId: String?, completion: CardBrandsResult?) {
viewModel.fetchAcceptedBrands(with: tenantId, completion: completion)
}
public func fetchBrandsWith(_ tenantId: String?, completion: (([NSString]?, NSError?) -> Void)?) {
viewModel.fetchAcceptedBrands(with: tenantId) { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let result):
let converted = result.map { (brand: CardBrand) -> NSString in return brand.rawValue as NSString }
completion?(converted, nil)
case .failure(let error):
completion?(nil, self.nsErrorConverter.convert(from: error))
}
}
}
public func validateCardForm() -> Bool {
updateCardNumberInput(input: cardFormProperties.cardNumberTextField.text,
forceShowError: true,
separator: cardFormProperties.cardNumberSeparator)
updateExpirationInput(input: cardFormProperties.expirationTextField.text, forceShowError: true)
updateCvcInput(input: cardFormProperties.cvcTextField.text, forceShowError: true)
updateCardHolderInput(input: cardFormProperties.cardHolderTextField.text, forceShowError: true)
resetTintColor()
notifyIsValidChanged()
return isValid
}
public func setupInputAccessoryView(view: UIView) {
cardFormProperties.cardNumberTextField.inputAccessoryView = view
cardFormProperties.expirationTextField.inputAccessoryView = view
cardFormProperties.cvcTextField.inputAccessoryView = view
cardFormProperties.cardHolderTextField.inputAccessoryView = view
}
}
// MARK: Event
@objc extension CardFormView {
func textFieldDidChange(_ textField: UITextField) {
if textField.markedTextRange != nil {
return
}
let selectedTextRangeOriginal = textField.selectedTextRange
if let newText = textField.text {
switch textField {
case cardFormProperties.cardNumberTextField:
updateCardNumberInput(input: newText, separator: cardFormProperties.cardNumberSeparator)
case cardFormProperties.expirationTextField:
updateExpirationInput(input: newText)
case cardFormProperties.cvcTextField:
updateCvcInput(input: newText)
case cardFormProperties.cardHolderTextField:
updateCardHolderInput(input: newText)
default:
break
}
}
notifyIsValidChanged()
resetTintColor()
guard let selectedTextRange = selectedTextRangeOriginal else {
return
}
// テキスト変更時にカーソル位置を復元するが、デリミタや0埋め前後でずらす
if let beforePosition = textField.position(from: selectedTextRange.start, offset: -1),
let beforeRange = textField.textRange(from: beforePosition, to: selectedTextRange.start),
let textBeforeCursor = textField.text(in: beforeRange),
!textBeforeCursor.isDigitsOnly || (textBeforeCursor == "0" && textField == cardFormProperties.expirationTextField),
let adjustPosition = textField.position(from: selectedTextRange.start, offset: 1),
let adjustSelectedRange = textField.textRange(from: adjustPosition, to: adjustPosition) {
textField.selectedTextRange = adjustSelectedRange
} else {
textField.selectedTextRange = selectedTextRange
}
}
}
// MARK: UITextFieldDelegate
extension CardFormView: UITextFieldDelegate {
public func textFieldShouldClear(_ textField: UITextField) -> Bool {
switch textField {
case cardFormProperties.cardNumberTextField:
updateCardNumberInput(input: nil, separator: cardFormProperties.cardNumberSeparator)
updateCvcInput(input: cardFormProperties.cvcTextField.text)
case cardFormProperties.expirationTextField:
updateExpirationInput(input: nil)
case cardFormProperties.cvcTextField:
updateCvcInput(input: nil)
case cardFormProperties.cardHolderTextField:
updateCardHolderInput(input: nil)
default:
break
}
resetTintColor()
notifyIsValidChanged()
return true
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
cardFormProperties.cardHolderTextField.resignFirstResponder()
if isValid {
delegate?.formInputDoneTapped(in: self)
}
return true
}
public func textFieldDidBeginEditing(_ textField: UITextField) {
textFieldDelegate?.didBeginEditing(textField: textField)
}
}
// MARK: CardIOProxyDelegate
extension CardFormView: CardIOProxyDelegate {
public func didCancel(in proxy: CardIOProxy) {
cardFormProperties.ocrButton.isHidden = !CardIOProxy.isCardIOAvailable()
}
public func cardIOProxy(_ proxy: CardIOProxy, didFinishWith cardParams: CardIOCardParams) {
updateCardNumberInput(input: cardParams.number, separator: cardFormProperties.cardNumberSeparator)
updateExpirationInput(input: expirationFormatter.string(month: cardParams.expiryMonth?.intValue,
year: cardParams.expiryYear?.intValue))
updateCvcInput(input: cardParams.cvc)
notifyIsValidChanged()
}
}
extension CardFormView: CardFormViewModelDelegate {
func startScanner() {
if let viewController = parentViewController, CardIOProxy.canReadCardWithCamera() {
cardIOProxy.presentCardIO(from: viewController)
}
}
func showPermissionAlert() {
showCameraPermissionAlert()
}
}
extension CardFormView: FormTextFieldDelegate {
func didDeleteBackward(_ textField: FormTextField) {
textFieldDelegate?.didDeleteBackward(textField: textField)
}
}
// swiftlint:enable type_body_length file_length
| mit | 6b57b503a31ed34c362b6b8d73617112 | 38.966292 | 126 | 0.660669 | 5.150097 | false | false | false | false |
NobodyNada/SwiftChatSE | Sources/SwiftChatSE/ErrorHandler.swift | 1 | 2491 | //
// ErrorHandler.swift
// FireAlarm
//
// Created by Jonathan Keller on 11/22/16.
// Copyright © 2016 NobodyNada. All rights reserved.
//
import Foundation
import Dispatch
public var errorRoom: ChatRoom?
public func errorAsNSError(_ error: Error) -> NSError? {
#if os(Linux)
//this is the only way I could find to check if an arbitrary Error is an NSError that doesn't crash on Linux
//it produces a warning "'is' test is always true"
return error is AnyObject ? unsafeBitCast(error, to: NSError.self) : nil
#else
return type(of: error) == NSError.self ? error as NSError : nil
#endif
}
public func formatNSError(_ e: NSError) -> String {
return "\(e.domain) code \(e.code) \(e.userInfo)"
}
///The maximum amount of errors that can occur in a 30-second period.
public var maxErrors = 2
///What to do after too many errors. Defaults to calling `abort`.
public var afterTooManyErrors: () -> () = { abort() }
///How many errors have occured within the last 30 seconds.
public var errorsInLast30Seconds = 0
///A string that will be appended to the error message so that the bot's author can be pinged by errors..
public var ping = " (cc @<enter owner name here>)"
///A bool variable which will control the usage of the ping ^ variable.
public var pingonerror = true
///Logs an error.
public func handleError(_ error: Error, _ context: String? = nil) {
let contextStr: String
let errorType: String
let errorDetails: String
/*#if os(Linux)
if let e = errorAsNSError(error) {
errorType = "NSError"
errorDetails = formatNSError(e)
} else {
errorType = String(reflecting: type(of: error))
errorDetails = String(describing: error)
}
#else*/
errorType = String(reflecting: type(of: error))
errorDetails = String(describing: error)
//#endif
if context != nil {
contextStr = " \(context!)"
}
else {
contextStr = ""
}
let message1: String
if (pingonerror == true) {
message1 = " An error (\(errorType)) occured\(contextStr)\(ping):"
} else {
message1 = " An error (\(errorType)) occured\(contextStr):"
}
print("\(message1)\n\(errorDetails)")
if let room = errorRoom {
room.postMessage(message1 + "\n " + errorDetails.replacingOccurrences(of: "\n", with: "\n "))
}
else {
print("\(message1)\n\(errorDetails)")
exit(1)
}
errorsInLast30Seconds += 1
if errorsInLast30Seconds > maxErrors {
afterTooManyErrors()
}
DispatchQueue.global(qos: .background).async {
sleep(30)
errorsInLast30Seconds -= 1
}
}
| mit | e1b6751aa5422f595b93c1668fb1229e | 25.210526 | 110 | 0.68755 | 3.351279 | false | false | false | false |
igordeoliveirasa/yolo-ios | mvt-ios/ViewController.swift | 1 | 2946 | //
// ViewController.swift
// mvt-ios
//
// Created by Igor de Oliveira Sa on 24/12/14.
// Copyright (c) 2014 Igor de Oliveira Sa. All rights reserved.
//
import UIKit
// Excelent tutorial: http://www.veasoftware.com/tutorials/2014/8/22/xcode-6-tutorial-ios-8-0-facebook-login-in-swift
class ViewController: UIViewController, FBLoginViewDelegate, GPPSignInDelegate {
@IBOutlet var fbLoginView : FBLoginView!
@IBOutlet var googleSignInButton : GPPSignInButton!
let kClientId = "230078211083-p7t54o5en03ectaa21t5c5chtvgv128b.apps.googleusercontent.com"
func finishedWithAuth(auth: GTMOAuth2Authentication!, error: NSError!) {
if error != nil {
println("Error: \(error.localizedDescription)")
} else {
println("Logged In with Google")
self.refreshInterfaceBasedOnSignIn()
}
}
func refreshInterfaceBasedOnSignIn() {
if GPPSignIn.sharedInstance().authentication != nil {
self.googleSignInButton.hidden = true;
}
else {
self.googleSignInButton.hidden = false;
}
}
func signOut() {
GPPSignIn.sharedInstance().signOut()
}
override func viewDidLoad() {
super.viewDidLoad()
self.fbLoginView.delegate = self
self.fbLoginView.readPermissions = ["public_profile", "email", "user_friends"]
//Google
var signIn = GPPSignIn.sharedInstance()
signIn.shouldFetchGooglePlusUser = true
signIn.shouldFetchGoogleUserEmail = true
// You previously set kClientId in the "Initialize the Google+ client" step
signIn.clientID = kClientId
// Uncomment one of these two statements for the scope you chose in the previous step
signIn.scopes = [ kGTLAuthScopePlusLogin ] // "https://www.googleapis.com/auth/plus.login" scope
//signIn.scopes = @[ @"profile" ]; // "profile" scope
// Optional: declare signIn.actions, see "app activities"
signIn.delegate = self
signIn.trySilentAuthentication()
}
func loginViewShowingLoggedInUser(loginView: FBLoginView!) {
println("User logged in")
println("This is where your perform segue")
}
func loginViewFetchedUserInfo(loginView: FBLoginView!, user: FBGraphUser!) {
println("User name: \(user.name)")
println("This is where your perform segue")
}
func loginViewShowingLoggedOutUser(loginView: FBLoginView!) {
println("User logged out")
}
func loginView(loginView: FBLoginView!, handleError: NSError!) {
println("Error: \(handleError.localizedDescription)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 323ea267973a123f5f1957e60146d386 | 28.757576 | 117 | 0.632043 | 4.683625 | false | false | false | false |
tlax/GaussSquad | GaussSquad/View/Scanner/VScannerCropperShade.swift | 1 | 3404 | import UIKit
class VScannerCropperShade:UIView
{
private let kBorderSize:CGFloat = 1
private let kAlpha:CGFloat = 0.8
class func noBorder() -> VScannerCropperShade
{
let shade:VScannerCropperShade = VScannerCropperShade()
return shade
}
class func borderTop() -> VScannerCropperShade
{
let shade:VScannerCropperShade = VScannerCropperShade(borderTop:true)
return shade
}
class func borderBottom() -> VScannerCropperShade
{
let shade:VScannerCropperShade = VScannerCropperShade(borderBottom:true)
return shade
}
class func borderLeft() -> VScannerCropperShade
{
let shade:VScannerCropperShade = VScannerCropperShade(borderLeft:true)
return shade
}
class func borderRight() -> VScannerCropperShade
{
let shade:VScannerCropperShade = VScannerCropperShade(borderRight:true)
return shade
}
private init(
borderTop:Bool = false,
borderBottom:Bool = false,
borderLeft:Bool = false,
borderRight:Bool = false)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = UIColor(white:0, alpha:kAlpha)
if borderTop
{
let border:VBorder = VBorder(color:UIColor.white)
addSubview(border)
NSLayoutConstraint.topToTop(
view:border,
toView:self)
NSLayoutConstraint.height(
view:border,
constant:kBorderSize)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
}
if borderBottom
{
let border:VBorder = VBorder(color:UIColor.white)
addSubview(border)
NSLayoutConstraint.bottomToBottom(
view:border,
toView:self)
NSLayoutConstraint.height(
view:border,
constant:kBorderSize)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
}
if borderLeft
{
let border:VBorder = VBorder(color:UIColor.white)
addSubview(border)
NSLayoutConstraint.equalsVertical(
view:border,
toView:self)
NSLayoutConstraint.leftToLeft(
view:border,
toView:self)
NSLayoutConstraint.width(
view:border,
constant:kBorderSize)
}
if borderRight
{
let border:VBorder = VBorder(color:UIColor.white)
addSubview(border)
NSLayoutConstraint.equalsVertical(
view:border,
toView:self)
NSLayoutConstraint.rightToRight(
view:border,
toView:self)
NSLayoutConstraint.width(
view:border,
constant:kBorderSize)
}
}
required init?(coder:NSCoder)
{
return nil
}
}
| mit | 317074bf0fd224887ddfacdaf4f01bfe | 25.59375 | 80 | 0.532609 | 5.562092 | false | false | false | false |
airspeedswift/swift | test/decl/protocol/req/associated_type_inference.swift | 2 | 16837 | // RUN: %target-typecheck-verify-swift
protocol P0 {
associatedtype Assoc1 : PSimple // expected-note{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}}
// expected-note@-1{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}}
// expected-note@-2{{unable to infer associated type 'Assoc1' for protocol 'P0'}}
// expected-note@-3{{unable to infer associated type 'Assoc1' for protocol 'P0'}}
func f0(_: Assoc1)
func g0(_: Assoc1)
}
protocol PSimple { }
extension Int : PSimple { }
extension Double : PSimple { }
struct X0a : P0 { // okay: Assoc1 == Int
func f0(_: Int) { }
func g0(_: Int) { }
}
struct X0b : P0 { // expected-error{{type 'X0b' does not conform to protocol 'P0'}}
func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}}
func g0(_: Double) { } // expected-note{{matching requirement 'g0' to this declaration inferred associated type to 'Double'}}
}
struct X0c : P0 { // okay: Assoc1 == Int
func f0(_: Int) { }
func g0(_: Float) { }
func g0(_: Int) { }
}
struct X0d : P0 { // okay: Assoc1 == Int
func f0(_: Int) { }
func g0(_: Double) { } // viable, but no corresponding f0
func g0(_: Int) { }
}
struct X0e : P0 { // expected-error{{type 'X0e' does not conform to protocol 'P0'}}
func f0(_: Double) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Double}}
func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}}
func g0(_: Double) { }
func g0(_: Int) { }
}
struct X0f : P0 { // okay: Assoc1 = Int because Float doesn't conform to PSimple
func f0(_: Float) { }
func f0(_: Int) { }
func g0(_: Float) { }
func g0(_: Int) { }
}
struct X0g : P0 { // expected-error{{type 'X0g' does not conform to protocol 'P0'}}
func f0(_: Float) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
func g0(_: Float) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
}
struct X0h<T : PSimple> : P0 {
func f0(_: T) { }
}
extension X0h {
func g0(_: T) { }
}
struct X0i<T : PSimple> {
}
extension X0i {
func g0(_: T) { }
}
extension X0i : P0 { }
extension X0i {
func f0(_: T) { }
}
// Protocol extension used to infer requirements
protocol P1 {
}
extension P1 {
func f0(_ x: Int) { }
func g0(_ x: Int) { }
}
struct X0j : P0, P1 { }
protocol P2 {
associatedtype P2Assoc
func h0(_ x: P2Assoc)
}
extension P2 where Self.P2Assoc : PSimple {
func f0(_ x: P2Assoc) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
func g0(_ x: P2Assoc) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}}
}
struct X0k : P0, P2 {
func h0(_ x: Int) { }
}
struct X0l : P0, P2 { // expected-error{{type 'X0l' does not conform to protocol 'P0'}}
func h0(_ x: Float) { }
}
// Prefer declarations in the type to those in protocol extensions
struct X0m : P0, P2 {
func f0(_ x: Double) { }
func g0(_ x: Double) { }
func h0(_ x: Double) { }
}
// Inference from properties.
protocol PropertyP0 {
associatedtype Prop : PSimple // expected-note{{unable to infer associated type 'Prop' for protocol 'PropertyP0'}}
var property: Prop { get }
}
struct XProp0a : PropertyP0 { // okay PropType = Int
var property: Int
}
struct XProp0b : PropertyP0 { // expected-error{{type 'XProp0b' does not conform to protocol 'PropertyP0'}}
var property: Float // expected-note{{candidate would match and infer 'Prop' = 'Float' if 'Float' conformed to 'PSimple'}}
}
// Inference from subscripts
protocol SubscriptP0 {
associatedtype Index
// expected-note@-1 2 {{protocol requires nested type 'Index'; do you want to add it?}}
associatedtype Element : PSimple
// expected-note@-1 {{unable to infer associated type 'Element' for protocol 'SubscriptP0'}}
// expected-note@-2 2 {{protocol requires nested type 'Element'; do you want to add it?}}
subscript (i: Index) -> Element { get }
}
struct XSubP0a : SubscriptP0 {
subscript (i: Int) -> Int { get { return i } }
}
struct XSubP0b : SubscriptP0 {
// expected-error@-1{{type 'XSubP0b' does not conform to protocol 'SubscriptP0'}}
subscript (i: Int) -> Float { get { return Float(i) } } // expected-note{{candidate would match and infer 'Element' = 'Float' if 'Float' conformed to 'PSimple'}}
}
struct XSubP0c : SubscriptP0 {
// expected-error@-1 {{type 'XSubP0c' does not conform to protocol 'SubscriptP0'}}
subscript (i: Index) -> Element { get { } }
}
struct XSubP0d : SubscriptP0 {
// expected-error@-1 {{type 'XSubP0d' does not conform to protocol 'SubscriptP0'}}
subscript (i: XSubP0d.Index) -> XSubP0d.Element { get { } }
}
// Inference from properties and subscripts
protocol CollectionLikeP0 {
associatedtype Index
// expected-note@-1 {{protocol requires nested type 'Index'; do you want to add it?}}
associatedtype Element
// expected-note@-1 {{protocol requires nested type 'Element'; do you want to add it?}}
var startIndex: Index { get }
var endIndex: Index { get }
subscript (i: Index) -> Element { get }
}
struct SomeSlice<T> { }
struct XCollectionLikeP0a<T> : CollectionLikeP0 {
var startIndex: Int
var endIndex: Int
subscript (i: Int) -> T { get { fatalError("blah") } }
subscript (r: Range<Int>) -> SomeSlice<T> { get { return SomeSlice() } }
}
struct XCollectionLikeP0b : CollectionLikeP0 {
// expected-error@-1 {{type 'XCollectionLikeP0b' does not conform to protocol 'CollectionLikeP0'}}
var startIndex: XCollectionLikeP0b.Index
// There was an error @-1 ("'startIndex' used within its own type"),
// but it disappeared and doesn't seem like much of a loss.
var startElement: XCollectionLikeP0b.Element
}
// rdar://problem/21304164
public protocol Thenable {
associatedtype T // expected-note{{protocol requires nested type 'T'}}
func then(_ success: (_: T) -> T) -> Self
}
public class CorePromise<U> : Thenable { // expected-error{{type 'CorePromise<U>' does not conform to protocol 'Thenable'}}
public func then(_ success: @escaping (_ t: U, _: CorePromise<U>) -> U) -> Self {
return self.then() { (t: U) -> U in // expected-error{{contextual closure type '(U, CorePromise<U>) -> U' expects 2 arguments, but 1 was used in closure body}}
return success(t: t, self)
// expected-error@-1 {{extraneous argument label 't:' in call}}
}
}
}
// rdar://problem/21559670
protocol P3 {
associatedtype Assoc = Int
associatedtype Assoc2
func foo(_ x: Assoc2) -> Assoc?
}
protocol P4 : P3 { }
extension P4 {
func foo(_ x: Int) -> Float? { return 0 }
}
extension P3 where Assoc == Int {
func foo(_ x: Int) -> Assoc? { return nil }
}
struct X4 : P4 { }
// rdar://problem/21738889
protocol P5 {
associatedtype A = Int
}
struct X5<T : P5> : P5 {
typealias A = T.A
}
protocol P6 : P5 {
associatedtype A : P5 = X5<Self>
}
extension P6 where A == X5<Self> { }
// rdar://problem/21774092
protocol P7 {
associatedtype A
associatedtype B
func f() -> A
func g() -> B
}
struct X7<T> { }
extension P7 {
func g() -> X7<A> { return X7() }
}
struct Y7<T> : P7 {
func f() -> Int { return 0 }
}
struct MyAnySequence<Element> : MySequence {
typealias SubSequence = MyAnySequence<Element>
func makeIterator() -> MyAnyIterator<Element> {
return MyAnyIterator<Element>()
}
}
struct MyAnyIterator<T> : MyIteratorType {
typealias Element = T
}
protocol MyIteratorType {
associatedtype Element
}
protocol MySequence {
associatedtype Iterator : MyIteratorType
associatedtype SubSequence
func foo() -> SubSequence
func makeIterator() -> Iterator
}
extension MySequence {
func foo() -> MyAnySequence<Iterator.Element> {
return MyAnySequence()
}
}
struct SomeStruct<Element> : MySequence {
let element: Element
init(_ element: Element) {
self.element = element
}
func makeIterator() -> MyAnyIterator<Element> {
return MyAnyIterator<Element>()
}
}
// rdar://problem/21883828 - ranking of solutions
protocol P8 {
}
protocol P9 : P8 {
}
protocol P10 {
associatedtype A
func foo() -> A
}
struct P8A { }
struct P9A { }
extension P8 {
func foo() -> P8A { return P8A() }
}
extension P9 {
func foo() -> P9A { return P9A() }
}
struct Z10 : P9, P10 {
}
func testZ10() -> Z10.A {
var zA: Z10.A
zA = P9A()
return zA
}
// rdar://problem/21926788
protocol P11 {
associatedtype A
associatedtype B
func foo() -> B
}
extension P11 where A == Int {
func foo() -> Int { return 0 }
}
protocol P12 : P11 {
}
extension P12 {
func foo() -> String { return "" }
}
struct X12 : P12 {
typealias A = String
}
// Infinite recursion -- we would try to use the extension
// initializer's argument type of 'Dough' as a candidate for
// the associated type
protocol Cookie {
associatedtype Dough
// expected-note@-1 {{protocol requires nested type 'Dough'; do you want to add it?}}
init(t: Dough)
}
extension Cookie {
init(t: Dough?) {}
}
struct Thumbprint : Cookie {}
// expected-error@-1 {{type 'Thumbprint' does not conform to protocol 'Cookie'}}
// Looking through typealiases
protocol Vector {
associatedtype Element
typealias Elements = [Element]
func process(elements: Elements)
}
struct Int8Vector : Vector {
func process(elements: [Int8]) { }
}
// SR-4486
protocol P13 {
associatedtype Arg // expected-note{{protocol requires nested type 'Arg'; do you want to add it?}}
func foo(arg: Arg)
}
struct S13 : P13 { // expected-error{{type 'S13' does not conform to protocol 'P13'}}
func foo(arg: inout Int) {}
}
// "Infer" associated type from generic parameter.
protocol P14 {
associatedtype Value
}
struct P14a<Value>: P14 { }
struct P14b<Value> { }
extension P14b: P14 { }
// Associated type defaults in overridden associated types.
struct X15 { }
struct OtherX15 { }
protocol P15a {
associatedtype A = X15
}
protocol P15b : P15a {
associatedtype A
}
protocol P15c : P15b {
associatedtype A
}
protocol P15d {
associatedtype A = X15
}
protocol P15e : P15b, P15d {
associatedtype A
}
protocol P15f {
associatedtype A = OtherX15
}
protocol P15g: P15c, P15f {
associatedtype A // expected-note{{protocol requires nested type 'A'; do you want to add it?}}
}
struct X15a : P15a { }
struct X15b : P15b { }
struct X15c : P15c { }
struct X15d : P15d { }
// Ambiguity.
// FIXME: Better diagnostic here?
struct X15g : P15g { } // expected-error{{type 'X15g' does not conform to protocol 'P15g'}}
// Associated type defaults in overidden associated types that require
// substitution.
struct X16<T> { }
protocol P16 {
associatedtype A = X16<Self>
}
protocol P16a : P16 {
associatedtype A
}
protocol P16b : P16a {
associatedtype A
}
struct X16b : P16b { }
// Refined protocols that tie associated types to a fixed type.
protocol P17 {
associatedtype T
}
protocol Q17 : P17 where T == Int { }
struct S17 : Q17 { }
// Typealiases from protocol extensions should not inhibit associated type
// inference.
protocol P18 {
associatedtype A
}
protocol P19 : P18 {
associatedtype B
}
extension P18 where Self: P19 {
typealias A = B
}
struct X18<A> : P18 { }
// rdar://problem/16316115
protocol HasAssoc {
associatedtype Assoc
}
struct DefaultAssoc {}
protocol RefinesAssocWithDefault: HasAssoc {
associatedtype Assoc = DefaultAssoc
}
struct Foo: RefinesAssocWithDefault {
}
protocol P20 {
associatedtype T // expected-note{{protocol requires nested type 'T'; do you want to add it?}}
typealias TT = T?
}
struct S19 : P20 { // expected-error{{type 'S19' does not conform to protocol 'P20'}}
typealias TT = Int?
}
// rdar://problem/44777661
struct S30<T> where T : P30 {}
protocol P30 {
static func bar()
}
protocol P31 {
associatedtype T : P30
}
extension S30 : P31 where T : P31 {}
extension S30 {
func foo() {
T.bar()
}
}
protocol P32 {
associatedtype A
associatedtype B
associatedtype C
func foo(arg: A) -> C
var bar: B { get }
}
protocol P33 {
associatedtype A
var baz: A { get } // expected-note {{protocol requires property 'baz' with type 'S31<T>.A' (aka 'Never'); do you want to add a stub?}}
}
protocol P34 {
associatedtype A
func boo() -> A // expected-note {{protocol requires function 'boo()' with type '() -> S31<T>.A' (aka '() -> Never'); do you want to add a stub?}}
}
struct S31<T> {}
extension S31: P32 where T == Int {} // OK
extension S31 where T == Int {
func foo(arg: Never) {}
}
extension S31 where T: Equatable {
var bar: Bool { true }
}
extension S31: P33 where T == Never {} // expected-error {{type 'S31<T>' does not conform to protocol 'P33'}}
extension S31 where T == String {
var baz: Bool { true } // expected-note {{candidate has non-matching type 'Bool' [with A = S31<T>.A]}}
}
extension S31: P34 {} // expected-error {{type 'S31<T>' does not conform to protocol 'P34'}}
extension S31 where T: P32 {
func boo() -> Void {} // expected-note {{candidate has non-matching type '<T> () -> Void' [with A = S31<T>.A]}}
}
// SR-12707
class SR_12707_C<T> {}
// Inference in the adoptee
protocol SR_12707_P1 {
associatedtype A
associatedtype B: SR_12707_C<(A, Self)>
func foo(arg: B)
}
struct SR_12707_Conform_P1: SR_12707_P1 {
typealias A = Never
func foo(arg: SR_12707_C<(A, SR_12707_Conform_P1)>) {}
}
// Inference in protocol extension
protocol SR_12707_P2: SR_12707_P1 {}
extension SR_12707_P2 {
func foo(arg: SR_12707_C<(A, Self)>) {}
}
struct SR_12707_Conform_P2: SR_12707_P2 {
typealias A = Never
}
// SR-13172: Inference when witness is an enum case
protocol SR_13172_P1 {
associatedtype Bar
static func bar(_ value: Bar) -> Self
}
enum SR_13172_E1: SR_13172_P1 {
case bar(String) // Okay
}
protocol SR_13172_P2 {
associatedtype Bar
static var bar: Bar { get }
}
enum SR_13172_E2: SR_13172_P2 {
case bar // Okay
}
/** References to type parameters in type witnesses. */
// Circular reference through a fixed type witness.
protocol P35a {
associatedtype A = Array<B> // expected-note {{protocol requires nested type 'A'}}
associatedtype B // expected-note {{protocol requires nested type 'B'}}
}
protocol P35b: P35a where B == A {}
// expected-error@+2 {{type 'S35' does not conform to protocol 'P35a'}}
// expected-error@+1 {{type 'S35' does not conform to protocol 'P35b'}}
struct S35: P35b {}
// Circular reference through a value witness.
protocol P36a {
associatedtype A // expected-note {{protocol requires nested type 'A'}}
func foo(arg: A)
}
protocol P36b: P36a {
associatedtype B = (Self) -> A // expected-note {{protocol requires nested type 'B'}}
}
// expected-error@+2 {{type 'S36' does not conform to protocol 'P36a'}}
// expected-error@+1 {{type 'S36' does not conform to protocol 'P36b'}}
struct S36: P36b {
func foo(arg: Array<B>) {}
}
// Test that we can resolve abstract type witnesses that reference
// other abstract type witnesses.
protocol P37 {
associatedtype A = Array<B>
associatedtype B: Equatable = Never
}
struct S37: P37 {}
protocol P38a {
associatedtype A = Never
associatedtype B: Equatable
}
protocol P38b: P38a where B == Array<A> {}
struct S38: P38b {}
protocol P39 where A: Sequence {
associatedtype A = Array<B>
associatedtype B
}
struct S39<B>: P39 {}
// Test that we can handle an analogous complex case involving all kinds of
// type witness resolution.
protocol P40a {
associatedtype A
associatedtype B: P40a
func foo(arg: A)
}
protocol P40b: P40a {
associatedtype C = (A, B.A, D.D, E) -> Self
associatedtype D: P40b
associatedtype E: Equatable
}
protocol P40c: P40b where D == S40<Never> {}
struct S40<E: Equatable>: P40c {
func foo(arg: Never) {}
typealias B = Self
}
// Self is not treated as a fixed type witness.
protocol FIXME_P1a {
associatedtype A // expected-note {{protocol requires nested type 'A'}}
}
protocol FIXME_P1b: FIXME_P1a where A == Self {}
// expected-error@+2 {{type 'FIXME_S1' does not conform to protocol 'FIXME_P1a'}}
// expected-error@+1 {{type 'FIXME_S1' does not conform to protocol 'FIXME_P1b'}}
struct FIXME_S1: FIXME_P1b {}
// Fails to find the fixed type witness B == FIXME_S2<A>.
protocol FIXME_P2a {
associatedtype A: Equatable = Never // expected-note {{protocol requires nested type 'A'}}
associatedtype B: FIXME_P2a // expected-note {{protocol requires nested type 'B'}}
}
protocol FIXME_P2b: FIXME_P2a where B == FIXME_S2<A> {}
// expected-error@+2 {{type 'FIXME_S2<T>' does not conform to protocol 'FIXME_P2a'}}
// expected-error@+1 {{type 'FIXME_S2<T>' does not conform to protocol 'FIXME_P2b'}}
struct FIXME_S2<T: Equatable>: FIXME_P2b {}
| apache-2.0 | 09527d8db466c4974a83b3a66e1528f1 | 23.191092 | 167 | 0.667815 | 3.252898 | false | false | false | false |
lanserxt/teamwork-ios-sdk | TeamWorkClient/TeamWorkClient/Requests/TWApiClient+TaskReminders.swift | 1 | 10510 | //
// TWApiClient+TaskReminders.swift
// TeamWorkClient
//
// Created by Anton Gubarenko on 02.02.17.
// Copyright © 2017 Anton Gubarenko. All rights reserved.
//
import Foundation
import Alamofire
extension TWApiClient{
func getAllRemindersOfTask(taskId:String, _ responseBlock: @escaping (Bool, Int, [Reminder]?, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getAllRemindersOfTask.path, taskId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = MultipleResponseContainer<Reminder>.init(rootObjectName: TWApiClientConstants.APIPath.getAllRemindersOfTask.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, responseContainer.rootObjects, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func createReminderForTask(taskId: String, reminder:Reminder, _ responseBlock: @escaping (Bool, Int, String?, Error?) -> Void){
let parameters: [String : Any] = ["reminder" : reminder.dictionaryRepresentation() as! [String : Any]]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.createReminderForTask.path, taskId), method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<Tag>.init(rootObjectName: TWApiClientConstants.APIPath.createReminderForTask.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, JSON.object(forKey: "id") as! String?, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func updateReminderForTask(taskId: String, reminder:Reminder, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
let parameters: [String : Any] = ["reminder" : reminder.dictionaryRepresentation() as! [String : Any]]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updateReminderForTask.path, taskId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<Reminder>.init(rootObjectName: TWApiClientConstants.APIPath.updateReminderForTask.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func updateReminderForTask(reminder:Reminder, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
let parameters: [String : Any] = ["reminder" : reminder.dictionaryRepresentation() as! [String : Any]]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updateReminder.path, reminder.id!), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<Reminder>.init(rootObjectName: TWApiClientConstants.APIPath.updateReminderForTask.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func deleteReminderForTask(taskId: String, reminder:Reminder, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteReminderForTask.path, taskId), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<Reminder>.init(rootObjectName: TWApiClientConstants.APIPath.deleteReminderForTask.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func deleteReminder(reminder:Reminder, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteReminder.path, reminder.id!), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<Reminder>.init(rootObjectName: TWApiClientConstants.APIPath.deleteReminder.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
}
| mit | 4ad0c4be6279f19a63f546207aae82aa | 52.617347 | 216 | 0.536778 | 6.092174 | false | false | false | false |
fgengine/quickly | Quickly/ViewControllers/QCollectionViewController.swift | 1 | 18664 | //
// Quickly
//
open class QCollectionViewController : QViewController, IQInputContentViewController, IQCollectionControllerObserver, IQKeyboardObserver, IQStackContentViewController, IQPageContentViewController, IQGroupContentViewController, IQModalContentViewController, IQDialogContentViewController, IQHamburgerContentViewController, IQJalousieContentViewController, IQLoadingViewDelegate {
public enum PagesPosition {
case top(offset: CGFloat)
case bottom(offset: CGFloat)
}
public private(set) var collectionView: QCollectionView? {
willSet {
guard let collectionView = self.collectionView else { return }
collectionView.removeFromSuperview()
}
didSet {
guard let collectionView = self.collectionView else { return }
self.view.addSubview(collectionView)
}
}
public var collectionController: IQCollectionController? {
set(value) {
if let collectionView = self.collectionView {
if let collectionController = collectionView.collectionController {
collectionController.remove(observer: self)
}
if let collectionController = value {
collectionController.add(observer: self, priority: 0)
}
collectionView.collectionController = value
}
}
get { return self.collectionView?.collectionController }
}
public var refreshControlHidden: Bool = false {
didSet { self._updateRefreshControlState() }
}
public var refreshControl: UIRefreshControl? {
set(value) {
if let refreshControl = self._refreshControl {
if refreshControl.isRefreshing == true {
refreshControl.endRefreshing()
}
}
self._refreshControl = value
self._updateRefreshControlState()
}
get { return self._refreshControl }
}
public var isRefreshing: Bool {
get {
guard let refreshControl = self._refreshControl else { return false }
return refreshControl.isRefreshing
}
}
public var pagesPosition: PagesPosition = .bottom(offset: 0) {
didSet {
guard let pagesView = self.pagesView else { return }
if self.isLoaded == true {
self._updateFrame(pagesView: pagesView, bounds: self.view.bounds)
}
}
}
public var pagesView: QPagesViewType? {
willSet {
guard let pagesView = self.pagesView else { return }
if self.isLoaded == true {
pagesView.removeFromSuperview()
}
}
didSet {
guard let pagesView = self.pagesView, let collectionView = self.collectionView else { return }
if self.isLoaded == true {
pagesView.sizeToFit()
self._updateNumberOfPages(pagesView: pagesView, bounds: self.view.bounds)
self._updateCurrentPage(pagesView: pagesView)
self.view.insertSubview(pagesView, aboveSubview: collectionView)
}
}
}
public var loadingView: QLoadingViewType? {
willSet {
guard let loadingView = self.loadingView else { return }
loadingView.removeFromSuperview()
loadingView.delegate = nil
}
didSet {
guard let loadingView = self.loadingView else { return }
loadingView.delegate = self
}
}
public var batchUpdateDelay: TimeInterval {
didSet { self._batchUpdateTimer?.interval = self.batchUpdateDelay }
}
private var _refreshControl: UIRefreshControl? {
willSet {
guard let refreshControl = self._refreshControl else { return }
refreshControl.removeValueChanged(self, action: #selector(self._triggeredRefreshControl(_:)))
}
didSet {
guard let refreshControl = self._refreshControl else { return }
refreshControl.addValueChanged(self, action: #selector(self._triggeredRefreshControl(_:)))
}
}
private var _edgesForExtendedLayout: UIRectEdge?
private var _batchUpdateTimer: QTimer? {
willSet { self._batchUpdateTimer?.stop() }
didSet { self._batchUpdateTimer?.start() }
}
private var _batchUpdateCounter: UInt
private var _keyboard: QKeyboard!
public override init() {
self.batchUpdateDelay = 0.2
self._batchUpdateCounter = 0
super.init()
}
deinit {
self.collectionController = nil
self._batchUpdateTimer = nil
self._keyboard.remove(observer: self)
}
open override func setup() {
super.setup()
self._keyboard = QKeyboard()
}
open override func didLoad() {
self.collectionView = QCollectionView(frame: self.view.bounds)
self._keyboard.add(observer: self, priority: 0)
}
open override func layout(bounds: CGRect) {
super.layout(bounds: bounds)
if let collectionView = self.collectionView {
collectionView.frame = bounds
}
if let pagesView = self.pagesView {
self._updateNumberOfPages(pagesView: pagesView, bounds: bounds)
}
if let loadingView = self.loadingView, loadingView.superview != nil {
self._updateFrame(loadingView: loadingView, bounds: bounds)
}
}
open override func didChangeContentEdgeInsets() {
super.didChangeContentEdgeInsets()
if let collectionView = self.collectionView {
self._updateContentInsets(collectionView)
}
if let pagesView = self.pagesView {
self._updateFrame(pagesView: pagesView, bounds: self.view.bounds)
}
if let loadingView = self.loadingView, loadingView.superview != nil {
self._updateFrame(loadingView: loadingView, bounds: self.view.bounds)
}
}
open override func prepareInteractivePresent() {
super.prepareInteractivePresent()
self._updateRefreshControlState()
if self._batchUpdateCounter > 0 {
self._triggeredBatchUpdate()
}
}
open override func willPresent(animated: Bool) {
super.willPresent(animated: animated)
self._updateRefreshControlState()
if self._batchUpdateCounter > 0 {
self._triggeredBatchUpdate()
}
}
open override func prepareInteractiveDismiss() {
super.prepareInteractiveDismiss()
if let collectionView = self.collectionView {
collectionView.endEditing(false)
}
}
open override func willDismiss(animated: Bool) {
super.willDismiss(animated: animated)
if let collectionView = self.collectionView {
collectionView.endEditing(false)
}
}
open override func didDismiss(animated: Bool) {
super.didDismiss(animated: animated)
self._updateRefreshControlState()
}
open override func willTransition(size: CGSize) {
super.willTransition(size: size)
if let collectionView = self.collectionView {
collectionView.collectionViewLayout.invalidateLayout()
}
}
public func beginRefreshing() {
guard let refreshControl = self._refreshControl else { return }
refreshControl.beginRefreshing()
}
public func endRefreshing() {
guard let refreshControl = self._refreshControl else { return }
refreshControl.endRefreshing()
}
open func triggeredRefreshControl() {
}
public func setNeedBatchUpdate() {
if self.isPresented == true {
if let timer = self._batchUpdateTimer {
timer.restart()
} else {
self._batchUpdateTimer = QTimer(interval: self.batchUpdateDelay, onFinished: { [weak self] _ in self?._triggeredBatchUpdate() })
}
} else {
self._batchUpdateCounter += 1
}
}
open func triggeredBatchUpdate() {
}
public func isLoading() -> Bool {
guard let loadingView = self.loadingView else { return false }
return loadingView.isAnimating()
}
public func startLoading() {
guard let loadingView = self.loadingView else { return }
loadingView.start()
}
public func stopLoading() {
guard let loadingView = self.loadingView else { return }
loadingView.stop()
}
// MARK: IQContentViewController
public var contentOffset: CGPoint {
get {
guard let collectionView = self.collectionView else { return CGPoint.zero }
let contentOffset = collectionView.contentOffset
let contentInset = collectionView.contentInset
return CGPoint(
x: contentInset.left + contentOffset.x,
y: contentInset.top + contentOffset.y
)
}
}
public var contentSize: CGSize {
get {
guard let collectionView = self.collectionView else { return CGSize.zero }
return collectionView.contentSize
}
}
open func notifyBeginUpdateContent() {
if let viewController = self.contentOwnerViewController {
viewController.beginUpdateContent()
}
}
open func notifyUpdateContent() {
if let viewController = self.contentOwnerViewController {
viewController.updateContent()
}
}
open func notifyFinishUpdateContent(velocity: CGPoint) -> CGPoint? {
if let viewController = self.contentOwnerViewController {
return viewController.finishUpdateContent(velocity: velocity)
}
return nil
}
open func notifyEndUpdateContent() {
if let viewController = self.contentOwnerViewController {
viewController.endUpdateContent()
}
}
// MARK: IQCollectionControllerObserver
open func beginScroll(_ controller: IQCollectionController, collectionView: UICollectionView) {
self.notifyBeginUpdateContent()
}
open func scroll(_ controller: IQCollectionController, collectionView: UICollectionView) {
if let pagesView = self.pagesView {
self._updateCurrentPage(pagesView: pagesView)
}
self.notifyUpdateContent()
}
open func finishScroll(_ controller: IQCollectionController, collectionView: UICollectionView, velocity: CGPoint) -> CGPoint? {
return self.notifyFinishUpdateContent(velocity: velocity)
}
open func endScroll(_ controller: IQCollectionController, collectionView: UICollectionView) {
self.notifyEndUpdateContent()
}
open func beginZoom(_ controller: IQCollectionController, collectionView: UICollectionView) {
self.notifyBeginUpdateContent()
}
open func zoom(_ controller: IQCollectionController, collectionView: UICollectionView) {
self.notifyUpdateContent()
}
open func endZoom(_ controller: IQCollectionController, collectionView: UICollectionView) {
self.notifyEndUpdateContent()
}
open func update(_ controller: IQCollectionController) {
if let pagesView = self.pagesView {
self._updateNumberOfPages(pagesView: pagesView, bounds: self.view.bounds)
}
}
// MARK: IQModalContentViewController
open func modalShouldInteractive() -> Bool {
return true
}
// MARK: IQDialogContentViewController
open func dialogDidPressedOutside() {
}
// MARK: IQHamburgerContentViewController
open func hamburgerShouldInteractive() -> Bool {
return true
}
// MARK: IQJalousieContentViewController
open func jalousieShouldInteractive() -> Bool {
return true
}
// MARK: IQKeyboardObserver
open func willShowKeyboard(_ keyboard: QKeyboard, animationInfo: QKeyboardAnimationInfo) {
guard self.isPresented == true else {
return
}
if self._edgesForExtendedLayout == nil {
self._edgesForExtendedLayout = self.edgesForExtendedLayout
var edgesForExtendedLayout = self.edgesForExtendedLayout
if edgesForExtendedLayout.contains(.bottom) == true {
edgesForExtendedLayout.remove(.bottom)
}
UIView.animate(withDuration: animationInfo.duration, delay: 0, options: animationInfo.animationOptions([]), animations: {
self.additionalEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: animationInfo.endFrame.height, right: 0)
self.edgesForExtendedLayout = edgesForExtendedLayout
})
}
}
open func didShowKeyboard(_ keyboard: QKeyboard, animationInfo: QKeyboardAnimationInfo) {
}
open func willHideKeyboard(_ keyboard: QKeyboard, animationInfo: QKeyboardAnimationInfo) {
guard self.isPresented == true else {
return
}
if let edgesForExtendedLayout = self._edgesForExtendedLayout {
self._edgesForExtendedLayout = nil
UIView.animate(withDuration: animationInfo.duration, delay: 0, options: animationInfo.animationOptions([]), animations: {
self.additionalEdgeInsets = UIEdgeInsets.zero
self.edgesForExtendedLayout = edgesForExtendedLayout
})
}
}
open func didHideKeyboard(_ keyboard: QKeyboard, animationInfo: QKeyboardAnimationInfo) {
}
// MARK: IQLoadingViewDelegate
public func willShow(loadingView: QLoadingViewType) {
self._updateFrame(loadingView: loadingView, bounds: self.view.bounds)
if let pagesView = self.pagesView {
self.view.insertSubview(loadingView, aboveSubview: pagesView)
} else if let collectionView = self.collectionView {
self.view.insertSubview(loadingView, aboveSubview: collectionView)
} else {
self.view.addSubview(loadingView)
}
}
public func didHide(loadingView: QLoadingViewType) {
loadingView.removeFromSuperview()
}
}
// MARK: Private
private extension QCollectionViewController {
@objc
func _triggeredRefreshControl(_ sender: Any) {
self.triggeredRefreshControl()
}
func _triggeredBatchUpdate() {
self.loadViewIfNeeded()
self._batchUpdateTimer?.stop()
self._batchUpdateCounter = 0
self.triggeredBatchUpdate()
}
func _updateRefreshControlState() {
if let collectionView = self.collectionView {
if self.refreshControlHidden == false && self.isPresented == true {
collectionView.refreshControl = self._refreshControl
} else {
if let refreshControl = self._refreshControl {
refreshControl.endRefreshing()
}
collectionView.refreshControl = nil
}
}
}
func _updateContentInsets(_ collectionView: QCollectionView) {
let edgeInsets = self.adjustedContentInset
let oldContentInset = collectionView.contentInset
let newContentInset = UIEdgeInsets(
top: edgeInsets.top,
left: 0,
bottom: edgeInsets.bottom,
right: 0
)
collectionView.contentLeftInset = edgeInsets.left
collectionView.contentRightInset = edgeInsets.right
collectionView.contentInset = newContentInset
collectionView.scrollIndicatorInsets = edgeInsets
let deltaContentInset = UIEdgeInsets(
top: newContentInset.top - oldContentInset.top,
left: newContentInset.left - oldContentInset.left,
bottom: newContentInset.bottom - oldContentInset.bottom,
right: newContentInset.right - oldContentInset.right
)
if abs(deltaContentInset.left) > CGFloat.leastNonzeroMagnitude || abs(deltaContentInset.top) > CGFloat.leastNonzeroMagnitude {
let oldContentOffset = collectionView.contentOffset
let newContentOffset = CGPoint(
x: max(oldContentOffset.x - deltaContentInset.left, -newContentInset.left),
y: max(oldContentOffset.y - deltaContentInset.top, -newContentInset.top)
)
collectionView.setContentOffset(newContentOffset, animated: false)
}
}
func _updateFrame(pagesView: QPagesViewType, bounds: CGRect) {
let edgeInset = self.adjustedContentInset
let pagesHeight = pagesView.frame.height
switch self.pagesPosition {
case .top(let offset):
pagesView.frame = CGRect(
x: edgeInset.left,
y: edgeInset.top + offset,
width: bounds.width - (edgeInset.left + edgeInset.right),
height: pagesHeight
)
case .bottom(let offset):
pagesView.frame = CGRect(
x: edgeInset.left,
y: bounds.height - (edgeInset.bottom + offset),
width: bounds.width - (edgeInset.left + edgeInset.right),
height: pagesHeight
)
}
}
func _updateFrame(loadingView: QLoadingViewType, bounds: CGRect) {
loadingView.frame = bounds
}
func _updateCurrentPage(pagesView: QPagesViewType) {
if let collectionView = self.collectionView {
let contentSize = collectionView.collectionViewLayout.collectionViewContentSize
let contentOffset = collectionView.contentOffset
if contentSize.width > CGFloat.leastNonzeroMagnitude && contentOffset.x > CGFloat.leastNonzeroMagnitude {
pagesView.currentProgress = contentSize.width / (contentSize.width - contentOffset.x)
} else {
pagesView.currentProgress = 0
}
}
}
func _updateNumberOfPages(pagesView: QPagesViewType, bounds: CGRect) {
if let collectionView = self.collectionView {
let contentBounds = collectionView.bounds
let contentSize = collectionView.collectionViewLayout.collectionViewContentSize
if contentBounds.width > CGFloat.leastNonzeroMagnitude {
pagesView.numberOfPages = UInt(contentSize.width / contentBounds.width)
}
pagesView.sizeToFit()
self._updateFrame(pagesView: pagesView, bounds: bounds)
}
}
}
| mit | d72db5d50f08abe1addfca9351456f07 | 34.823417 | 378 | 0.628161 | 5.564699 | false | false | false | false |
Mikelulu/BaiSiBuDeQiJie | LKBS/LKBS/Classes/Essence(精华)/Views/LKVideoView.swift | 1 | 1945 | //
// LKVideoView.swift
// LKBS
//
// Created by admin on 2017/8/31.
// Copyright © 2017年 LK. All rights reserved.
//
import UIKit
import BMPlayer
class LKVideoView: LKCellContentView {
private let maskV = UIView()
private let player = BMPlayerLayerView()
private var model: ListModel?
override init(frame: CGRect) {
super.init(frame: frame)
maskV.backgroundColor = UIColor.black
bgImageV.addSubview(maskV)
maskV.addSubview(player)
maskV.isHidden = true
player.isHidden = true
playBtn.addTarget(self, action: #selector(play(_:)), for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func configVideo(model: ListModel) {
self.model = model
let urlString = model.video_thumbnail!
playBtn.setImage(UIImage.init(named: "video-play"), for: .normal)
bgImageV.kf.setImage(with: URL.init(string: urlString), placeholder: nil, options: nil, progressBlock: nil, completionHandler: nil)
playBtn.backgroundColor = UIColor.clear
}
override func layoutSubviews() {
super.layoutSubviews()
bgImageV.snp.remakeConstraints({ (make) in
make.edges.equalTo(UIEdgeInsets.zero)
})
playBtn.snp.remakeConstraints({ (make) in
make.center.equalTo(bgImageV)
})
maskV.snp.remakeConstraints { (make) in
make.edges.equalTo(UIEdgeInsets.zero)
}
player.snp.remakeConstraints { (make) in
make.edges.equalTo(UIEdgeInsets.zero)
}
}
@objc fileprivate func play(_ btn: UIButton) {
maskV.isHidden = false
player.isHidden = false
player.playURL(url: URL.init(string: self.model!.video_uri!)!)
}
}
| mit | 8cd9fb538f53cc289a3ef1c63fc26e44 | 25.60274 | 139 | 0.602987 | 4.413636 | false | false | false | false |
stunjiturner/Spring | SpringApp/OptionsViewController.swift | 3 | 4894 | //
// OptionsViewController.swift
// DesignerNewsApp
//
// Created by Meng To on 2015-01-04.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import UIKit
import Spring
protocol OptionsViewControllerDelegate: class {
func dampingSliderChanged(_ sender: AnyObject)
func velocitySliderChanged(_ sender: AnyObject)
func scaleSliderChanged(_ sender: AnyObject)
func xSliderChanged(_ sender: AnyObject)
func ySliderChanged(_ sender: AnyObject)
func rotateSliderChanged(_ sender: AnyObject)
func resetButtonPressed(_ sender: AnyObject)
}
class OptionsViewController: UIViewController {
@IBOutlet weak var modalView: SpringView!
@IBOutlet weak var dampingLabel: UILabel!
@IBOutlet weak var velocityLabel: UILabel!
@IBOutlet weak var scaleLabel: UILabel!
@IBOutlet weak var xLabel: UILabel!
@IBOutlet weak var yLabel: UILabel!
@IBOutlet weak var rotateLabel: UILabel!
@IBOutlet weak var dampingSlider: UISlider!
@IBOutlet weak var velocitySlider: UISlider!
@IBOutlet weak var scaleSlider: UISlider!
@IBOutlet weak var xSlider: UISlider!
@IBOutlet weak var ySlider: UISlider!
@IBOutlet weak var rotateSlider: UISlider!
var selectedDamping: CGFloat = 0.7
var selectedVelocity: CGFloat = 0.7
var selectedScale: CGFloat = 1
var selectedX: CGFloat = 0
var selectedY: CGFloat = 0
var selectedRotate: CGFloat = 0
weak var delegate: OptionsViewControllerDelegate?
var data: SpringView!
override func viewDidLoad() {
super.viewDidLoad()
modalView.transform = CGAffineTransform(translationX: 0, y: 300)
dampingSlider.setValue(Float(data.damping), animated: true)
velocitySlider.setValue(Float(data.velocity), animated: true)
scaleSlider.setValue(Float(data.scaleX), animated: true)
xSlider.setValue(Float(data.x), animated: true)
ySlider.setValue(Float(data.y), animated: true)
rotateSlider.setValue(Float(data.rotate), animated: true)
dampingLabel.text = getString("Damping", value: data.damping)
velocityLabel.text = getString("Velocity", value: data.velocity)
scaleLabel.text = getString("Scale", value: data.scaleX)
xLabel.text = getString("x", value: data.x)
yLabel.text = getString("y", value: data.y)
rotateLabel.text = getString("Rotate", value: data.rotate)
}
@IBAction func dampingSliderChanged(_ sender: AnyObject) {
selectedDamping = sender.value(forKey: "value") as! CGFloat
delegate?.dampingSliderChanged(sender)
dampingLabel.text = getString("Damping", value: selectedDamping)
}
@IBAction func velocitySliderChanged(_ sender: AnyObject) {
selectedVelocity = sender.value(forKey: "value") as! CGFloat
delegate?.velocitySliderChanged(sender)
velocityLabel.text = getString("Velocity", value: selectedVelocity)
}
@IBAction func scaleSliderChanged(_ sender: AnyObject) {
selectedScale = sender.value(forKey: "value") as! CGFloat
delegate?.scaleSliderChanged(sender)
scaleLabel.text = getString("Scale", value: selectedScale)
}
@IBAction func xSliderChanged(_ sender: AnyObject) {
selectedX = sender.value(forKey: "value") as! CGFloat
delegate?.xSliderChanged(sender)
xLabel.text = getString("X", value: selectedX)
}
@IBAction func ySliderChanged(_ sender: AnyObject) {
selectedY = sender.value(forKey: "value") as! CGFloat
delegate?.ySliderChanged(sender)
yLabel.text = getString("Y", value: selectedY)
}
@IBAction func rotateSliderChanged(_ sender: AnyObject) {
selectedRotate = sender.value(forKey: "value") as! CGFloat
delegate?.rotateSliderChanged(sender)
rotateLabel.text = getString("Rotate", value: selectedRotate)
}
@IBAction func resetButtonPressed(_ sender: AnyObject) {
delegate?.resetButtonPressed(sender)
dismiss(animated: true, completion: nil)
UIApplication.shared.sendAction(#selector(SpringViewController.maximizeView(_:)), to: nil, from: self, for: nil)
}
@IBAction func closeButtonPressed(_ sender: AnyObject) {
dismiss(animated: true, completion: nil)
UIApplication.shared.sendAction(#selector(SpringViewController.maximizeView(_:)), to: nil, from: self, for: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
UIApplication.shared.sendAction(#selector(SpringViewController.minimizeView(_:)), to: nil, from: self, for: nil)
modalView.animate()
}
func getString(_ name: String, value: CGFloat) -> String {
return String(format: "\(name): %.1f", Double(value))
}
}
| mit | 5b2289fb0d6efc0dc737a2205806a8ca | 36.646154 | 120 | 0.673069 | 4.603951 | false | false | false | false |
krummler/SKPhotoBrowser | SKPhotoBrowser/SKCaptionView.swift | 1 | 2672 | //
// SKCaptionView.swift
// SKPhotoBrowser
//
// Created by suzuki_keishi on 2015/10/07.
// Copyright © 2015 suzuki_keishi. All rights reserved.
//
import UIKit
public class SKCaptionView: UIView {
private var photo: SKPhotoProtocol?
private var photoLabel: UILabel!
private var photoLabelPadding: CGFloat = 10
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public convenience init(photo: SKPhotoProtocol) {
let screenBound = UIScreen.mainScreen().bounds
self.init(frame: CGRect(x: 0, y: 0, width: screenBound.size.width, height: screenBound.size.height))
self.photo = photo
setup()
}
public override func sizeThatFits(size: CGSize) -> CGSize {
guard let text = photoLabel.text else {
return CGSize.zero
}
guard photoLabel.text?.characters.count > 0 else {
return CGSize.zero
}
let font: UIFont = photoLabel.font
let width: CGFloat = size.width - photoLabelPadding * 2
let height: CGFloat = photoLabel.font.lineHeight * CGFloat(photoLabel.numberOfLines)
let attributedText = NSAttributedString(string: text, attributes: [NSFontAttributeName: font])
let textSize = attributedText.boundingRectWithSize(CGSize(width: width, height: height), options: .UsesLineFragmentOrigin, context: nil).size
return CGSize(width: textSize.width, height: textSize.height + photoLabelPadding * 2)
}
}
private extension SKCaptionView {
func setup() {
opaque = false
autoresizingMask = [.FlexibleWidth, .FlexibleTopMargin, .FlexibleRightMargin, .FlexibleLeftMargin]
// setup photoLabel
setupPhotoLabel()
}
func setupPhotoLabel() {
photoLabel = UILabel(frame: CGRect(x: photoLabelPadding, y: 0, width: bounds.size.width - (photoLabelPadding * 2), height: bounds.size.height))
photoLabel.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
photoLabel.opaque = false
photoLabel.backgroundColor = .clearColor()
photoLabel.textColor = .whiteColor()
photoLabel.textAlignment = .Center
photoLabel.lineBreakMode = .ByTruncatingTail
photoLabel.numberOfLines = 3
photoLabel.shadowColor = UIColor(white: 0.0, alpha: 0.5)
photoLabel.shadowOffset = CGSize(width: 0.0, height: 1.0)
photoLabel.font = UIFont.systemFontOfSize(17.0)
photoLabel.text = photo?.caption
addSubview(photoLabel)
}
}
| mit | 4243265cb406dde6685c7cbb7b4b25d3 | 34.613333 | 151 | 0.657806 | 4.57363 | false | false | false | false |
ppth0608/BPStatusBarAlert | BPStatusBarAlert/Classes/BPStatusBarAlert.swift | 1 | 6843 | //
// BPStatusBarAlert.swift
// Pods
//
// Created by Ben.Park on 2017. 1. 24..
//
//
import UIKit
public enum AlertPosition {
case statusBar
case navigationBar
}
public class BPStatusBarAlert: UIView {
typealias Position = AlertPosition
typealias Completion = () -> Void
fileprivate var containerWindow: UIWindow?
fileprivate var deviceStatusBarHeight:CGFloat {
let deviceDimensions = DeviceDimensions()
return deviceDimensions.statusBarHeight
}
fileprivate var duration: TimeInterval
fileprivate var delay: TimeInterval
fileprivate var isShowing: Bool = false
fileprivate var position: Position
fileprivate var completion: Completion?
fileprivate var messageLabel: UILabel = UILabel()
fileprivate var messageColor: UIColor = UIColor.white
fileprivate var statusBarHeight:CGFloat {
return UIApplication.shared.statusBarFrame.size.height
}
fileprivate let navigationBarHeight: CGFloat = 44.0
fileprivate let screenWidth = UIScreen.main.bounds.width
fileprivate let screenHeight = UIScreen.main.bounds.height
public init(duration: TimeInterval = 0.3, delay: TimeInterval = 2, position: AlertPosition = .statusBar) {
self.duration = duration
self.delay = delay
self.position = position
self.completion = nil
super.init(frame: CGRect.zero)
setupView(position: self.position)
setupMessageLabel()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: setup function
extension BPStatusBarAlert {
fileprivate func frame(position: Position) -> CGRect {
var frame = CGRect()
switch position {
case .statusBar:
frame = CGRect(x: 0, y: -statusBarHeight, width: screenWidth, height: statusBarHeight)
case .navigationBar:
frame = CGRect(x: 0, y: navigationBarHeight, width: screenWidth, height: statusBarHeight)
}
return frame
}
fileprivate func setupView(position: Position) {
self.backgroundColor = UIColor.bgColor
self.position = position
frame = frame(position: position)
}
fileprivate func setupMessageLabel() {
// messageLabel.frame = CGRect(x: 10, y: deviceStatusBarHeight, width: frame.size.width - 10, height: statusBarHeight)
messageLabel.frame = CGRect(x: 10, y: statusBarHeight - deviceStatusBarHeight, width: frame.size.width - 10, height: deviceStatusBarHeight)
messageLabel.textColor = messageColor
messageLabel.textAlignment = .center
messageLabel.numberOfLines = 0
messageLabel.font = UIFont.systemFont(ofSize: 13, weight: .medium)
messageLabel.backgroundColor = UIColor.clear
messageLabel.text = ""
addSubview(messageLabel)
}
}
// MARK: chaning function and show / hide functions
extension BPStatusBarAlert {
public func message(message: String) -> Self {
self.messageLabel.text = message
return self
}
public func messageColor(color: UIColor) -> Self {
self.messageLabel.textColor = color
return self
}
public func bgColor(color: UIColor) -> Self {
self.backgroundColor = color
return self
}
public func completion(_ completion: @escaping () -> Void) -> Self {
self.completion = completion
return self
}
public func show() {
adjustViewHierarchy(position: position)
startAnimation {
DispatchQueue.main.asyncAfter(deadline: .now() + self.delay) {
self.finishAnimating()
}
}
}
}
// MARK: animation functions
extension BPStatusBarAlert {
fileprivate func startAnimation(completion: @escaping () -> Void) {
guard !isShowing else {
return
}
isShowing = true
UIView.animate(withDuration: duration, animations: {
switch self.position {
case .statusBar:
self.frame.origin.y = 0
case .navigationBar:
self.frame.origin.y = self.navigationBarHeight + self.statusBarHeight
}
self.layoutIfNeeded()
}) { _ in
completion()
}
}
fileprivate func finishAnimating() {
UIView.animate(withDuration: duration, animations: {
switch self.position {
case .statusBar:
self.frame.origin.y = -self.statusBarHeight
case .navigationBar:
self.frame.origin.y = self.navigationBarHeight
}
self.layoutIfNeeded()
}) { _ in
self.isShowing = false
self.containerWindow?.isHidden = true
self.completion?()
}
}
}
// MARK: manage window hierarchy functions
extension BPStatusBarAlert {
fileprivate func adjustViewHierarchy(position: Position) {
switch position {
case .statusBar:
addAlertViewInContainerWindow()
case .navigationBar:
addAlertViewInCurrentWindow()
}
}
fileprivate func addAlertViewInContainerWindow() {
guard let keyWindow = UIApplication.shared.keyWindow else {
return
}
containerWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: keyWindow.frame.width, height: statusBarHeight))
containerWindow?.backgroundColor = UIColor.clear
containerWindow?.windowLevel = UIWindow.Level.statusBar
containerWindow?.rootViewController = UIViewController()
containerWindow?.rootViewController?.view.addSubview(self)
containerWindow?.isHidden = false
}
fileprivate func addAlertViewInCurrentWindow() {
guard let keyWindow = UIApplication.shared.keyWindow else {
return
}
if let rootViewController = keyWindow.rootViewController as? UINavigationController
{
let navigationBar = rootViewController.navigationBar
rootViewController.view.insertSubview(self, belowSubview: navigationBar)
}
else if let rootTabController = keyWindow.rootViewController as? UITabBarController, let rootViewController = rootTabController.selectedViewController as? UINavigationController
{
let navigationBar = rootViewController.navigationBar
rootViewController.view.insertSubview(self, belowSubview: navigationBar)
}
}
}
// MARK: Extensions
fileprivate extension UIColor {
static var bgColor: UIColor {
return UIColor(red: 77/255, green: 188/255, blue: 201/255, alpha: 1)
}
}
| mit | c7ab5fb57f4f6c0ce67673d925452db1 | 30.389908 | 185 | 0.635832 | 5.371272 | false | false | false | false |
benlangmuir/swift | test/DebugInfo/inlined-generics.swift | 30 | 1211 | // RUN: %target-swift-frontend -Xllvm -sil-inline-generics=true %s -O -g -o - -emit-ir | %FileCheck %s
public protocol P {
associatedtype DT1
func getDT() -> DT1
}
@inline(__always)
func foo1<T:P>(_ t: T, _ dt: T.DT1) -> T.DT1 {
var dttmp: T.DT1 = dt
return dttmp
}
// CHECK: define {{.*}}@"$s4main4foo2yyxAA1PRzlF"
public func foo2<S:P>(_ s: S) {
// CHECK: call void @llvm.dbg.value(metadata %swift.type* %S,
// CHECK-SAME: metadata ![[META:[0-9]+]]
foo1(s, s.getDT())
// T should get substituted with S
// CHECK: ![[META]] = !DILocalVariable(name: "$\CF\84_0_0"
}
// More complex example -- we inline an alloc_stack that references a VarDecl
// with generic type.
public protocol Q : class {
associatedtype T : Equatable
var old: T? { get set }
var new: T? { get }
}
@inline(__always)
public func update<S : Q>(_ s: S) -> (S.T?, S.T?)? {
let oldValue = s.old
let newValue = s.new
if oldValue != newValue {
s.old = newValue
return (oldValue, newValue)
} else {
return nil
}
}
public class C : Q {
public typealias T = String
public var old: String? = nil
public var new: T? = nil
}
public func updateC(_ c: C) {
update(c)
}
| apache-2.0 | 0f63a268bcf304ba7295898e5cfbefbe | 21.018182 | 102 | 0.602808 | 2.982759 | false | false | false | false |
scottkawai/sendgrid-swift | Sources/SendGrid/API/V3/Suppression/Global Unsubscribes/RetrieveGlobalUnsubscribes.swift | 1 | 3501 | import Foundation
/// The `RetrieveGlobalUnsubscribes` class represents the API call to [retrieve
/// the global unsubscribe list](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/global_suppressions.html#List-all-globally-unsubscribed-email-addresses-GET).
/// You can use it to retrieve the entire list, or specific entries on the
/// list.
///
/// ## Get All Global Unsubscribes
///
/// To retrieve the list of all global unsubscribes, use the
/// `RetrieveGlobalUnsubscribes` class with the `init(start:end:page:)`
/// initializer. The library will automatically map the response to the
/// `GlobalUnsubscribe` struct model, accessible via the `model` property on
/// the response instance you get back.
///
/// ```swift
/// do {
/// // If you don't specify any parameters, then the first page of your
/// // entire global unsubscribe list will be fetched:
/// let request = RetrieveGlobalUnsubscribes()
/// try Session.shared.send(modeledRequest: request) { result in
/// switch result {
/// case .success(let response, let model):
/// // The `model` property will be an array of `GlobalUnsubscribe` structs.
/// model.forEach { print($0.email) }
///
/// // The response object has a `Pagination` instance on it as well.
/// // You can use this to get the next page, if you wish.
/// if let nextPage = response.pages?.next {
/// let nextRequest = RetrieveGlobalUnsubscribes(page: nextPage)
/// }
/// case .failure(let err):
/// print(err)
/// }
/// }
/// } catch {
/// print(error)
/// }
/// ```
///
/// You can also specify any or all of the init parameters to filter your
/// search down:
///
/// ```swift
/// do {
/// // Retrieve page 2
/// let page = Page(limit: 500, offset: 500)
/// // Global unsubscribes starting from yesterday
/// let now = Date()
/// let start = now.addingTimeInterval(-86400) // 24 hours
///
/// let request = RetrieveGlobalUnsubscribes(start: start, end: now, page: page)
/// try Session.shared.send(modeledRequest: request) { result in
/// switch result {
/// case .success(_, let model):
/// model.forEach { print($0.email) }
/// case .failure(let err):
/// print(err)
/// }
/// }
/// } catch {
/// print(error)
/// }
/// ```
///
/// ## Get Specific Global Unsubscribe
///
/// If you're looking for a specific email address in the global unsubscribe
/// list, you can use the `init(email:)` initializer on
/// `RetrieveGlobalUnsubscribes`:
///
/// ```swift
/// do {
/// let request = RetrieveGlobalUnsubscribes(email: "foo@example")
/// try Session.shared.send(modeledRequest: request) { result in
/// switch result {
/// case .success(_, let model):
/// if let unsub = model.first {
/// print(unsub)
/// }
/// case .failure(let err):
/// print(err)
/// }
/// }
/// } catch {
/// print(error)
/// }
/// ```
public class RetrieveGlobalUnsubscribes: SuppressionListReader<GlobalUnsubscribe> {
/// :nodoc:
internal override init(path: String?, email: String?, start: Date?, end: Date?, page: Page?) {
super.init(
path: "/v3/suppression/unsubscribes",
email: email,
start: start,
end: end,
page: page
)
}
}
| mit | 7848319a178d6aef75b1d832eb1eaaa8 | 34.01 | 184 | 0.587261 | 3.929293 | false | false | false | false |
kishikawakatsumi/TextKitExamples | BulletPoint/BulletPoint/ViewController.swift | 1 | 6338 | //
// ViewController.swift
// BulletPoint
//
// Created by Kishikawa Katsumi on 9/2/16.
// Copyright © 2016 Kishikawa Katsumi. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let textView = UITextView(frame: CGRectInset(view.bounds, 10, 10))
textView.editable = false
textView.textContainerInset = UIEdgeInsetsZero
textView.textContainer.lineFragmentPadding = 0
textView.layoutManager.usesFontLeading = false
view.addSubview(textView)
let headFont = UIFont.boldSystemFontOfSize(20)
let subheadFont = UIFont.boldSystemFontOfSize(16)
let bodyFont = UIFont.systemFontOfSize(12)
let text = try! String(contentsOfFile: NSBundle.mainBundle().pathForResource("List", ofType: "txt")!)
let attributedText = NSMutableAttributedString(string: text)
let image = UIImage(named: "bullet")
let attachment = NSTextAttachment(data: nil, ofType: nil)
attachment.image = image
attachment.bounds = CGRect(x: 0, y: -2, width: bodyFont.pointSize, height: bodyFont.pointSize)
let bulletText = NSAttributedString(attachment: attachment)
attributedText.replaceCharactersInRange(NSRange(location: 350, length: 1), withAttributedString: bulletText)
attributedText.replaceCharactersInRange(NSRange(location: 502, length: 1), withAttributedString: bulletText)
attributedText.replaceCharactersInRange(NSRange(location: 617, length: 1), withAttributedString: bulletText)
attributedText.replaceCharactersInRange(NSRange(location: 650, length: 1), withAttributedString: bulletText)
do {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = ceil(headFont.lineHeight)
paragraphStyle.maximumLineHeight = ceil(headFont.lineHeight)
paragraphStyle.paragraphSpacing = ceil(headFont.pointSize / 2)
let attributes = [
NSFontAttributeName: headFont,
NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0),
NSParagraphStyleAttributeName: paragraphStyle,
]
attributedText.addAttributes(attributes, range: NSRange(location: 0, length: 33))
}
do {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = ceil(subheadFont.lineHeight)
paragraphStyle.maximumLineHeight = ceil(subheadFont.lineHeight)
paragraphStyle.paragraphSpacing = ceil(subheadFont.lineHeight / 2)
let attributes = [
NSFontAttributeName: subheadFont,
NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0),
NSParagraphStyleAttributeName: paragraphStyle,
]
attributedText.addAttributes(attributes, range: NSRange(location: 34, length: 20))
}
do {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = ceil(bodyFont.lineHeight)
paragraphStyle.maximumLineHeight = ceil(bodyFont.lineHeight)
paragraphStyle.lineSpacing = 2
paragraphStyle.paragraphSpacing = ceil(bodyFont.lineHeight / 2)
paragraphStyle.alignment = .Justified
let attributes = [
NSFontAttributeName: bodyFont,
NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0),
NSParagraphStyleAttributeName: paragraphStyle,
]
attributedText.addAttributes(attributes, range: NSRange(location: 55, length: 275))
}
do {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = ceil(subheadFont.lineHeight)
paragraphStyle.maximumLineHeight = ceil(subheadFont.lineHeight)
paragraphStyle.paragraphSpacing = ceil(subheadFont.lineHeight / 2)
let attributes = [
NSFontAttributeName: subheadFont,
NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0),
NSParagraphStyleAttributeName: paragraphStyle,
]
attributedText.addAttributes(attributes, range: NSRange(location: 330, length: 19))
}
do {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = ceil(bodyFont.lineHeight)
paragraphStyle.maximumLineHeight = ceil(bodyFont.lineHeight)
paragraphStyle.lineSpacing = 2
paragraphStyle.paragraphSpacing = ceil(bodyFont.lineHeight / 2)
paragraphStyle.headIndent = bodyFont.pointSize * 2
paragraphStyle.alignment = .Justified
paragraphStyle.tabStops = []
paragraphStyle.defaultTabInterval = bodyFont.pointSize * 2
let attributes = [
NSFontAttributeName: bodyFont,
NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0),
NSParagraphStyleAttributeName: paragraphStyle,
]
attributedText.addAttributes(attributes, range: NSRange(location: 350, length: 472))
}
do {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = ceil(bodyFont.lineHeight)
paragraphStyle.maximumLineHeight = ceil(bodyFont.lineHeight)
paragraphStyle.lineSpacing = 2
paragraphStyle.paragraphSpacing = ceil(bodyFont.lineHeight / 2)
paragraphStyle.alignment = .Justified
let attributes = [
NSFontAttributeName: bodyFont,
NSForegroundColorAttributeName: UIColor(red: 0.22, green: 0.28, blue: 0.50, alpha: 1.0),
NSParagraphStyleAttributeName: paragraphStyle,
]
attributedText.addAttributes(attributes, range: NSRange(location: 822, length: 126))
}
textView.attributedText = attributedText
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | ede5b227282d87cc06423c511dba1fd7 | 40.149351 | 116 | 0.652517 | 5.678315 | false | false | false | false |
gregomni/swift | benchmark/single-source/AngryPhonebook.swift | 10 | 5448 | //===--- AngryPhonebook.swift ---------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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
//
//===----------------------------------------------------------------------===//
// This test is based on single-source/Phonebook, with
// to test uppercase and lowercase ASCII string fast paths.
import TestsUtils
let t: [BenchmarkCategory] = [.validation, .api, .String]
public let benchmarks = [
BenchmarkInfo(
name: "AngryPhonebook",
runFunction: run_AngryPhonebook,
tags: t,
legacyFactor: 7),
// Small String Workloads
BenchmarkInfo(
name: "AngryPhonebook.ASCII2.Small",
runFunction: { angryPhonebook($0*10, ascii) },
tags: t,
setUpFunction: { blackHole(ascii) }),
BenchmarkInfo(
name: "AngryPhonebook.Strasse.Small",
runFunction: { angryPhonebook($0, strasse) },
tags: t,
setUpFunction: { blackHole(strasse) }),
BenchmarkInfo(
name: "AngryPhonebook.Armenian.Small",
runFunction: { angryPhonebook($0, armenian) },
tags: t,
setUpFunction: { blackHole(armenian) }),
BenchmarkInfo(
name: "AngryPhonebook.Cyrillic.Small",
runFunction: { angryPhonebook($0, cyrillic) },
tags: t,
setUpFunction: { blackHole(cyrillic) }),
// Regular String Workloads
BenchmarkInfo(
name: "AngryPhonebook.ASCII2",
runFunction: { angryPhonebook($0*10, precomposed: longASCII) },
tags: t,
setUpFunction: { blackHole(longASCII) }),
BenchmarkInfo(
name: "AngryPhonebook.Strasse",
runFunction: { angryPhonebook($0, precomposed: longStrasse) },
tags: t,
setUpFunction: { blackHole(longStrasse) }),
BenchmarkInfo(
name: "AngryPhonebook.Armenian",
runFunction: { angryPhonebook($0, precomposed: longArmenian) },
tags: t,
setUpFunction: { blackHole(longArmenian) }),
BenchmarkInfo(
name: "AngryPhonebook.Cyrillic",
runFunction: { angryPhonebook($0, precomposed: longCyrillic) },
tags: t,
setUpFunction: { blackHole(longCyrillic) })
]
let words = [
"James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph",
"Charles", "Thomas", "Christopher", "Daniel", "Matthew", "Donald", "Anthony",
"Paul", "Mark", "George", "Steven", "Kenneth", "Andrew", "Edward", "Brian",
"Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Gary", "Ryan",
"Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Frank"]
@inline(never)
public func run_AngryPhonebook(_ n: Int) {
// Permute the names.
for _ in 1...n {
for firstname in words {
for lastname in words {
_ = (firstname.uppercased(), lastname.lowercased())
}
}
}
}
// Workloads for various scripts. Always 20 names for 400 pairings.
// To keep the performance of various scripts roughly comparable, aim for
// a total length of approximately 120 characters.
// E.g.: `ascii.joined(separator: "").count == 124`
// Every name should fit in 15-bytes UTF-8 encoded, to excercise the small
// string optimization.
// E.g.: `armenian.allSatisfy { $0._guts.isSmall } == true`
// Workload Size Statistics
// SMALL | UTF-8 | UTF-16 | REGULAR | UTF-8 | UTF-16
// ---------|-------|--------|--------------|---------|--------
// ascii | 124 B | 248 B | longASCII | 6158 B | 12316 B
// strasse | 140 B | 240 B | longStrasse | 6798 B | 11996 B
// armenian | 232 B | 232 B | longArmenian | 10478 B | 11676 B
// cyrillic | 238 B | 238 B | longCyrillic | 10718 B | 11916 B
let ascii = Array(words.prefix(20))
// Pathological case, uppercase: ß -> SS
let strasse = Array(repeating: "Straße", count: 20)
let armenian = [
"Արմեն", "Աննա", "Հարութ", "Միքայել", "Մարիա", "Դավիթ", "Վարդան",
"Նարինե", "Տիգրան", "Տաթևիկ", "Թագուհի", "Թամարա", "Ազնաուր", "Գրիգոր",
"Կոմիտաս", "Հայկ", "Գառնիկ", "Վահրամ", "Վահագն", "Գևորգ"]
let cyrillic = [
"Ульяна", "Аркадий", "Аня", "Даниил", "Дмитрий", "Эдуард", "Юрій", "Давид",
"Анна", "Дмитрий", "Евгений", "Борис", "Ксения", "Артур", "Аполлон",
"Соломон", "Николай", "Кристи", "Надежда", "Спартак"]
/// Precompose the phonebook into one large string of comma separated names.
func phonebook(_ names: [String]) -> String {
names.map { firstName in
names.map { lastName in
firstName + " " + lastName
}.joined(separator: ", ")
}.joined(separator: ", ")
}
let longASCII = phonebook(ascii)
let longStrasse = phonebook(strasse)
let longArmenian = phonebook(armenian)
let longCyrillic = phonebook(cyrillic)
@inline(never)
public func angryPhonebook(_ n: Int, _ names: [String]) {
assert(names.count == 20)
// Permute the names.
for _ in 1...n {
for firstname in names {
for lastname in names {
blackHole((firstname.uppercased(), lastname.lowercased()))
}
}
}
}
@inline(never)
public func angryPhonebook(_ n: Int, precomposed names: String) {
for _ in 1...n {
blackHole((names.uppercased(), names.lowercased()))
}
}
| apache-2.0 | a74d23e0a9ee519160beea141e91c6b7 | 33.282895 | 80 | 0.631932 | 3.024376 | false | false | false | false |
noppoMan/Skelton | Sources/SkeltonPerformance/main.swift | 1 | 1278 | import Skelton
import Foundation
func observeWorker(_ worker: Worker){
worker.send(.message("message from master"))
worker.onEvent { event in
if case .message(let str) = event {
print(str)
}
else if case .online = event {
print("Worker: \(worker.id) is online")
}
else if case .exit(let status) = event {
print("Worker: \(worker.id) is dead. status: \(status)")
let worker = try! Cluster.fork(silent: false)
observeWorker(worker)
}
}
}
if Cluster.isMaster {
for _ in 0..<ProcessInfo.cpus().count {
var worker = try! Cluster.fork(silent: false)
observeWorker(worker)
}
let server = Skelton()
try! server.bind(host: "0.0.0.0", port: 8888)
try! server.listen()
} else {
let server = Skelton() { result in
switch result {
case .onRequest(let request, let stream):
ResponseSerializer(stream: stream).serialize(Response(body: "Welecom to Slimane!".data)) { _ in
stream.close()
}
case .onError(let error):
print(error)
default:
break
}
}
print("listening: \(Process.pid)")
try! server.listen()
}
| mit | b87b065e512b0b5eb2f6ef87c1c2e23a | 24.058824 | 107 | 0.549296 | 4.018868 | false | false | false | false |
minimoog/MetalToy | MetalToy/CodeViewController.swift | 1 | 13228 | //
// ViewController.swift
// MetalToy
//
// Created by Toni Jovanoski on 8/20/17.
// Copyright © 2017 Toni Jovanoski. All rights reserved.
//
import UIKit
let GutterWidth: CGFloat = 22.0
enum KeywordState {
case entering, other
}
extension String {
func isAlphaNumeric() -> Bool {
return rangeOfCharacter(from: CharacterSet.alphanumerics.inverted) == nil && self != ""
}
}
class CodeViewController: UIViewController, UITextViewDelegate {
var document: ShaderDocument?
var codeView: UITextView?
var previousBarItems: [UIBarButtonItem] = []
var undoBarItem: UIBarButtonItem?
var redoBarItem: UIBarButtonItem?
let textStorage = CodeAttributedString()
let inputAssistantView: InputAssistantView = InputAssistantView()
var messageButtons = [CompilerMessageButton]()
var bottomConstraint: NSLayoutConstraint?
let allSuggestions = SuggestionList
let fixedSuggestion = ["[ ]", "{ }"]
var matchedSuggestions: [String] = []
var keywordBuffer: String = String()
var suggestionKeyWordState: KeywordState = .other
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textStorage.language = "cpp"
if traitCollection.userInterfaceStyle == .dark {
textStorage.highlightr.setTheme(to: "qtcreator_dark")
} else {
textStorage.highlightr.setTheme(to: "qtcreator_light")
}
textStorage.highlightr.theme.setCodeFont(UIFont(name: "Menlo-Regular", size: 16)!)
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: view.bounds.size)
layoutManager.addTextContainer(textContainer)
codeView = UITextView(frame: view.frame, textContainer: textContainer)
view.addSubview(codeView!)
codeView?.autoresizingMask = [.flexibleHeight, .flexibleWidth]
codeView?.autocorrectionType = .no
codeView?.autocapitalizationType = .none
codeView?.text = DefaultComputeShader
codeView?.translatesAutoresizingMaskIntoConstraints = false
codeView?.textContainerInset = UIEdgeInsets(top: 10, left: GutterWidth, bottom: 8, right: 0)
codeView?.backgroundColor = UIColor.systemBackground
//constraints
codeView?.widthAnchor.constraint(equalTo: view.safeAreaLayoutGuide.widthAnchor).isActive = true
codeView?.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
codeView?.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
//codeView delegate
codeView?.delegate = self
bottomConstraint = view.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: codeView!.bottomAnchor)
bottomConstraint?.isActive = true
//keyboard
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown), name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: UIResponder.keyboardWillHideNotification, object: nil)
//input assistant view
inputAssistantView.delegate = self
inputAssistantView.dataSource = self
inputAssistantView.attach(to: codeView!)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//install undo/redo buttons
undoBarItem = UIBarButtonItem(image: UIImage(systemName: "arrow.uturn.left.circle"),
style: .plain,
target: self,
action: #selector(self.onUndoButtonTapped))
redoBarItem = UIBarButtonItem(image: UIImage(systemName: "arrow.uturn.right.circle"),
style: .plain,
target: self,
action: #selector(self.onRedoButtonTapped))
if let parent = parent, let leftBarItems = parent.navigationItem.leftBarButtonItems {
previousBarItems = leftBarItems
parent.navigationItem.leftBarButtonItems = previousBarItems + [undoBarItem!, redoBarItem!]
}
guard let doc = document else { fatalError("document is null") }
codeView?.text = doc.shaderInfo?.fragment
updateUndoButtons()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
//remove undo/redo buttons
if let parent = parent {
parent.navigationItem.leftBarButtonItems = previousBarItems
}
guard let doc = document else { fatalError("document is null") }
doc.close { [weak self] (success) in
guard success else { fatalError("failed closing the document") }
print("Success closing the document")
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle {
if traitCollection.userInterfaceStyle == .dark {
textStorage.highlightr.setTheme(to: "qtcreator_dark")
textStorage.highlightr.theme.setCodeFont(UIFont(name: "Menlo-Regular", size: 16)!) //yeah sets need to be set again
} else {
textStorage.highlightr.setTheme(to: "qtcreator_light")
textStorage.highlightr.theme.setCodeFont(UIFont(name: "Menlo-Regular", size: 16)!)
}
}
}
@objc func keyboardWasShown(notification: NSNotification) {
let info = notification.userInfo!
let keyboardFrame: CGRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
//self.view.layoutIfNeeded()
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.bottomConstraint?.constant = keyboardFrame.size.height
self.view.layoutIfNeeded()
})
}
@objc func keyboardWillBeHidden(notification: NSNotification) {
//self.view.layoutIfNeeded()
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.bottomConstraint?.constant = 0
self.view.layoutIfNeeded()
})
}
@objc func keyboardNotification(notification: NSNotification) {
}
@objc func onUndoButtonTapped(sender: UIBarButtonItem) {
codeView?.undoManager?.undo()
updateUndoButtons()
}
@objc func onRedoButtonTapped(sender: UIBarButtonItem) {
codeView?.undoManager?.redo()
updateUndoButtons()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent // .default
}
func setTexture(filename: String, index: Int) {
guard let doc = document else { fatalError("No document set") }
//convert from full filename to texture name ### needs rework
let urlPath = URL(fileURLWithPath: filename)
let textureName = urlPath.lastPathComponent
doc.shaderInfo?.textures[index] = textureName
doc.updateChangeCount(.done)
}
func updateUndoButtons() {
undoBarItem?.isEnabled = codeView?.undoManager?.canUndo ?? false
redoBarItem?.isEnabled = codeView?.undoManager?.canRedo ?? false
}
// MARK: - UITextViewDelegate
func textViewDidChange(_ textView: UITextView) {
guard let doc = document else { fatalError("No document set") }
doc.shaderInfo?.fragment = textView.text
doc.updateChangeCount(.done)
updateUndoButtons()
}
func textViewDidEndEditing(_ textView: UITextView) {
guard let doc = document else { fatalError("No document set") }
doc.shaderInfo?.fragment = textView.text
doc.updateChangeCount(.done)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
matchedSuggestions = []
if range.length == 1 { //delete
//remove character from keyword buffer
if !keywordBuffer.isEmpty {
keywordBuffer.removeLast()
}
} else {
if text.isAlphaNumeric() {
suggestionKeyWordState = .entering
keywordBuffer.append(text)
matchedSuggestions = allSuggestions.filter { $0.hasPrefix(keywordBuffer) }
} else {
suggestionKeyWordState = .other
keywordBuffer = String()
}
}
//matchedSuggestions.append(contentsOf: fixedSuggestion)
inputAssistantView.reloadData()
return true
}
// MARK: private functions
func linePosition(inString: String, lastOccurence: Int) -> String.Index? {
let splitted = inString.split(separator: "\n", maxSplits: Int.max, omittingEmptySubsequences: false)
if lastOccurence > splitted.count - 1 {
return nil
} else {
return splitted[lastOccurence].startIndex
}
}
func pointForMessage(lineNumber: Int, columnNumber: Int) -> CGPoint? {
let rangeOfPrecedingNewLine: Int
let lineNumberPlusOffset = lineNumber - 1
if let indexPos = linePosition(inString: codeView!.text, lastOccurence: lineNumberPlusOffset) {
//rangeOfPrecedingNewLine = indexPos.encodedOffset
rangeOfPrecedingNewLine = indexPos.utf16Offset(in: codeView!.text)
} else {
rangeOfPrecedingNewLine = 0
}
let offendingCharacterIndex = rangeOfPrecedingNewLine + columnNumber
guard let beginningOfDocument = codeView?.beginningOfDocument else { return nil }
guard let errorStartPosition = codeView?.position(from: beginningOfDocument, offset: offendingCharacterIndex) else { return nil }
guard let errorStartPositionPlusOne = codeView?.position(from: errorStartPosition, offset: 1) else { return nil }
guard let textRangeForError = codeView?.textRange(from: errorStartPosition, to: errorStartPositionPlusOne) else { return nil }
guard let offendingCharacterREct = codeView?.firstRect(for: textRangeForError) else { return nil }
let y = floor(offendingCharacterREct.midY - ButtonSize * 0.5)
return CGPoint(x: 5, y: y)
}
func updateViewWithPoints(messages: [CompilerErrorMessage]) {
messageButtons.forEach { $0.removeFromSuperview() }
messageButtons = []
for message in messages {
guard let buttonOrigin = pointForMessage(lineNumber: message.lineNumber, columnNumber: message.columnNumber) else { continue }
let buttonRect = CGRect(x: buttonOrigin.x, y: buttonOrigin.y,width: CGFloat(ButtonSize), height: CGFloat(ButtonSize))
let button = CompilerMessageButton(frame: buttonRect, rootViewController: self)
button.message = message.message
codeView?.addSubview(button)
messageButtons.append(button)
}
}
func removePoints() {
messageButtons.forEach {
$0.removeFromSuperview()
}
messageButtons.removeAll()
}
}
extension CodeViewController: InputAssistantViewDataSource {
func textForEmptySuggestionsInInputAssistantView() -> String? {
return nil
}
func numberOfSuggestionsInInputAssistantView() -> Int {
return matchedSuggestions.count + fixedSuggestion.count
}
func inputAssistantView(_ inputAssistantView: InputAssistantView, nameForSuggestionAtIndex index: Int) -> String {
return (matchedSuggestions + fixedSuggestion)[index]
}
}
extension CodeViewController: InputAssistantViewDelegate {
func inputAssistantView(_ inputAssistantView: InputAssistantView, didSelectSuggestionAtIndex index: Int) {
if index < (matchedSuggestions.endIndex - fixedSuggestion.count) {
let lengthOfMatched = matchedSuggestions[index].count
let textToInsert = matchedSuggestions[index].suffix(lengthOfMatched - keywordBuffer.count)
self.codeView!.insertText(String(textToInsert))
} else {
self.codeView!.insertText(matchedSuggestions[index])
}
}
}
| mit | 1f102606be12acb34fc3f699db8dba1f | 36.791429 | 156 | 0.634989 | 5.486105 | false | false | false | false |
k0nserv/SwiftTracer-Core | Sources/Misc/Intersection.swift | 1 | 762 | //
// Intersection.swift
// SwiftTracer
//
// Created by Hugo Tunius on 09/08/15.
// Copyright © 2015 Hugo Tunius. All rights reserved.
//
public struct Intersection {
public let t: Double
public let point: Vector
public let normal: Vector
public let shape: Shape
// Wether or not the hit is
// from inside the shape itself
public let inside: Bool
init (t: Double, point: Vector, normal: Vector, shape: Shape) {
self.init(t: t, point: point, normal: normal, shape: shape, inside: false)
}
init(t: Double, point: Vector, normal: Vector, shape: Shape, inside: Bool) {
self.t = t
self.point = point
self.normal = normal
self.shape = shape
self.inside = inside
}
}
| mit | 7dc8277b240b59ec37f3a04d386e59fa | 24.366667 | 82 | 0.622865 | 3.748768 | false | false | false | false |
danielsaidi/KeyboardKit | UIKit/Demo/KeyboardKitDemoKeyboard/Keyboards/HFloatingHeaderButtonCollectionView.swift | 1 | 8834 | //
// HFloatingHeaderButtonCollectionView.swift
// KeyboardKitDemoKeyboard
//
// Created by 于留传 on 2021/1/16.
//
import KeyboardKit
import UIKit
open class HFloatingHeaderButtonCollectionView: UIKeyboardCollectionView, HorizontalFloatingHeaderLayoutDelegate, UICollectionViewDelegate {
// MARK: - Initialization
public init(
id: String = "HFloatingHeaderButtonCollectionView",
categoryActions: [(String, KeyboardActions)],
configuration: Configuration,
buttonCreator: @escaping KeyboardButtonCreator){
self.id = id
self.categoryActions = categoryActions
self.categorySectionAction = Self.createCategorySectionAction(for: categoryActions)
self.configuration = configuration
self.buttonCreator = buttonCreator
super.init(actions: []) // Unused
setup()
}
public required init?(coder aDecoder: NSCoder) {
self.id = ""
self.categoryActions = []
self.categorySectionAction = []
self.configuration = .empty
self.buttonCreator = { _ in fatalError() }
super.init(coder: aDecoder)
setup()
}
// MARK: - Setup
func setup(){
dataSource = self
delegate = self
height = configuration.totalHeight
collectionViewLayout = HorizontalFloatingHeaderLayout()
register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)
}
// MARK: - Types
public typealias KeyboardButtonCreator = (KeyboardAction) -> (UIView)
public struct Configuration {
public init(headerSize: CGSize, itemSize: CGSize, rowsCount: Int, titleColor: UIColor?, titleFont: UIFont?,
headerWidthToFitText: Bool?, itemFont: UIFont?, itemWidthToFitText: Bool?, edgeInsets: UIEdgeInsets?){
self.headerSize = headerSize
self.itemSize = itemSize
self.rowsCount = rowsCount
self.titleColor = titleColor ?? UIColor(white: 0.6, alpha: 1.0)
self.titleFont = titleFont ?? UIFont.boldSystemFont(ofSize: UIFont.labelFontSize)
self.headerWidthToFitText = headerWidthToFitText ?? false
self.itemFont = itemFont ?? UIFont.boldSystemFont(ofSize: UIFont.labelFontSize)
self.itemWidthToFitText = itemWidthToFitText ?? false
self.edgeInsets = edgeInsets ?? UIEdgeInsets.zero
}
public let edgeInsets: UIEdgeInsets
public let itemWidthToFitText: Bool
public let itemFont: UIFont
public let headerWidthToFitText: Bool
public let titleColor: UIColor
public let titleFont: UIFont
public let headerSize: CGSize
public let itemSize: CGSize
public let rowsCount: Int
private let padding: CGFloat = 10
public var totalHeight: CGFloat {
headerSize.height + itemSize.height * CGFloat(rowsCount) + padding * 2
}
public static var empty: Configuration {
Configuration(headerSize: .zero, itemSize: .zero, rowsCount: 0, titleColor: nil, titleFont: nil, headerWidthToFitText: false, itemFont: nil, itemWidthToFitText: false, edgeInsets: .zero)
}
}
// MARK: - Properties
public let headerIdentifier = "Header"
public let id: String
public let configuration: Configuration
public let categoryActions: [(String, KeyboardActions)]
private let categorySectionAction: [(String, Int, Int)]
private let buttonCreator: KeyboardButtonCreator
// MARK: - Category
static func createCategorySectionAction(for categoryActions: [(String, KeyboardActions)]) -> [(String, Int, Int)] {
categoryActions.enumerated().map { (index: Int, arg1) -> (String, Int, Int) in
let (cat, actions) = arg1
return (cat, index, actions.count)
}
}
// MARK: - UICollectionViewDataSource
// Number of Sections
open override func numberOfSections(in collectionView: UICollectionView) -> Int {
self.categorySectionAction.count
}
// Number of Items
open override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let index = self.categorySectionAction.first(where: { $0.1 == section }) else { return 0 }
return index.2
}
// Cells
open override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = super.collectionView(collectionView, cellForItemAt: indexPath)
cell.subviews.forEach { $0.removeFromSuperview() }
let action = self.categoryActions[indexPath.section].1[indexPath.item]
cell.addSubview(self.buttonCreator(action), fill: true)
return cell
}
// Headers
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath)
cell.subviews.forEach { $0.removeFromSuperview() }
let titleLabel = UILabel()
titleLabel.text = self.categoryActions[indexPath.section].0
titleLabel.textColor = configuration.titleColor
titleLabel.font = configuration.titleFont
cell.addSubview(titleLabel, fill: true)
return cell
}
// MARK: - HorizontalFloatingHeaderDelegate
// Item Size
public func collectionView(_ collectionView: UICollectionView, horizontalFloatingHeaderItemSizeAt indexPath: IndexPath) -> CGSize {
if !configuration.itemWidthToFitText{
return configuration.itemSize
}
// Dynamic Item Width
let actionText: String? = {
let action = self.categoryActions[indexPath.section].1[indexPath.item]
switch action {
case .character(let text): return text
default:
return nil
}
}()
if let text = actionText{
let size = self.sizeToFitText(text: text, font: configuration.itemFont)
let width = size.width + configuration.edgeInsets.left + configuration.edgeInsets.right
return CGSize(width: width, height: configuration.itemSize.height)
}else{
// Use default size
return configuration.itemSize
}
}
// Header Size
public func collectionView(_ collectionView: UICollectionView, horizontalFloatingHeaderSizeAt section: Int) -> CGSize {
if configuration.headerWidthToFitText{
let headerText:String = self.categoryActions[section].0
let size:CGSize = self.sizeToFitText(text: headerText, font: configuration.titleFont)
// `width + 1` to fix bugs, like 'FLAGS --> FLA...'
return CGSize(width: size.width + 1, height: configuration.headerSize.height)
}else{
return configuration.headerSize
}
}
// Vertial Spacing: Spacing Between Vertial Items
public func collectionView(_ collectionView: UICollectionView, horizontalFloatingHeaderItemSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
// Horizontal Spacing: Spacing Between Horizontal Items
public func collectionView(_ collectionView: UICollectionView, horizontalFloatingHeaderColumnSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
// Section Insets
public func collectionView(_ collectionView: UICollectionView, horizontalFloatingHeaderSectionInsetAt section: Int) -> UIEdgeInsets {
switch section{
case 0:
return UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0)
default:
return UIEdgeInsets(top: 8, left: 8, bottom: 0, right: 0)
}
}
// MARK: - Size Function
private func sizeToFitText(text: String, font: UIFont) -> CGSize{
return text.size(withAttributes: [.font: font])
}
}
public extension HFloatingHeaderButtonCollectionView{
@objc func moveToSection(bySection section: Int){
guard section <= self.categorySectionAction.count else { return }
self.scrollToItem(at: IndexPath(item: 0, section: section), at: .left, animated: true)
}
@objc func moveToSection(byCategory category: String){
guard let index = self.categorySectionAction.first(where: { $0.0 == category }) else { return }
self.moveToSection(bySection: index.1)
}
}
| mit | bf239fe2b359870fd8024810c415b3dd | 37.719298 | 198 | 0.656434 | 5.177713 | false | true | false | false |
904388172/-TV | DouYuTV/DouYuTV/Classes/Home/Controller/HomeViewController.swift | 1 | 4372 | //
// HomeViewController.swift
// DouYuTV
//
// Created by GS on 2017/10/19.
// Copyright © 2017年 Demo. All rights reserved.
//
import UIKit
private let kTitleViewH: CGFloat = 40
class HomeViewController: UIViewController {
let titles = ["推荐","游戏","娱乐","趣玩"]
//MARK: - 懒记载属性(闭包的形式)
private lazy var pageTitleView: PageTitleView = {
[weak self] in
let titleFrame = CGRect(x: 0, y: kStatebarH + kNavigationBarH, width: kScreenW, height: kTitleViewH)
let titleView = PageTitleView(frame: titleFrame, titles: titles)
titleView.delegate = self
return titleView
}()
//MARK: - 懒记载
private lazy var pageContentView: PageContentView = {
[weak self] in
let contentH = kScreenH - kStatebarH - kNavigationBarH - kTitleViewH - kTabbarH
let contentFrame = CGRect(x: 0, y: kStatebarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH)
//确定所有的子控件
var childVcs = [UIViewController]()
//将创建的控制器加到控制器数组中
childVcs.append(RecommendViewController())
childVcs.append(GameViewController())
childVcs.append(AmuseViewController())
childVcs.append(FunnyViewController())
//随机设置颜色
for _ in 0..<(titles.count - childVcs.count) {
let vc = UIViewController()
vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
childVcs.append(vc)
}
let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self)
contentView.delegate = self
return contentView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
//设置UI界面
setUpUI()
}
}
// MARK: - 设置UI界面
extension HomeViewController {
private func setUpUI() {
//1.不需要调整UIScrollView的内边距
automaticallyAdjustsScrollViewInsets = false
//2.设置导航栏
setupNavigationBar()
//3.添加titleView
view.addSubview(pageTitleView)
//4.添加ContentView
view.addSubview(pageContentView)
pageContentView.backgroundColor = UIColor.purple
}
private func setupNavigationBar() {
//左边按钮
//调用自己封装的构造方法创建UIBarButtonItem
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
//设置右边的items
let size = CGSize(width: 40, height: 40)
/*
//类方法封装
let historyItem = UIBarButtonItem.createItem(imageName:"image_my_history", highImageName: "Image_my_history_click", size: size)
let searchItem = UIBarButtonItem.createItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size)
let qrcodeItem = UIBarButtonItem.createItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size)
*/
//构造函数方法封装
let historyItem = UIBarButtonItem(imageName:"image_my_history", highImageName: "Image_my_history_click", size: size)
let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size)
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size)
navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem]
}
}
//MARK: - 遵守PageTitleViewDelegate协议
extension HomeViewController: PageTitleViewDelegate {
func pageTitleView(titelView: PageTitleView, selextedIndex index: Int) {
pageContentView.setCurrentIndex(currentIndex: index)
}
}
//MARK: - 遵守PageTContentViewDelegate协议
extension HomeViewController: PageContentViewDelegate {
func pageContentView(cintentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
| mit | a99ed03d27e2934a2154c14f1bdbba93 | 33.714286 | 156 | 0.652869 | 4.882979 | false | false | false | false |
Royal-J/TestKitchen1607 | TestKitchen1607/TestKitchen1607/classes/ingredient(食材)/recommend(推荐)/FoodCourse食材课程/model/FoodCourseComment.swift | 1 | 3122 | //
// FoodCourseComment.swift
// TestKitchen1607
//
// Created by HJY on 2016/11/4.
// Copyright © 2016年 HJY. All rights reserved.
//
import UIKit
import SwiftyJSON
class FoodCourseComment: NSObject {
var code: String?
var data: FoodCourseCommentData?
var msg: String?
var timestamp: NSNumber?
var version: String?
class func parseData(data: NSData) -> FoodCourseComment {
let json = JSON(data: data)
let model = FoodCourseComment()
model.code = json["code"].string
model.data = FoodCourseCommentData.parse(json["data"])
model.msg = json["msg"].string
model.timestamp = json["timestamp"].number
model.version = json["version"].string
return model
}
}
class FoodCourseCommentData: NSObject {
var count: String?
var data: Array<FoodCourseCommentDetail>?
var page: String?
var size: String?
var total: String?
class func parse(json: JSON) -> FoodCourseCommentData {
let model = FoodCourseCommentData()
model.count = json["count"].string
var array = Array<FoodCourseCommentDetail>()
for (_,subjson) in json["data"] {
let detail = FoodCourseCommentDetail.parse(subjson)
array.append(detail)
}
model.data = array
model.page = json["page"].string
model.size = json["size"].string
model.total = json["total"].string
return model
}
}
class FoodCourseCommentDetail: NSObject {
/*
"content" : "我觉得嫩豆腐比北豆腐更适合一些",
"create_time" : "10月22日",
"head_img" : "http://q.qlogo.cn/qqapp/100956582/A4C8D71FA25B90742D10725FEC112CB4/100",
"id" : "88317",
"istalent" : 0,
"nick" : "野渡无人有面就好",
"parent_id" : "0",
"parents" : [],
"relate_id" : "118",
"type" : "2",
"user_id" : "1736506"
*/
var content: String?
var create_time: String?
var head_img: String?
var id: String?
var istalent: NSNumber?
var nick: String?
var parent_id: String?
var parents: Array<FoodCourseCommentDetail>?
var relate_id: String?
var type: String?
var user_id: String?
class func parse(json: JSON) -> FoodCourseCommentDetail {
let model = FoodCourseCommentDetail()
model.content = json["content"].string
model.create_time = json["create_time"].string
model.head_img = json["head_img"].string
model.id = json["id"].string
model.istalent = json[""].number
model.nick = json["nick"].string
model.parent_id = json["parent_id"].string
var array = Array<FoodCourseCommentDetail>()
for (_,subjson) in json["parents"] {
let pModel = FoodCourseCommentDetail.parse(subjson)
array.append(pModel)
}
model.parents = array
model.relate_id = json["relate_id"].string
model.type = json["type"].string
model.user_id = json["user_id"].string
return model
}
} | mit | 44d956faeb26fbb31784bd9abd36bbfe | 25.239316 | 87 | 0.594005 | 3.812422 | false | false | false | false |
wusuowei/WTCarouselFlowLayout | Example/WTCarouselFlowLayout/MovieModel.swift | 1 | 830 | //
// MovieModel.swift
// WTCarouselFlowLayout
//
// Created by 温天恩 on 2017/8/31.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import UIKit
class MovieModel: NSObject {
@objc var title = ""
@objc var imageName = ""
@objc var detail = ""
@objc class func movieModels() -> [MovieModel] {
var models = [MovieModel]()
for i in 0...6 {
let model = MovieModel()
model.title = "第\(i)部电影"
model.imageName = "\(i).jpeg"
model.detail = "第\(i)部电影是一部很精彩的电影, 讲述了一个脑残和另外一个脑残一起打败一帮脑残的故事。。。☺\n故事的经过曲折离奇,扣人心弦。。。\n故事的结局。。。"
models.append(model)
}
return models
}
}
| mit | 91703bd32521fead7f21c0d423015efc | 24.074074 | 106 | 0.565731 | 2.820833 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Models/PXSplitPaymentMethod.swift | 1 | 3037 | import Foundation
/// :nodoc:
open class PXSplitPaymentMethod: NSObject, Codable {
open var amount: Double = 0
open var id: String = ""
open var discount: PXDiscount?
open var message: String?
open var selectedPayerCostIndex: Int?
open var payerCosts: [PXPayerCost]?
open var selectedPayerCost: PXPayerCost? {
if let remotePayerCosts = payerCosts, let selectedIndex = selectedPayerCostIndex, remotePayerCosts.indices.contains(selectedIndex) {
return remotePayerCosts[selectedIndex]
}
return nil
}
init(amount: Double, id: String, discount: PXDiscount?, message: String?, selectedPayerCostIndex: Int?, payerCosts: [PXPayerCost]?) {
self.amount = amount
self.id = id
self.discount = discount
self.message = message
self.selectedPayerCostIndex = selectedPayerCostIndex
self.payerCosts = payerCosts
}
public enum PXPayerCostConfiguration: String, CodingKey {
case amount = "amount"
case id = "id"
case discount = "discount"
case message = "message"
case selectedPayerCostIndex = "selected_payer_cost_index"
case payerCosts = "payer_costs"
}
public required convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: PXPayerCostConfiguration.self)
let amount: Double = try container.decodeIfPresent(Double.self, forKey: .amount) ?? 0
let id: String = try container.decodeIfPresent(String.self, forKey: .id) ?? ""
let discount: PXDiscount? = try container.decodeIfPresent(PXDiscount.self, forKey: .discount)
let message: String? = try container.decodeIfPresent(String.self, forKey: .message)
let selectedPayerCostIndex: Int? = try container.decodeIfPresent(Int.self, forKey: .selectedPayerCostIndex)
let payerCosts: [PXPayerCost]? = try container.decodeIfPresent([PXPayerCost].self, forKey: .payerCosts)
self.init(amount: amount, id: id, discount: discount, message: message, selectedPayerCostIndex: selectedPayerCostIndex, payerCosts: payerCosts)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: PXPayerCostConfiguration.self)
try container.encodeIfPresent(self.id, forKey: .id)
try container.encodeIfPresent(self.amount, forKey: .amount)
try container.encodeIfPresent(self.message, forKey: .message)
try container.encodeIfPresent(self.discount, forKey: .discount)
try container.encodeIfPresent(self.selectedPayerCostIndex, forKey: .selectedPayerCostIndex)
try container.encodeIfPresent(self.payerCosts, forKey: .payerCosts)
}
open func toJSONString() throws -> String? {
let encoder = JSONEncoder()
let data = try encoder.encode(self)
return String(data: data, encoding: .utf8)
}
open func toJSON() throws -> Data {
let encoder = JSONEncoder()
return try encoder.encode(self)
}
}
| mit | af4737b38c3ce356c75e46af32b0b3c8 | 44.328358 | 151 | 0.69246 | 4.427114 | false | false | false | false |
nottombrown/HausClock | HausClock/Models/Player.swift | 2 | 1475 | //
// Player.swift
// HausClock
//
// Created by Tom Brown on 11/28/14.
// Copyright (c) 2014 not. All rights reserved.
//
import Foundation
import ReactiveCocoa
class Player {
enum State {
case Active
case Waiting
}
enum Position {
case Top
case Bottom
func opposite() -> Position {
// Is there a less verbose way? This seems like a common case
switch self {
case .Top:
return .Bottom
case .Bottom:
return .Top
}
}
}
let initialTimeInSeconds:Double = 300.0
let position: Position
var state: ObservableProperty<State> = ObservableProperty(.Waiting)
var secondsRemaining: ObservableProperty<Double>
var secondsRemainingAsStringStream: ColdSignal<String>
init(position:Position) {
self.position = position
secondsRemaining = ObservableProperty(initialTimeInSeconds)
// Convert the seconds remaining into a stream and skip the repeats
secondsRemainingAsStringStream = secondsRemaining.values().map(Player.formatSecondsRemainingAsString).skipRepeats{ $0 == $1 }
}
private class func formatSecondsRemainingAsString(seconds: Double) -> String {
let minutes = Int(seconds)/60
let seconds = Int(seconds) % 60
let spacer = seconds < 10 ? "0" : ""
return "\(minutes):\(spacer)\(seconds)"
}
}
| mit | c25408fafb281297b51a7da1d0d1deed | 26.314815 | 133 | 0.612881 | 4.884106 | false | false | false | false |
rob-brown/SwiftRedux | Source/Persist.swift | 1 | 2206 | //
// Persist.swift
// SwiftRedux
//
// Created by Robert Brown on 11/11/15.
// Copyright © 2015 Robert Brown. All rights reserved.
//
import Foundation
public typealias SessionID = String
public struct Persister<T> {
public typealias State = T
public typealias StateSerializer = ((SessionID, State, Action)throws->())
public typealias StateDeserializer = ((SessionID)throws->(State))
public let stateSerializer: StateSerializer
public let stateDeserializer: StateDeserializer
public init(stateSerializer: StateSerializer, stateDeserializer: StateDeserializer) {
self.stateSerializer = stateSerializer
self.stateDeserializer = stateDeserializer
}
}
public struct Persist<T> {
public static func apply(sessionID: SessionID, persister: Persister<T>) -> StoreEnhancer<T,T> {
let queue = dispatch_queue_create("redux.swift.persist", DISPATCH_QUEUE_SERIAL)
return StoreEnhancer<T,T> { (next: StoreCreator<T>) in
return StoreCreator<T> { (reducer: Reducer<T>, initialState: T) in
let state: T
do {
state = try persister.stateDeserializer(sessionID)
}
catch {
NSLog("Error restoring state. Falling back to initial state.")
state = initialState
}
let store = next.createStore(reducer: reducer, initialState: state)
let dispatcher = store.dispatchFunction()
store.replaceDispatchFunction { action in
try dispatcher(action)
let newState = store.currentState()
dispatch_async(queue) {
do {
try persister.stateSerializer(sessionID, newState, action)
}
catch {
NSLog("ERROR: Unable to persist state.")
}
}
return action
}
return store
}
}
}
}
| mit | 55a866e40f21546be31e3966b0eaa5d3 | 33.453125 | 99 | 0.537415 | 5.444444 | false | false | false | false |
groschovskiy/firebase-for-banking-app | Barclays/Barclays/BMAccountClub.swift | 1 | 5978 | //
// BMAccountClub.swift
// Barclays
//
// Created by Dmitriy Groschovskiy on 22/03/2017.
// Copyright © 2017 Accenture, PLC. All rights reserved.
//
import UIKit
import Firebase
import MessageUI
import Security
import NetworkExtension
class BMAccountClub: UIViewController, MFMessageComposeViewControllerDelegate {
@IBOutlet weak var backgroundAccountView: UIView!
@IBOutlet weak var backgroundLoanView: UIView!
@IBOutlet weak var backgroundSalaryView: UIView!
@IBOutlet weak var backgroundToolsView: UIView!
@IBOutlet weak var backgroundSupportView: UIView!
@IBOutlet weak var accountHolder: UILabel!
@IBOutlet weak var lastTimeLogin: UILabel!
@IBOutlet weak var currentAccountDetails: UILabel!
@IBOutlet weak var currentAccountAmount: UILabel!
@IBOutlet weak var personalLoanMessage: UILabel!
@IBOutlet weak var personalSalaryMessage: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.backgroundAccountView.layer.cornerRadius = 5
self.backgroundLoanView.layer.cornerRadius = 5
self.backgroundSalaryView.layer.cornerRadius = 5
self.backgroundToolsView.layer.cornerRadius = 5
self.backgroundSupportView.layer.cornerRadius = 5
self.backgroundAccountView.layer.masksToBounds = true
self.backgroundLoanView.layer.masksToBounds = true
self.backgroundSalaryView.layer.masksToBounds = true
self.backgroundToolsView.layer.masksToBounds = true
self.backgroundSupportView.layer.masksToBounds = true
let userRef = FIRAuth.auth()?.currentUser?.uid
let purchaseRef = FIRDatabase.database().reference(withPath: "Customers/\(userRef!)")
purchaseRef.queryOrdered(byChild: "systemLastLogin").observe(.value, with: { snapshot in
let dataSnapshot = snapshot.value as! [String: AnyObject]
self.currentAccountAmount.text = String(format: "£%.2f", dataSnapshot["accountPayments"] as! Double!)
self.lastTimeLogin.text = String(format: "Last login: %@", dataSnapshot["systemLastLogin"] as! String!)
self.accountHolder.text = String(format: "%@ %@", dataSnapshot["holderFirstName"] as! String!, dataSnapshot["holderLastName"] as! String!)
self.currentAccountDetails.text = "\((dataSnapshot["holderNationalID"] as! String!)!) | \((dataSnapshot["accountNumber"] as! Int!)!)"
self.personalLoanMessage.text = String(format: "Your personal loan is £%.2f over %i month. Your current credit rating: %i", dataSnapshot["accountLoanCredit"] as! Double!, dataSnapshot["accountLoanMonth"] as! Int!, dataSnapshot["accountCreditScore"] as! Int!)
self.personalSalaryMessage.text = String(format: "The amount of your salary is £%.2f and is paid each %@ by %@", dataSnapshot["companySalary"] as! Double!, dataSnapshot["companyPayPeriod"] as! String!, dataSnapshot["employerName"] as! String!)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Account view with functional scheme
@IBAction func showCustomerCards(sender: UIButton) {
let storyboardIdent = UIStoryboard(name:"Accounts", bundle:nil)
let viewController = storyboardIdent.instantiateViewController(withIdentifier: "PSCards")
self.present(viewController, animated:true, completion:nil)
}
@IBAction func showCustomerAccounts(sender: UIButton) {
let storyboardIdent = UIStoryboard(name:"Accounts", bundle:nil)
let viewController = storyboardIdent.instantiateViewController(withIdentifier: "PSAccounts")
self.present(viewController, animated:true, completion:nil)
}
@IBAction func showCustomerDeposits(sender: UIButton) {
let storyboardIdent = UIStoryboard(name:"Accounts", bundle:nil)
let viewController = storyboardIdent.instantiateViewController(withIdentifier: "PSDeposits")
self.present(viewController, animated:true, completion:nil)
}
// MARK: - Tools view with functional scheme
@IBAction func personalManagerAssist(sender: UIButton) {
}
@IBAction func establishSecureConnection(sender: UIButton) {
}
@IBAction func generateDocumentReport(sender: UIButton) {
}
// MARK: - Support view with functional scheme
@IBAction func supportByPhone(sender: UIButton) {
if let url = NSURL(string: "tel://+442476842100") {
UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
}
}
@IBAction func supportByMail(sender: UIButton) {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.setToRecipients(["[email protected]"])
mail.setSubject("Barclays Support: Fraud Center")
mail.setMessageBody("<p>Hi Barclays Technical Support!</p>\n\n I have a trouble with ...", isHTML: true)
present(mail, animated: true)
} else {
// Show failure alert
}
}
@IBAction func supportByChat(sender: UIButton) {
if (MFMessageComposeViewController.canSendText()) {
let controller = MFMessageComposeViewController()
controller.body = ""
controller.recipients = ["+442476842100"]
controller.messageComposeDelegate = self
self.present(controller, animated: true, completion: nil)
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
self.dismiss(animated: true, completion: nil)
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = false
}
}
| apache-2.0 | 86daabdbb542b0e473d0d5bf8ca3315b | 43.251852 | 270 | 0.701707 | 4.829426 | false | false | false | false |
Jamnitzer/MBJ_Mipmapping | MBJ_Mipmapping/MBJ_Mipmapping/MBJViewController.swift | 1 | 3378 | //
// MBEViewController.m
// Mipmapping
//
// Created by Warren Moore on 12/8/14.
// Copyright (c) 2014 Metal By Example. All rights reserved.
//------------------------------------------------------------------------
// converted to Swift by Jamnitzer (Jim Wrenholt)
//------------------------------------------------------------------------
import UIKit
import Metal
import simd
import Accelerate
//------------------------------------------------------------------------------
class MBJViewController : UIViewController
{
var metalView:MBJMetalView! = nil
var renderer:MBJRenderer! = nil
var displayLink:CADisplayLink! = nil
var baseZoomFactor:Float = 0.0
var pinchZoomFactor:Float = 0.0
//------------------------------------------------------------------------
override func viewDidLoad()
{
super.viewDidLoad()
self.metalView = self.view as? MBJMetalView
self.baseZoomFactor = 2
self.pinchZoomFactor = 1
self.renderer = MBJRenderer(layer: self.metalView.metalLayer)
self.displayLink = CADisplayLink(target: self,
selector: Selector("displayLinkDidFire:"))
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(),
forMode: NSRunLoopCommonModes)
let pinchGesture = UIPinchGestureRecognizer(target: self,
action: "pinchGestureDidRecognize:")
self.view.addGestureRecognizer(pinchGesture)
let tapGesture = UITapGestureRecognizer(target: self,
action: "tapGestureDidRecognize:")
self.view.addGestureRecognizer(tapGesture)
}
//------------------------------------------------------------------------
override func prefersStatusBarHidden() -> Bool
{
return true
}
//------------------------------------------------------------------------
func displayLinkDidFire(sender:CADisplayLink)
{
self.renderer.cameraDistance = self.baseZoomFactor * self.pinchZoomFactor
// print("self.renderer.cameraDistance \(self.renderer.cameraDistance) ")
self.renderer.draw()
}
//------------------------------------------------------------------------
func pinchGestureDidRecognize(gesture: UIPinchGestureRecognizer)
{
switch (gesture.state)
{
case UIGestureRecognizerState.Changed:
self.pinchZoomFactor = Float(1.0) / Float(gesture.scale)
break
case UIGestureRecognizerState.Ended:
self.baseZoomFactor = self.baseZoomFactor * self.pinchZoomFactor
self.pinchZoomFactor = 1.0
default:
break
}
let constrainedZoom:Float = fmax(1.0, fmin(100.0,
self.baseZoomFactor * self.pinchZoomFactor))
self.pinchZoomFactor = constrainedZoom / self.baseZoomFactor
}
//------------------------------------------------------------------------
func tapGestureDidRecognize(recognize: UITapGestureRecognizer)
{
var mipmap_num:UInt = UInt(self.renderer.mipmappingMode.rawValue)
mipmap_num = (mipmap_num + 1) % 4
print("mipmap_num \(mipmap_num) ")
self.renderer.mipmappingMode = MIPMAP_MODE(rawValue:mipmap_num)!
}
//------------------------------------------------------------------------
}
| mit | 15a005f78a1c946b2f9937cd9f3ce6c6 | 35.717391 | 81 | 0.512137 | 5.60199 | false | false | false | false |
digitalasia/Colors | Colors/Colors/AppDelegate.swift | 1 | 7631 | //
// AppDelegate.swift
// Colors
//
// Created by Bryan Lim on 6/23/14.
// Copyright (c) 2014 TADA. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.endIndex-1] as UINavigationController
splitViewController.delegate = navigationController.topViewController as DetailViewController
let masterNavigationController = splitViewController.viewControllers[0] as UINavigationController
let controller = masterNavigationController.topViewController as MasterViewController
controller.managedObjectContext = self.managedObjectContext
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()
}
func saveContext () {
var error: NSError? = nil
let managedObjectContext = self.managedObjectContext
if managedObjectContext != nil {
if managedObjectContext.hasChanges && !managedObjectContext.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.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
// #pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
var managedObjectContext: NSManagedObjectContext {
if !_managedObjectContext {
let coordinator = self.persistentStoreCoordinator
if coordinator != nil {
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = coordinator
}
}
return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
var managedObjectModel: NSManagedObjectModel {
if !_managedObjectModel {
let modelURL = NSBundle.mainBundle().URLForResource("Colors", withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
}
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
if !_persistentStoreCoordinator {
let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Colors.sqlite")
var error: NSError? = nil
_persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
/*
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.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil)
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true}
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
return _persistentStoreCoordinator!
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil
// #pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex-1] as NSURL
}
}
| mit | c6ac35e45f403c40a5624eda2f46a895 | 52.739437 | 285 | 0.710916 | 6.327529 | false | false | false | false |
exoplatform/exo-ios | eXoTests/FakeUserDefaults.swift | 1 | 1766 | // Copyright (c) 2014 Mark Grimes. All rights reserved.
import Foundation
class FakeUserDefaults : UserDefaults {
typealias FakeDefaults = Dictionary<String, AnyObject?>
var data : FakeDefaults
init () {
data = FakeDefaults()
super.init(suiteName: "UnitTest")!
}
// NOP
override func synchronize() -> Bool {
return true
}
// Accessors
override func object(forKey defaultName: String) -> Any? {
return data[defaultName]!
}
override func value(forKey key: String) -> Any? {
return data[key]!
}
override func bool(forKey defaultName: String) -> Bool {
return data[defaultName] as! Bool
}
override func integer(forKey defaultName: String) -> Int {
return data[defaultName] as! Int
}
override func float(forKey defaultName: String) -> Float {
return data[defaultName] as! Float
}
// Mutators
override func set(_ value: Any?, forKey defaultName: String) {
data[defaultName] = value as AnyObject
}
override func setValue(_ value: Any?, forKey key: String) {
data[key] = value as AnyObject
}
override func set(_ value: Bool, forKey defaultName: String) {
data[defaultName] = value as Bool as AnyObject
}
override func set(_ value: Int, forKey defaultName: String) {
data[defaultName] = value as Int as AnyObject
}
override func set(_ value: Float, forKey defaultName: String) {
data[defaultName] = value as Float as AnyObject
}
}
extension UserDefaults {
@objc class func mockDefaults() -> FakeUserDefaults {
return FakeUserDefaults()
}
}
| lgpl-3.0 | 586a908904b800e14f8d34b2f1d1e6e3 | 23.191781 | 67 | 0.602492 | 4.734584 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Views/Cells/Chat/ChatDirectMessageHeaderCell.swift | 1 | 1984 | //
// ChatDirectMessageHeaderCell.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 24/08/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
final class ChatDirectMessageHeaderCell: UICollectionViewCell {
static let minimumHeight = CGFloat(240)
static let identifier = "ChatDirectMessageHeaderCell"
var subscription: Subscription? {
didSet {
guard subscription?.directMessageUser != nil else {
return fetchUser()
}
updateUser()
}
}
@IBOutlet weak var avatarViewContainer: UIView! {
didSet {
avatarView.frame = avatarViewContainer.bounds
avatarViewContainer.addSubview(avatarView)
}
}
lazy var avatarView: AvatarView = {
let avatarView = AvatarView()
avatarView.layer.cornerRadius = 4
avatarView.layer.masksToBounds = true
return avatarView
}()
@IBOutlet weak var labelUser: UILabel!
@IBOutlet weak var labelStartConversation: UILabel!
override func prepareForReuse() {
super.prepareForReuse()
avatarView.username = nil
labelUser.text = ""
labelStartConversation.text = ""
}
func updateUser() {
guard let user = subscription?.directMessageUser else {
labelUser.text = ""
labelStartConversation.text = ""
return
}
labelUser.text = user.displayName()
avatarView.username = user.username
let startText = localized("chat.dm.start_conversation")
labelStartConversation.text = String(format: startText, user.displayName())
}
func fetchUser() {
guard
let userId = subscription?.otherUserId,
!userId.isEmpty
else {
updateUser()
return
}
User.fetch(by: .userId(userId), completion: { _ in
self.updateUser()
})
}
}
| mit | 45039ec7150cc6cc9d2a8c36a141968c | 24.101266 | 83 | 0.604639 | 5.110825 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/27369-swift-type-transform.swift | 1 | 922 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
if true {{} k. "
if true{
class d<T {let:a{}
g {class B<T B:C{let f=e()
typealias e
enum S<T> : A?
func a== f=Dictionary<T.E
}
class c{struct B<T{
class b<T{struct Q<T B : T{
class c<a
typealias ()
struct B<a:a{
}
class A{let a{} k. "
}
class A<T{}
class B<T {
struct B
class A{var f
"
class B<T{
class A{{
func f
}struct c<T B:C{let f=e()
}
func g:a{
import a:a{
}
enum S<T a{
class A{
func p{
class B<H : T.E
struct c<T B :a{
class B< E {}
class A{let ad{}
let T h.h =b()
1
typealias ()
let T B :b: AsB
class A? f{
typeal
| apache-2.0 | 16ddfddda05f11fe644894f8b6132626 | 17.44 | 79 | 0.665944 | 2.568245 | false | false | false | false |
rnystrom/GitHawk | Pods/MessageViewController/MessageViewController/MessageAutocompleteController.swift | 1 | 8955 | //
// MessageAutocompleteController.swift
// MessageViewController
//
// Created by Ryan Nystrom on 12/31/17.
//
import UIKit
public protocol MessageAutocompleteControllerDelegate: class {
func didFind(controller: MessageAutocompleteController, prefix: String, word: String)
}
public protocol MessageAutocompleteControllerLayoutDelegate: class {
func needsLayout(controller: MessageAutocompleteController)
}
public final class MessageAutocompleteController: MessageTextViewListener {
public let textView: MessageTextView
public let tableView = UITableView()
public weak var delegate: MessageAutocompleteControllerDelegate?
public weak var layoutDelegate: MessageAutocompleteControllerLayoutDelegate?
public struct Selection {
public let prefix: String
public let word: String
public let range: NSRange
}
public private(set) var selection: Selection?
/// Adds an additional space after the autocompleted text when true. Default value is `TRUE`
public var appendSpaceOnCompletion = true
/// The text attributes applied to highlighted substrings for each prefix
private var autocompleteTextAttributes: [String: [NSAttributedString.Key: Any]] = [:]
/// A key used for referencing which substrings were autocompletes
private let NSAttributedAutocompleteKey = NSAttributedString.Key.init("com.messageviewcontroller.autocompletekey")
internal var registeredPrefixes = Set<String>()
internal let border = CALayer()
internal var keyboardHeight: CGFloat = 0
public init(textView: MessageTextView) {
self.textView = textView
textView.add(listener: self)
tableView.isHidden = true
border.isHidden = true
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(
self,
selector: #selector(keyboardWillChangeFrame(notification:)),
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil
)
}
// MARK: Public API
public final func register(prefix: String) {
registeredPrefixes.insert(prefix)
}
public final func show(_ doShow: Bool) {
tableView.reloadData()
tableView.layoutIfNeeded()
tableView.isHidden = !doShow
border.isHidden = !doShow
layoutDelegate?.needsLayout(controller: self)
}
public final func accept(autocomplete: String, keepPrefix: Bool = true) {
defer { cancel() }
guard let selection = self.selection,
let text = textView.text
else { return }
let prefixLength = selection.prefix.utf16.count
let insertionRange = NSRange(
location: selection.range.location + (keepPrefix ? prefixLength : 0),
length: selection.word.utf16.count + (!keepPrefix ? prefixLength : 0)
)
guard let range = Range(insertionRange, in: text) else { return }
// Create an NSRange to use with attributedText replacement
let nsrange = NSRange(range, in: textView.text)
insertAutocomplete(autocomplete, at: selection, for: nsrange, keepPrefix: keepPrefix)
let selectedLocation = insertionRange.location + autocomplete.utf16.count + (appendSpaceOnCompletion ? 1 : 0)
textView.selectedRange = NSRange(
location: selectedLocation,
length: 0
)
}
internal func cancel() {
selection = nil
show(false)
}
public final var maxHeight: CGFloat = 200 {
didSet { layoutDelegate?.needsLayout(controller: self) }
}
public func layout(in view: UIView, bottomY: CGFloat? = nil) {
if tableView.superview != view {
view.addSubview(tableView)
view.layer.addSublayer(border)
}
let bounds = view.bounds
let pinY = bottomY ?? (bounds.height - keyboardHeight)
let height = min(maxHeight, tableView.contentSize.height)
let frame = CGRect(
x: bounds.minX,
y: pinY - height,
width: bounds.width,
height: height
)
tableView.frame = frame
let borderHeight = 1 / UIScreen.main.scale
CATransaction.begin()
CATransaction.setDisableActions(true)
border.frame = CGRect(
x: bounds.minX,
y: frame.minY - borderHeight,
width: bounds.width,
height: borderHeight
)
CATransaction.commit()
}
public var borderColor: UIColor? {
get {
guard let color = border.backgroundColor else { return nil }
return UIColor(cgColor: color)
}
set {
border.backgroundColor = newValue?.cgColor
}
}
public func registerAutocomplete(prefix: String, attributes: [NSAttributedString.Key: Any]) {
registeredPrefixes.insert(prefix)
autocompleteTextAttributes[prefix] = attributes
}
// MARK: Private API
private func insertAutocomplete(_ autocomplete: String, at selection: Selection, for range: NSRange, keepPrefix: Bool) {
let defaultTypingTextAttributes = textView.typingAttributes
var attrs = defaultTypingTextAttributes
attrs[NSAttributedAutocompleteKey] = true
if let autoAttrs = autocompleteTextAttributes[selection.prefix] {
for (k, v) in autoAttrs {
attrs[k] = v
}
}
let newString = (keepPrefix ? selection.prefix : "") + autocomplete
let newAttributedString = NSAttributedString(string: newString, attributes: attrs)
// Modify the NSRange to include the prefix length
let rangeModifier = keepPrefix ? selection.prefix.count : 0
let highlightedRange = NSRange(location: range.location - rangeModifier, length: range.length + rangeModifier)
// Replace the attributedText with a modified version including the autocompete
let newAttributedText = textView.attributedText.replacingCharacters(in: highlightedRange, with: newAttributedString)
if appendSpaceOnCompletion {
newAttributedText.append(NSAttributedString(string: " ", attributes: defaultTypingTextAttributes))
}
// set to a blank attributed string to prevent keyboard autocorrect from cloberring the insert
textView.attributedText = NSAttributedString()
textView.attributedText = newAttributedText
}
internal func check() {
guard let result = textView.find(prefixes: registeredPrefixes) else {
cancel()
return
}
let wordWithoutPrefix = (result.word as NSString).substring(from: result.prefix.utf16.count)
selection = Selection(prefix: result.prefix, word: wordWithoutPrefix, range: result.range)
delegate?.didFind(controller: self, prefix: result.prefix, word: wordWithoutPrefix)
}
@objc internal func keyboardWillChangeFrame(notification: Notification) {
guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
else { return }
keyboardHeight = keyboardFrame.height
}
// MARK: MessageTextViewListener
public func didChangeSelection(textView: MessageTextView) {
check()
}
public func didChange(textView: MessageTextView) {}
public func willChangeRange(textView: MessageTextView, to range: NSRange) {
// range.length == 1: Remove single character
// range.lowerBound < textView.selectedRange.lowerBound: Ignore trying to delete
// the substring if the user is already doing so
if range.length == 1, range.lowerBound < textView.selectedRange.lowerBound {
// Backspace/removing text
let attribute = textView.attributedText
.attributes(at: range.lowerBound, longestEffectiveRange: nil, in: range)
.filter { return $0.key == NSAttributedAutocompleteKey }
if let isAutocomplete = attribute[NSAttributedAutocompleteKey] as? Bool, isAutocomplete {
// Remove the autocompleted substring
let lowerRange = NSRange(location: 0, length: range.location + 1)
textView.attributedText.enumerateAttribute(NSAttributedAutocompleteKey, in: lowerRange, options: .reverse, using: { (_, range, stop) in
// Only delete the first found range
defer { stop.pointee = true }
let emptyString = NSAttributedString(string: "", attributes: textView.typingAttributes)
textView.attributedText = textView.attributedText.replacingCharacters(in: range, with: emptyString)
textView.selectedRange = NSRange(location: range.location, length: 0)
})
}
}
}
}
| mit | 2cf74fa2a2c01b8a2dc2961582f9fc75 | 35.55102 | 151 | 0.656951 | 5.267647 | false | false | false | false |
britez/sdk-ios | sdk_ios_v2/Models/ValidationError.swift | 2 | 791 | //
// ValidationError.swift
//
import Foundation
open class ValidationError: JSONEncodable {
public var code: String?
public var param: String?
public init() {}
// MARK: JSONEncodable
open func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["code"] = self.code
nillableDictionary["param"] = self.param
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
open func toString() -> String {
var validationText = "[\n"
validationText += "code: \(self.code!) \n"
validationText += "param: \(self.param!) \n"
validationText += "]"
return validationText
}
}
| mit | 3faaf19694cd6a709ba3c58ad4f22f0a | 22.264706 | 85 | 0.579014 | 4.852761 | false | false | false | false |
Estimote/iOS-Mirror-SDK | Tools/Mirrorator/ios/Mirrorator/Helpers/Func.swift | 1 | 824 | //
// Func.swift
// Trello
//
// Created by Mac Book on 09/07/2017.
// Copyright © 2017 Facebook. All rights reserved.
//
import Foundation
/// Add inplace two dictionaries of same type
func += <K,V> (left: inout Dictionary<K,V>, right: Dictionary<K,V>?) {
guard let right = right else { return }
right.forEach { key, value in
left.updateValue(value, forKey: key)
}
}
/// Add inplace two arrays of same type
func += <V> (left: inout Array<V>, right: Array<V>?) {
guard let right = right else { return }
right.forEach { value in
left.append(value)
}
}
/// Add inplace array on left and same type on right
func += <V> (left: inout Array<V>, right: V?) {
guard let right = right else { return }
left.append(right)
}
extension Int {
var i32: Int32 {
return Int32.init(Double(self))
}
}
| apache-2.0 | bc001f38f60e0d6eabd15e4880321e36 | 21.243243 | 70 | 0.6452 | 3.177606 | false | false | false | false |
flathead/Flame | Flame/Scene.swift | 1 | 3827 | //
// Scene.swift
// Flame
//
// Created by Kenny Deriemaeker on 29/03/16.
// Copyright © 2016 Kenny Deriemaeker. All rights reserved.
//
import Foundation
import MetalKit
class Scene {
static let sharedInstance = Scene()
// MARK: - Properties
var entities = [Entity]()
var camera: Camera? {
for entity in entities {
if let camera = entity.getComponent(Camera) {
return camera
}
}
return nil
}
// MARK: - Init & deinit
func setup() {
let camera = Entity()
camera.name = "Camera"
camera.addComponent(Camera)
camera.transform.position = Vector3(0, 128, 512)
entities.append(camera)
/*
let grid = Entity()
grid.name = "Grid"
let gridComponent = grid.addComponent(GridRenderer)
gridComponent.side = 128
gridComponent.color = Vector4(0, 0.5, 0, 1)
grid.transform.scale = Vector3(128, 128, 128)
entities.append(grid)
*/
guard let bspFilePath = NSBundle.mainBundle().pathForResource("e1m1", ofType: "bsp") else {
print("BSP file not found.")
return
}
let bspImportStartTime = mach_absolute_time()
guard let bsp = QuakeBSP(filePath: bspFilePath) else {
print("Failed to parse BSP file.")
return
}
let bspImportEndTime = mach_absolute_time()
let bspImportTime = NSTimeInterval(Double(bspImportEndTime - bspImportStartTime) / Double(NSEC_PER_SEC))
print("Imported BSP in \(bspImportTime * 1000) ms.")
print("\(bsp.edges.count) edges")
print("\(bsp.vertices.count) vertices")
print("\(bsp.entities.count) entities")
print("\(bsp.planes.count) planes")
print("\(bsp.faces.count) faces")
print("\(bsp.mipTextures.count) textures")
guard let paletteFilePath = NSBundle.mainBundle().pathForResource("palette", ofType: "lmp") else {
print("❌ Palette file not found.")
return
}
guard let paletteData = NSFileManager.defaultManager().contentsAtPath(paletteFilePath) else {
print("❌ Couldn't read palette file.")
return
}
guard let palette = QuakePalette(data: paletteData) else { return }
let quakeMapRenderer = QuakeMapRenderer()
quakeMapRenderer.bsp = bsp
quakeMapRenderer.palette = palette
let quakeMap = Entity()
quakeMap.name = "QuakeMap"
quakeMap.addComponent(quakeMapRenderer)
entities.append(quakeMap)
// Try to move camera to the first info_player_start in the map.
if let playerStart = bsp.entities.filter({ $0.className == "info_player_start" }).first {
if let pos = playerStart.origin {
camera.transform.position = Vector3(pos.x, pos.z + 32, -pos.y)
}
if playerStart.properties.keys.contains("angle") {
if let angle = Float(playerStart.properties["angle"]!) {
camera.transform.rotation.y = (angle - 90) * Scalar.RadiansPerDegree
}
}
}
}
// MARK: - Public API
func update(deltaTime: NSTimeInterval) {
for entity in entities {
entity.update(deltaTime)
}
}
func getMeshRenderers() -> [MeshRenderer] {
var renderers = [MeshRenderer]()
for entity in entities {
for renderer in entity.getComponents(MeshRenderer) {
renderers.append(renderer)
}
}
return renderers
}
}
| mit | 2789db0bb55a8fcf9853629df07c20fc | 28.627907 | 112 | 0.555207 | 4.480657 | false | false | false | false |
tavultesoft/keymanweb | ios/engine/KMEI/KeymanEngine/Classes/Log.swift | 1 | 980 | //
// Log.swift
// KeymanEngine
//
// Created by Gabriel Wong on 2017-12-07.
// Copyright © 2017 SIL International. All rights reserved.
//
import XCGLogger
// From XCGLogger docs:
// Note: This creates the log object lazily, which means it's not created until it's actually needed.
public let log: XCGLogger = {
// Default: the 'console', which is read by Xcode but doesn't reach the system logs.
let mainLog = XCGLogger(identifier: "KeymanEngine", includeDefaultDestinations: false)
// Ensures our log messages go out to the device's system log as well as the console.
let systemLogDest = AppleSystemLogDestination(identifier: "")
systemLogDest.showLogIdentifier = true
mainLog.add(destination: systemLogDest)
// Temporary logging level to ensure that app details are reported properly.
mainLog.outputLevel = .info
mainLog.logAppDetails()
#if DEBUG
mainLog.outputLevel = .debug
#else
mainLog.outputLevel = .warning
#endif
return mainLog
}()
| apache-2.0 | 3655b4c0bdcfc344854db130831be72e | 27.794118 | 101 | 0.741573 | 4.096234 | false | false | false | false |
dfsilva/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/ElegantPresentationController.swift | 4 | 6273 | //
// ElegantPresentation.swift
// TwitterPresentationController
//
// Created by Kyle Bashour on 2/21/16.
// Copyright © 2016 Kyle Bashour. All rights reserved.
//
import UIKit
typealias CoordinatedAnimation = (UIViewControllerTransitionCoordinatorContext?) -> Void
class ElegantPresentationController: UIPresentationController {
// MARK: - Properties
/// Dims the presenting view controller, if option is set
fileprivate lazy var dimmingView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
view.alpha = 0
view.isUserInteractionEnabled = false
return view
}()
/// For dismissing on tap if option is set
fileprivate lazy var recognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ElegantPresentationController.dismiss(_:)))
/// An options struct containing the customization options set
fileprivate let options: PresentationOptions
// MARK: - Lifecycle
/**
Initializes and returns a presentation controller for transitioning between the specified view controllers
- parameter presentedViewController: The view controller being presented modally.
- parameter presentingViewController: The view controller whose content represents the starting point of the transition.
- parameter options: An options struct for customizing the appearance and behavior of the presentation.
- returns: An initialized presentation controller object.
*/
init(presentedViewController: UIViewController, presentingViewController: UIViewController, options: PresentationOptions) {
self.options = options
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
}
// MARK: - Presenting and dismissing
override func presentationTransitionWillBegin() {
// If the option is set, then add the gesture recognizer for dismissal to the container
if options.dimmingViewTapDismisses {
containerView!.addGestureRecognizer(recognizer)
}
// Prepare and position the dimming view
dimmingView.alpha = 0
dimmingView.frame = containerView!.bounds
containerView?.insertSubview(dimmingView, at: 0)
// Animate these properties with the transtion coordinator if possible
let animations: CoordinatedAnimation = { [unowned self] _ in
self.dimmingView.alpha = self.options.dimmingViewAlpha
self.presentingViewController.view.transform = self.options.presentingTransform
}
transtionWithCoordinator(animations)
}
override func dismissalTransitionWillBegin() {
// Animate these properties with the transtion coordinator if possible
let animations: CoordinatedAnimation = { [unowned self] _ in
self.dimmingView.alpha = 0
self.presentingViewController.view.transform = CGAffineTransform.identity
}
transtionWithCoordinator(animations)
}
// MARK: - Adaptation
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
/*
There's a bug when rotating that makes the presented view controller permanently
larger or smaller if this isn't here. I'm probably doing something wrong :P
It jumps because it's not in the animation block, but isn't noticiable unless in
slow-mo. Placing it in the animation block does not fix the issue, so here it is.
*/
presentingViewController.view.transform = CGAffineTransform.identity
// Animate these with the coordinator
let animations: CoordinatedAnimation = { [unowned self] _ in
self.dimmingView.frame = self.containerView!.bounds
self.presentingViewController.view.transform = self.options.presentingTransform
self.presentedView?.frame = self.frameOfPresentedViewInContainerView
}
coordinator.animate(alongsideTransition: animations, completion: nil)
}
override func size(forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize {
// Percent height doesn't make sense as a negative value or greater than zero, so we'll enforce it
let percentHeight = min(abs(options.presentedPercentHeight), 1)
// Return the appropiate height based on which option is set
if options.usePercentHeight {
return CGSize(width: parentSize.width, height: parentSize.height * CGFloat(percentHeight))
}
else if options.presentedHeight > 0 {
return CGSize(width: parentSize.width, height: options.presentedHeight)
}
return parentSize
}
override var frameOfPresentedViewInContainerView : CGRect {
// Grab the parent and child sizes
let parentSize = containerView!.bounds.size
let childSize = size(forChildContentContainer: presentedViewController, withParentContainerSize: parentSize)
// Create and return an appropiate frame
return CGRect(x: 0, y: parentSize.height - childSize.height, width: childSize.width, height: childSize.height)
}
// MARK: - Helper functions
// For the tap-to-dismiss
func dismiss(_ sender: UITapGestureRecognizer) {
presentedViewController.dismiss(animated: true, completion: nil)
}
/*
I noticed myself doing this a lot (more so in earlier versions) so I made a quick function.
Simply takes a closure with animations in them and attempts to animate with the coordinator.
*/
fileprivate func transtionWithCoordinator(_ animations: @escaping CoordinatedAnimation) {
if let coordinator = presentingViewController.transitionCoordinator {
coordinator.animate(alongsideTransition: animations, completion: nil)
}
else {
animations(nil)
}
}
}
| agpl-3.0 | f525df1bb2413a9c39346035ed2a6182 | 38.696203 | 160 | 0.680804 | 5.922568 | false | false | false | false |
thomas-mcdonald/SoundTop | SoundTop/STPlayPauseButton.swift | 1 | 4264 | // STPlayPauseButton.swift
//
// Copyright (c) 2015 Thomas McDonald
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer. Redistributions in binary
// form must reproduce the above copyright notice, this list of conditions and
// the following disclaimer in the documentation and/or other materials
// provided with the distribution. Neither the name of the nor the names of
// its contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import Cocoa
class STPlayPauseButton: NSControl {
private var pauseImageView: NSImageView!
private var playImageView: NSImageView!
private var playState = false
override init(frame: NSRect) {
super.init(frame: frame)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
func setup() {
let playImage = NSImage(byReferencingFile: NSBundle.mainBundle().pathForImageResource("play_b3b3b3_20.png")!)
let pauseImage = NSImage(byReferencingFile: NSBundle.mainBundle().pathForImageResource("pause_b3b3b3_20.png")!)
playImageView = NSImageView()
playImageView.image = playImage
playImageView.translatesAutoresizingMaskIntoConstraints = false
pauseImageView = NSImageView()
pauseImageView.image = pauseImage
pauseImageView.hidden = true
pauseImageView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(pauseImageView)
self.addSubview(playImageView)
// add constraints
let viewsDict = ["pauseImageView": pauseImageView, "playImageView": playImageView]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[playImageView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[pauseImageView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[playImageView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[pauseImageView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDict))
}
override func mouseDown(e: NSEvent) {
var keepOn = true
while(keepOn) {
let mask = NSEventMask.LeftMouseUp
let event = self.window!.nextEventMatchingMask(NSEventMask(rawValue: UInt64(Int(mask.rawValue))))
nextState()
keepOn = false
}
}
private func nextState() {
if(playState) {
NSNotificationCenter.defaultCenter().postNotificationName("paused", object: nil)
} else {
NSNotificationCenter.defaultCenter().postNotificationName("playing", object: nil)
}
}
func showPause() {
playState = true
playImageView.hidden = true
pauseImageView.hidden = false
}
func showPlay() {
playState = false
pauseImageView.hidden = true
playImageView.hidden = false
}
}
| bsd-3-clause | 5d876199e050ec006069819a55f31369 | 42.070707 | 177 | 0.715525 | 4.998828 | false | false | false | false |
mrchenhao/Cheater | Cheater/Cheater/Cheater.swift | 1 | 1108 | //
// Cheater.swift
// Cheater
//
// Created by ChenHao on 16/3/26.
// Copyright © 2016年 HarriesChen. All rights reserved.
//
import Foundation
public class Cheater {
var isStarted: Bool
var hook: NSURLSessionHook
var stubRequests = [StubRequest]()
public static let shareInstance = Cheater()
init() {
isStarted = false
hook = NSURLSessionHook()
}
func responseForRequest(request: NSURLRequest) -> StubResponse? {
let resquests = Cheater.shareInstance.stubRequests
for stub in resquests {
if stub.matchRequest(request) {
return stub.response
}
}
return nil
}
public func start() {
if !self.isStarted {
loadHook()
isStarted = true
}
}
public func stop() {
unloadHook()
isStarted = false
}
private func loadHook() {
hook.load()
}
private func unloadHook() {
hook.unload()
}
func addStubRequest(request: StubRequest) {
stubRequests.append(request)
}
}
| mit | 4dac38883a9442145d8f1005ec32d54c | 18.051724 | 69 | 0.571041 | 4.333333 | false | false | false | false |
ricebook/Kingsroad | Core/KingsroadViewController.swift | 1 | 6001 | //
// KingsroadViewController.swift
// Daenerys
//
// Created by Carl Chen on 3/1/16.
// Copyright © 2016 Carl Chen. All rights reserved.
//
import UIKit
import WebKit
public class KingsroadViewController: UIViewController {
public private(set) var webView: WKWebView!
public var jsScriptRunAfterWebViewInit: String?
// MAKR: - init
public init?(baseURL: NSURL, indexPath: String) {
super.init(nibName: nil, bundle: nil)
if baseURL.fileURL {
// 如果是本地文件,则判断对应文件夹是否存在
var isDirectory: ObjCBool = ObjCBool(false)
let fileFolderPath = baseURL.path ?? ""
let isExist = NSFileManager.defaultManager().fileExistsAtPath(fileFolderPath, isDirectory: &isDirectory)
if !isExist || !isDirectory.boolValue {
print("\(fileFolderPath) does not exist" )
return nil
}
}
_baseURL = baseURL
_indexPath = indexPath
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Private properties
private var _baseURL: NSURL = NSURL(fileURLWithPath: "/")
private var _indexPath: String = "index.html"
}
// MARK: - Extension: Life cycle
extension KingsroadViewController {
// MARK: - Life Cycle
override public func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
p_constructSubviews()
let wholeURLString = _baseURL.absoluteString.map { $0 + "/" + _indexPath }
guard let wholeURL = NSURL(string: wholeURLString ?? "") else { return }
if #available(iOS 9.0, *) {
if _baseURL.fileURL {
webView.loadFileURL(wholeURL, allowingReadAccessToURL: _baseURL)
return
}
}
webView.loadRequest(NSURLRequest(URL: wholeURL))
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - Extension: Delegates
// MARK: KingsroadCommandDelegate
extension KingsroadViewController: KingsroadCommandDelegate {
public func sendPluginResult(result: KingsroadPluginResult, callbackID: String) {
let resultJS = result.constructResultJSWithCallbackID(callbackID)
webView.evaluateJavaScript(resultJS) { (obj, error) -> Void in
if error == nil {
// print("Callback JS run successfully. Result : \(obj)")
} else {
print("Callback JS run error. \(error)")
}
}
}
}
// MARK: WKNavigationDelegate
extension KingsroadViewController: WKNavigationDelegate {
public func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
// print(navigationAction)
decisionHandler(.Allow)
}
public func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
print(navigation)
}
}
// MARK: WKUIDelegate
extension KingsroadViewController: WKUIDelegate {
// HTML页面Alert出内容
public func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) {
let ac = UIAlertController(title: "提示", message: message, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: { (_) -> Void in
completionHandler()
}))
presentViewController(ac, animated: true, completion: nil)
}
// HTML页面弹出Confirm时调用此方法
public func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) {
let ac = UIAlertController(title: "提示", message: message, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler:
{ (_) -> Void in
completionHandler(true)
}))
ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler:
{ (_) -> Void in
completionHandler(false)
}))
presentViewController(ac, animated: true, completion: nil)
}
}
// MARK: - Extension: Private methods
extension KingsroadViewController {
private func p_constructSubviews() {
let userContentController = WKUserContentController()
if let jsString = jsScriptRunAfterWebViewInit where !jsString.isEmpty {
let userScript = WKUserScript(source: jsString, injectionTime: .AtDocumentEnd, forMainFrameOnly: true)
userContentController.addUserScript(userScript)
}
let cordovaMessageHandler = CordovaScriptMessageHandler()
cordovaMessageHandler.commandDelgete = self
userContentController.addScriptMessageHandler(cordovaMessageHandler, name: "cordova")
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
webView = WKWebView(frame: CGRectZero, configuration: configuration)
webView.navigationDelegate = self
webView.UIDelegate = self
webView.allowsBackForwardNavigationGestures = false
view.addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
let viewDic: [String: AnyObject] = [
"webView": webView
]
var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: NSLayoutFormatOptions(), metrics: nil, views: viewDic)
view.addConstraints(cons)
cons = NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView]|", options: NSLayoutFormatOptions(), metrics: nil, views: viewDic)
view.addConstraints(cons)
}
}
| mit | 470e871a42475bf5b8d9f42f77d114aa | 33.231214 | 171 | 0.661094 | 5.105172 | false | false | false | false |
rstoner19/iOSStockProject | StockApp/StockApp/DetailedViewController.swift | 1 | 5040 | //
// DetailedViewController.swift
// StockApp
//
// Created by Rick on 7/1/16.
// Copyright © 2016 Rick . All rights reserved.
//
import UIKit
class DetailedViewController: UIViewController, Setup {
@IBOutlet weak var symbolLabel: UILabel!
@IBOutlet weak var priceChangeLabel: UILabel!
@IBOutlet weak var currentPriceLabel: UILabel!
@IBOutlet weak var directionImage: UIImageView!
@IBOutlet weak var percentChangeLabel: UILabel!
//Detailed Price Compenonents
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var priceCurrentLabel: UILabel!
@IBOutlet weak var priceTimeLabel: UILabel!
@IBOutlet weak var priceBidAskLabel: UILabel!
@IBOutlet weak var priceDayHighLabel: UILabel!
@IBOutlet weak var priceDayLowLabel: UILabel!
@IBOutlet weak var priceDayRangeLabel: UILabel!
@IBOutlet weak var priceYearHighLabel: UILabel!
@IBOutlet weak var priceYearLowLabel: UILabel!
@IBOutlet weak var priceYearRangeLabel: UILabel!
// Earnings Components
@IBOutlet weak var earningsLabel: UILabel!
@IBOutlet weak var epsLabel: UILabel!
@IBOutlet weak var priceEarningsLabel: UILabel!
@IBOutlet weak var pEGrowthLabel: UILabel!
@IBOutlet weak var eBITDALabel: UILabel!
@IBOutlet weak var bookValueLabel: UILabel!
@IBOutlet weak var priceSalesLabel: UILabel!
@IBOutlet weak var currentEPSEstLabel: UILabel!
@IBOutlet weak var nextQtrEpsLabel: UILabel!
@IBOutlet weak var nextYrEPSLabel: UILabel!
//Dividends
@IBOutlet weak var dividendLabel: UILabel!
@IBOutlet weak var dividendAmountLabel: UILabel!
@IBOutlet weak var dividendYield: UILabel!
@IBOutlet weak var payDateLabel: UILabel!
var quote: Quote?
override func viewDidLoad() {
super.viewDidLoad()
setup()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setup() {
self.priceLabel.text = "Price"
if let quote = self.quote {
// Main Section
self.title = quote.company
self.symbolLabel.text = quote.symbol
self.currentPriceLabel.text = "$\(quote.lastPrice!)"
self.percentChangeLabel.text = quote.percentChangeString
if quote.dollarChange > 0 {
let color = UIColor(colorLiteralRed: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)
self.percentChangeLabel.textColor = color
self.priceChangeLabel.textColor = color
self.directionImage.image = UIImage(named: "up.png")
} else if quote.dollarChange < 0 {
let color = UIColor(colorLiteralRed: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
self.priceChangeLabel.textColor = color
self.percentChangeLabel.textColor = color
self.directionImage.image = UIImage(named: "down.png")
}
self.priceChangeLabel.text = "$\(quote.dollarChange!)"
//Price Section
self.priceLabel.text = "Price"
self.priceCurrentLabel.text = "Mkt Cap: $\(quote.marketCap)"
self.priceTimeLabel.text = "\(quote.lastTradeTime)"
self.priceBidAskLabel.text = "Bid/Ask: $\(quote.bid) / $\(quote.askPrice)"
self.priceDayHighLabel.text = "Day High: $\(quote.daysHigh)"
self.priceDayLowLabel.text = "Day Low: $\(quote.daysLow)"
self.priceDayRangeLabel.text = "Day Rng: \(quote.daysRange)"
self.priceYearLowLabel.text = "Year Low: $\(quote.yearLow)"
self.priceYearHighLabel.text = "Year High: $\(quote.yearHigh)"
self.priceYearRangeLabel.text = "Year Range: $\(quote.yearRange)"
//Earnings Section
self.earningsLabel.text = "Earnings"
self.epsLabel.text = "EPS: $\(quote.earningsPerShare)"
self.priceEarningsLabel.text = "P/E: \(quote.peRatioString)"
self.pEGrowthLabel.text = "PEG \(quote.pEGRatio)"
self.eBITDALabel.text = "EBITDA: \(quote.eBITDA)"
self.bookValueLabel.text = "Book Val: \(quote.bookValue)"
self.priceSalesLabel.text = "Price/Sales: \(quote.priceSales)"
self.currentEPSEstLabel.text = "Cur. Yr. EPS Est: $\(quote.curYrEPSEst)"
self.nextQtrEpsLabel.text = "Next Qtr EPS ESt: $\(quote.nextQtrEPSEst)"
self.nextYrEPSLabel.text = "Next Yr. EPS Est: $\(quote.nextYrEPSEst)"
//Dividend Section
self.dividendLabel.text = "Dividends"
self.dividendAmountLabel.text = "Dividend: $\(quote.dividend)"
self.dividendYield.text = "Yield: \(quote.dividendYield)%"
self.payDateLabel.text = "Paydate: " + quote.dividendPayDate
}
}
func setupAppearance() {
//
}
}
| mit | 45ddd3199ab0c750b8bfad229ac47c1e | 39.96748 | 92 | 0.632268 | 4.140509 | false | false | false | false |
CodetrixStudio/CSJson | CSJson/CSJsonSettings.swift | 1 | 710 | //
// CSJsonSettings.swift
// CSJson
//
// Created by Parveen Khatkar on 3/25/16.
// Copyright © 2016 Codetrix Studio. All rights reserved.
//
import Foundation
open class CSJsonSettings
{
fileprivate static var isInitialized = false;
open static var GlobalSettings: CSJsonSettings = CSJsonSettings();
open var DateFormat: String = "yyyy-MM-dd HH:mm:ss ZZZZ";
open var DateFormats = Dictionary<String, String>();
public init()
{
if CSJsonSettings.isInitialized == true
{
self.DateFormat = CSJsonSettings.GlobalSettings.DateFormat;
}
else
{
CSJsonSettings.isInitialized = true;
}
}
}
| gpl-3.0 | 32eec502c6b0c0f07add478420fa5954 | 21.15625 | 71 | 0.623413 | 4.146199 | false | false | false | false |
DeliciousRaspberryPi/MockFive | TestTrack.playground/Contents.swift | 1 | 2197 | import MockFive
//MARK: Object-Oriented Example
// --- Production File
class ExampleClass {
func returnsOptional() -> String? { return "hamstrings" }
}
// --- Mock File (in test target)
class ExampleClassMock: ExampleClass, Mock {
let mockFiveLock = "A" // use 'lock()' in non-playground
override func returnsOptional() -> String? { return stub(identifier: "returns optional") { super.returnsOptional() } }
}
// --- Now, you can stub the method if you like, or use the default behavior in specs
let myClassMock = ExampleClassMock()
// Default behavior from super
myClassMock.returnsOptional()
// Pass an identifier and a closure to MockFive, and your closure will be invoked instead of the original implementation.
var thingToReturn: String? = "not hamstrings"
myClassMock.registerStub("returns optional") { thingToReturn }
myClassMock.returnsOptional()
thingToReturn = "some other value"
myClassMock.returnsOptional()
// Unregister mock, get default behavior
myClassMock.unregisterStub("returns optional")
myClassMock.returnsOptional()
//MARK: Protocol-Oriented Example
// --- Production file
protocol ExampleProtocol {
func returnsVoid()
func returnsOptional() -> String?
func complex(string string: String, factors: Int...) -> (Float, Int)
}
// --- Mock file (in test target)
struct ExampleProtocolMock: ExampleProtocol, Mock {
let mockFiveLock = "B" // use 'lock()' in non-playground
func returnsVoid() { stub(identifier: "returns void") }
func returnsOptional() -> String? { return stub(identifier: "returns optional") }
func complex(string string: String, factors: Int...) -> (Float, Int) { return stub(identifier: "complex", arguments: string, factors) { (0.1, 7) } }
}
// --- Now, you can use your mock in any spec you choose.
var myMock = ExampleProtocolMock()
// Call some methods on your mock...
myMock.returnsVoid()
myMock.returnsOptional()
myMock.complex(string: "inputString", factors: 7, 8, 9)
// ... and examine the log!
let first = myMock.invocations[0]
let second = myMock.invocations[1]
let third = myMock.invocations[2]
| apache-2.0 | 64e363a55062c3dd0bf47919650a018e | 31.791045 | 155 | 0.688211 | 4.046041 | false | false | false | false |
ibm-cloud-security/appid-serversdk-swift | Sources/IBMCloudAppID/AppIDPlugin.swift | 1 | 4231 | /*
Copyright 2018 IBM Corp.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import LoggerAPI
import Credentials
import KituraNet
///
/// App ID Plugin parent class
/// - Contains shared methods used in api and web strategies
///
@available(OSX 10.12, *)
public class AppIDPlugin {
var publicKeyUtil: PublicKeyUtil
let config: AppIDPluginConfig
init(config: AppIDPluginConfig) {
self.config = config
self.publicKeyUtil = PublicKeyUtil(url: config.publicKeyServerURL)
}
/// Parses / validates the given identity token
///
/// - Parameter idTokenString: The id token to parse and validate
/// - Parameter completion: Handler returning the user context information or an error
///
func parseIdentityToken(idTokenString: String?, completion: @escaping (([String: Any], UserProfile)?, AppIDError?) -> Void) {
guard let idTokenString = idTokenString else {
Log.debug("Identity token does not exist")
return completion(nil, AppIDError.invalidToken("Identity token does not exist"))
}
Utils.decodeAndValidate(tokenString: idTokenString, publicKeyUtil: publicKeyUtil, options: config) { payload, error in
guard let payload = payload, error == nil else {
Log.debug("Identity token is malformed")
return completion(nil, error ?? AppIDError.invalidToken("Identity token could not be decoded"))
}
guard let authContext = Utils.getAuthorizedIdentities(from: payload) else {
Log.debug("Identity token is malformed")
return completion(nil, error ?? AppIDError.invalidToken("Identity token could not be decoded"))
}
Log.debug("Identity token successfully parsed")
let identityContext = [
"identityToken": idTokenString,
"identityTokenPayload": payload as Any
]
let provider = authContext.userIdentity.authBy.count > 0 ?
authContext.userIdentity.authBy[0]["provider"].stringValue : ""
let profile = UserProfile(id: authContext.userIdentity.id,
displayName: authContext.userIdentity.displayName,
provider: provider)
return completion((identityContext, profile), nil)
}
}
/// Parses / validates the given identity token
///
/// - Parameter scope: The expected scopes of the request
/// - Parameter error: The OAuth Error code
/// - Parameter description: An optional error description
/// - Parameter completion: onFailure error handler
/// - Returns: The id token identityContext dictionary and the user's profile
///
func sendUnauthorized(scope: String,
error: OauthError,
description: String? = nil,
completion: @escaping (HTTPStatusCode?, [String: String]?) -> Void) {
Log.debug("Sending unauthorized response")
var msg = Constants.bearer + " scope=\"" + scope + "\", error=\"" + error.rawValue + "\""
var status: HTTPStatusCode!
if let description = description {
msg += ", error_description=\"" + description + "\""
}
switch error {
case .invalidRequest : status = .badRequest
case .invalidToken : status = .unauthorized
case .insufficientScope : status = .forbidden
case .missingAuth :
status = .unauthorized
msg = Constants.bearer + " realm=\"AppID\""
}
completion(status, ["Www-Authenticate": msg])
}
}
| apache-2.0 | 770d7ebfb1dc21e732ce262e4601622f | 37.463636 | 129 | 0.628693 | 5.178703 | false | true | false | false |
congncif/SiFUtilities | Example/Pods/Boardy/Boardy/Core/Board/Motherboard.swift | 1 | 3317 | //
// Motherboard.swift
// Boardy
//
// Created by NGUYEN CHI CONG on 11/1/19.
// Copyright © 2019 NGUYEN CHI CONG. All rights reserved.
//
import Foundation
import UIKit
open class Motherboard: Board, MotherboardRepresentable, BoardDelegate, FlowMotherboard, LazyMotherboard {
public var flows: [BoardFlow] = []
override public var debugDescription: String {
let superDesc = super.debugDescription
return superDesc + "\n" + """
● [Children] ➤ \(String(describing: boards.map { $0.identifier }))
● [Flows] ➤ \(String(describing: flows.count))
● [Producer] ➤ \(String(describing: boardProducer))
"""
}
public init(identifier: BoardID = .random(),
boards: [ActivatableBoard] = []) {
boardProducer = NoBoardProducer()
super.init(identifier: identifier)
for board in boards {
addBoard(board)
}
registerDefaultFlows()
}
public init(identifier: BoardID = .random(),
boardProducer: ActivableBoardProducer) {
self.boardProducer = boardProducer
super.init(identifier: identifier)
registerDefaultFlows()
}
public convenience init(identifier: BoardID = .random(), boardProducer: ActivableBoardProducer, boards: [ActivatableBoard]) {
self.init(identifier: identifier, boardProducer: boardProducer)
for board in boards {
addBoard(board)
}
}
func registerDefaultFlows() {
// Forward action through chain
forwardActionFlow(to: self)
// Register Interaction flow
registerGeneralFlow { [weak self] in
self?.interactWithBoard(command: $0)
}
// Register activation flow
registerGeneralFlow { [weak self] in
self?.activateBoard(model: $0)
}
// Register complete flow
registerGeneralFlow { [weak self] (action: CompleteAction) in
self?.removeBoard(withIdentifier: action.identifier)
}
}
override open func putIntoContext(_ context: AnyObject) {
super.putIntoContext(context)
for board in boards {
board.putIntoContext(context)
}
}
@discardableResult
public func registerFlow(_ flow: BoardFlow) -> Self {
flows.append(flow)
return self
}
public func resetFlows() {
flows = []
registerDefaultFlows()
}
// MARK: - MotherboardRepresentable
var mainboard: [ActivatableBoard] = [] {
didSet {
for board in boards {
board.delegate = self
if board.context == nil, let root = context {
board.putIntoContext(root)
}
}
}
}
// MARK: - LazyMotherboard
public private(set) var boardProducer: ActivableBoardProducer
}
/// A Motherboard is a special board which only accepts a BoardInputModel as input. When activate func is called, the motherboard will activate a Board with identifier in list of boards it manages.
extension Motherboard: GuaranteedBoard {
public typealias InputType = BoardInputModel
open func activate(withGuaranteedInput input: BoardInputModel) {
activateBoard(model: input)
}
}
| mit | 7091c7195620225d64583e6dfff86312 | 27.982456 | 197 | 0.618039 | 4.476965 | false | false | false | false |
exyte/Macaw | Source/render/ShapeRenderer.swift | 1 | 11154 | import Foundation
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
class ShapeRenderer: NodeRenderer {
var shape: Shape
init(shape: Shape, view: DrawingView?, parentRenderer: GroupRenderer? = nil) {
self.shape = shape
super.init(node: shape, view: view, parentRenderer: parentRenderer)
}
deinit {
dispose()
}
override var node: Node {
return shape
}
override func doAddObservers() {
super.doAddObservers()
observe(shape.formVar)
observe(shape.fillVar)
observe(shape.strokeVar)
}
override func doRender(in context: CGContext, force: Bool, opacity: Double, coloringMode: ColoringMode = .rgb) {
if shape.fill == nil && shape.stroke == nil {
return
}
RenderUtils.setGeometry(shape.form, ctx: context)
var fillRule = FillRule.nonzero
if let path = shape.form as? Path {
fillRule = path.fillRule
}
switch coloringMode {
case .rgb:
drawPath(fill: shape.fill, stroke: shape.stroke, ctx: context, opacity: opacity, fillRule: fillRule)
case .greyscale:
drawPath(fill: shape.fill?.fillUsingGrayscaleNoAlpha(), stroke: shape.stroke?.strokeUsingGrayscaleNoAlpha(), ctx: context, opacity: opacity, fillRule: fillRule)
case .alphaOnly:
drawPath(fill: shape.fill?.fillUsingAlphaOnly(), stroke: shape.stroke?.strokeUsingAlphaOnly(), ctx: context, opacity: opacity, fillRule: fillRule)
}
}
override func doFindNodeAt(path: NodePath, ctx: CGContext) -> NodePath? {
RenderUtils.setGeometry(shape.form, ctx: ctx)
var drawingMode: CGPathDrawingMode?
if let stroke = shape.stroke {
RenderUtils.setStrokeAttributes(stroke, ctx: ctx)
if shape.fill != nil {
drawingMode = .fillStroke
} else {
drawingMode = .stroke
}
} else {
drawingMode = .fill
}
var contains = false
if let mode = drawingMode {
contains = ctx.pathContains(path.location, mode: mode)
if contains {
return path
}
}
// Prepare for next figure hittesting - clear current context path
ctx.beginPath()
return .none
}
fileprivate func drawPath(fill: Fill?, stroke: Stroke?, ctx: CGContext?, opacity: Double, fillRule: FillRule) {
var shouldStrokePath = false
if fill is Gradient || stroke?.fill is Gradient {
shouldStrokePath = true
}
if let fill = fill, let stroke = stroke {
let path = ctx!.path
setFill(fill, ctx: ctx, opacity: opacity)
if stroke.fill is Gradient && !(fill is Gradient) {
ctx!.drawPath(using: fillRule == .nonzero ? .fill : .eoFill)
}
drawWithStroke(stroke, ctx: ctx, opacity: opacity, shouldStrokePath: shouldStrokePath, path: path, mode: fillRule == .nonzero ? .fillStroke : .eoFillStroke)
return
}
if let fill = fill {
setFill(fill, ctx: ctx, opacity: opacity)
ctx!.drawPath(using: fillRule == .nonzero ? .fill : .eoFill)
return
}
if let stroke = stroke {
drawWithStroke(stroke, ctx: ctx, opacity: opacity, shouldStrokePath: shouldStrokePath, mode: .stroke)
return
}
}
fileprivate func setFill(_ fill: Fill?, ctx: CGContext?, opacity: Double) {
guard let fill = fill else {
return
}
if let fillColor = fill as? Color {
let color = RenderUtils.applyOpacity(fillColor, opacity: opacity)
ctx!.setFillColor(color.toCG())
} else if let gradient = fill as? Gradient {
drawGradient(gradient, ctx: ctx, opacity: opacity)
} else if let pattern = fill as? Pattern {
drawPattern(pattern, ctx: ctx, opacity: opacity)
} else {
print("Unsupported fill: \(fill)")
}
}
fileprivate func drawWithStroke(_ stroke: Stroke, ctx: CGContext?, opacity: Double, shouldStrokePath: Bool = false, path: CGPath? = nil, mode: CGPathDrawingMode) {
if let path = path, shouldStrokePath {
ctx!.addPath(path)
}
RenderUtils.setStrokeAttributes(stroke, ctx: ctx)
if stroke.fill is Gradient {
gradientStroke(stroke, ctx: ctx, opacity: opacity)
return
} else if stroke.fill is Color {
colorStroke(stroke, ctx: ctx, opacity: opacity)
}
if shouldStrokePath {
ctx!.strokePath()
} else {
ctx!.drawPath(using: mode)
}
}
fileprivate func colorStroke(_ stroke: Stroke, ctx: CGContext?, opacity: Double) {
guard let strokeColor = stroke.fill as? Color else {
return
}
let color = RenderUtils.applyOpacity(strokeColor, opacity: opacity)
ctx!.setStrokeColor(color.toCG())
}
fileprivate func gradientStroke(_ stroke: Stroke, ctx: CGContext?, opacity: Double) {
guard let gradient = stroke.fill as? Gradient else {
return
}
ctx!.replacePathWithStrokedPath()
drawGradient(gradient, ctx: ctx, opacity: opacity)
}
fileprivate func drawPattern(_ pattern: Pattern, ctx: CGContext?, opacity: Double) {
var patternNode = pattern.content
if !pattern.userSpace, let node = BoundsUtils.createNodeFromRespectiveCoords(respectiveNode: pattern.content, absoluteLocus: shape.form) {
patternNode = node
}
let renderer = RenderUtils.createNodeRenderer(patternNode, view: view)
var patternBounds = pattern.bounds
if !pattern.userSpace {
let boundsTranform = BoundsUtils.transformForLocusInRespectiveCoords(respectiveLocus: pattern.bounds, absoluteLocus: shape.form)
patternBounds = pattern.bounds.applying(boundsTranform)
}
guard let tileCGImage = renderer.renderToImage(bounds: patternBounds, inset: 0)?.cgImage else {
return
}
ctx?.clip()
ctx?.draw(tileCGImage, in: patternBounds.toCG(), byTiling: true)
}
fileprivate func drawGradient(_ gradient: Gradient, ctx: CGContext?, opacity: Double) {
ctx!.saveGState()
var colors: [CGColor] = []
var stops: [CGFloat] = []
for stop in gradient.stops {
stops.append(CGFloat(stop.offset))
let color = RenderUtils.applyOpacity(stop.color, opacity: opacity)
colors.append(color.toCG())
}
if let gradient = gradient as? LinearGradient {
var start = CGPoint(x: CGFloat(gradient.x1), y: CGFloat(gradient.y1))
var end = CGPoint(x: CGFloat(gradient.x2), y: CGFloat(gradient.y2))
if !gradient.userSpace {
let bounds = ctx!.boundingBoxOfPath
start = CGPoint(x: start.x * bounds.width + bounds.minX, y: start.y * bounds.height + bounds.minY)
end = CGPoint(x: end.x * bounds.width + bounds.minX, y: end.y * bounds.height + bounds.minY)
}
ctx!.clip()
let cgGradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors as CFArray, locations: stops)
ctx!.drawLinearGradient(cgGradient!, start: start, end: end, options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
} else if let gradient = gradient as? RadialGradient {
var innerCenter = CGPoint(x: CGFloat(gradient.fx), y: CGFloat(gradient.fy))
var outerCenter = CGPoint(x: CGFloat(gradient.cx), y: CGFloat(gradient.cy))
var radius = CGFloat(gradient.r)
if !gradient.userSpace {
var bounds = ctx!.boundingBoxOfPath
var scaleX: CGFloat = 1
var scaleY: CGFloat = 1
if bounds.width > bounds.height {
scaleY = bounds.height / bounds.width
} else {
scaleX = bounds.width / bounds.height
}
ctx!.scaleBy(x: scaleX, y: scaleY)
bounds = ctx!.boundingBoxOfPath
innerCenter = CGPoint(x: innerCenter.x * bounds.width + bounds.minX, y: innerCenter.y * bounds.height + bounds.minY)
outerCenter = CGPoint(x: outerCenter.x * bounds.width + bounds.minX, y: outerCenter.y * bounds.height + bounds.minY)
radius = min(radius * bounds.width, radius * bounds.height)
}
ctx!.clip()
let cgGradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors as CFArray, locations: stops)
ctx!.drawRadialGradient(cgGradient!, startCenter: innerCenter, startRadius: 0, endCenter: outerCenter, endRadius: radius, options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
}
ctx!.restoreGState()
}
}
extension Stroke {
func strokeUsingAlphaOnly() -> Stroke {
return Stroke(fill: fill.fillUsingAlphaOnly(), width: width, cap: cap, join: join, dashes: dashes, offset: offset)
}
func strokeUsingGrayscaleNoAlpha() -> Stroke {
return Stroke(fill: fill.fillUsingGrayscaleNoAlpha(), width: width, cap: cap, join: join, dashes: dashes, offset: offset)
}
}
extension Fill {
func fillUsingAlphaOnly() -> Fill {
if let color = self as? Color {
return color.colorUsingAlphaOnly()
}
let gradient = self as! Gradient
let newStops = gradient.stops.map { Stop(offset: $0.offset, color: $0.color.colorUsingAlphaOnly()) }
if let radial = self as? RadialGradient {
return RadialGradient(cx: radial.cx, cy: radial.cy, fx: radial.fx, fy: radial.fy, r: radial.r, userSpace: radial.userSpace, stops: newStops)
}
let linear = self as! LinearGradient
return LinearGradient(x1: linear.x1, y1: linear.y1, x2: linear.x2, y2: linear.y2, userSpace: linear.userSpace, stops: newStops)
}
func fillUsingGrayscaleNoAlpha() -> Fill {
if let color = self as? Color {
return color.toGrayscaleNoAlpha()
}
let gradient = self as! Gradient
let newStops = gradient.stops.map { Stop(offset: $0.offset, color: $0.color.toGrayscaleNoAlpha()) }
if let radial = self as? RadialGradient {
return RadialGradient(cx: radial.cx, cy: radial.cy, fx: radial.fx, fy: radial.fy, r: radial.r, userSpace: radial.userSpace, stops: newStops)
}
let linear = self as! LinearGradient
return LinearGradient(x1: linear.x1, y1: linear.y1, x2: linear.x2, y2: linear.y2, userSpace: linear.userSpace, stops: newStops)
}
}
extension Color {
func colorUsingAlphaOnly() -> Color {
return Color.black.with(a: Double(a()) / 255.0)
}
func toGrayscaleNoAlpha() -> Color {
let grey = Int(0.21 * Double(r()) + 0.72 * Double(g()) + 0.07 * Double(b()))
return Color.rgb(r: grey, g: grey, b: grey)
}
}
| mit | 08f5b326766f25a10da66a903615d9a9 | 39.122302 | 195 | 0.607226 | 4.273563 | false | false | false | false |
nicolafiorillo/BarcodeReader | BarcodeReader/Camera.swift | 1 | 13662 | //
// Camera.swift
// BarcodeReader
//
// Created by Nicola Fiorillo on 28/06/15.
// Copyright (c) 2015 White Peaks Mobile Software Sagl. All rights reserved.
//
import UIKit
import AVFoundation
class Camera : NSObject, AVCaptureMetadataOutputObjectsDelegate {
var cameraDelegate: CameraDelegate? = nil
private let videoPreview: VideoPreviewView?
private var cameraDevice: AVCaptureDevice! = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
private var captureSession: AVCaptureSession? = nil
private var videoInput: AVCaptureDeviceInput? = nil
private var imageOutput: AVCaptureStillImageOutput? = nil
private var metadataOutput: AVCaptureMetadataOutput? = nil
private var metadataQueue: dispatch_queue_t? = nil
private static let barcodes2D: Set<String> = [
AVMetadataObjectTypePDF417Code,
AVMetadataObjectTypeQRCode,
AVMetadataObjectTypeAztecCode,
AVMetadataObjectTypeEAN13Code,
AVMetadataObjectTypeEAN8Code ]
private var captureConnection: AVCaptureConnection? {
get {
if imageOutput == nil {
return nil
}
if let connections = imageOutput?.connections {
for connection in connections {
if let ports = connection.inputPorts {
for port in ports {
if port.mediaType == AVMediaTypeVideo {
return connection as? AVCaptureConnection
}
}
}
}
}
return nil
}
}
private var alternativeCameraToCurrent: AVCaptureDevice? {
get {
if captureSession == nil {
return nil
}
if let cameras = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) {
for cam in cameras as! [AVCaptureDevice] {
if cam != cameraDevice {
return cam
}
}
}
return nil
}
}
init(view: UIView) {
assert(view.isKindOfClass(VideoPreviewView), "View must be of type VideoPreviewView")
videoPreview = view as? VideoPreviewView
super.init()
if cameraDevice == nil {
println("BarcodeReader: camera not found")
return
}
authorizeAndSetupCamera()
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserverForName(AVCaptureDeviceSubjectAreaDidChangeNotification, object: nil, queue: NSOperationQueue.currentQueue()) { notification in
self.subjetChanged(notification)
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func authorizeAndSetupCamera() {
let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
switch (status) {
case AVAuthorizationStatus.Authorized:
println("BarcodeReader: authorized to use camera")
setupCamera()
break;
case AVAuthorizationStatus.NotDetermined:
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { granted in
dispatch_async(dispatch_get_main_queue(), {
if granted {
self.setupCamera()
// self.captureSession?.startRunning()
}
else {
println("BarcodeReader: unauthorized to use camera")
}
})
})
break;
case AVAuthorizationStatus.Restricted:
println("BarcodeReader: unauthorized to use camera (Restricted)")
break;
case AVAuthorizationStatus.Denied:
println("BarcodeReader: unauthorized to use camera (Denied)")
break;
default:
break;
}
}
func setupCamera() {
if (cameraDevice == nil) {
println("BarcodeReader: camera not found")
return
}
captureSession = AVCaptureSession()
videoInput = Camera.addVideoInputToCaptureSession(cameraDevice, captureSession: captureSession)
// image outmpu
imageOutput = AVCaptureStillImageOutput()
if captureSession?.canAddOutput(imageOutput) == false {
println("BarcodeReader: unable to add still image output to capture session")
return
}
captureSession?.addOutput(imageOutput)
// metadata output
metadataOutput = AVCaptureMetadataOutput()
metadataQueue = dispatch_get_main_queue()
metadataOutput?.setMetadataObjectsDelegate(self, queue: metadataQueue)
if captureSession?.canAddOutput(metadataOutput) == false {
println("BarcodeReader: unable to add metadata output to capture session")
return
}
captureSession?.addOutput(metadataOutput)
Camera.configureMetadata(metadataOutput!)
videoPreview?.previewLayer?.session = captureSession
Camera.configureCamera(cameraDevice)
println("BarcodeReader: ok")
}
func start() {
if captureSession == nil {
println("BarcodeReader: camera not initialized")
return;
}
println("BarcodeReader: start camera")
self.captureSession?.startRunning()
}
func stop() {
if captureSession == nil {
println("BarcodeReader: camera not initialized")
return;
}
println("BarcodeReader: stop camera")
self.captureSession?.stopRunning()
}
func switchCamera() {
if (cameraDevice == nil) {
println("BarcodeReader: camera not found")
return
}
if captureSession == nil {
println("BarcodeReader: camera not initialized")
return;
}
captureSession?.beginConfiguration()
let newCamera = alternativeCameraToCurrent
captureSession?.removeInput(videoInput)
if let newVideoInput = Camera.addVideoInputToCaptureSession(newCamera, captureSession: captureSession) {
cameraDevice = newCamera
videoInput = newVideoInput
CameraViewControllerOld.configureCamera(cameraDevice)
}
else {
captureSession?.addInput(videoInput)
}
updateConnectionToInterfaceOrientation(UIApplication.sharedApplication().statusBarOrientation)
captureSession?.commitConfiguration()
}
var hasTorch: Bool {
get {
return hasTorchInternal
}
}
func snap(completionHandler handler: ((CMSampleBuffer!, NSError!) -> Void)!) {
if captureSession == nil {
println("BarcodeReader: camera not initialized")
return;
}
if let videoConnection = captureConnection {
imageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: handler)
}
else {
println("BarcodeReader: no video connection for still image output")
handler(nil, NSError(domain: "BarcodeReader", code: 1, userInfo: nil))
}
}
private var hasTorchInternal: Bool {
get {
return cameraDevice != nil ? cameraDevice.hasTorch : false
}
}
func toggleTorch() {
if captureSession == nil {
println("BarcodeReader: camera not initialized")
return;
}
if hasTorchInternal {
println("BarcodeReader: trying set torch")
var error: NSError? = nil
if !cameraDevice.lockForConfiguration(&error) {
println("BarcodeReader: error locking camera configuration \(error?.localizedDescription)")
return
}
Camera.toggleTorchInternal(cameraDevice)
cameraDevice.unlockForConfiguration()
}
}
func updateOrientation() {
let interfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
updateConnectionToInterfaceOrientation(interfaceOrientation)
}
func handleTap(gesture: UITapGestureRecognizer) {
if !cameraDevice.focusPointOfInterestSupported || !cameraDevice.isFocusModeSupported(AVCaptureFocusMode.AutoFocus) {
println("BarcodeReader: focus point not supported by current camera")
return
}
let locationInPreview = gesture.locationInView(videoPreview)
let locationInCapture = videoPreview?.previewLayer?.captureDevicePointOfInterestForPoint(locationInPreview)
if cameraDevice.lockForConfiguration(nil) {
cameraDevice.focusPointOfInterest = locationInCapture!
cameraDevice.focusMode = AVCaptureFocusMode.AutoFocus
println("BarcodeReader: focus mode - locked to focus point")
cameraDevice.unlockForConfiguration()
}
}
private static func toggleTorchInternal(camera: AVCaptureDevice) {
let torchMode = camera.torchActive ? AVCaptureTorchMode.Off : AVCaptureTorchMode.On
if camera.isTorchModeSupported(torchMode) {
camera.torchMode = torchMode
println(String(format: "BarcodeReader: torch is %@", torchMode.rawValue == 0 ? "off" : "on"))
}
}
private static func addVideoInputToCaptureSession(camera: AVCaptureDevice?, captureSession: AVCaptureSession?) -> AVCaptureDeviceInput? {
var error: NSError? = nil
let videoInput = AVCaptureDeviceInput(device:camera, error: &error)
if videoInput == nil {
println("BarcodeReader: \(error?.localizedDescription)")
return nil
}
if captureSession?.canAddInput(videoInput) == false {
println("BarcodeReader: unable to add video input to capture session")
return nil
}
captureSession?.addInput(videoInput)
return videoInput
}
private static func configureCamera(camera: AVCaptureDevice?) {
if (camera?.isFocusModeSupported(AVCaptureFocusMode.Locked) != nil) {
if (camera?.lockForConfiguration(nil) != nil) {
camera?.subjectAreaChangeMonitoringEnabled = true
camera?.unlockForConfiguration()
}
}
}
private static func getVideoOrientationForUIInterfaceOrientation(interfaceOrientation: UIInterfaceOrientation) -> AVCaptureVideoOrientation {
switch (interfaceOrientation) {
case UIInterfaceOrientation.LandscapeLeft:
return AVCaptureVideoOrientation.LandscapeLeft
case UIInterfaceOrientation.LandscapeRight:
return AVCaptureVideoOrientation.LandscapeRight
case UIInterfaceOrientation.Portrait:
return AVCaptureVideoOrientation.Portrait
case UIInterfaceOrientation.PortraitUpsideDown:
return AVCaptureVideoOrientation.PortraitUpsideDown
default:
return AVCaptureVideoOrientation.Portrait
}
}
private func updateConnectionToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation) {
if captureSession == nil {
return;
}
let capturedOrientation = Camera.getVideoOrientationForUIInterfaceOrientation(toInterfaceOrientation)
if let connections = imageOutput?.connections {
for connection in connections as! [AVCaptureConnection] {
if connection.supportsVideoOrientation {
connection.videoOrientation = capturedOrientation
}
}
}
if let layer = videoPreview?.previewLayer {
if layer.connection.supportsVideoOrientation {
videoPreview?.previewLayer?.connection.videoOrientation = capturedOrientation
}
}
}
private func subjetChanged(notification: NSNotification) {
if cameraDevice.focusMode == AVCaptureFocusMode.Locked {
if cameraDevice.lockForConfiguration(nil) {
if cameraDevice.focusPointOfInterestSupported {
cameraDevice.focusPointOfInterest = CGPoint(x: 0.5, y: 0.5)
}
if cameraDevice.isFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus) {
cameraDevice.focusMode = AVCaptureFocusMode.ContinuousAutoFocus
}
cameraDevice.unlockForConfiguration()
println("BarcodeReader: continuous focus mode")
}
}
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
for metadataObject in metadataObjects as! [AVMetadataObject] {
if metadataObject.isKindOfClass(AVMetadataMachineReadableCodeObject) {
let barcode = metadataObject as! AVMetadataMachineReadableCodeObject
if cameraDelegate != nil {
let shapeLayer = Camera.flashBarcode(videoPreview, barcode: barcode)
Camera.delay(0.1) {
shapeLayer.removeFromSuperlayer()
self.cameraDelegate!.barcodeDetected!(Barcode(type: barcode.type, content: barcode.stringValue))
}
}
}
}
}
private static func configureMetadata(metadataOutput: AVCaptureMetadataOutput) {
let availableTypes = metadataOutput.availableMetadataObjectTypes as! [String]
if availableTypes.count == 0 {
println("BarcodeReader: no metadata types available")
return
}
let supported = barcodes2D.intersect(availableTypes)
println("Supported requested barcodes type: \(supported)")
println("Unsupported requested barcodes type: \(barcodes2D.subtract(supported))")
metadataOutput.metadataObjectTypes = Array(supported)
metadataOutput.rectOfInterest = CGRect(x: 0, y: 0, width: 1, height: 1)
}
private static let boxColor = UIColor(red: 0, green: 1, blue: 0, alpha: 0.25).CGColor
private static func flashBarcode(videoPreview: VideoPreviewView?, barcode: AVMetadataMachineReadableCodeObject) -> CAShapeLayer {
let path = Camera.createBarcodeBox((videoPreview?.previewLayer)!, barcode: barcode)
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = boxColor
shapeLayer.fillColor = boxColor
shapeLayer.lineWidth = 1
videoPreview?.layer.addSublayer(shapeLayer)
shapeLayer.frame = (videoPreview?.bounds)!
shapeLayer.path = path
return shapeLayer
}
private static func delay(delay:Double, closure:()->()) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure)
}
private static func createBarcodeBox(videoPreviewLayer: AVCaptureVideoPreviewLayer, barcode: AVMetadataMachineReadableCodeObject) -> CGPath {
let object = videoPreviewLayer.transformedMetadataObjectForMetadataObject(barcode) as! AVMetadataMachineReadableCodeObject
var path = CGPathCreateMutable()
var point = CGPointZero
CGPointMakeWithDictionaryRepresentation(object.corners[0] as! CFDictionary, &point)
CGPathMoveToPoint(path, nil, point.x, point.y)
CGPointMakeWithDictionaryRepresentation(object.corners[1] as! CFDictionary, &point)
CGPathAddLineToPoint(path, nil, point.x, point.y)
CGPointMakeWithDictionaryRepresentation(object.corners[2] as! CFDictionary, &point)
CGPathAddLineToPoint(path, nil, point.x, point.y)
CGPointMakeWithDictionaryRepresentation(object.corners[3] as! CFDictionary, &point)
CGPathAddLineToPoint(path, nil, point.x, point.y)
CGPathCloseSubpath(path)
return path
}
} | mit | 015d9adf8b75f938d505be10191a8bf4 | 28.194444 | 159 | 0.751135 | 4.557038 | false | false | false | false |
Bluthwort/Bluthwort | Sources/Classes/Style/UIViewStyle.swift | 1 | 11882 | //
// UIViewStyle.swift
//
// Copyright (c) 2018 Bluthwort
//
// 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 SnapKit
extension Bluthwort where Base: UIView {
@discardableResult
public func addSubview(_ subview: UIView,
with constraints: (ConstraintMaker) -> Swift.Void) -> Bluthwort {
base.addSubview(subview)
subview.snp.makeConstraints(constraints)
return self
}
@discardableResult
public func add(to superview: UIView,
with constraints: (ConstraintMaker) -> Swift.Void) -> Bluthwort {
superview.addSubview(base)
base.snp.makeConstraints(constraints)
return self
}
}
extension Bluthwort where Base: UIView {
@discardableResult
public func backgroundColor(_ color: UIColor) -> Bluthwort {
// The view’s background color.
base.backgroundColor = color
return self
}
@discardableResult
public func isHidden(_ flag: Bool) -> Bluthwort {
// A Boolean value that determines whether the view is hidden.
base.isHidden = flag
return self
}
@discardableResult
public func alpha(_ alpha: CGFloat) -> Bluthwort {
// The view’s alpha value.
base.alpha = alpha
return self
}
@discardableResult
public func isOpaque(_ flag: Bool) -> Bluthwort {
// A Boolean value that determines whether the view is opaque.
base.isOpaque = flag
return self
}
@discardableResult
public func tintColor(_ color: UIColor) -> Bluthwort {
// The first nondefault tint color value in the view’s hierarchy, ascending from and
// starting with the view itself.
base.tintColor = color
return self
}
@discardableResult
public func tintAdjustmentMode(_ mode: UIViewTintAdjustmentMode) -> Bluthwort {
// The first non-default tint adjustment mode value in the view’s hierarchy, ascending from
// and starting with the view itself.
base.tintAdjustmentMode = mode
return self
}
@discardableResult
public func clipsToBounds(_ flag: Bool) -> Bluthwort {
// A Boolean value that determines whether subviews are confined to the bounds of the view.
base.clipsToBounds = flag
return self
}
@discardableResult
public func clearsContextBeforeDrawing(_ flag: Bool) -> Bluthwort {
// A Boolean value that determines whether the view’s bounds should be automatically cleared
// before drawing.
base.clearsContextBeforeDrawing = flag
return self
}
@discardableResult
public func mask(_ mask: UIView) -> Bluthwort {
// An optional view whose alpha channel is used to mask a view’s content.
base.mask = mask
return self
}
@discardableResult
public func isUserInteractionEnabled(_ flag: Bool) -> Bluthwort {
// A Boolean value that determines whether user events are ignored and removed from the
// event queue.
base.isUserInteractionEnabled = flag
return self
}
@discardableResult
public func isMultipleTouchEnabled(_ flag: Bool) -> Bluthwort {
// A Boolean value that indicates whether the view receives more than one touch at a time.
base.isMultipleTouchEnabled = flag
return self
}
@discardableResult
public func isExclusiveTouch(_ flag: Bool) -> Bluthwort {
// A Boolean value that indicates whether the receiver handles touch events exclusively.
base.isExclusiveTouch = flag
return self
}
@discardableResult
public func frame(_ rect: CGRect) -> Bluthwort {
// The frame rectangle, which describes the view’s location and size in its superview’s
// coordinate system.
base.frame = rect
return self
}
@discardableResult
public func bounds(_ rect: CGRect) -> Bluthwort {
// The bounds rectangle, which describes the view’s location and size in its own coordinate
// system.
base.bounds = rect
return self
}
@discardableResult
public func center(_ point: CGPoint) -> Bluthwort {
// The center point of the view's frame rectangle.
base.center = point
return self
}
@discardableResult
public func transform(_ transform: CGAffineTransform) -> Bluthwort {
// Specifies the transform applied to the view, relative to the center of its bounds.
base.transform = transform
return self
}
@discardableResult
public func translatedBy(x offsetX: CGFloat, y offsetY: CGFloat) -> Bluthwort {
base.transform = base.transform.translatedBy(x: offsetX, y: offsetY)
return self
}
@discardableResult
public func scaledBy(x scaleX: CGFloat, y scaleY: CGFloat) -> Bluthwort {
base.transform = base.transform.scaledBy(x: scaleX, y: scaleY)
return self
}
@discardableResult
public func rotatedBy(angle: CGFloat) -> Bluthwort {
base.transform = base.transform.rotated(by: angle.bw.toRadian())
return self
}
@available(iOS 11.0, *)
@discardableResult
public func directionalLayoutMargins(_ margins: NSDirectionalEdgeInsets) -> Bluthwort {
// The default spacing to use when laying out content in a view, taking into account the
// current language direction.
base.directionalLayoutMargins = margins
return self
}
@discardableResult
public func layoutMargins(_ margins: UIEdgeInsets) -> Bluthwort {
// The default spacing to use when laying out content in the view.
base.layoutMargins = margins
return self
}
@discardableResult
public func preservesSuperviewLayoutMargins(_ flag: Bool) -> Bluthwort {
// A Boolean value indicating whether the current view also respects the margins of its
// superview.
base.preservesSuperviewLayoutMargins = flag
return self
}
@available(iOS 11.0, *)
@discardableResult
public func insetsLayoutMarginsFromSafeArea(_ flag: Bool) -> Bluthwort {
// A Boolean value indicating whether the view's layout margins are updated automatically to
// reflect the safe area.
insetsLayoutMarginsFromSafeArea
return self
}
@discardableResult
public func contentMode(_ mode: UIViewContentMode) -> Bluthwort {
// A flag used to determine how a view lays out its content when its bounds change.
base.contentMode = mode
return self
}
@discardableResult
public func autoresizesSubviews(_ flag: Bool) -> Bluthwort {
// A Boolean value that determines whether the receiver automatically resizes its subviews
// when its bounds change.
base.autoresizesSubviews = flag
return self
}
@discardableResult
public func autoresizingMask(_ mask: UIViewAutoresizing) -> Bluthwort {
// An integer bit mask that determines how the receiver resizes itself when its superview’s
// bounds change.
base.autoresizingMask = mask
return self
}
@discardableResult
public func translatesAutoresizingMaskIntoConstraints(_ flag: Bool) -> Bluthwort {
// A Boolean value that determines whether the view’s autoresizing mask is translated into
// Auto Layout constraints.
base.translatesAutoresizingMaskIntoConstraints = flag
return self
}
@available(iOS 9.0, *)
@discardableResult
public func semanticContentAttribute(_ attributes: UISemanticContentAttribute) -> Bluthwort {
// A semantic description of the view’s contents, used to determine whether the view should
// be flipped when switching between left-to-right and right-to-left layouts.
base.semanticContentAttribute = attributes
return self
}
@available(iOS 11.0, *)
@discardableResult
public func interactions(_ interactions: [UIInteraction]) -> Bluthwort {
// The array of interactions for the view.
base.interactions = interactions
return self
}
@discardableResult
public func contentScaleFactor(_ factor: CGFloat) -> Bluthwort {
// The scale factor applied to the view.
base.contentScaleFactor = factor
return self
}
@discardableResult
public func addGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) -> Bluthwort {
base.isUserInteractionEnabled = true
base.addGestureRecognizer(gestureRecognizer)
return self
}
@discardableResult
public func gestureRecognizers(_ gestureRecognizers: [UIGestureRecognizer]?) -> Bluthwort {
// The gesture-recognizer objects currently attached to the view.
base.gestureRecognizers = gestureRecognizers
return self
}
@discardableResult
public func addMotionEffect(_ effect: UIMotionEffect) -> Bluthwort {
base.addMotionEffect(effect)
return self
}
@discardableResult
public func motionEffects(_ motionEffects: [UIMotionEffect]) -> Bluthwort {
// The array of motion effects for the view.
base.motionEffects = motionEffects
return self
}
@discardableResult
public func restorationIdentifier(_ identifier: String?) -> Bluthwort {
// The identifier that determines whether the view supports state restoration.
base.restorationIdentifier = identifier
return self
}
@discardableResult
public func tag(_ tag: Int) -> Bluthwort {
// An integer that you can use to identify view objects in your application.
base.tag = tag
return self
}
@available(iOS 11.0, *)
@discardableResult
public func accessibilityIgnoresInvertColors(_ flag: Bool) -> Bluthwort {
// A Boolean value indicating whether the view ignores an accessibility request to invert
// its colors.
base.accessibilityIgnoresInvertColors = flag
return self
}
@discardableResult
public func cornerRadius(_ radius: CGFloat) -> Bluthwort {
base.layer.cornerRadius = radius
return self
}
@discardableResult
public func border(width: CGFloat, color: UIColor = .gray) -> Bluthwort {
base.layer.borderWidth = width
base.layer.borderColor = color.cgColor
return self
}
@discardableResult
public func shadow(radius: CGFloat, opacity: Float, color: UIColor, offset: CGSize) -> Bluthwort {
base.layer.shadowRadius = radius
base.layer.shadowOpacity = opacity
base.layer.shadowColor = color.cgColor
base.layer.shadowOffset = offset
return self
}
}
| mit | a17803c356aee415542f4afe6f19f200 | 33.371014 | 102 | 0.671108 | 5.327044 | false | false | false | false |
joshua7v/ResearchOL-iOS | ResearchOL/Class/Main/Controller/ROLTabBarController.swift | 1 | 10185 | //
// ROLTabBarController.swift
// ResearchOL
//
// Created by Joshua on 15/4/11.
// Copyright (c) 2015年 SigmaStudio. All rights reserved.
//
import UIKit
class ROLTabBarController: UITabBarController, UIGestureRecognizerDelegate {
let sideMenu = SESideMenu()
let kMenuWidth: CGFloat = 240
let coverView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width(), height: UIScreen.height()))
// var edgePanRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: "handleEdgePanRecognizer:")
let storyboardIdForMe = "ROLMeController"
let storyboardIdForMore = "ROLMoreController"
let storyboardIdForAbout = "ROLAboutController"
let storyboardIdForFeedback = "ROLFeedbackController"
let coverViewAlpha: CGFloat = 0.25
var progress: CGFloat = 0
var currentIndex = 0
var edgePanRecognizer: UIScreenEdgePanGestureRecognizer?
var coverTapRecognizer: UITapGestureRecognizer?
override func viewDidLoad() {
super.viewDidLoad()
self.configueBlocks()
self.configueGestrues()
self.configueViews()
self.configueNotifications()
// self.setBlurredScreenShoot()
}
private func configueNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "sideMenuWillShow", name: ROLNotifications.showMenuNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleUserLogoutNotification", name: ROLNotifications.userLogoutNotification, object: nil)
}
@objc private func handleUserLogoutNotification() {
self.showControllerWithIndex(0)
}
@objc private func sideMenuWillShow() {
self.coverView.hidden = false
self.coverView.alpha = 0
UIView.animateWithDuration(NSTimeInterval(0.5), delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
self.coverView.alpha = self.coverViewAlpha
self.setMenuOffset(self.kMenuWidth)
}) { (finished) -> Void in
}
}
private func configueBlocks() {
self.sideMenu.avatarBtnDidClickedBlock = {
if ROLUserInfoManager.sharedManager.isUserLogin {
UIView.animateWithDuration(NSTimeInterval(0.3), animations: { () -> Void in
self.setMenuOffset(0)
self.coverView.hidden = true
})
self.showControllerWithIndex(4)
} else {
UIView.animateWithDuration(NSTimeInterval(0.3), animations: { () -> Void in
self.setMenuOffset(0)
self.coverView.hidden = true
})
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(UIStoryboard(name: "Login", bundle: nil).instantiateInitialViewController() as! UINavigationController, animated: true, completion: { () -> Void in
})
}
}
self.sideMenu.didSelectedIndexBlock = { (index) -> Void in
UIView.animateWithDuration(NSTimeInterval(0.3), animations: { () -> Void in
self.setMenuOffset(0)
self.coverView.hidden = true
})
self.showControllerWithIndex(index)
}
}
private func showControllerWithIndex(index: NSInteger) {
if currentIndex == index { return }
self.sideMenu.removeFromSuperview()
self.coverView.removeFromSuperview()
self.coverView.hidden = true
var nextController: UIViewController? = nil
switch index {
case 0:
nextController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as! ROLTabBarController
self.currentIndex = 0
case 1:
nextController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(self.storyboardIdForMore) as! ROLNavigationController
self.currentIndex = 1
case 2:
nextController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(self.storyboardIdForFeedback) as! ROLNavigationController
self.currentIndex = 2
case 3:
nextController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(self.storyboardIdForAbout) as! ROLNavigationController
self.currentIndex = 3
case 4:
nextController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier(self.storyboardIdForMe) as! ROLNavigationController
self.currentIndex = 4
default:
nextController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() as! ROLTabBarController
self.currentIndex = 0
}
if !nextController!.isKindOfClass(ROLTabBarController.classForCoder()) {
nextController?.view.addGestureRecognizer(self.edgePanRecognizer!)
nextController?.view.addSubview(self.coverView)
nextController?.view.subviews.last!.addGestureRecognizer(self.coverTapRecognizer!)
nextController?.view.addSubview(self.sideMenu)
}
UIApplication.sharedApplication().keyWindow?.rootViewController = nextController
}
deinit {
println("--------deinit-----")
NSNotificationCenter.defaultCenter().removeObserver(self, name: ROLNotifications.showMenuNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: ROLNotifications.userLogoutNotification, object: nil)
}
private func configueViews() {
self.tabBar.tintColor = UIColor.blackColor()
var home = self.tabBar.items?.first as! UITabBarItem
home.selectedImage = UIImage(named: "tabbar_home_highlighted")
var mine = self.tabBar.items?.last as! UITabBarItem
mine.selectedImage = UIImage(named: "tabbar_mine_highlighted")
self.coverView.backgroundColor = UIColor(hexString: "000000")
self.coverView.hidden = true
self.coverView.alpha = self.coverViewAlpha
self.view.addSubview(self.coverView)
self.sideMenu.frame = CGRect(x: -kMenuWidth, y: 0, width: kMenuWidth, height: UIScreen.height())
self.view.addSubview(self.sideMenu)
}
private func configueGestrues() {
var edgePanRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: "handleEdgePanRecognizer:")
edgePanRecognizer.edges = UIRectEdge.Left
edgePanRecognizer.delegate = self
self.edgePanRecognizer = edgePanRecognizer
self.view.addGestureRecognizer(edgePanRecognizer)
var coverTapRecognizer = UITapGestureRecognizer(target: self, action: "handleCoverTapRecognizer:")
coverTapRecognizer.delegate = self
self.coverTapRecognizer = coverTapRecognizer
self.coverView.addGestureRecognizer(coverTapRecognizer)
}
private func setBlurredScreenShoot() {
var screenShot = self.view.screenshot()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
var blurColor = UIColor(white: 0.970, alpha: self.coverViewAlpha)
screenShot = screenShot.applyBlurWithRadius(12.0, tintColor: blurColor, saturationDeltaFactor: 1, maskImage: nil)
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self.sideMenu.blurredImage = screenShot
})
})
}
@objc private func leftBarButtonItemDidClicked() {
UIView.animateWithDuration(NSTimeInterval((1 - progress) / 1.5), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
self.setMenuOffset(self.kMenuWidth)
}, completion: nil)
}
@objc private func handleCoverTapRecognizer(recognizer: UITapGestureRecognizer) {
UIView.animateWithDuration(NSTimeInterval(0.3), animations: { () -> Void in
self.setMenuOffset(0)
self.coverView.hidden = true
})
}
@objc private func handleEdgePanRecognizer(recognizer: UIScreenEdgePanGestureRecognizer) {
var translation = recognizer.translationInView(self.view)
var progress = translation.x / kMenuWidth
progress = min(1.0, max(0.0, progress))
self.progress = progress
if recognizer.state == UIGestureRecognizerState.Began {
self.coverView.hidden = false
self.coverView.alpha = self.coverViewAlpha * progress
} else if recognizer.state == UIGestureRecognizerState.Changed {
self.setMenuOffset(kMenuWidth * progress)
self.coverView.alpha = self.coverViewAlpha * progress
} else if recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled {
var velocity = recognizer.velocityInView(self.view).x
if velocity > 20 || progress > 0.5 {
UIView.animateWithDuration(NSTimeInterval((1 - progress) / 1.5), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 3.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
self.setMenuOffset(self.kMenuWidth)
self.coverView.alpha = self.coverViewAlpha
}, completion: nil)
} else {
UIView.animateWithDuration(NSTimeInterval(progress / 3), delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
self.setMenuOffset(0)
self.coverView.hidden = true
}, completion: { (finished) -> Void in
})
}
}
}
private func setMenuOffset(offset: CGFloat) {
self.sideMenu.x = offset - kMenuWidth
self.sideMenu.setOffsetProgress(offset / kMenuWidth)
}
}
| mit | 424f3e6dba087b99bf46ff4ce9c7a15d | 46.362791 | 250 | 0.657174 | 5.158561 | false | false | false | false |
kevinbungeneers/SwiftInvaders | SwiftInvaders/Laser.swift | 1 | 1069 | //
// Laser.swift
// SwiftInvaders
//
// Created by Kevin Bungeneers on 28/11/14.
// Copyright (c) 2014 Kevin Bungeneers. All rights reserved.
//
import SpriteKit
class Laser: Entity {
convenience init() {
self.init(spriteName: "laserRed01")
}
override init(spriteName: String) {
super.init(spriteName: spriteName)
self.sprite.physicsBody = SKPhysicsBody(rectangleOfSize: self.sprite.size)
self.sprite.physicsBody?.categoryBitMask = CollisionType.Bullet.rawValue
self.sprite.physicsBody?.collisionBitMask = 0
self.sprite.physicsBody?.affectedByGravity = false
self.sprite.physicsBody?.contactTestBitMask = CollisionType.Edge.rawValue
}
internal func fire(position: CGPoint, parent: SKNode) {
let copy = self.sprite.copy() as! SKSpriteNode
copy.position = position
parent.addChild(copy)
let action: SKAction = SKAction.moveByX(0, y: 600, duration: 1.0)
copy.runAction(SKAction.repeatActionForever(action))
}
}
| mit | 683198994f2e670e8c99de5a12342672 | 28.694444 | 82 | 0.666043 | 4.225296 | false | false | false | false |
mohamede1945/quran-ios | Quran/GappedAudioPlayerInteractor.swift | 2 | 1252 | //
// GappedAudioPlayerInteractor.swift
// Quran
//
// Created by Mohamed Afifi on 5/14/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Foundation
class GappedAudioPlayerInteractor: DefaultAudioPlayerInteractor {
weak var delegate: AudioPlayerInteractorDelegate?
let downloader: AudioFilesDownloader
let lastAyahFinder: LastAyahFinder
let player: AudioPlayer
var downloadCancelled: Bool = false
init(downloader: AudioFilesDownloader, lastAyahFinder: LastAyahFinder, player: AudioPlayer) {
self.downloader = downloader
self.lastAyahFinder = lastAyahFinder
self.player = player
self.player.delegate = self
}
}
| gpl-3.0 | f43a133cbe0af3eac397b01b78d461b7 | 29.536585 | 97 | 0.734026 | 4.471429 | false | false | false | false |
vornet/mapdoodle-ios | Example/Tests/Tests.swift | 1 | 1176 | // https://github.com/Quick/Quick
import Quick
import Nimble
import MapDoodle
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | 1b5b7a77d54e5916a61409b4a703a0d3 | 22.4 | 63 | 0.363248 | 5.44186 | false | false | false | false |
borland/MTGLifeCounter2 | MTGLifeCounter2/StarViewController.swift | 1 | 7817 | //
// StarViewController.swift
// MTGLifeCounter2
//
// Created by Orion Edwards on 10/07/16.
// Copyright © 2016 Orion Edwards. All rights reserved.
//
import Foundation
import UIKit
class StarViewController : AbstractGameViewController {
override var initialLifeTotal:Int { return 20 }
override var configKey:String { return "star" }
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var d20Button: UIButton!
@IBOutlet weak var refreshButton: UIButton!
@IBOutlet weak var c1: UIView!
@IBOutlet weak var c2: UIView!
@IBOutlet weak var c3: UIView!
@IBOutlet weak var c4: UIView!
@IBOutlet weak var c5: UIView!
override func viewDidLoad() {
super.viewDidLoad()
for p in _players {
p.displaySize = .small
}
}
override func playerColorDidChange(deviceOrientation: ContainerOrientation) {
if(_players.count != 5) { return } // gets called spuriously during load
switch (deviceOrientation,
_players[0].color, _players[1].color, _players[2].color, _players[3].color, _players[4].color) {
case (.portrait, .white, _, _, _, _), // portrait, top VC is white
(.landscape, _, .white, _, _, _): // landscape, middle white
statusBarStyle = .default
default:
statusBarStyle = .lightContent
}
}
override func setConstraints(for size: CGSize) {
let constraints = view.constraints as [NSLayoutConstraint]
let toRemove = [c1!, c2!, c3!, c4!, c5!, backButton!, refreshButton!, d20Button!].flatMap{ constraints.affectingView($0) }
view.removeAllConstraints(toRemove)
let views = ["c1":c1!, "c2":c2!, "c3":c3!, "c4":c4!, "c5":c5!]
assert(_players.count == 5) // called before view loaded?
for p in _players {
p.buttonPosition = .rightLeft // force buttons on the side even though we don't normally do this in landscape
p.innerHorizontalOffset = 0
}
let safeArea = view.safeAreaLayoutGuide
if size.orientation == .portrait {
_players[0].orientation = .upsideDown
_players[1].orientation = .right
_players[1].buttonPosition = .aboveBelow
_players[2].orientation = .right
_players[2].buttonPosition = .aboveBelow
_players[3].orientation = .left
_players[3].buttonPosition = .belowAbove
_players[4].orientation = .left
_players[4].buttonPosition = .belowAbove
view.addConstraints([
// c1 fills horizontal
c1.leadingAnchor.constraint(equalTo: view.leadingAnchor),
c1.trailingAnchor.constraint(equalTo: view.trailingAnchor),
// c4, c2 (weird order is so it lines up with landscape view)
c4.leadingAnchor.constraint(equalTo: view.leadingAnchor),
c2.leadingAnchor.constraint(equalTo: c4.trailingAnchor),
c2.trailingAnchor.constraint(equalTo: view.trailingAnchor),
c4.widthAnchor.constraint(equalTo: c2.widthAnchor),
c4.heightAnchor.constraint(equalTo: c2.heightAnchor),
c4.topAnchor.constraint(equalTo: c2.topAnchor),
// c3, c5 (order reversed for some reason)
c5.leadingAnchor.constraint(equalTo: view.leadingAnchor),
c3.leadingAnchor.constraint(equalTo: c5.trailingAnchor),
c3.trailingAnchor.constraint(equalTo: view.trailingAnchor),
c5.widthAnchor.constraint(equalTo: c3.widthAnchor),
c5.heightAnchor.constraint(equalTo: c3.heightAnchor),
c5.topAnchor.constraint(equalTo: c3.topAnchor),
// stack the left row all vertically
c1.topAnchor.constraint(equalTo: view.topAnchor),
c4.topAnchor.constraint(equalTo: c1.bottomAnchor),
c5.topAnchor.constraint(equalTo: c4.bottomAnchor),
c5.bottomAnchor.constraint(equalTo: view.bottomAnchor),
// top view gets less space (not 33%) because it's wider, other views split evenly
c1.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.28),
// second row gets a bit more space as they're overlapped by buttons
c4.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.38),
// buttons
backButton.leftAnchor.constraint(equalTo: safeArea.leftAnchor, constant: 8),
backButton.centerYAnchor.constraint(equalTo: c1.bottomAnchor),
d20Button.centerXAnchor.constraint(equalTo: c1.centerXAnchor),
d20Button.centerYAnchor.constraint(equalTo: c1.bottomAnchor),
refreshButton.rightAnchor.constraint(equalTo: safeArea.rightAnchor, constant: -8),
refreshButton.centerYAnchor.constraint(equalTo: c1.bottomAnchor)
])
}
else { // landscape view
assert(size.orientation == .landscape)
_players[0].orientation = .upsideDown
_players[1].orientation = .upsideDown
_players[2].orientation = .upsideDown
_players[3].orientation = .normal
_players[4].orientation = .normal
_players[3].innerHorizontalOffset = 20
_players[4].innerHorizontalOffset = -20
// first row horizontally
view.addConstraints("H:|[c1(==c2)][c2(==c3)][c3(==c1)]|", views: views)
// second row horizontally
view.addConstraints("H:|[c4(==c5)][c5(==c4)]|", views: views)
view.addAllConstraints(
// stack two rows vertically (just align the leftmost and let the others stick to those)
// we USED to allocate 55% to the top row to account for the clock/navbar, but since iOS 12 it doesn't show in landscape anyway
[
c1.topAnchor.constraint(equalTo: view.topAnchor),
c1.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
c4.topAnchor.constraint(equalTo: c1.bottomAnchor),
c4.bottomAnchor.constraint(equalTo: view.bottomAnchor),
],
// all top row equal height and top aligned
[c2, c3].map { $0.heightAnchor.constraint(equalTo: c1.heightAnchor) },
[c2, c3].map { $0.topAnchor.constraint(equalTo: c1.topAnchor) },
// second row equal height and top aligned
[
c5.heightAnchor.constraint(equalTo: c4.heightAnchor),
c5.topAnchor.constraint(equalTo: c4.topAnchor),
// back button
backButton.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor, constant: 8),
backButton.centerYAnchor.constraint(equalTo: c1.bottomAnchor),
// refresh button
refreshButton.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -8),
refreshButton.centerYAnchor.constraint(equalTo: c1.bottomAnchor),
// d20 button
d20Button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
d20Button.centerYAnchor.constraint(equalTo: c1.bottomAnchor)
]
)
}
}
}
| mit | d8d93fec76171df91849cae4e2194316 | 43.662857 | 143 | 0.578045 | 4.900313 | false | false | false | false |
RyanTech/QueryKit | QueryKit/Expression.swift | 4 | 2817 | import Foundation
/// Returns an equality predicate for the two given expressions
public func == (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.EqualToPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
/// Returns an inequality predicate for the two given expressions
public func != (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.NotEqualToPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
public func > (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.GreaterThanPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
public func >= (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.GreaterThanOrEqualToPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
public func < (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.LessThanPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
public func <= (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.LessThanOrEqualToPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
public func ~= (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.LikePredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
public func << (left: NSExpression, right: NSExpression) -> NSPredicate {
return NSComparisonPredicate(leftExpression: left, rightExpression: right, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.InPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0))
}
| bsd-2-clause | 44f1b033cb341b0536d484f0525041eb | 79.485714 | 266 | 0.840256 | 5.74898 | false | false | false | false |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/CoreStore/CoreStore/Convenience Helpers/NSProgress+Convenience.swift | 2 | 4079 | //
// NSProgress+Convenience.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - NSProgress
public extension NSProgress {
/**
Sets a closure that the `NSProgress` calls whenever its `fractionCompleted` changes. You can use this instead of setting up KVO.
- parameter closure: the closure to execute on progress change
*/
public func setProgressHandler(closure: ((progress: NSProgress) -> Void)?) {
self.progressObserver.progressHandler = closure
}
// MARK: Private
private struct PropertyKeys {
static var progressObserver: Void?
}
private var progressObserver: ProgressObserver {
get {
let object: ProgressObserver? = getAssociatedObjectForKey(&PropertyKeys.progressObserver, inObject: self)
if let observer = object {
return observer
}
let observer = ProgressObserver(self)
setAssociatedRetainedObject(
observer,
forKey: &PropertyKeys.progressObserver,
inObject: self
)
return observer
}
}
}
@objc private final class ProgressObserver: NSObject {
private unowned let progress: NSProgress
private var progressHandler: ((progress: NSProgress) -> Void)? {
didSet {
let progressHandler = self.progressHandler
if (progressHandler == nil) == (oldValue == nil) {
return
}
if let _ = progressHandler {
self.progress.addObserver(
self,
forKeyPath: "fractionCompleted",
options: [.Initial, .New],
context: nil
)
}
else {
self.progress.removeObserver(self, forKeyPath: "fractionCompleted")
}
}
}
private init(_ progress: NSProgress) {
self.progress = progress
super.init()
}
deinit {
if let _ = self.progressHandler {
self.progressHandler = nil
self.progress.removeObserver(self, forKeyPath: "fractionCompleted")
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard let progress = object as? NSProgress where progress == self.progress && keyPath == "fractionCompleted" else {
return
}
GCDQueue.Main.async { [weak self] () -> Void in
self?.progressHandler?(progress: progress)
}
}
}
| apache-2.0 | 79c86ffb03fa55feeea4fea0755503db | 29.893939 | 157 | 0.590486 | 5.518268 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.