repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
imjerrybao/SocketIO-Kit | Source/SocketIOObject.swift | 2 | 468 | //
// SocketIOObject.swift
// Smartime
//
// Created by Ricardo Pereira on 12/05/2015.
// Copyright (c) 2015 Ricardo Pereira. All rights reserved.
//
import Foundation
/**
Socket.io object protocol.
*/
public protocol SocketIOObject {
/**
Creates an instance with data from a dictionary.
:param: dict Data dictionary.
*/
init(dict: NSDictionary)
/// Retrieve a dictionary.
var asDictionary: NSDictionary { get }
} | mit |
titoi2/IchigoJamSerialConsole | IchigoJamSerialConsole/Views/IJCTextView.swift | 1 | 596 | //
// IJCTextView.swift
// IchigoJamSerialConsole
//
// Created by titoi2 on 2015/04/01.
// Copyright (c) 2015年 titoi2. All rights reserved.
//
import Cocoa
protocol IJCTextViewDelegate {
func onTextViewKeyDown(theEvent: NSEvent)
}
class IJCTextView: NSTextView {
var keyDownDelegate : IJCTextViewDelegate?
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
}
override func keyDown(theEvent: NSEvent) {
// NSLog("override keyDown")
keyDownDelegate?.onTextViewKeyDown(theEvent)
}
}
| mit |
semiroot/SwiftyConstraints | Examples/iOS/iOS/MarginViewController.swift | 1 | 2128 | //
// MarginViewController.swift
// iOS
//
// Created by Hansmartin Geiser on 16/04/17.
// Copyright © 2017 Hansmartin Geiser. All rights reserved.
//
import UIKit
import SwiftyConstraints
class MarginViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Margin"
view.backgroundColor = .white
navigationController?.navigationBar.isTranslucent = false
let label = UILabel()
label.text = "There is no special margin functionality as of yet"
label.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
label.layer.cornerRadius = 5
label.numberOfLines = 0
label.textAlignment = .center
label.clipsToBounds = true
let box1 = SCView(); box1.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1); box1.layer.cornerRadius = 5
let box2 = SCView(); box2.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.15); box2.layer.cornerRadius = 5
let box3 = SCView(); box3.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2); box3.layer.cornerRadius = 5
let helper = SCView()
swiftyConstraints()
.attach(label)
.top(20)
.right(20)
.left(20)
.stackTop()
// Equidistant (by fixed space) tripplets with one helper view (I know, helper views, but at least it's not html tables)
.attach(helper)
.top(20)
.right(20).left() // You could also write left().widthOfSuperview(1, -20)
.execute({ (view) in
view.swiftyConstraints()
.attach(box1)
.top()
.bottom()
.widthOfSuperview(0.333, -20)
.heightFromWidth()
.left(20)
.stackLeft()
.attach(box2)
.top()
.bottom()
.widthOfSuperview(0.333, -20)
.heightFromWidth()
.left(20)
.stackLeft()
.attach(box3)
.top()
.bottom()
.widthOfSuperview(0.333, -20)
.heightFromWidth()
.left(20)
})
}
}
| mit |
volochaev/pokedex-example | pokedex/AppDelegate.swift | 1 | 2155 | //
// AppDelegate.swift
// pokedex
//
// Created by Nikolai Volochaev on 01/11/15.
// Copyright © 2015 Nikolai Volochaev. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
hyperoslo/Orchestra | Example/OrchestraDemo/OrchestraDemo/Sources/Models/Developer.swift | 1 | 1043 | import Foundation
struct Developer {
var id: Int
var name: String
var imageURL: NSURL
var githubURL: NSURL
// MARK: - Initializers
init(id: Int, name: String, imageURL: NSURL, githubURL: NSURL) {
self.id = id
self.name = name
self.imageURL = imageURL
self.githubURL = githubURL
}
// MARK: - Factory
static var developers: [Developer] {
return [
Developer(id: 0, name: "Christoffer Winterkvist",
imageURL: NSURL(string: "https://avatars2.githubusercontent.com/u/57446?v=3&s=460")!,
githubURL: NSURL(string: "https://github.com/zenangst")!),
Developer(id: 0, name: "Ramon Gilabert",
imageURL: NSURL(string: "https://avatars1.githubusercontent.com/u/6138120?v=3&s=460")!,
githubURL: NSURL(string: "https://github.com/RamonGilabert")!),
Developer(id: 0, name: "Vadym Markov",
imageURL: NSURL(string: "https://avatars2.githubusercontent.com/u/10529867?v=3&s=460")!,
githubURL: NSURL(string: "https://github.com/vadymmarkov")!)
]
}
}
| mit |
yangyueguang/MyCocoaPods | CarryOn/XUIKit.swift | 1 | 4341 | //
import UIKit
@IBDesignable
open class XButton: UIButton {
private var titleSize = CGSize.zero
private var imageSize = CGSize.zero
@IBInspectable open var direction: Int = 0
@IBInspectable open var interval: CGFloat = 0
override open func titleRect(forContentRect contentRect: CGRect) -> CGRect {
guard shouldLayout(contentRect) else {
return super.titleRect(forContentRect: contentRect)
}
var targetRect:CGRect = CGRect.zero
switch direction % 4 {
case 0:
targetRect = CGRect(x: (contentRect.width - titleSize.width)/2, y: (contentRect.height - titleSize.height - imageSize.height - interval)/2 + imageSize.height + interval, width: titleSize.width, height: titleSize.height)
case 1:
targetRect = CGRect(x: (contentRect.width - titleSize.width - imageSize.width - interval)/2, y: (contentRect.height - titleSize.height)/2, width: titleSize.width, height: titleSize.height)
case 2:
targetRect = CGRect(x: (contentRect.width - titleSize.width)/2, y: (contentRect.height - titleSize.height - imageSize.height - interval)/2, width: titleSize.width, height: titleSize.height)
default:
targetRect = CGRect(x: (contentRect.width - titleSize.width - imageSize.width - interval)/2 + imageSize.width + interval, y: (contentRect.height - titleSize.height)/2, width: titleSize.width, height: titleSize.height)
}
return targetRect
}
override open func imageRect(forContentRect contentRect: CGRect) -> CGRect {
guard shouldLayout(contentRect) else {
return super.imageRect(forContentRect: contentRect)
}
var targetRect:CGRect = CGRect.zero
switch direction % 4 {
case 0:
targetRect = CGRect.init(x: (contentRect.width - imageSize.width)/2, y: (contentRect.height - titleSize.height - imageSize.height - interval)/2, width: imageSize.width, height: imageSize.height)
case 1:
targetRect = CGRect.init(x: (contentRect.width - titleSize.width - imageSize.width - interval)/2 + titleSize.width + interval, y: (contentRect.height - imageSize.height)/2, width: imageSize.width, height: imageSize.height)
case 2:
targetRect = CGRect.init(x: (contentRect.width - imageSize.width)/2, y: (contentRect.height - titleSize.height - imageSize.height - interval)/2 + titleSize.height + interval, width: imageSize.width, height: imageSize.height)
default:
targetRect = CGRect.init(x: (contentRect.width - titleSize.width - imageSize.width - interval)/2, y: (contentRect.height - imageSize.height)/2, width: imageSize.width, height: imageSize.height)
}
return targetRect
}
private func shouldLayout(_ contentRect:CGRect) -> Bool {
guard subviews.count > 1, let image = currentImage,let _ = currentTitle,let titleL = titleLabel,let _ = imageView else {
return false
}
let titleFitSize = titleL.sizeThatFits(contentRect.size)
titleL.numberOfLines = 0
titleL.textAlignment = NSTextAlignment.center
switch direction % 4 {
case 1,3:
imageSize.width = min(min(contentRect.height, contentRect.width - 20 - interval),image.size.width)
imageSize.height = image.size.height * imageSize.width / image.size.width
titleSize.width = max(min(contentRect.width - imageSize.width - interval, titleFitSize.width), 20)
titleSize.height = contentRect.height
default:
titleSize.height = max(min(contentRect.height - image.size.height - interval, titleFitSize.height), 20)
titleSize.width = min(contentRect.width, titleFitSize.width)
imageSize.height = min(contentRect.height - titleFitSize.height, image.size.height)
imageSize.width = image.size.width * imageSize.height / image.size.height
}
return true
}
}
@IBDesignable
open class holdLabel: UILabel {
@IBInspectable open var placeholder: String = "" {
didSet {
text = placeholder
}
}
override open var text: String? {
didSet {
if text?.isEmpty ?? true && !placeholder.isEmpty {
self.text = placeholder
}
}
}
}
| mit |
victorpimentel/SwiftLint | Source/SwiftLintFramework/Rules/NotificationCenterDetachmentRule.swift | 2 | 3027 | //
// NotificationCenterDetachmentRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 01/15/17.
// Copyright © 2017 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct NotificationCenterDetachmentRule: ASTRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "notification_center_detachment",
name: "Notification Center Detachment",
description: "An object should only remove itself as an observer in `deinit`.",
nonTriggeringExamples: NotificationCenterDetachmentRuleExamples.nonTriggeringExamples,
triggeringExamples: NotificationCenterDetachmentRuleExamples.triggeringExamples
)
public func validate(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard kind == .class else {
return []
}
return violationOffsets(file: file, dictionary: dictionary).map { offset in
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset))
}
}
func violationOffsets(file: File, dictionary: [String: SourceKitRepresentable]) -> [Int] {
return dictionary.substructure.flatMap { subDict -> [Int] in
guard let kindString = subDict.kind,
let kind = SwiftExpressionKind(rawValue: kindString) else {
return []
}
// complete detachment is allowed on `deinit`
if kind == .other,
SwiftDeclarationKind(rawValue: kindString) == .functionMethodInstance,
subDict.name == "deinit" {
return []
}
if kind == .call, subDict.name == methodName,
parameterIsSelf(dictionary: subDict, file: file),
let offset = subDict.offset {
return [offset]
}
return violationOffsets(file: file, dictionary: subDict)
}
}
private var methodName = "NotificationCenter.default.removeObserver"
private func parameterIsSelf(dictionary: [String: SourceKitRepresentable], file: File) -> Bool {
guard let bodyOffset = dictionary.bodyOffset,
let bodyLength = dictionary.bodyLength else {
return false
}
let range = NSRange(location: bodyOffset, length: bodyLength)
let tokens = file.syntaxMap.tokens(inByteRange: range)
let types = tokens.flatMap { SyntaxKind(rawValue: $0.type) }
guard types == [.keyword], let token = tokens.first else {
return false
}
let body = file.contents.bridge().substringWithByteRange(start: token.offset, length: token.length)
return body == "self"
}
}
| mit |
adrfer/swift | test/BuildConfigurations/pound-if-inside-function.swift | 12 | 330 | // RUN: %target-parse-verify-swift
// Check that if config statement has range properly nested in its parent
// EOF.
func foo() { // expected-note {{to match this opening '{'}}
#if BLAH
// expected-error@+2{{expected '}' at end of brace statement}}
// expected-error@+1{{expected #else or #endif at end of configuration block}}
| apache-2.0 |
nextcloud/ios | iOSClient/More/NCMore.swift | 1 | 18979 | //
// NCMore.swift
// Nextcloud
//
// Created by Marino Faggiana on 03/04/17.
// Copyright © 2017 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <marino.faggiana@nextcloud.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.
//
// 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 UIKit
import NextcloudKit
import MarqueeLabel
class NCMore: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var labelQuota: UILabel!
@IBOutlet weak var labelQuotaExternalSite: UILabel!
@IBOutlet weak var progressQuota: UIProgressView!
@IBOutlet weak var viewQuota: UIView!
var functionMenu: [NKExternalSite] = []
var externalSiteMenu: [NKExternalSite] = []
var settingsMenu: [NKExternalSite] = []
var quotaMenu: [NKExternalSite] = []
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let defaultCornerRadius: CGFloat = 10.0
var tabAccount: tableAccount?
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = NSLocalizedString("_more_", comment: "")
view.backgroundColor = .systemGroupedBackground
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = .systemGroupedBackground
tableView.register(UINib(nibName: "NCMoreUserCell", bundle: nil), forCellReuseIdentifier: "userCell")
// create tap gesture recognizer
let tapQuota = UITapGestureRecognizer(target: self, action: #selector(tapLabelQuotaExternalSite))
labelQuotaExternalSite.isUserInteractionEnabled = true
labelQuotaExternalSite.addGestureRecognizer(tapQuota)
// Notification
NotificationCenter.default.addObserver(self, selector: #selector(initialize), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterInitialize), object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setGroupeAppreance()
appDelegate.activeViewController = self
loadItems()
tableView.reloadData()
}
// MARK: - NotificationCenter
@objc func initialize() {
loadItems()
}
// MARK: -
func loadItems() {
var item = NKExternalSite()
var quota: String = ""
// Clear
functionMenu.removeAll()
externalSiteMenu.removeAll()
settingsMenu.removeAll()
quotaMenu.removeAll()
labelQuotaExternalSite.text = ""
progressQuota.progressTintColor = NCBrandColor.shared.brandElement
// ITEM : Transfer
item = NKExternalSite()
item.name = "_transfers_"
item.icon = "arrow.left.arrow.right"
item.url = "segueTransfers"
functionMenu.append(item)
// ITEM : Recent
item = NKExternalSite()
item.name = "_recent_"
item.icon = "recent"
item.url = "segueRecent"
functionMenu.append(item)
// ITEM : Notification
item = NKExternalSite()
item.name = "_notification_"
item.icon = "bell"
item.url = "segueNotification"
functionMenu.append(item)
// ITEM : Activity
item = NKExternalSite()
item.name = "_activity_"
item.icon = "bolt"
item.url = "segueActivity"
functionMenu.append(item)
// ITEM : Shares
let isFilesSharingEnabled = NCManageDatabase.shared.getCapabilitiesServerBool(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesFileSharingApiEnabled, exists: false)
if isFilesSharingEnabled {
item = NKExternalSite()
item.name = "_list_shares_"
item.icon = "share"
item.url = "segueShares"
functionMenu.append(item)
}
// ITEM : Offline
item = NKExternalSite()
item.name = "_manage_file_offline_"
item.icon = "tray.and.arrow.down"
item.url = "segueOffline"
functionMenu.append(item)
// ITEM : Scan
item = NKExternalSite()
item.name = "_scanned_images_"
item.icon = "scan"
item.url = "openStoryboardNCScan"
functionMenu.append(item)
// ITEM : Trash
let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
if serverVersionMajor >= NCGlobal.shared.nextcloudVersion15 {
item = NKExternalSite()
item.name = "_trash_view_"
item.icon = "trash"
item.url = "segueTrash"
functionMenu.append(item)
}
// ITEM : Settings
item = NKExternalSite()
item.name = "_settings_"
item.icon = "gear"
item.url = "segueSettings"
settingsMenu.append(item)
// ITEM: Test API
/*
if NCUtility.shared.isSimulator() {
item = NKExternalSite()
item.name = "Test API"
item.icon = "swift"
item.url = "test"
settingsMenu.append(item)
}
*/
if quotaMenu.count > 0 {
let item = quotaMenu[0]
labelQuotaExternalSite.text = item.name
}
// Display Name user & Quota
if let activeAccount = NCManageDatabase.shared.getActiveAccount() {
self.tabAccount = activeAccount
if activeAccount.quotaRelative > 0 {
progressQuota.progress = Float(activeAccount.quotaRelative) / 100
} else {
progressQuota.progress = 0
}
switch activeAccount.quotaTotal {
case -1:
quota = "0"
case -2:
quota = NSLocalizedString("_quota_space_unknown_", comment: "")
case -3:
quota = NSLocalizedString("_quota_space_unlimited_", comment: "")
default:
quota = CCUtility.transformedSize(activeAccount.quotaTotal)
}
let quotaUsed: String = CCUtility.transformedSize(activeAccount.quotaUsed)
labelQuota.text = String.localizedStringWithFormat(NSLocalizedString("_quota_using_", comment: ""), quotaUsed, quota)
}
// ITEM : External
if NCBrandOptions.shared.disable_more_external_site == false {
if let externalSites = NCManageDatabase.shared.getAllExternalSites(account: appDelegate.account) {
for externalSite in externalSites {
if (externalSite.name != "" && externalSite.url != ""), let urlEncoded = externalSite.url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
item = NKExternalSite()
item.name = externalSite.name
item.url = urlEncoded
item.icon = "network"
if externalSite.type == "settings" {
item.icon = "gear"
}
externalSiteMenu.append(item)
}
}
}
}
}
// MARK: - Action
@objc func tapLabelQuotaExternalSite() {
if quotaMenu.count > 0 {
let item = quotaMenu[0]
let browserWebVC = UIStoryboard(name: "NCBrowserWeb", bundle: nil).instantiateInitialViewController() as! NCBrowserWeb
browserWebVC.urlBase = item.url
browserWebVC.isHiddenButtonExit = true
self.navigationController?.pushViewController(browserWebVC, animated: true)
self.navigationController?.navigationBar.isHidden = false
}
}
@objc func tapImageLogoManageAccount() {
let controller = CCManageAccount()
self.navigationController?.pushViewController(controller, animated: true)
}
// MARK: -
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return 75
} else {
return NCGlobal.shared.heightCellSettings
}
}
func numberOfSections(in tableView: UITableView) -> Int {
if externalSiteMenu.count == 0 {
return 3
} else {
return 4
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 10
} else {
return 20
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var cont = 0
if section == 0 {
cont = tabAccount == nil ? 0 : 1
} else if section == 1 {
// Menu Normal
cont = functionMenu.count
} else {
switch numberOfSections(in: tableView) {
case 3:
// Menu Settings
if section == 2 {
cont = settingsMenu.count
}
case 4:
// Menu External Site
if section == 2 {
cont = externalSiteMenu.count
}
// Menu Settings
if section == 3 {
cont = settingsMenu.count
}
default:
cont = 0
}
}
return cont
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var item = NKExternalSite()
// change color selection and disclosure indicator
let selectionColor: UIView = UIView()
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as! NCMoreUserCell
cell.avatar.image = nil
cell.icon.image = nil
cell.status.text = ""
cell.displayName.text = ""
if let account = tabAccount {
cell.avatar.image = NCUtility.shared.loadUserImage(
for: account.user,
displayName: account.displayName,
userBaseUrl: appDelegate)
if account.alias == "" {
cell.displayName?.text = account.displayName
} else {
cell.displayName?.text = account.displayName + " (" + account.alias + ")"
}
cell.displayName.textColor = .label
}
cell.selectedBackgroundView = selectionColor
cell.backgroundColor = .secondarySystemGroupedBackground
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
if NCManageDatabase.shared.getCapabilitiesServerBool(account: appDelegate.account, elements: NCElementsJSON.shared.capabilitiesUserStatusEnabled, exists: false) {
if let account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", appDelegate.account)) {
let status = NCUtility.shared.getUserStatus(userIcon: account.userStatusIcon, userStatus: account.userStatusStatus, userMessage: account.userStatusMessage)
cell.icon.image = status.onlineStatus
cell.status.text = status.statusMessage
cell.status.textColor = .label
cell.status.trailingBuffer = cell.status.frame.width
if cell.status.labelShouldScroll() {
cell.status.tapToScroll = true
} else {
cell.status.tapToScroll = false
}
}
}
cell.layer.cornerRadius = defaultCornerRadius
cell.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner, .layerMaxXMaxYCorner, .layerMinXMaxYCorner]
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CCCellMore
// Menu Normal
if indexPath.section == 1 {
item = functionMenu[indexPath.row]
}
// Menu External Site
if numberOfSections(in: tableView) == 4 && indexPath.section == 2 {
item = externalSiteMenu[indexPath.row]
}
// Menu Settings
if (numberOfSections(in: tableView) == 3 && indexPath.section == 2) || (numberOfSections(in: tableView) == 4 && indexPath.section == 3) {
item = settingsMenu[indexPath.row]
}
cell.imageIcon?.image = NCUtility.shared.loadImage(named: item.icon)
cell.labelText?.text = NSLocalizedString(item.name, comment: "")
cell.labelText.textColor = .label
cell.selectedBackgroundView = selectionColor
cell.backgroundColor = .secondarySystemGroupedBackground
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
cell.separator.backgroundColor = .separator
cell.separatorHeigth.constant = 0.4
cell.layer.cornerRadius = 0
let rows = tableView.numberOfRows(inSection: indexPath.section)
if indexPath.row == 0 {
cell.layer.cornerRadius = defaultCornerRadius
if indexPath.row == rows - 1 {
cell.separator.backgroundColor = .clear
cell.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner, .layerMaxXMaxYCorner, .layerMinXMaxYCorner]
} else {
cell.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]
}
} else if indexPath.row == rows - 1 {
cell.layer.cornerRadius = defaultCornerRadius
cell.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner]
cell.separator.backgroundColor = .clear
}
return cell
}
}
// method to run when table view cell is tapped
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var item = NKExternalSite()
if indexPath.section == 0 {
tapImageLogoManageAccount()
return
}
// Menu Function
if indexPath.section == 1 {
item = functionMenu[indexPath.row]
}
// Menu External Site
if numberOfSections(in: tableView) == 4 && indexPath.section == 2 {
item = externalSiteMenu[indexPath.row]
}
// Menu Settings
if (numberOfSections(in: tableView) == 3 && indexPath.section == 2) || (numberOfSections(in: tableView) == 4 && indexPath.section == 3) {
item = settingsMenu[indexPath.row]
}
// Action
if item.url.contains("segue") && !item.url.contains("//") {
self.navigationController?.performSegue(withIdentifier: item.url, sender: self)
} else if item.url.contains("openStoryboard") && !item.url.contains("//") {
let nameStoryboard = item.url.replacingOccurrences(of: "openStoryboard", with: "")
let storyboard = UIStoryboard(name: nameStoryboard, bundle: nil)
if let controller = storyboard.instantiateInitialViewController() {
controller.modalPresentationStyle = UIModalPresentationStyle.pageSheet
present(controller, animated: true, completion: nil)
}
} else if item.url.contains("//") {
let browserWebVC = UIStoryboard(name: "NCBrowserWeb", bundle: nil).instantiateInitialViewController() as! NCBrowserWeb
browserWebVC.urlBase = item.url
browserWebVC.isHiddenButtonExit = true
browserWebVC.titleBrowser = item.name
self.navigationController?.pushViewController(browserWebVC, animated: true)
self.navigationController?.navigationBar.isHidden = false
} else if item.url == "logout" {
let alertController = UIAlertController(title: "", message: NSLocalizedString("_want_delete_", comment: ""), preferredStyle: .alert)
let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (_: UIAlertAction) in
let manageAccount = CCManageAccount()
manageAccount.delete(self.appDelegate.account)
self.appDelegate.openLogin(viewController: self, selector: NCGlobal.shared.introLogin, openLoginWeb: false)
}
let actionNo = UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (_: UIAlertAction) in
print("You've pressed No button")
}
alertController.addAction(actionYes)
alertController.addAction(actionNo)
self.present(alertController, animated: true, completion: nil)
} else if item.url == "test" {
}
}
}
class CCCellMore: UITableViewCell {
@IBOutlet weak var labelText: UILabel!
@IBOutlet weak var imageIcon: UIImageView!
@IBOutlet weak var separator: UIView!
@IBOutlet weak var separatorHeigth: NSLayoutConstraint!
override var frame: CGRect {
get {
return super.frame
}
set (newFrame) {
var frame = newFrame
let newWidth = frame.width * 0.90
let space = (frame.width - newWidth) / 2
frame.size.width = newWidth
frame.origin.x += space
super.frame = frame
}
}
}
class NCMoreUserCell: UITableViewCell {
@IBOutlet weak var displayName: UILabel!
@IBOutlet weak var avatar: UIImageView!
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var status: MarqueeLabel!
override var frame: CGRect {
get {
return super.frame
}
set (newFrame) {
var frame = newFrame
let newWidth = frame.width * 0.90
let space = (frame.width - newWidth) / 2
frame.size.width = newWidth
frame.origin.x += space
super.frame = frame
}
}
}
| gpl-3.0 |
mabels/ipaddress | swift/Sources/IpAddress/rle.swift | 1 | 2219 |
public class Last<T: Equatable&Hashable> {
var val: Rle<T>?;
var max_poses = [T: [Int]]();
var ret: [Rle<T>] = [Rle<T>]();
public init() { }
func handle_last() {
if (nil == val) {
return;
}
let _last = val!;
var max_rles = max_poses[_last.part];
if (max_rles == nil) {
max_rles = [Int]();
//print("handle_last:push:\(_last.part)")
max_poses[_last.part] = max_rles;
}
//print("\(_last.part), \(max_rles!)");
for idx in max_rles! {
let prev = ret[idx];
if (prev.cnt > _last.cnt) {
//print(">>>>> last=\(_last)->\(idx)->prev=\(prev)");
_last.max = false;
} else if (prev.cnt == _last.cnt) {
// nothing
} else if (prev.cnt < _last.cnt) {
//print("<<<<< last=\(_last)->\(idx)->prev=\(prev)");
prev.max = false;
}
}
//println!("push:{}:{:?}", self.ret.len(), _last);
max_rles!.append(ret.count);
_last.pos = ret.count;
ret.append(_last);
max_poses[_last.part] = max_rles // funky swift
}
}
public class Rle<T: Equatable&Hashable>: Equatable, CustomStringConvertible {
var part: T;
var pos = 0;
var cnt = 0;
var max: Bool = false;
public init(part: T, pos: Int, cnt: Int, max: Bool) {
self.part = part;
self.pos = pos;
self.cnt = cnt;
self.max = max;
}
public var description: String {
return "<Rle@part:\(part),pos\(pos),cnt:\(cnt),max:\(max)>";
}
public final class func ==(lhs: Rle<T>, rhs: Rle<T>) -> Bool {
return lhs.eq(rhs)
}
public func eq(_ other: Rle<T>) -> Bool {
return part == other.part && pos == other.pos &&
cnt == other.cnt && max == other.max;
}
public func ne(_ other: Rle<T>) -> Bool {
return !eq(other);
}
public class func code<T: Equatable&Hashable>(_ parts: [T]) -> [Rle<T>] {
let last = Last<T>();
//print("code");
for part in parts {
// console.log(`part:${part}`);
if (last.val != nil && last.val!.part == part) {
last.val!.cnt += 1;
} else {
last.handle_last();
last.val = Rle<T>(part: part, pos: 0, cnt: 1, max: true);
}
}
last.handle_last();
return last.ret;
}
}
| mit |
LYM-mg/DemoTest | 其他功能/MGBookViews/MGBookViews/Camera/CameraBlurView.swift | 1 | 2442 | //
// CameraBlurView.swift
// MGBookViews
//
// Created by newunion on 2017/12/28.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
import SnapKit
class CameraBlurView: UIView {
@IBOutlet weak var tipLabel1: UILabel!
@IBOutlet weak var takePhotoView: UIView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var tipLabel2: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
tipLabel1.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/2))
tipLabel2.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/2))
let str: NSString = "请保持人像面朝上"
let range = str.range(of: "人像面朝上")
let attr2 = NSMutableAttributedString(string: str as String)
attr2.addAttribute(NSForegroundColorAttributeName, value: UIColor.colorHex(hex: "#FA5532"), range: range)
// attr2.addAttribute(NSVerticalGlyphFormAttributeName, value: 1, range: NSRange(location: 0, length: 6))
tipLabel2.attributedText = attr2
}
override func layoutSubviews() {
super.layoutSubviews()
tipLabel1.x = takePhotoView.x-15-tipLabel1.width
tipLabel1.center.y = takePhotoView.center.y
tipLabel2.x = takePhotoView.frame.maxX+15
tipLabel2.center.y = takePhotoView.center.y
// tipLabel1.snp.makeConstraints { (make) in
// make.centerY.equalTo(takePhotoView.snp.centerY)
// make.right.equalTo(takePhotoView.snp.left).offset(-15)
// }
// tipLabel2.snp.makeConstraints { (make) in
// make.centerY.equalTo(takePhotoView.snp.centerY)
// make.left.equalTo(takePhotoView.snp.right).offset(15)
// }
}
}
extension UIView {
}
@IBDesignable class VertricalLabel: UILabel {
@IBInspectable var angle: CGFloat {
get{
return super.transform.a
} set {
self.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)/angle)
}
}
/**
* 值为整型NSNumber,0为水平排版的字,1为垂直排版的字。注意,在iOS中, 总是以横向排版
*
* In iOS, horizontal text is always used and specifying a different value is undefined.
*/
// @IBInspectable var vertical: String {
// get{
// return super.attributedText as String
// } set {
// }
// }
}
| mit |
alienorb/Vectorized | VectorizedTests/HexColorTests.swift | 1 | 3957 | //---------------------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2016 Alien Orb Software LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//---------------------------------------------------------------------------------------
import XCTest
@testable import Vectorized
class HexColorTests: XCTestCase {
func testEmptyHex() {
XCTAssertNil(SVGColor(hex: ""))
XCTAssertNil(SVGColor(hex: " "))
}
func testRandomStrings() {
XCTAssertNil(SVGColor(hex: "this is not a hex string"))
XCTAssertNil(SVGColor(hex: "1"))
XCTAssertNil(SVGColor(hex: "#"))
XCTAssertNotNil(SVGColor(hex: "FFFFFF"))
XCTAssertNotNil(SVGColor(hex: "#FFF"))
XCTAssertNil(SVGColor(hex: "#QWERTY"))
}
func compareHex(hex: String, toWhite whiteCompare: CGFloat) {
if let color = SVGColor(hex: hex) {
var white: CGFloat = 0.0
var alpha: CGFloat = 0.0
color.getWhite(&white, alpha: &alpha)
XCTAssertEqualWithAccuracy(white, whiteCompare, accuracy: CGFloat(FLT_EPSILON))
} else {
XCTFail("Color \(hex) should not be nil")
}
}
func compareHex(hex: String, toRed redCompare: CGFloat, green greenCompare: CGFloat, blue blueCompare: CGFloat, alpha alphaCompare: CGFloat = 1.0) {
if let color = SVGColor(hex: hex) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 0.0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
XCTAssertEqualWithAccuracy(red, redCompare, accuracy: CGFloat(FLT_EPSILON))
XCTAssertEqualWithAccuracy(green, greenCompare, accuracy: CGFloat(FLT_EPSILON))
XCTAssertEqualWithAccuracy(blue, blueCompare, accuracy: CGFloat(FLT_EPSILON))
XCTAssertEqualWithAccuracy(alpha, alphaCompare, accuracy: CGFloat(FLT_EPSILON))
} else {
XCTFail("Color \(hex) should not be nil")
}
}
func testWhiteHex() {
compareHex("#FFFFFF", toWhite: 1.0)
compareHex("ffffff", toWhite: 1.0)
compareHex("FFF", toWhite: 1.0)
compareHex("#fff", toWhite: 1.0)
}
func testBlackHex() {
compareHex("#000000", toWhite: 0.0)
compareHex("#000", toWhite: 0.0)
}
func testRedHex() {
compareHex("#FF0000", toRed: 1.0, green: 0.0, blue: 0.0)
compareHex("ff0000", toRed: 1.0, green: 0.0, blue: 0.0)
compareHex("#f00", toRed: 1.0, green: 0.0, blue: 0.0)
}
func testGreenHex() {
compareHex("00FF00", toRed: 0.0, green: 1.0, blue: 0.0)
compareHex("#00ff00", toRed: 0.0, green: 1.0, blue: 0.0)
compareHex("0f0", toRed: 0.0, green: 1.0, blue: 0.0)
}
func testBlueHex() {
compareHex("#0000FF", toRed: 0.0, green: 0.0, blue: 1.0)
compareHex("0000ff", toRed: 0.0, green: 0.0, blue: 1.0)
compareHex("#00f", toRed: 0.0, green: 0.0, blue: 1.0)
}
func testRGBAHex() {
compareHex("#FF000000", toRed: 1.0, green: 0.0, blue: 0.0, alpha: 0.0)
compareHex("00ff00FF", toRed: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)
}
}
| mit |
xlexi/Textual-Inline-Media | Textual Inline Media/Inline Media Handlers/Wikipedia.swift | 1 | 7738 | /*
Copyright (c) 2015, Alex S. Glomsaas
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.
3. Neither the name of the copyright holder 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 Foundation
class Wikipedia: NSObject, InlineMediaHandler {
static func name() -> String {
return "Wikipedia"
}
static func icon() -> NSImage? {
return NSImage.fromAssetCatalogue("Wikipedia")
}
required convenience init(url: NSURL, controller: TVCLogController, line: String) {
self.init()
if let query = url.pathComponents?[2] {
let requestString = "format=json&action=query&exsentences=4&prop=extracts|pageimages&titles=\(query)&pithumbsize=200"
.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
let subdomain = url.host?.componentsSeparatedByString(".")[0]
guard subdomain != nil else {
return
}
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = ["User-Agent": "TextualInlineMedia/1.0 (https://github.com/xlexi/Textual-Inline-Media/; alex@sorlie.co.uk)"]
let session = NSURLSession(configuration: config)
if let requestUrl = NSURL(string: "https://\(subdomain!).wikipedia.org/w/api.php?\(requestString)") {
session.dataTaskWithURL(requestUrl, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
guard data != nil else {
return
}
do {
/* Attempt to serialise the JSON results into a dictionary. */
let root = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
guard let query = root["query"] as? Dictionary<String, AnyObject> else {
return
}
guard let pages = query["pages"] as? Dictionary<String, AnyObject> else {
WebRequest(url: response!.URL!, controller: controller, line: line).start()
return
}
let page = pages.first!
if page.0 != "-1" {
guard let article = page.1 as? Dictionary<String, AnyObject> else {
return
}
let title = article["title"] as? String
let description = article["extract"] as? String
var thumbnailUrl = ""
if let thumbnail = article["thumbnail"] as? Dictionary<String, AnyObject> {
guard let source = thumbnail["source"] as? String else {
return
}
thumbnailUrl = source
}
self.performBlockOnMainThread({
let document = controller.webView.mainFrameDocument
/* Create the container for the entire inline media element. */
let wikiContainer = document.createElement("a")
wikiContainer.setAttribute("href", value: url.absoluteString)
wikiContainer.className = "inline_media_wiki"
/* If we found a preview image element, we will add it. */
if thumbnailUrl.characters.count > 0 {
let previewImage = document.createElement("img")
previewImage.className = "inline_media_wiki_thumbnail"
previewImage.setAttribute("src", value: thumbnailUrl)
wikiContainer.appendChild(previewImage)
}
/* Create the container that holds the title and description. */
let infoContainer = document.createElement("div")
infoContainer.className = "inline_media_wiki_info"
wikiContainer.appendChild(infoContainer)
/* Create the title element */
let titleElement = document.createElement("div")
titleElement.className = "inline_media_wiki_title"
titleElement.appendChild(document.createTextNode(title))
infoContainer.appendChild(titleElement)
/* If we found a description, create the description element. */
if description!.characters.count > 0 {
let descriptionElement = document.createElement("div")
descriptionElement.className = "inline_media_wiki_desc"
descriptionElement.innerHTML = description
infoContainer.appendChild(descriptionElement)
}
controller.insertInlineMedia(line, node: wikiContainer, url: url.absoluteString)
})
}
} catch {
return
}
}).resume()
}
}
}
static func matchesServiceSchema(url: NSURL) -> Bool {
if url.host?.hasSuffix(".wikipedia.org") == true && url.pathComponents?.count === 3 {
return url.pathComponents![1] == "wiki"
}
return false
}
}
| bsd-3-clause |
vimac/BearRemoter-iOS | BearRemoter/BearRemoterViewController.swift | 1 | 3485 | //
// FirstViewController.swift
// BearRemoter
//
// Created by Mac on 8/15/15.
// Copyright (c) 2015 vifix.cn. All rights reserved.
//
import UIKit
class BearRemoterViewController: UITableViewController {
let tableData: [String] = ["我饿了😂", "我渴了😂", "我要睡觉了😂", "我要看电视了😂", "我要穿衣服了😂", "我要起床了😂", "我热了😂", "我冷了😂", "我要召唤神龙😂!"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cellRemoter")
// userInfo = BearUserInfo(cellPhone: "123456789")
let data = BearCache.sharedInstance.loadData()
NSLog(data.cellPhone!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let row = indexPath.row as Int
let content = tableData[row] as String
NSLog("pressed %@", content)
let userInfo = BearCache.sharedInstance.userInfo
let alert = UIAlertController(title: "将要发送", message: content, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction) in
let urlPath: String = "http://vifix.cn/remoter/send.php"
let url: NSURL = NSURL(string: urlPath)!
let req: NSMutableURLRequest = NSMutableURLRequest(URL: url)
req.HTTPMethod = "POST"
let stringPost = "cellPhone=\(userInfo?.cellPhone as String!)&nickname=\(userInfo?.nickname as String!)&targetCellPhone=\(userInfo?.targetCellPhone as String!)&message=\(content)"
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
req.timeoutInterval = 60
req.HTTPBody = data
req.HTTPShouldHandleCookies = false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(req, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
var err: NSError
//var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
//println("AsSynchronous\(jsonResult)")
// println(NSString(data: <#NSData#>, encoding: <#UInt#>))
})
}))
alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellRemoter", forIndexPath: indexPath)
let row = indexPath.row as Int
cell.textLabel?.text = tableData[row]
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell;
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/01514-swift-optional-swift-diagnostic-operator.swift | 11 | 497 | // 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
// RUN: not %target-swift-frontend %s -parse
protocol b : a {
func b(t.b {
}
func f(a(Any, object2: Sequence where d<T>()
}
protocol a {
protocol a {
| apache-2.0 |
kstaring/swift | validation-test/compiler_crashers_fixed/00470-swift-constraints-constraintsystem-simplifyconstraint.swift | 11 | 473 | // 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
// RUN: not %target-swift-frontend %s -parse
let h: U -> {
let d<T> Void>()
protocol a {
}
}
protocol C {
typealias e : e, U)
| apache-2.0 |
minikin/Algorithmics | Pods/PSOperations/PSOperations/LocationCondition.swift | 1 | 5628 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows an example of implementing the OperationCondition protocol.
*/
#if !os(OSX)
import CoreLocation
/// A condition for verifying access to the user's location.
@available(*, deprecated, message="use Capability(Location...) instead")
public struct LocationCondition: OperationCondition {
/**
Declare a new enum instead of using `CLAuthorizationStatus`, because that
enum has more case values than are necessary for our purposes.
*/
public enum Usage {
case WhenInUse
#if !os(tvOS)
case Always
#endif
}
public static let name = "Location"
static let locationServicesEnabledKey = "CLLocationServicesEnabled"
static let authorizationStatusKey = "CLAuthorizationStatus"
public static let isMutuallyExclusive = false
let usage: Usage
public init(usage: Usage) {
self.usage = usage
}
public func dependencyForOperation(operation: Operation) -> NSOperation? {
return LocationPermissionOperation(usage: usage)
}
public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) {
let enabled = CLLocationManager.locationServicesEnabled()
let actual = CLLocationManager.authorizationStatus()
var error: NSError?
// There are several factors to consider when evaluating this condition
switch (enabled, usage, actual) {
case (true, _, .AuthorizedAlways):
// The service is enabled, and we have "Always" permission -> condition satisfied.
break
case (true, .WhenInUse, .AuthorizedWhenInUse):
/*
The service is enabled, and we have and need "WhenInUse"
permission -> condition satisfied.
*/
break
default:
/*
Anything else is an error. Maybe location services are disabled,
or maybe we need "Always" permission but only have "WhenInUse",
or maybe access has been restricted or denied,
or maybe access hasn't been request yet.
The last case would happen if this condition were wrapped in a `SilentCondition`.
*/
error = NSError(code: .ConditionFailed, userInfo: [
OperationConditionKey: self.dynamicType.name,
self.dynamicType.locationServicesEnabledKey: enabled,
self.dynamicType.authorizationStatusKey: Int(actual.rawValue)
])
}
if let error = error {
completion(.Failed(error))
}
else {
completion(.Satisfied)
}
}
}
/**
A private `Operation` that will request permission to access the user's location,
if permission has not already been granted.
*/
class LocationPermissionOperation: Operation {
let usage: LocationCondition.Usage
var manager: CLLocationManager?
init(usage: LocationCondition.Usage) {
self.usage = usage
super.init()
/*
This is an operation that potentially presents an alert so it should
be mutually exclusive with anything else that presents an alert.
*/
addCondition(AlertPresentation())
}
override func execute() {
/*
Not only do we need to handle the "Not Determined" case, but we also
need to handle the "upgrade" (.WhenInUse -> .Always) case.
*/
#if os(tvOS)
switch (CLLocationManager.authorizationStatus(), usage) {
case (.NotDetermined, _):
dispatch_async(dispatch_get_main_queue()) {
self.requestPermission()
}
default:
finish()
}
#else
switch (CLLocationManager.authorizationStatus(), usage) {
case (.NotDetermined, _), (.AuthorizedWhenInUse, .Always):
dispatch_async(dispatch_get_main_queue()) {
self.requestPermission()
}
default:
finish()
}
#endif
}
private func requestPermission() {
manager = CLLocationManager()
manager?.delegate = self
let key: String
#if os(tvOS)
switch usage {
case .WhenInUse:
key = "NSLocationWhenInUseUsageDescription"
manager?.requestWhenInUseAuthorization()
}
#else
switch usage {
case .WhenInUse:
key = "NSLocationWhenInUseUsageDescription"
manager?.requestWhenInUseAuthorization()
case .Always:
key = "NSLocationAlwaysUsageDescription"
manager?.requestAlwaysAuthorization()
}
#endif
// This is helpful when developing the app.
assert(NSBundle.mainBundle().objectForInfoDictionaryKey(key) != nil, "Requesting location permission requires the \(key) key in your Info.plist")
}
}
extension LocationPermissionOperation: CLLocationManagerDelegate {
@objc func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if manager == self.manager && executing && status != .NotDetermined {
finish()
}
}
}
#endif
| mit |
practicalswift/swift | test/stdlib/OptionalBridge.swift | 34 | 5791 | //===--- OptionalBridge.swift - Tests of Optional bridging ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
import StdlibUnittest
let tests = TestSuite("OptionalBridge")
// Work around bugs in the type checker preventing casts back to optional.
func cast<T>(_ value: AnyObject, to: T.Type) -> T {
return value as! T
}
// expectEqual() helpers for deeper-nested nullability than StdlibUnittest
// provides.
func expectEqual<T: Equatable>(_ x: T??, _ y: T??) {
switch (x, y) {
case (.some(let xx), .some(let yy)):
expectEqual(xx, yy)
case (.none, .none):
return
default:
expectUnreachable("\(T.self)?? values don't match: \(x) vs. \(y)")
}
}
func expectEqual<T: Equatable>(_ x: T???, _ y: T???) {
switch (x, y) {
case (.some(let xx), .some(let yy)):
expectEqual(xx, yy)
case (.none, .none):
return
default:
expectUnreachable("\(T.self)??? values don't match: \(x) vs. \(y)")
}
}
tests.test("wrapped value") {
let unwrapped = "foo"
let wrapped = Optional(unwrapped)
let doubleWrapped = Optional(wrapped)
let unwrappedBridged = unwrapped as AnyObject
let wrappedBridged = wrapped as AnyObject
let doubleWrappedBridged = doubleWrapped as AnyObject
expectTrue(unwrappedBridged.isEqual(wrappedBridged)
&& wrappedBridged.isEqual(doubleWrappedBridged))
let unwrappedCastBack = cast(unwrappedBridged, to: String.self)
let wrappedCastBack = cast(wrappedBridged, to: Optional<String>.self)
let doubleWrappedCastBack = cast(doubleWrappedBridged, to: Optional<String?>.self)
expectEqual(unwrapped, unwrappedCastBack)
expectEqual(wrapped, wrappedCastBack)
expectEqual(doubleWrapped, doubleWrappedCastBack)
}
struct NotBridged: Hashable {
var x: Int
func hash(into hasher: inout Hasher) {
hasher.combine(x)
}
static func ==(x: NotBridged, y: NotBridged) -> Bool {
return x.x == y.x
}
}
tests.test("wrapped boxed value") {
let unwrapped = NotBridged(x: 1738)
let wrapped = Optional(unwrapped)
let doubleWrapped = Optional(wrapped)
let unwrappedBridged = unwrapped as AnyObject
let wrappedBridged = wrapped as AnyObject
let doubleWrappedBridged = doubleWrapped as AnyObject
expectTrue(unwrappedBridged.isEqual(wrappedBridged))
expectTrue(wrappedBridged.isEqual(doubleWrappedBridged))
let unwrappedCastBack = cast(unwrappedBridged, to: NotBridged.self)
let wrappedCastBack = cast(wrappedBridged, to: Optional<NotBridged>.self)
let doubleWrappedCastBack = cast(doubleWrappedBridged, to: Optional<NotBridged?>.self)
expectEqual(unwrapped, unwrappedCastBack)
expectEqual(wrapped, wrappedCastBack)
expectEqual(doubleWrapped, doubleWrappedCastBack)
}
tests.test("wrapped class instance") {
let unwrapped = LifetimeTracked(0)
let wrapped = Optional(unwrapped)
expectTrue(wrapped as AnyObject === unwrapped as AnyObject)
}
tests.test("nil") {
let null: String? = nil
let wrappedNull = Optional(null)
let doubleWrappedNull = Optional(wrappedNull)
let nullBridged = null as AnyObject
let wrappedNullBridged = wrappedNull as AnyObject
let doubleWrappedNullBridged = doubleWrappedNull as AnyObject
expectTrue(nullBridged === NSNull())
expectTrue(wrappedNullBridged === NSNull())
expectTrue(doubleWrappedNullBridged === NSNull())
let nullCastBack = cast(nullBridged, to: Optional<String>.self)
let wrappedNullCastBack = cast(nullBridged, to: Optional<String?>.self)
let doubleWrappedNullCastBack = cast(nullBridged, to: Optional<String??>.self)
expectEqual(nullCastBack, null)
expectEqual(wrappedNullCastBack, wrappedNull)
expectEqual(doubleWrappedNullCastBack, doubleWrappedNull)
}
tests.test("nil in nested optional") {
let doubleNull: String?? = nil
let wrappedDoubleNull = Optional(doubleNull)
let doubleNullBridged = doubleNull as AnyObject
let wrappedDoubleNullBridged = wrappedDoubleNull as AnyObject
expectTrue(doubleNullBridged === wrappedDoubleNullBridged)
expectTrue(doubleNullBridged !== NSNull())
let doubleNullCastBack = cast(doubleNullBridged, to: Optional<String?>.self)
let wrappedDoubleNullCastBack = cast(doubleNullBridged, to: Optional<String??>.self)
expectEqual(doubleNullCastBack, doubleNull)
expectEqual(wrappedDoubleNullCastBack, wrappedDoubleNull)
let tripleNull: String??? = nil
let tripleNullBridged = tripleNull as AnyObject
expectTrue(doubleNullBridged !== tripleNullBridged)
let tripleNullCastBack = cast(tripleNullBridged, to: Optional<String??>.self)
expectEqual(tripleNullCastBack, tripleNull)
}
tests.test("collection of Optional") {
let holeyArray: [LifetimeTracked?] = [LifetimeTracked(0), nil, LifetimeTracked(1)]
let nsArray = holeyArray as NSArray
autoreleasepool {
expectTrue((nsArray[0] as AnyObject) === holeyArray[0]!)
expectTrue((nsArray[1] as AnyObject) === NSNull())
expectTrue((nsArray[2] as AnyObject) === holeyArray[2]!)
}
}
tests.test("NSArray of NSNull") {
let holeyNSArray: NSArray = [LifetimeTracked(2), NSNull(), LifetimeTracked(3)]
autoreleasepool {
let swiftArray = holeyNSArray as! [LifetimeTracked?]
expectTrue(swiftArray[0]! === holeyNSArray[0] as AnyObject)
expectTrue(swiftArray[1] == nil)
expectTrue(swiftArray[2]! === holeyNSArray[2] as AnyObject)
}
}
runAllTests()
| apache-2.0 |
eurofurence/ef-app_ios | Packages/EurofurenceComponents/Sources/XCTComponentBase/Contracts/URLBasedActivityItemTestCase.swift | 1 | 2096 | import ComponentBase
import LinkPresentation
import XCTest
open class URLBasedActivityItemTestCase: XCTestCase {
private var activityViewController: UIActivityViewController!
private var activityItem: URLBasedActivityItem!
override open func setUp() {
super.setUp()
activityViewController = UIActivityViewController(activityItems: [], applicationActivities: nil)
}
open func makeActivityItem() throws -> URLBasedActivityItem {
let url = try XCTUnwrap(URL(string: "https://test.com"))
return URLBasedActivityItem(url: url)
}
public func linkMetadata(from activityItem: UIActivityItemSource) -> LPLinkMetadata? {
activityItem.activityViewControllerLinkMetadata?(activityViewController)
}
open func testUsesURLForPlaceholderItem() throws {
activityItem = try makeActivityItem()
let expected = activityItem.url
let activityController = UIActivityViewController(activityItems: [], applicationActivities: nil)
let actual = activityItem.activityViewController(activityController, itemForActivityType: nil)
XCTAssertEqual(expected, actual as? URL)
}
open func testItemUsesURL() throws {
activityItem = try makeActivityItem()
let expected = activityItem.url
let activityController = UIActivityViewController(activityItems: [], applicationActivities: nil)
let actual = activityItem.activityViewController(activityController, itemForActivityType: nil)
XCTAssertEqual(expected, actual as? URL)
}
open func testPreparingLinkMetadata() throws {
activityItem = try makeActivityItem()
let linkMetadata = try XCTUnwrap(self.linkMetadata(from: activityItem))
assertAgainstLinkMetadata(linkMetadata, activityItem: activityItem)
}
open func assertAgainstLinkMetadata(_ metadata: LPLinkMetadata, activityItem: URLBasedActivityItem) {
XCTAssertEqual(activityItem.url, metadata.url)
XCTAssertNotNil(metadata.iconProvider)
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/19503-void.swift | 11 | 257 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func a( ) {
let h = 0.g
class C {
class d {
{
}
struct B<T where g: Int {
struct B<T: a
| mit |
BBRick/wp | wp/Scenes/Deal/HistoryDealVC.swift | 1 | 7017 | //
// HistoryDealVC.swift
// wp
//
// Created by 木柳 on 2017/1/4.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
import RealmSwift
import DKNightVersion
class HistoryDealCell: OEZTableViewCell{
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var winLabel: UILabel!
@IBOutlet weak var failLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var handleLabel: UILabel!
// 盈亏
@IBOutlet weak var statuslb: UILabel!
override func update(_ data: Any!) {
if let model: PositionModel = data as! PositionModel? {
print(model.description)
nameLabel.text = "\(model.name)"
timeLabel.text = Date.yt_convertDateToStr(Date.init(timeIntervalSince1970: TimeInterval(model.closeTime)), format: "yyyy.MM.dd HH:mm:ss")
//com.yundian.trip
priceLabel.text = "¥" + String(format: "%.2f", model.openCost)
priceLabel.dk_textColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main)
statuslb.backgroundColor = model.result ? UIColor.init(hexString: "E9573F") : UIColor.init(hexString: "0EAF56")
statuslb.text = model.result ? "盈" : "亏"
titleLabel.text = model.buySell == 1 ? "买入" : "卖出"
let handleText = [" 未操作 "," 双倍返还 "," 货运 "," 退舱 "]
if model.handle < handleText.count{
handleLabel.text = handleText[model.handle]
}
if model.buySell == -1 && UserModel.share().currentUser?.type == 0 && model.result == false{
handleLabel.backgroundColor = UIColor.clear
handleLabel.text = ""
}else if model.handle == 0{
handleLabel.backgroundColor = UIColor.init(rgbHex: 0xc2cfd7)
}else{
handleLabel.dk_backgroundColorPicker = DKColorTable.shared().picker(withKey: AppConst.Color.main)
}
}
}
}
class HistoryDealVC: BasePageListTableViewController {
var historyModels: [PositionModel] = []
//MARK: --LIFECYCLE
override func viewDidLoad() {
super.viewDidLoad()
}
override func didRequest(_ pageIndex: Int) {
historyModels = dataSource == nil ? [] : dataSource as! [PositionModel]
let index = pageIndex == 1 ? 0: historyModels.count
AppAPIHelper.deal().historyDeals(start: index, count: 10, complete: { [weak self](result) -> ()? in
if let models: [PositionModel] = result as! [PositionModel]?{
if pageIndex == 1 {
self?.didRequestComplete(models as AnyObject?)
}else{
var moreModels: [PositionModel] = []
for model in models{
if model.closeTime < (self?.historyModels.last!.closeTime)!{
moreModels.append(model)
}
}
self?.didRequestComplete(moreModels as AnyObject?)
}
}
return nil
}, error: errorBlockFunc())
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let model = self.dataSource?[indexPath.row] as? PositionModel{
print(model.handle)
if model.handle != 0{
return
}
if model.buySell == -1 && UserModel.share().currentUser?.type == 0 && model.result == false{
return
}
let param = BenifityParam()
param.tid = model.positionId
let alterController = UIAlertController.init(title: "恭喜盈利", message: "请选择盈利方式", preferredStyle: .alert)
let productAction = UIAlertAction.init(title: "货运", style: .default, handler: {[weak self] (resultDic) in
param.handle = 2
AppAPIHelper.deal().benifity(param: param, complete: {(result) -> ()? in
if let resultDic: [String: AnyObject] = result as? [String: AnyObject]{
if let id = resultDic[SocketConst.Key.id] as? Int{
if id != UserModel.share().currentUserId{
return nil
}
}
if let handle = resultDic[SocketConst.Key.handle] as? Int{
if let selectModel = self?.dataSource?[indexPath.row] as? PositionModel{
UserModel.updateUser(info: { (info) -> ()? in
selectModel.handle = handle
tableView.reloadData()
return nil
})
}
}
}
return nil
}, error: self?.errorBlockFunc())
})
let moneyAction = UIAlertAction.init(title: "双倍返还", style: .default, handler: { [weak self](resultDic) in
param.handle = 1
AppAPIHelper.deal().benifity(param: param, complete: {(result) -> ()? in
if let resultDic: [String: AnyObject] = result as? [String: AnyObject]{
if let id = resultDic[SocketConst.Key.id] as? Int{
if id != UserModel.share().currentUserId{
return nil
}
}
if let handle = resultDic[SocketConst.Key.handle] as? Int{
if let selectModel = self?.dataSource?[indexPath.row] as? PositionModel{
UserModel.updateUser(info: { (info) -> ()? in
selectModel.handle = handle
tableView.reloadData()
return nil
})
}
}
}
return nil
}, error: self?.errorBlockFunc())
})
if model.buySell == 1{
if model.result{
alterController.addAction(moneyAction)
}
alterController.addAction(productAction)
present(alterController, animated: true, completion: nil)
}else{
if UserModel.share().currentUser?.type == 0 && model.result{
alterController.addAction(moneyAction)
}else{
alterController.addAction(productAction)
}
present(alterController, animated: true, completion: nil)
}
}
}
}
| apache-2.0 |
aranasaurus/minutes-app | minutesTests/SessionTests.swift | 1 | 3539 | //
// SessionTests.swift
// Minutes
//
// Created by Ryan Arana on 11/26/16.
// Copyright © 2016 Aranasaurus. All rights reserved.
//
import XCTest
@testable import Minutes
class SessionTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testDuration() {
let expected = TimeInterval(10)
let startTime = Date(timeIntervalSinceNow: -3600)
// Given a start and end time it should report the time between them
XCTAssertEqual(Session(rate: 0, startTime: startTime, endTime: Date(timeInterval: expected, since: startTime)).duration, expected)
// Given a start time and no end time it should report the time that has passed since the
// start time
XCTAssertEqual(Session(rate: 0, startTime: startTime).duration, Date().timeIntervalSince(startTime), accuracy: 0.001)
}
func testCost() {
let hour = Measurement(value: 1, unit: UnitDuration.hours)
// A session with rate 0, should always have a cost of 0
XCTAssertEqual(Session(rate: 0, startTime: Date(timeIntervalSinceReferenceDate: 0), endTime: Date()).cost, 0)
let rate = Double(42)
// A session with a rate should multiply that rate by the number of hours of the session.
XCTAssertEqual(Session(rate: rate, startTime: Date(timeIntervalSinceNow: -hour.converted(to: .seconds).value)).cost, rate, accuracy: 0.001)
XCTAssertEqual(Session(rate: rate, startTime: Date(timeIntervalSinceNow: -hour.converted(to: .seconds).value/2)).cost, rate/2, accuracy: 0.001)
}
func testDictionaryForSession() {
var s = Session(rate: 42, startTime: Date(timeIntervalSinceNow: -3600), endTime: Date())
var expected: [String: Any] = [
Session.Keys.rate: s.rate,
Session.Keys.startTime: s.startTime,
Session.Keys.endTime: s.endTime!
]
verify(Session.dictionary(for: s), with: expected)
s = Session(rate: 42)
expected = [
Session.Keys.rate: s.rate,
Session.Keys.startTime: s.startTime
]
verify(Session.dictionary(for: s), with: expected)
}
func testParseFromDictionary() {
let s = Session(rate: 42, startTime: Date(timeIntervalSinceNow: -3600), endTime: Date())
let d = Session.dictionary(for: s)
verify(Session.parse(from: d), with: d)
verify(Session.parse(from: [d]).first, with: d)
}
private func verify(_ dict: [String: Any], with expected: [String: Any]) {
XCTAssertEqual(dict[Session.Keys.rate] as? Double, expected[Session.Keys.rate] as? Double)
XCTAssertEqual(dict[Session.Keys.startTime] as? Date, expected[Session.Keys.startTime] as? Date)
XCTAssertEqual(dict[Session.Keys.endTime] as? Date, expected[Session.Keys.endTime] as? Date)
}
private func verify(_ session: Session?, with dict: [String: Any]) {
guard let session = session else { XCTFail("Session was nil"); return }
XCTAssertEqual(session.rate, dict[Session.Keys.rate] as? Double)
XCTAssertEqual(session.startTime, dict[Session.Keys.startTime] as? Date)
XCTAssertEqual(session.endTime, dict[Session.Keys.endTime] as? Date)
}
}
| mit |
danielrcardenas/ac-course-2017 | frameworks/SwarmChemistry-Swif/Demo_iOS/RecipeInputViewController.swift | 1 | 1487 | //
// RecipeInputViewController.swift
// SwarmChemistry
//
// Created by Yamazaki Mitsuyoshi on 2017/08/14.
// Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved.
//
import UIKit
import SwarmChemistry
protocol RecipeInputViewControllerDelegate: class {
func recipeInputViewController(_ controller: RecipeInputViewController, didInput recipe: Recipe)
}
class RecipeInputViewController: UIViewController {
weak var delegate: RecipeInputViewControllerDelegate?
var currentRecipe: Recipe? {
didSet {
textView?.text = currentRecipe?.description ?? ""
}
}
@IBOutlet private weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textView.text = currentRecipe?.description ?? ""
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textView.becomeFirstResponder()
}
@IBAction func done(sender: AnyObject!) {
guard let recipe = Recipe.init(textView.text, name: "Manual Input") else {
let alertController = UIAlertController.init(title: "Error", message: "Cannot parse recipe", preferredStyle: .alert)
alertController.addAction(.init(title: "OK", style: .cancel, handler: nil))
present(alertController, animated: true, completion: nil)
return
}
currentRecipe = recipe
let delegate = self.delegate
dismiss(animated: true) {
delegate?.recipeInputViewController(self, didInput: recipe)
}
}
}
| apache-2.0 |
kostickm/mobileStack | MobileStack/Volume.swift | 1 | 901 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import UIKit
struct Volume {
var name: String?
var id: String?
var status: String?
var size: String?
init(name: String?, id: String?, status: String?, size: String?) {
self.name = name
self.id = id
self.status = status
self.size = size
}
}
| apache-2.0 |
mightydeveloper/swift | test/Interpreter/SDK/Reflection_KVO.swift | 9 | 1098 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// rdar://problem/19060227
import Foundation
class ObservedValue: NSObject {
dynamic var amount = 0
}
class ValueObserver: NSObject {
private var observeContext = 0
let observedValue: ObservedValue
init(value: ObservedValue) {
observedValue = value
super.init()
observedValue.addObserver(self, forKeyPath: "amount", options: .New, context: &observeContext)
}
deinit {
observedValue.removeObserver(self, forKeyPath: "amount")
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &observeContext {
if let change_ = change {
if let amount = change_[NSKeyValueChangeNewKey as String] as? Int {
print("Observed value updated to \(amount)")
}
}
}
}
}
let value = ObservedValue()
value.amount = 42
let observer = ValueObserver(value: value)
// CHECK: updated to 43
value.amount++
// CHECK: amount: 43
dump(value)
| apache-2.0 |
huangboju/QMUI.swift | QMUI.swift/Demo/Modules/Demos/Components/QDPopupContainerViewController.swift | 1 | 10038 | //
// QDPopupContainerViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/5/17.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
class QDPopupContainerView: QMUIPopupContainerView {
private var emotionInputManager: QMUIEmotionInputManager!
override init(frame: CGRect) {
super.init(frame: frame)
contentEdgeInsets = .zero
emotionInputManager = QMUIEmotionInputManager()
emotionInputManager.emotionView.emotions = QDUIHelper.qmuiEmotions()
emotionInputManager.emotionView.sendButton.isHidden = true
contentView.addSubview(emotionInputManager.emotionView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func sizeThatFitsInContentView(_ size: CGSize) -> CGSize {
return CGSize(width: 300, height: 320)
}
override func layoutSubviews() {
super.layoutSubviews()
// 所有布局都参照 contentView
emotionInputManager.emotionView.frame = contentView.bounds
}
}
class QDPopupContainerViewController: QDCommonViewController {
private var button1: QMUIButton!
private var popupView1: QMUIPopupContainerView!
private var button2: QMUIButton!
private var popupView2: QMUIPopupMenuView!
private var button3: QMUIButton!
private var popupView3: QDPopupContainerView!
private var separatorLayer1: CALayer!
private var separatorLayer2: CALayer!
private var popupView4: QMUIPopupMenuView!
override func initSubviews() {
super.initSubviews()
separatorLayer1 = CALayer()
separatorLayer1.qmui_removeDefaultAnimations()
separatorLayer1.backgroundColor = UIColorSeparator.cgColor
view.layer.addSublayer(separatorLayer1)
separatorLayer2 = CALayer()
separatorLayer2.qmui_removeDefaultAnimations()
separatorLayer2.backgroundColor = UIColorSeparator.cgColor
view.layer.addSublayer(separatorLayer2)
button1 = QDUIHelper.generateLightBorderedButton()
button1.addTarget(self, action: #selector(handleButtonEvent(_:)), for: .touchUpInside)
button1.setTitle("显示默认浮层", for: .normal)
view.addSubview(button1)
// 使用方法 1,以 addSubview: 的形式显示到界面上
popupView1 = QMUIPopupContainerView()
popupView1.imageView.image = UIImageMake("icon_emotion")?.qmui_imageResized(in: CGSize(width: 24, height: 24), contentMode: .scaleToFill)?.qmui_image(tintColor: QDThemeManager.shared.currentTheme?.themeTintColor)
popupView1.textLabel.text = "默认自带 imageView、textLabel,可展示简单的内容"
popupView1.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)
popupView1.didHideClosure = { [weak self] (hidesByUserTap) in
self?.button1.setTitle("显示默认浮层", for: .normal)
}
// 使用方法 1 时,显示浮层前需要先手动隐藏浮层,并自行添加到目标 UIView 上
popupView1.isHidden = true
view.addSubview(popupView1)
button2 = QDUIHelper.generateLightBorderedButton()
button2.addTarget(self, action: #selector(handleButtonEvent), for: .touchUpInside)
button2.setTitle("显示菜单浮层", for: .normal)
view.addSubview(button2)
// 使用方法 2,以 UIWindow 的形式显示到界面上,这种无需默认隐藏,也无需 add 到某个 UIView 上
popupView2 = QMUIPopupMenuView()
popupView2.automaticallyHidesWhenUserTap = true // 点击空白地方消失浮层
popupView2.maskViewBackgroundColor = UIColorMaskWhite // 使用方法 2 并且打开了 automaticallyHidesWhenUserTap 的情况下,可以修改背景遮罩的颜色
popupView2.maximumWidth = 180;
popupView2.shouldShowItemSeparator = true
popupView2.separatorInset = UIEdgeInsets(top: 0, left: popupView2.padding.left, bottom: 0, right: popupView2.padding.right)
popupView2.items = [
QMUIPopupMenuItem(image: UIImageMake("icon_tabbar_uikit")?.withRenderingMode(.alwaysTemplate), title: "QMUIKit", handler: { [weak self] in
self?.popupView2.hide(with: true)
}),
QMUIPopupMenuItem(image: UIImageMake("icon_tabbar_component")?.withRenderingMode(.alwaysTemplate), title: "Components", handler: { [weak self] in
self?.popupView2.hide(with: true)
}),
QMUIPopupMenuItem(image: UIImageMake("icon_tabbar_lab")?.withRenderingMode(.alwaysTemplate), title: "Lab", handler: { [weak self] in
self?.popupView2.hide(with: true)
})]
popupView2.didHideClosure = { [weak self] (hidesByUserTap) in
self?.button2.setTitle("显示菜单浮层", for: .normal)
}
button3 = QDUIHelper.generateLightBorderedButton()
button3.addTarget(self, action: #selector(handleButtonEvent), for: .touchUpInside)
button3.setTitle("显示自定义浮层", for: .normal)
view.addSubview(button3)
popupView3 = QDPopupContainerView()
popupView3.preferLayoutDirection = .below // 默认在目标的下方,如果目标下方空间不够,会尝试放到目标上方。若上方空间也不够,则缩小自身的高度。
popupView3.didHideClosure = { [weak self] (hidesByUserTap) in
self?.button3.setTitle("显示自定义浮层", for: .normal)
}
// 在 UIBarButtonItem 上显示
popupView4 = QMUIPopupMenuView()
popupView4.automaticallyHidesWhenUserTap = true // 点击空白地方消失浮层
popupView4.maximumWidth = 180
popupView4.shouldShowItemSeparator = true
popupView4.separatorInset = UIEdgeInsets(top: 0, left: popupView4.padding.left, bottom: 0, right: popupView4.padding.right)
popupView4.items = [
QMUIPopupMenuItem(image: UIImageMake("icon_tabbar_uikit")?.withRenderingMode(.alwaysTemplate), title: "QMUIKit", handler: nil),
QMUIPopupMenuItem(image: UIImageMake("icon_tabbar_component")?.withRenderingMode(.alwaysTemplate), title: "Components", handler: nil),
QMUIPopupMenuItem(image: UIImageMake("icon_tabbar_lab")?.withRenderingMode(.alwaysTemplate), title: "Lab", handler: nil),
]
}
override func setNavigationItems(_ isInEditMode: Bool, animated: Bool) {
super.setNavigationItems(isInEditMode, animated: animated)
navigationItem.rightBarButtonItem = UIBarButtonItem.item(image: UIImageMake("icon_nav_about"), target: self, action: #selector(handleRightBarButtonItemEvent(_:)))
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// popupView3 使用方法 2 显示,并且没有打开 automaticallyHidesWhenUserTap,则需要手动隐藏
if popupView3.isShowing {
popupView3.hide(with: animated)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let minY = qmui_navigationBarMaxYInViewCoordinator
let viewportHeight = view.bounds.height - minY
let sectionHeight = viewportHeight / 3
button1.frame = button1.frame.setXY(view.bounds.width.center(button1.frame.width), minY + (sectionHeight - button1.frame.height) / 2)
popupView1.safetyMarginsOfSuperview.top = qmui_navigationBarMaxYInViewCoordinator + 10
popupView1.layout(with: button1) // 相对于 button1 布局
separatorLayer1.frame = CGRectFlat(0, minY + sectionHeight, view.bounds.width, PixelOne)
button2.frame = button1.frame.setY(button1.frame.maxY + sectionHeight - button2.frame.height)
popupView2.layout(with: button2) // 相对于 button2 布局
separatorLayer2.frame = separatorLayer1.frame.setY(minY + sectionHeight * 2)
button3.frame = button1.frame.setY(button2.frame.maxY + sectionHeight - button3.frame.height)
popupView3.layoutWithTargetRectInScreenCoordinate(button3.convert(button3.bounds, to: nil)) // 将 button3 的坐标转换到相对于 UIWindow 的坐标系里,然后再传给浮层布局
// 在横竖屏旋转时,viewDidLayoutSubviews 这个时机还无法获取到正确的 navigationItem 的 frame,所以直接隐藏掉
if popupView4.isShowing {
popupView4.hide(with: false)
}
}
@objc private func handleRightBarButtonItemEvent(_ button: QMUIButton) {
if popupView4.isShowing {
popupView4.hide(with: true)
} else {
// 相对于右上角的按钮布局,显示前重新对准布局,避免横竖屏导致位置不准确
if let qmui_view = navigationItem.rightBarButtonItem?.qmui_view {
popupView4.layout(with: qmui_view)
popupView4.show(with: true)
}
}
}
@objc private func handleButtonEvent(_ button: QMUIButton) {
if button == button1 {
if popupView1.isShowing {
popupView1.hide(with: true)
button1.setTitle("显示默认浮层", for: .normal)
} else {
popupView1.show(with: true)
button1.setTitle("隐藏默认浮层", for: .normal)
}
return
}
if button == button2 {
popupView2.show(with: true)
button2.setTitle("隐藏菜单浮层", for: .normal)
return
}
if button == button3 {
if popupView3.isShowing {
popupView3.hide(with: true)
} else {
popupView3.show(with: true)
button3.setTitle("隐藏自定义浮层", for: .normal)
}
return
}
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/09491-swift-sourcemanager-getmessage.swift | 11 | 257 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
init {
for in {
extension NSSet {
let f = ( ) {
class A {
{
}
{
}
func g {
class
case ,
| mit |
Maaimusic/BTree | Sources/BTreeIterator.swift | 1 | 4777 | //
// BTreeIterator.swift
// BTree
//
// Created by Károly Lőrentey on 2016-02-11.
// Copyright © 2015–2017 Károly Lőrentey.
//
/// An iterator for all elements stored in a B-tree, in ascending key order.
public struct BTreeIterator<Key: Comparable, Value>: IteratorProtocol {
public typealias Element = (Key, Value)
@usableFromInline typealias Node = BTreeNode<Key, Value>
@usableFromInline typealias State = BTreeStrongPath<Key, Value>
@usableFromInline var state: State
@usableFromInline internal init(_ state: State) {
self.state = state
}
/// Advance to the next element and return it, or return `nil` if no next element exists.
///
/// - Complexity: Amortized O(1)
@inlinable public mutating func next() -> Element? {
if state.isAtEnd { return nil }
let result = state.element
state.moveForward()
return result
}
}
/// A dummy, zero-size key that is useful in B-trees that don't need key-based lookup.
@usableFromInline internal struct EmptyKey: Comparable {
@usableFromInline internal init() { }
@usableFromInline internal static func ==(a: EmptyKey, b: EmptyKey) -> Bool { return true }
@usableFromInline internal static func <(a: EmptyKey, b: EmptyKey) -> Bool { return false }
}
/// An iterator for the values stored in a B-tree with an empty key.
public struct BTreeValueIterator<Value>: IteratorProtocol {
@usableFromInline internal typealias Base = BTreeIterator<EmptyKey, Value>
@usableFromInline internal var base: Base
@usableFromInline internal init(_ base: Base) {
self.base = base
}
/// Advance to the next element and return it, or return `nil` if no next element exists.
///
/// - Complexity: Amortized O(1)
@inlinable public mutating func next() -> Value? {
return base.next()?.1
}
}
/// An iterator for the keys stored in a B-tree without a value.
public struct BTreeKeyIterator<Key: Comparable>: IteratorProtocol {
@usableFromInline internal typealias Base = BTreeIterator<Key, Void>
@usableFromInline internal var base: Base
@usableFromInline internal init(_ base: Base) {
self.base = base
}
/// Advance to the next element and return it, or return `nil` if no next element exists.
///
/// - Complexity: Amortized O(1)
@inlinable public mutating func next() -> Key? {
return base.next()?.0
}
}
/// A mutable path in a B-tree, holding strong references to nodes on the path.
/// This path variant does not support modifying the tree itself; it is suitable for use in generators.
@usableFromInline internal struct BTreeStrongPath<Key: Comparable, Value>: BTreePath {
@usableFromInline typealias Node = BTreeNode<Key, Value>
@usableFromInline var root: Node
@usableFromInline var offset: Int
@usableFromInline var _path: [Node]
@usableFromInline var _slots: [Int]
@usableFromInline var node: Node
@usableFromInline var slot: Int?
@usableFromInline init(root: Node) {
self.root = root
self.offset = root.count
self._path = []
self._slots = []
self.node = root
self.slot = nil
}
@usableFromInline var count: Int { return root.count }
@usableFromInline var length: Int { return _path.count + 1 }
@usableFromInline mutating func popFromSlots() {
assert(self.slot != nil)
offset += node.count - node.offset(ofSlot: slot!)
slot = nil
}
@usableFromInline mutating func popFromPath() {
assert(_path.count > 0 && slot == nil)
node = _path.removeLast()
slot = _slots.removeLast()
}
@usableFromInline mutating func pushToPath() {
assert(slot != nil)
let child = node.children[slot!]
_path.append(node)
node = child
_slots.append(slot!)
slot = nil
}
@usableFromInline mutating func pushToSlots(_ slot: Int, offsetOfSlot: Int) {
assert(self.slot == nil)
offset -= node.count - offsetOfSlot
self.slot = slot
}
@usableFromInline func forEach(ascending: Bool, body: (Node, Int) -> Void) {
if ascending {
body(node, slot!)
for i in (0 ..< _path.count).reversed() {
body(_path[i], _slots[i])
}
}
else {
for i in 0 ..< _path.count {
body(_path[i], _slots[i])
}
body(node, slot!)
}
}
@usableFromInline func forEachSlot(ascending: Bool, body: (Int) -> Void) {
if ascending {
body(slot!)
_slots.reversed().forEach(body)
}
else {
_slots.forEach(body)
body(slot!)
}
}
}
| mit |
tkausch/swiftalgorithms | CodePuzzles/AlphabetCipher.playground/Contents.swift | 1 | 2676 | import UIKit
typealias CodeMap = [Character : Character]
class AlphabetCipher {
var key: String
static var matrix = [Character : CodeMap]()
static var alphabet = Array("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
lazy var encryptionMaps : [CodeMap] = {
return pickCodeMaps(key: key)
}()
lazy var decryptionMaps: [CodeMap] = {
return pickCodeMaps(key: key, invert: true)
}()
init(key: String) {
// initialize class property matrix - if not yet done.
if Self.matrix.isEmpty {
for (shift, char) in Self.alphabet.enumerated() {
// create codemap by shifting alphabet
var codemap = [Character : Character]()
for (idx, ch) in Self.alphabet.enumerated() {
codemap[ch] = Self.alphabet[(idx + shift) % Self.alphabet.count]
}
Self.matrix[char] = codemap
}
}
self.key = key
}
func encrypt(_ plaintText: String) -> String {
return substitute(text: plaintText, codeMaps: encryptionMaps)
}
func decrypt(_ cipherText: String) -> String {
return substitute(text: cipherText, codeMaps: decryptionMaps)
}
func substitute(text: String, codeMaps: [CodeMap]) -> String {
var current = 0
let mappedText = text.map { (char) -> Character in
if let ch = codeMaps[current][char] {
current = (current + 1) % codeMaps.count
return ch
}
return char
}
return String(mappedText)
}
func pickCodeMaps(key: String, invert: Bool = false) -> [CodeMap] {
var codeMaps = [CodeMap]()
for ch in key {
if let codeMap = Self.matrix[ch] {
if invert {
codeMaps.append(inverse(codeMap))
} else {
codeMaps.append(codeMap)
}
} else {
assertionFailure("Only ASCII characters supported in encoding key")
}
}
return codeMaps
}
func inverse(_ codeMap: CodeMap) -> CodeMap {
var inverseMap = CodeMap()
for key in codeMap.keys {
if let mappedKey = codeMap[key] {
inverseMap[mappedKey] = key
}
}
return inverseMap
}
}
var cipher = AlphabetCipher(key: "vigilance")
let cipherText = cipher.encrypt("meet me😀 at tuesday evening 🎯at seven")
let plainText = cipher.decrypt(cipherText)
print(cipherText)
print(plainText)
| gpl-3.0 |
auth0/Auth0.swift | Auth0Tests/Responses.swift | 1 | 5621 | import Foundation
import OHHTTPStubs
@testable import Auth0
let UserId = "auth0|\(UUID().uuidString.replacingOccurrences(of: "-", with: ""))"
let SupportAtAuth0 = "support@auth0.com"
let Support = "support"
let Auth0Phone = "+10123456789"
let Nickname = "sup"
let PictureURL = URL(string: "https://auth0.com/picture")!
let WebsiteURL = URL(string: "https://auth0.com/website")!
let ProfileURL = URL(string: "https://auth0.com/profile")!
let UpdatedAt = "2015-08-19T17:18:01.000Z"
let UpdatedAtUnix = "1440004681"
let UpdatedAtTimestamp = 1440004681.000
let CreatedAt = "2015-08-19T17:18:00.000Z"
let CreatedAtUnix = "1440004680"
let CreatedAtTimestamp = 1440004680.000
let Sub = "auth0|123456789"
let Kid = "key123"
let LocaleUS = "en-US"
let ZoneEST = "US/Eastern"
let OTP = "123456"
let OOB = "654321"
let BindingCode = "214365"
let RecoveryCode = "162534"
let MFAToken = UUID().uuidString.replacingOccurrences(of: "-", with: "")
let AuthenticatorId = UUID().uuidString.replacingOccurrences(of: "-", with: "")
let ChallengeTypes = ["oob", "otp"]
let APISuccessStatusCode = Int32(200)
let APIResponseHeaders = ["Content-Type": "application/json"]
func catchAllResponse() -> HTTPStubsResponse {
return HTTPStubsResponse(error: NSError(domain: "com.auth0", code: -99999, userInfo: nil))
}
func apiSuccessResponse(json: [AnyHashable: Any] = [:]) -> HTTPStubsResponse {
return HTTPStubsResponse(jsonObject: json, statusCode: APISuccessStatusCode, headers: APIResponseHeaders)
}
func apiSuccessResponse(jsonArray: [Any]) -> HTTPStubsResponse {
return HTTPStubsResponse(jsonObject: jsonArray, statusCode: APISuccessStatusCode, headers: APIResponseHeaders)
}
func apiSuccessResponse(string: String) -> HTTPStubsResponse {
return HTTPStubsResponse(data: string.data(using: .utf8)!, statusCode: APISuccessStatusCode, headers: APIResponseHeaders)
}
func apiFailureResponse(json: [AnyHashable: Any] = [:], statusCode: Int = 400) -> HTTPStubsResponse {
return HTTPStubsResponse(jsonObject: json, statusCode: Int32(statusCode), headers: APIResponseHeaders)
}
func apiFailureResponse(string: String, statusCode: Int) -> HTTPStubsResponse {
return HTTPStubsResponse(data: string.data(using: .utf8)!, statusCode: Int32(statusCode), headers: APIResponseHeaders)
}
func authResponse(accessToken: String, idToken: String? = nil, refreshToken: String? = nil, expiresIn: Double? = nil) -> HTTPStubsResponse {
var json = [
"access_token": accessToken,
"token_type": "bearer",
]
if let idToken = idToken {
json["id_token"] = idToken
}
if let refreshToken = refreshToken {
json["refresh_token"] = refreshToken
}
if let expires = expiresIn {
json["expires_in"] = String(expires)
}
return apiSuccessResponse(json: json)
}
func authFailure(code: String, description: String, name: String? = nil) -> HTTPStubsResponse {
return apiFailureResponse(json: ["code": code, "description": description, "statusCode": 400, "name": name ?? code])
}
func authFailure(error: String, description: String) -> HTTPStubsResponse {
return apiFailureResponse(json: ["error": error, "error_description": description])
}
func createdUser(email: String, username: String? = nil, verified: Bool = true) -> HTTPStubsResponse {
var json: [String: Any] = [
"email": email,
"email_verified": verified ? "true" : "false",
]
if let username = username {
json["username"] = username
}
return apiSuccessResponse(json: json)
}
func resetPasswordResponse() -> HTTPStubsResponse {
return apiSuccessResponse(string: "We've just sent you an email to reset your password.")
}
func revokeTokenResponse() -> HTTPStubsResponse {
return apiSuccessResponse(string: "")
}
func passwordless(_ email: String, verified: Bool) -> HTTPStubsResponse {
return apiSuccessResponse(json: ["email": email, "verified": "\(verified)"])
}
func managementErrorResponse(error: String, description: String, code: String, statusCode: Int = 400) -> HTTPStubsResponse {
return apiFailureResponse(json: ["code": code, "description": description, "statusCode": statusCode, "error": error], statusCode: statusCode)
}
func jwksResponse(kid: String? = Kid) -> HTTPStubsResponse {
var jwks: [String: Any] = ["keys": [["alg": "RS256",
"kty": "RSA",
"use": "sig",
"n": "uGbXWiK3dQTyCbX5xdE4yCuYp0AF2d15Qq1JSXT_lx8CEcXb9RbDddl8jGDv-spi5qPa8qEHiK7FwV2KpRE983wGPnYsAm9BxLFb4YrLYcDFOIGULuk2FtrPS512Qea1bXASuvYXEpQNpGbnTGVsWXI9C-yjHztqyL2h8P6mlThPY9E9ue2fCqdgixfTFIF9Dm4SLHbphUS2iw7w1JgT69s7of9-I9l5lsJ9cozf1rxrXX4V1u_SotUuNB3Fp8oB4C1fLBEhSlMcUJirz1E8AziMCxS-VrRPDM-zfvpIJg3JljAh3PJHDiLu902v9w-Iplu1WyoB2aPfitxEhRN0Yw",
"e": "AQAB",
"kid": kid]]]
#if WEB_AUTH_PLATFORM
let jwk = generateRSAJWK()
jwks = ["keys": [["alg": jwk.algorithm,
"kty": jwk.keyType,
"use": jwk.usage,
"n": jwk.modulus,
"e": jwk.exponent,
"kid": kid]]]
#endif
return apiSuccessResponse(json: jwks)
}
func multifactorChallengeResponse(challengeType: String, oobCode: String? = nil, bindingMethod: String? = nil) -> HTTPStubsResponse {
var json: [String: Any] = ["challenge_type": challengeType]
json["oob_code"] = oobCode
json["binding_method"] = bindingMethod
return apiSuccessResponse(json: json)
}
| mit |
jrmgx/swift | jrmgx/Classes/Helper/JrmgxAsync.swift | 1 | 3488 |
import UIKit
open class JrmgxAsync {
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public typealias UIImageResultBlock = (_ image: UIImage?, _ error: NSError?) -> Void
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public typealias NSURLResultBlock = (_ url: URL?, _ error: NSError?) -> Void
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public typealias AnyObjectsResultBlock = (_ objects: [AnyObject]?, _ error: NSError?) -> Void
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public typealias StringResultBlock = (_ string: String?, _ error: NSError?) -> Void
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public typealias NumberResultBlock = (_ number: NSNumber?, _ error: NSError?) -> Void
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public typealias IntResultBlock = (_ number: Int?, _ error: NSError?) -> Void
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
public typealias BoolResultBlock = (_ success: Bool, _ error: NSError?) -> Void
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open static let NOOPBoolResultBlock: BoolResultBlock = { success, error in }
//
fileprivate static var namedQueues = ["main": DispatchQueue.main]
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open static func GetNamedQueue(_ name: String = "main") -> DispatchQueue {
if namedQueues[name] == nil {
namedQueues[name] = DispatchQueue(label: name, attributes: [])
}
return namedQueues[name]!
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open static func Execute(_ block: @escaping () -> Void) {
Execute(onNamedQueue: "main", block: block)
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open static func Execute(onNamedQueue name: String, block: @escaping () -> Void) {
let queue = GetNamedQueue(name)
Execute(onQueue: queue, block: block)
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open static func Execute(onNamedQueue name: String, afterSeconds delay: Double, block: @escaping () -> Void) {
let queue = GetNamedQueue(name)
Execute(onQueue: queue, afterSeconds: delay, block: block)
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open static func Execute(onQueue queue: DispatchQueue, block: @escaping () -> Void) {
queue.async(execute: block)
}
/**
* NAME
*
* - parameters
* - name: String
* - returns: nothing
*/
open static func Execute(onQueue queue: DispatchQueue, afterSeconds delay: Double, block: @escaping () -> Void) {
let time = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: time, execute: block)
}
}
| mit |
SuperJerry/Swift | ToDoList/ToDoList/AppDelegate.swift | 1 | 2534 | //
// AppDelegate.swift
// ToDoList
//
// Created by Jerry on 7/24/15.
// Copyright (c) 2015 Jerry. All rights reserved.
//
import Parse
import Bolts
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.enableLocalDatastore()
// Initialize Parse.
Parse.setApplicationId("ShPgtdfQyymw0vlhWV1kB2119ifAkkAs9McbxPx6",
clientKey: "64KEn6hGUcxXoZ7f7xETukmzQwILupC6tuElg2hj")
// [Optional] Track statistics around application opens.
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
austinzheng/swift | validation-test/compiler_crashers_fixed/26685-swift-printingdiagnosticconsumer-handlediagnostic.swift | 65 | 506 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct S<T where g:a{
class a{
class A{class A{
class B<T
struct B{class A{
let t=B
}
{
}func a{
{struct B{
| apache-2.0 |
austinzheng/swift | stdlib/private/StdlibCollectionUnittest/CheckRangeReplaceableSliceType.swift | 17 | 13547 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import StdlibUnittest
extension TestSuite {
/// Adds a set of tests for `RangeReplaceableCollection` that is also a
/// slice type.
public func addRangeReplaceableSliceTests<
C : RangeReplaceableCollection,
CollectionWithEquatableElement : RangeReplaceableCollection
>(
_ testNamePrefix: String = "",
makeCollection: @escaping ([C.Element]) -> C,
wrapValue: @escaping (OpaqueValue<Int>) -> C.Element,
extractValue: @escaping (C.Element) -> OpaqueValue<Int>,
makeCollectionOfEquatable: @escaping ([CollectionWithEquatableElement.Element]) -> CollectionWithEquatableElement,
wrapValueIntoEquatable: @escaping (MinimalEquatableValue) -> CollectionWithEquatableElement.Element,
extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Element) -> MinimalEquatableValue),
resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1,
collectionIsBidirectional: Bool = false
) where
C.SubSequence == C,
CollectionWithEquatableElement.SubSequence == CollectionWithEquatableElement,
CollectionWithEquatableElement.Element : Equatable {
var testNamePrefix = testNamePrefix
// Don't run the same tests twice.
if !checksAdded.insert(
"\(testNamePrefix).\(C.self).\(#function)"
).inserted {
return
}
addRangeReplaceableCollectionTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset,
collectionIsBidirectional: collectionIsBidirectional
)
func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C {
return makeCollection(elements.map(wrapValue))
}
testNamePrefix += String(describing: C.Type.self)
//===------------------------------------------------------------------===//
// removeFirst()
//===------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeFirst()/semantics") {
for test in removeFirstTests.filter({ $0.numberToRemove == 1 }) {
var c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
let survivingIndices = _allIndices(
into: c,
in: c.index(after: c.startIndex)..<c.endIndex)
let removedElement = c.removeFirst()
expectEqual(test.collection.first, extractValue(removedElement).value)
expectEqualSequence(
test.expectedCollection,
c.map { extractValue($0).value },
"removeFirst() shouldn't mutate the tail of the collection",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(c[$0]).value },
"removeFirst() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
}
}
self.test("\(testNamePrefix).removeFirst()/empty/semantics") {
var c = makeWrappedCollection(Array<OpaqueValue<Int>>())
expectCrashLater()
_ = c.removeFirst() // Should trap.
}
//===----------------------------------------------------------------------===//
// removeFirst(n: Int)
//===----------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeFirst(n: Int)/semantics") {
for test in removeFirstTests {
var c = makeWrappedCollection(test.collection.map(OpaqueValue.init))
let survivingIndices = _allIndices(
into: c,
in: c.index(c.startIndex, offsetBy: numericCast(test.numberToRemove)) ..<
c.endIndex
)
c.removeFirst(test.numberToRemove)
expectEqualSequence(
test.expectedCollection,
c.map { extractValue($0).value },
"removeFirst() shouldn't mutate the tail of the collection",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(c[$0]).value },
"removeFirst() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
}
}
self.test("\(testNamePrefix).removeFirst(n: Int)/empty/semantics") {
var c = makeWrappedCollection(Array<OpaqueValue<Int>>())
expectCrashLater()
c.removeFirst(1) // Should trap.
}
self.test("\(testNamePrefix).removeFirst(n: Int)/removeNegative/semantics") {
var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
expectCrashLater()
c.removeFirst(-1) // Should trap.
}
self.test("\(testNamePrefix).removeFirst(n: Int)/removeTooMany/semantics") {
var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
expectCrashLater()
c.removeFirst(3) // Should trap.
}
//===----------------------------------------------------------------------===//
} // addRangeReplaceableSliceTests
public func addRangeReplaceableBidirectionalSliceTests<
C : BidirectionalCollection & RangeReplaceableCollection,
CollectionWithEquatableElement : BidirectionalCollection & RangeReplaceableCollection
>(
_ testNamePrefix: String = "",
makeCollection: @escaping ([C.Element]) -> C,
wrapValue: @escaping (OpaqueValue<Int>) -> C.Element,
extractValue: @escaping (C.Element) -> OpaqueValue<Int>,
makeCollectionOfEquatable: @escaping ([CollectionWithEquatableElement.Element]) -> CollectionWithEquatableElement,
wrapValueIntoEquatable: @escaping (MinimalEquatableValue) -> CollectionWithEquatableElement.Element,
extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Element) -> MinimalEquatableValue),
resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1
) where
C.SubSequence == C,
CollectionWithEquatableElement.SubSequence == CollectionWithEquatableElement,
CollectionWithEquatableElement.Element : Equatable {
var testNamePrefix = testNamePrefix
// Don't run the same tests twice.
if !checksAdded.insert(
"\(testNamePrefix).\(C.self).\(#function)"
).inserted {
return
}
addRangeReplaceableSliceTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset,
collectionIsBidirectional: true
)
addRangeReplaceableBidirectionalCollectionTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset)
func makeWrappedCollection(_ elements: [OpaqueValue<Int>]) -> C {
return makeCollection(elements.map(wrapValue))
}
testNamePrefix += String(describing: C.Type.self)
//===------------------------------------------------------------------===//
// removeLast()
//===------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeLast()/semantics") {
for test in removeLastTests.filter({ $0.numberToRemove == 1 }) {
var c = makeWrappedCollection(test.collection)
let survivingIndices = _allIndices(
into: c,
in: c.startIndex..<c.index(before: c.endIndex))
let removedElement = c.removeLast()
expectEqual(
test.collection.last!.value,
extractValue(removedElement).value)
expectEqualSequence(
test.expectedCollection,
c.map { extractValue($0).value },
"removeLast() shouldn't mutate the head of the collection",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(c[$0]).value },
"removeLast() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
}
}
self.test("\(testNamePrefix).removeLast()/empty/semantics") {
var c = makeWrappedCollection(Array<OpaqueValue<Int>>())
expectCrashLater()
_ = c.removeLast() // Should trap.
}
//===------------------------------------------------------------------===//
// removeLast(n: Int)
//===------------------------------------------------------------------===//
self.test("\(testNamePrefix).removeLast(n: Int)/semantics") {
for test in removeLastTests {
var c = makeWrappedCollection(test.collection)
let survivingIndices = _allIndices(
into: c,
in: c.startIndex ..<
c.index(c.endIndex, offsetBy: numericCast(-test.numberToRemove))
)
c.removeLast(test.numberToRemove)
expectEqualSequence(
test.expectedCollection,
c.map { extractValue($0).value },
"removeLast() shouldn't mutate the head of the collection",
stackTrace: SourceLocStack().with(test.loc)
)
expectEqualSequence(
test.expectedCollection,
survivingIndices.map { extractValue(c[$0]).value },
"removeLast() shouldn't invalidate indices",
stackTrace: SourceLocStack().with(test.loc)
)
}
}
self.test("\(testNamePrefix).removeLast(n: Int)/empty/semantics") {
var c = makeWrappedCollection(Array<OpaqueValue<Int>>())
expectCrashLater()
c.removeLast(1) // Should trap.
}
self.test("\(testNamePrefix).removeLast(n: Int)/removeNegative/semantics") {
var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
expectCrashLater()
c.removeLast(-1) // Should trap.
}
self.test("\(testNamePrefix).removeLast(n: Int)/removeTooMany/semantics") {
var c = makeWrappedCollection([1010, 2020].map(OpaqueValue.init))
expectCrashLater()
c.removeLast(3) // Should trap.
}
//===----------------------------------------------------------------------===//
} // addRangeReplaceableBidirectionalSliceTests
public func addRangeReplaceableRandomAccessSliceTests<
C : RandomAccessCollection & RangeReplaceableCollection,
CollectionWithEquatableElement : RandomAccessCollection & RangeReplaceableCollection
>(
_ testNamePrefix: String = "",
makeCollection: @escaping ([C.Element]) -> C,
wrapValue: @escaping (OpaqueValue<Int>) -> C.Element,
extractValue: @escaping (C.Element) -> OpaqueValue<Int>,
makeCollectionOfEquatable: @escaping ([CollectionWithEquatableElement.Element]) -> CollectionWithEquatableElement,
wrapValueIntoEquatable: @escaping (MinimalEquatableValue) -> CollectionWithEquatableElement.Element,
extractValueFromEquatable: @escaping ((CollectionWithEquatableElement.Element) -> MinimalEquatableValue),
resiliencyChecks: CollectionMisuseResiliencyChecks = .all,
outOfBoundsIndexOffset: Int = 1
) where
C.SubSequence == C,
CollectionWithEquatableElement.SubSequence == CollectionWithEquatableElement,
CollectionWithEquatableElement.Element : Equatable {
var testNamePrefix = testNamePrefix
// Don't run the same tests twice.
if !checksAdded.insert(
"\(testNamePrefix).\(C.self).\(#function)"
).inserted {
return
}
addRangeReplaceableBidirectionalSliceTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset)
addRangeReplaceableRandomAccessCollectionTests(
testNamePrefix,
makeCollection: makeCollection,
wrapValue: wrapValue,
extractValue: extractValue,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: wrapValueIntoEquatable,
extractValueFromEquatable: extractValueFromEquatable,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: outOfBoundsIndexOffset)
testNamePrefix += String(describing: C.Type.self)
// No tests yet.
} // addRangeReplaceableRandomAccessSliceTests
}
| apache-2.0 |
DotSquaresDeveloper/CoffeeShopFinder_iOS | Programming Exercise/AppDelegate.swift | 1 | 2535 | //
// AppDelegate.swift
// Programming Exercise
//
// Created by admin on 9/28/15.
//
//
import UIKit
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var window: UIWindow?
let locationManager = CLLocationManager()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Sound | .Alert | .Badge, categories: nil))
UIApplication.sharedApplication().cancelAllLocalNotifications()
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| gpl-2.0 |
gu704823/huobanyun | huobanyun/taskdescriptionViewController.swift | 1 | 481 | //
// taskdescriptionViewController.swift
// huobanyun
//
// Created by swift on 2017/6/24.
// Copyright © 2017年 AirBook. All rights reserved.
//
import UIKit
class taskdescriptionViewController: UIViewController {
@IBOutlet weak var test: UILabel!
@IBOutlet weak var taskdescription: UITextView!
var taskblock:((_ taskde:String)->())?
var taskdescriptionlabel:String?
override func viewDidLoad() {
super.viewDidLoad()
}
}
| mit |
SuPair/firefox-ios | Client/Frontend/Widgets/SearchInputView.swift | 3 | 6708 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import SnapKit
private struct SearchInputViewUX {
static let horizontalSpacing: CGFloat = 16
static let titleFont: UIFont = UIFont.systemFont(ofSize: 16)
static let borderLineWidth: CGFloat = 0.5
static let closeButtonSize: CGFloat = 36
}
@objc protocol SearchInputViewDelegate: AnyObject {
func searchInputView(_ searchView: SearchInputView, didChangeTextTo text: String)
func searchInputViewBeganEditing(_ searchView: SearchInputView)
func searchInputViewFinishedEditing(_ searchView: SearchInputView)
}
class SearchInputView: UIView {
weak var delegate: SearchInputViewDelegate?
var showBottomBorder: Bool = true {
didSet {
bottomBorder.isHidden = !showBottomBorder
}
}
lazy var inputField: UITextField = {
let textField = UITextField()
textField.delegate = self
textField.addTarget(self, action: #selector(inputTextDidChange), for: .editingChanged)
textField.accessibilityLabel = NSLocalizedString("Search Input Field", tableName: "LoginManager", comment: "Accessibility label for the search input field in the Logins list")
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
return textField
}()
lazy var titleLabel: UILabel = {
let label = UILabel()
label.text = NSLocalizedString("Search", tableName: "LoginManager", comment: "Title for the search field at the top of the Logins list screen")
label.font = SearchInputViewUX.titleFont
return label
}()
lazy var searchIcon: UIImageView = {
return UIImageView(image: UIImage(named: "quickSearch"))
}()
fileprivate lazy var closeButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: #selector(tappedClose), for: .touchUpInside)
button.setImage(UIImage(named: "clear"), for: [])
button.accessibilityLabel = NSLocalizedString("Clear Search", tableName: "LoginManager",
comment: "Accessibility message e.g. spoken by VoiceOver after the user taps the close button in the search field to clear the search and exit search mode")
return button
}()
fileprivate var centerContainer = UIView()
fileprivate lazy var bottomBorder: UIView = {
let border = UIView()
return border
}()
fileprivate lazy var overlay: UIView = {
let view = UIView()
view.backgroundColor = UIColor.Photon.White100
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedSearch)))
view.isAccessibilityElement = true
view.accessibilityLabel = NSLocalizedString("Enter Search Mode", tableName: "LoginManager", comment: "Accessibility label for entering search mode for logins")
return view
}()
fileprivate(set) var isEditing = false {
didSet {
if isEditing {
overlay.isHidden = true
inputField.isHidden = false
inputField.accessibilityElementsHidden = false
closeButton.isHidden = false
closeButton.accessibilityElementsHidden = false
} else {
overlay.isHidden = false
inputField.isHidden = true
inputField.accessibilityElementsHidden = true
closeButton.isHidden = true
closeButton.accessibilityElementsHidden = true
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.Photon.White100
isUserInteractionEnabled = true
addSubview(inputField)
addSubview(closeButton)
centerContainer.addSubview(searchIcon)
centerContainer.addSubview(titleLabel)
overlay.addSubview(centerContainer)
addSubview(overlay)
addSubview(bottomBorder)
setupConstraints()
setEditing(false)
}
fileprivate func setupConstraints() {
centerContainer.snp.makeConstraints { make in
make.center.equalTo(overlay)
}
overlay.snp.makeConstraints { make in
make.edges.equalTo(self)
}
searchIcon.snp.makeConstraints { make in
make.right.equalTo(titleLabel.snp.left).offset(-SearchInputViewUX.horizontalSpacing)
make.centerY.equalTo(centerContainer)
}
titleLabel.snp.makeConstraints { make in
make.center.equalTo(centerContainer)
}
inputField.snp.makeConstraints { make in
make.left.equalTo(self).offset(SearchInputViewUX.horizontalSpacing)
make.centerY.equalTo(self)
make.right.equalTo(closeButton.snp.left).offset(-SearchInputViewUX.horizontalSpacing)
}
closeButton.snp.makeConstraints { make in
make.right.equalTo(self).offset(-SearchInputViewUX.horizontalSpacing)
make.centerY.equalTo(self)
make.size.equalTo(SearchInputViewUX.closeButtonSize)
}
bottomBorder.snp.makeConstraints { make in
make.left.right.bottom.equalTo(self)
make.height.equalTo(SearchInputViewUX.borderLineWidth)
}
}
// didSet callbacks don't trigger when a property is being set in the init() call
// but calling a method that does works fine.
fileprivate func setEditing(_ editing: Bool) {
isEditing = editing
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Selectors
extension SearchInputView {
@objc func tappedSearch() {
isEditing = true
inputField.becomeFirstResponder()
delegate?.searchInputViewBeganEditing(self)
}
@objc func tappedClose() {
isEditing = false
delegate?.searchInputViewFinishedEditing(self)
inputField.text = nil
inputField.resignFirstResponder()
}
@objc func inputTextDidChange(_ textField: UITextField) {
delegate?.searchInputView(self, didChangeTextTo: textField.text ?? "")
}
}
// MARK: - UITextFieldDelegate
extension SearchInputView: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
// If there is no text, go back to showing the title view
if textField.text?.isEmpty ?? true {
isEditing = false
delegate?.searchInputViewFinishedEditing(self)
}
}
}
| mpl-2.0 |
catloafsoft/AudioKit | AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Amplitude Envelope.xcplaygroundpage/Contents.swift | 1 | 1145 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Amplitude Envelope
//: ### Enveloping an FM Oscillator with an ADSR envelope
import XCPlayground
import AudioKit
//: Try changing the table type to triangle or another AKTableType
//: or changing the number of points to a smaller number (has to be a power of 2)
var fm = AKFMOscillator(waveform: AKTable(.Sine, size: 4096))
var fmWithADSR = AKAmplitudeEnvelope(fm, attackDuration: 0.1, decayDuration: 0.3, sustainLevel: 0.8, releaseDuration: 1.0)
AudioKit.output = fmWithADSR
AudioKit.start()
fm.start()
fmWithADSR.start()
AKPlaygroundLoop(every:1) {
if fmWithADSR.isStarted {
fmWithADSR.stop()
} else {
fm.baseFrequency = random(220, 880)
fmWithADSR.attackDuration = random(0.01, 0.5)
fmWithADSR.decayDuration = random(0.01, 0.2)
fmWithADSR.sustainLevel = random(0.01, 1)
fmWithADSR.releaseDuration = random(0.01, 1)
fmWithADSR.start()
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit |
catloafsoft/AudioKit | AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Convolution.xcplaygroundpage/Contents.swift | 1 | 1396 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Convolution
//: ### Allows you to create a large variety of effects, usually reverbs or environments, but it could also be for modeling.
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("drumloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
let stairwell = bundle.URLForResource("Impulse Responses/stairwell", withExtension: "wav")!
let dish = bundle.URLForResource("Impulse Responses/dish", withExtension: "wav")!
var stairwellConvolution = AKConvolution.init(player, impulseResponseFileURL: stairwell, partitionLength: 8192)
var dishConvolution = AKConvolution.init(player, impulseResponseFileURL: dish, partitionLength: 8192)
var mixer = AKDryWetMixer(stairwellConvolution, dishConvolution, balance: 1)
AudioKit.output = mixer
AudioKit.start()
stairwellConvolution.start()
dishConvolution.start()
player.play()
var increment = 0.01
AKPlaygroundLoop(every: 3.428/100.0) { () -> () in
mixer.balance += increment
if mixer.balance >= 1 && increment > 0 {
increment = -0.01
}
if mixer.balance <= 0 && increment < 0 {
increment = 0.01
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit |
hectr/swift-idioms | Sources/Idioms/StringProtocol+Subscript.swift | 1 | 3144 | // Copyright (c) 2019 Hèctor Marquès Ranea
//
// 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
// Source: https://stackoverflow.com/a/38215613
extension StringProtocol {
public subscript(offset: Int) -> Element? {
guard offset >= 0 else { return nil }
guard let index = index(startIndex, offsetBy: offset, limitedBy: index(before: endIndex)) else { return nil }
return self[index]
}
public subscript(_ range: Range<Int>) -> SubSequence? {
guard range.lowerBound >= 0 else { return nil }
let prefixLength = range.lowerBound + range.count
guard prefixLength >= 0 else { return nil }
guard prefixLength <= count else { return nil }
return prefix(prefixLength).suffix(range.count)
}
public subscript(range: ClosedRange<Int>) -> SubSequence? {
guard range.lowerBound >= 0 else { return nil }
let prefixLength = range.lowerBound + range.count
guard prefixLength >= 0 else { return nil }
guard prefixLength <= count else { return nil }
return prefix(prefixLength).suffix(range.count)
}
public subscript(range: PartialRangeThrough<Int>) -> SubSequence? {
guard range.upperBound >= 0 else { return nil }
let prefixLength = range.upperBound.advanced(by: 1)
guard prefixLength >= 0 else { return nil }
guard prefixLength <= count else { return nil }
return prefix(prefixLength)
}
public subscript(range: PartialRangeUpTo<Int>) -> SubSequence? {
guard range.upperBound >= 0 else { return nil }
let prefixLength = range.upperBound
guard prefixLength >= 0 else { return nil }
guard prefixLength <= count else { return nil }
return prefix(prefixLength)
}
public subscript(range: PartialRangeFrom<Int>) -> SubSequence? {
guard range.lowerBound >= 0 else { return nil }
let suffixLength = count - range.lowerBound
guard suffixLength >= 0 else { return nil }
guard suffixLength <= count else { return nil }
return suffix(suffixLength)
}
}
| mit |
PomTTcat/SourceCodeGuideRead_JEFF | ObjectMapperGuideRead_Jeff/ObjectGuide/ObjectGuide/ObjectMapper/ObjectMapperDemo.swift | 2 | 3178 |
/*
Swift - 使用ObjectMapper实现模型转换1
http://www.hangge.com/blog/cache/detail_1673.html
*/
import Foundation
class User: Mappable {
var username: String?
var age: Int?
var weight: Double!
var bestFriend: User? // User对象
var friends: [User]? // Users数组
var birthday: Date?
var array: [AnyObject]?
var dictionary: [String : AnyObject] = [:]
init(){
}
required init?(map: Map) {
// 在对象序列化之前验证 JSON 合法性。在不符合的条件时,返回 nil 阻止映射发生。
if map.JSON["username"] == nil {
return nil
}
/*
let json = "[{\"age\":18,\"username\":\"李雷\"},{\"age\":17}]"
let users:[User] = Mapper<User>().mapArray(JSONString: json)!
print(users.count) // 1
*/
}
// Mappable
func mapping(map: Map) {
username <- map["username"]
age <- map["age"]
weight <- map["weight"]
bestFriend <- map["best_friend"]
friends <- map["friends"]
birthday <- (map["birthday"], DateTransform())
array <- map["arr"]
dictionary <- map["dict"]
}
//MARK: Model -> Dictionary
class func modelWithDict() {
let lilei = User()
lilei.username = "李雷"
lilei.age = 18
let meimei = User()
meimei.username = "梅梅"
meimei.age = 17
meimei.bestFriend = lilei
// // model -> dict
// let meimeiDic:[String: Any] = meimei.toJSON()
// print("meimeiDic\n \(meimeiDic)")
//
// // [model] -> [dict]
// let users = [lilei, meimei]
// let usersArray:[[String: Any]] = users.toJSON()
// print("usersArray\n \(usersArray)")
let dic = ["age": 17, "best_friend": ["dict": [:], "age": 18, "username": "李雷"], "username": "梅梅", "dict": [:]] as [String : Any]
// dict -> model
let meimeiModel = User(JSON: dic)
print("meimeiModel\n \(String(describing: meimeiModel))")
// [dict] -> [model]
// let usersArray2:[User] = Mapper<User>().mapArray(JSONArray: usersArray)
// print("usersArray2\n \(String(describing: usersArray2))")
}
//MARK: Model -> JSONString
class func modelWithJSONString() {
let lilei = User()
lilei.username = "李雷"
lilei.age = 18
let meimei = User()
meimei.username = "梅梅"
meimei.age = 17
meimei.bestFriend = lilei
// model to json string
let meimeiJSON:String = meimei.toJSONString()!
print(meimeiJSON)
// [model] to json string
let users = [lilei, meimei]
let json:String = users.toJSONString()!
print(json)
// json string to model
let meimei2 = User(JSONString: meimeiJSON)
print(meimei2)
// json string to [model]
let users2:[User] = Mapper<User>().mapArray(JSONString: json)!
print(users2)
}
}
| mit |
alblue/swift-corelibs-foundation | Foundation/Data.swift | 1 | 82686 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if DEPLOYMENT_RUNTIME_SWIFT
#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
import CoreFoundation
internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) {
munmap(mem, length)
}
internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) {
free(mem)
}
internal func __NSDataIsCompact(_ data: NSData) -> Bool {
return data._isCompact()
}
#else
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
import _SwiftCoreFoundationOverlayShims
internal func __NSDataIsCompact(_ data: NSData) -> Bool {
if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) {
return data._isCompact()
} else {
var compact = true
let len = data.length
data.enumerateBytes { (_, byteRange, stop) in
if byteRange.length != len {
compact = false
}
stop.pointee = true
}
return compact
}
}
#endif
public final class _DataStorage {
public enum Backing {
// A mirror of the Objective-C implementation that is suitable to inline in Swift
case swift
// these two storage points for immutable and mutable data are reserved for references that are returned by "known"
// cases from Foundation in which implement the backing of struct Data, these have signed up for the concept that
// the backing bytes/mutableBytes pointer does not change per call (unless mutated) as well as the length is ok
// to be cached, this means that as long as the backing reference is retained no further objc_msgSends need to be
// dynamically dispatched out to the reference.
case immutable(NSData) // This will most often (perhaps always) be NSConcreteData
case mutable(NSMutableData) // This will often (perhaps always) be NSConcreteMutableData
// These are reserved for foreign sources where neither Swift nor Foundation are fully certain whom they belong
// to from an object inheritance standpoint, this means that all bets are off and the values of bytes, mutableBytes,
// and length cannot be cached. This also means that all methods are expected to dynamically dispatch out to the
// backing reference.
case customReference(NSData) // tracks data references that are only known to be immutable
case customMutableReference(NSMutableData) // tracks data references that are known to be mutable
}
public static let maxSize = Int.max >> 1
public static let vmOpsThreshold = NSPageSize() * 4
public static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? {
if clear {
return calloc(1, size)
} else {
return malloc(size)
}
}
public static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) {
var dest = dest_
var source = source_
var num = num_
if _DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 {
let pages = NSRoundDownToMultipleOfPageSize(num)
NSCopyMemoryPages(source!, dest, pages)
source = source!.advanced(by: pages)
dest = dest.advanced(by: pages)
num -= pages
}
if num > 0 {
memmove(dest, source!, num)
}
}
public static func shouldAllocateCleared(_ size: Int) -> Bool {
return (size > (128 * 1024))
}
public var _bytes: UnsafeMutableRawPointer?
public var _length: Int
public var _capacity: Int
public var _needToZero: Bool
public var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?
public var _backing: Backing = .swift
public var _offset: Int
public var bytes: UnsafeRawPointer? {
@inline(__always)
get {
switch _backing {
case .swift:
return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
case .immutable:
return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
case .mutable:
return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
case .customReference(let d):
return d.bytes.advanced(by: -_offset)
case .customMutableReference(let d):
return d.bytes.advanced(by: -_offset)
}
}
}
@discardableResult
public func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
switch _backing {
case .swift: fallthrough
case .immutable: fallthrough
case .mutable:
return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, _length)))
case .customReference(let d):
if __NSDataIsCompact(d) {
let len = d.length
guard len > 0 else {
return try apply(UnsafeRawBufferPointer(start: nil, count: 0))
}
return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len)))
} else {
var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment)
defer { buffer.deallocate() }
let sliceRange = NSRange(location: range.lowerBound - _offset, length: range.count)
var enumerated = 0
d.enumerateBytes { (ptr, byteRange, stop) in
if byteRange.upperBound - _offset < range.lowerBound {
// before the range that we are looking for...
} else if byteRange.lowerBound - _offset > range.upperBound {
stop.pointee = true // we are past the range in question so we need to stop
} else {
// the byteRange somehow intersects the range in question that we are looking for...
let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound)
let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound)
let len = upper - lower
memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len)
enumerated += len
if upper == range.upperBound {
stop.pointee = true
}
}
}
return try apply(UnsafeRawBufferPointer(buffer))
}
case .customMutableReference(let d):
if __NSDataIsCompact(d) {
let len = d.length
guard len > 0 else {
return try apply(UnsafeRawBufferPointer(start: nil, count: 0))
}
return try apply(UnsafeRawBufferPointer(start: d.bytes.advanced(by: range.lowerBound - _offset), count: Swift.min(range.count, len)))
} else {
var buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: range.count, alignment: MemoryLayout<UInt>.alignment)
defer { buffer.deallocate() }
let sliceRange = NSRange(location: range.lowerBound - _offset, length: range.count)
var enumerated = 0
d.enumerateBytes { (ptr, byteRange, stop) in
if byteRange.upperBound - _offset < range.lowerBound {
// before the range that we are looking for...
} else if byteRange.lowerBound - _offset > range.upperBound {
stop.pointee = true // we are past the range in question so we need to stop
} else {
// the byteRange somehow intersects the range in question that we are looking for...
let lower = Swift.max(byteRange.lowerBound - _offset, range.lowerBound)
let upper = Swift.min(byteRange.upperBound - _offset, range.upperBound)
let len = upper - lower
memcpy(buffer.baseAddress!.advanced(by: enumerated), ptr.advanced(by: lower - (byteRange.lowerBound - _offset)), len)
enumerated += len
if upper == range.upperBound {
stop.pointee = true
}
}
}
return try apply(UnsafeRawBufferPointer(buffer))
}
}
}
@discardableResult
public func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
switch _backing {
case .swift: fallthrough
case .mutable:
return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length)))
case .customMutableReference(let d):
let len = d.length
return try apply(UnsafeMutableRawBufferPointer(start: d.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len)))
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
_backing = .mutable(data)
_bytes = data.mutableBytes
return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, _length)))
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
_backing = .customMutableReference(data)
let len = data.length
return try apply(UnsafeMutableRawBufferPointer(start: data.mutableBytes.advanced(by:range.lowerBound - _offset), count: Swift.min(range.count, len)))
}
}
public var mutableBytes: UnsafeMutableRawPointer? {
@inline(__always)
get {
switch _backing {
case .swift:
return _bytes?.advanced(by: -_offset)
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .mutable(data)
_bytes = data.mutableBytes
return _bytes?.advanced(by: -_offset)
case .mutable:
return _bytes?.advanced(by: -_offset)
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .customMutableReference(data)
return data.mutableBytes.advanced(by: -_offset)
case .customMutableReference(let d):
return d.mutableBytes.advanced(by: -_offset)
}
}
}
public var length: Int {
@inline(__always)
get {
switch _backing {
case .swift:
return _length
case .immutable:
return _length
case .mutable:
return _length
case .customReference(let d):
return d.length
case .customMutableReference(let d):
return d.length
}
}
@inline(__always)
set {
setLength(newValue)
}
}
public func _freeBytes() {
if let bytes = _bytes {
if let dealloc = _deallocator {
dealloc(bytes, length)
} else {
free(bytes)
}
}
}
public func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) {
var stopv: Bool = false
var data: NSData
switch _backing {
case .swift: fallthrough
case .immutable: fallthrough
case .mutable:
block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.count, _length)), 0, &stopv)
return
case .customReference(let d):
data = d
break
case .customMutableReference(let d):
data = d
break
}
data.enumerateBytes { (ptr, region, stop) in
// any region that is not in the range should be skipped
guard range.contains(region.lowerBound) || range.contains(region.upperBound) else { return }
var regionAdjustment = 0
if region.lowerBound < range.lowerBound {
regionAdjustment = range.lowerBound - (region.lowerBound - _offset)
}
let bytePtr = ptr.advanced(by: regionAdjustment).assumingMemoryBound(to: UInt8.self)
let effectiveLength = Swift.min((region.location - _offset) + region.length, range.upperBound) - (region.location - _offset)
block(UnsafeBufferPointer(start: bytePtr, count: effectiveLength - regionAdjustment), region.location + regionAdjustment - _offset, &stopv)
if stopv {
stop.pointee = true
}
}
}
@inline(never)
public func _grow(_ newLength: Int, _ clear: Bool) {
let cap = _capacity
var additionalCapacity = (newLength >> (_DataStorage.vmOpsThreshold <= newLength ? 2 : 1))
if Int.max - additionalCapacity < newLength {
additionalCapacity = 0
}
var newCapacity = Swift.max(cap, newLength + additionalCapacity)
let origLength = _length
var allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity)
var newBytes: UnsafeMutableRawPointer? = nil
if _bytes == nil {
newBytes = _DataStorage.allocate(newCapacity, allocateCleared)
if newBytes == nil {
/* Try again with minimum length */
allocateCleared = clear && _DataStorage.shouldAllocateCleared(newLength)
newBytes = _DataStorage.allocate(newLength, allocateCleared)
}
} else {
let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4)
if allocateCleared && tryCalloc {
newBytes = _DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
_DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
/* Where calloc/memmove/free fails, realloc might succeed */
if newBytes == nil {
allocateCleared = false
if _deallocator != nil {
newBytes = _DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
_DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
_deallocator = nil
}
} else {
newBytes = realloc(_bytes!, newCapacity)
}
}
/* Try again with minimum length */
if newBytes == nil {
newCapacity = newLength
allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity)
if allocateCleared && tryCalloc {
newBytes = _DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
_DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
if newBytes == nil {
allocateCleared = false
newBytes = realloc(_bytes!, newCapacity)
}
}
}
if newBytes == nil {
/* Could not allocate bytes */
// At this point if the allocation cannot occur the process is likely out of memory
// and Bad-Things™ are going to happen anyhow
fatalError("unable to allocate memory for length (\(newLength))")
}
if origLength < newLength && clear && !allocateCleared {
memset(newBytes!.advanced(by: origLength), 0, newLength - origLength)
}
/* _length set by caller */
_bytes = newBytes
_capacity = newCapacity
/* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */
_needToZero = !allocateCleared
}
@inline(__always)
public func setLength(_ length: Int) {
switch _backing {
case .swift:
let origLength = _length
let newLength = length
if _capacity < newLength || _bytes == nil {
_grow(newLength, true)
} else if origLength < newLength && _needToZero {
memset(_bytes! + origLength, 0, newLength - origLength)
} else if newLength < origLength {
_needToZero = true
}
_length = newLength
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .mutable(data)
_length = length
_bytes = data.mutableBytes
case .mutable(let d):
d.length = length
_length = length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.length = length
}
}
@inline(__always)
public func append(_ bytes: UnsafeRawPointer, length: Int) {
precondition(length >= 0, "Length of appending bytes must not be negative")
switch _backing {
case .swift:
let origLength = _length
let newLength = origLength + length
if _capacity < newLength || _bytes == nil {
_grow(newLength, false)
}
_length = newLength
_DataStorage.move(_bytes!.advanced(by: origLength), bytes, length)
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.append(bytes, length: length)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
case .mutable(let d):
d.append(bytes, length: length)
_length = d.length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.append(bytes, length: length)
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.append(bytes, length: length)
}
}
// fast-path for appending directly from another data storage
@inline(__always)
public func append(_ otherData: _DataStorage, startingAt start: Int, endingAt end: Int) {
let otherLength = otherData.length
if otherLength == 0 { return }
if let bytes = otherData.bytes {
append(bytes.advanced(by: start), length: end - start)
}
}
@inline(__always)
public func append(_ otherData: Data) {
otherData.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, _, _) in
append(buffer.baseAddress!, length: buffer.count)
}
}
@inline(__always)
public func increaseLength(by extraLength: Int) {
if extraLength == 0 { return }
switch _backing {
case .swift:
let origLength = _length
let newLength = origLength + extraLength
if _capacity < newLength || _bytes == nil {
_grow(newLength, true)
} else if _needToZero {
memset(_bytes!.advanced(by: origLength), 0, extraLength)
}
_length = newLength
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.increaseLength(by: extraLength)
_backing = .mutable(data)
_length += extraLength
_bytes = data.mutableBytes
case .mutable(let d):
d.increaseLength(by: extraLength)
_length += extraLength
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.increaseLength(by: extraLength)
_backing = .customReference(data)
case .customMutableReference(let d):
d.increaseLength(by: extraLength)
}
}
public func get(_ index: Int) -> UInt8 {
switch _backing {
case .swift: fallthrough
case .immutable: fallthrough
case .mutable:
return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
case .customReference(let d):
if __NSDataIsCompact(d) {
return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
} else {
var byte: UInt8 = 0
d.enumerateBytes { (ptr, range, stop) in
if NSLocationInRange(index, range) {
let offset = index - range.location - _offset
byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee
stop.pointee = true
}
}
return byte
}
case .customMutableReference(let d):
if __NSDataIsCompact(d) {
return d.bytes.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
} else {
var byte: UInt8 = 0
d.enumerateBytes { (ptr, range, stop) in
if NSLocationInRange(index, range) {
let offset = index - range.location - _offset
byte = ptr.advanced(by: offset).assumingMemoryBound(to: UInt8.self).pointee
stop.pointee = true
}
}
return byte
}
}
}
@inline(__always)
public func set(_ index: Int, to value: UInt8) {
switch _backing {
case .swift:
fallthrough
case .mutable:
_bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value
default:
var theByte = value
let range = NSRange(location: index, length: 1)
replaceBytes(in: range, with: &theByte, length: 1)
}
}
@inline(__always)
public func replaceBytes(in range: NSRange, with bytes: UnsafeRawPointer?) {
if range.length == 0 { return }
switch _backing {
case .swift:
if _length < range.location + range.length {
let newLength = range.location + range.length
if _capacity < newLength {
_grow(newLength, false)
}
_length = newLength
}
_DataStorage.move(_bytes!.advanced(by: range.location - _offset), bytes!, range.length)
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
case .mutable(let d):
d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!)
_length = d.length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!)
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.replaceBytes(in: NSRange(location: range.location - _offset, length: range.length), withBytes: bytes!)
}
}
@inline(__always)
public func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) {
let range = NSRange(location: range_.location - _offset, length: range_.length)
let currentLength = _length
let resultingLength = currentLength - range.length + replacementLength
switch _backing {
case .swift:
let shift = resultingLength - currentLength
var mutableBytes = _bytes
if resultingLength > currentLength {
setLength(resultingLength)
mutableBytes = _bytes!
}
/* shift the trailing bytes */
let start = range.location
let length = range.length
if shift != 0 {
memmove(mutableBytes! + start + replacementLength, mutableBytes! + start + length, currentLength - start - length)
}
if replacementLength != 0 {
if let replacementBytes = replacementBytes {
memmove(mutableBytes! + start, replacementBytes, replacementLength)
} else {
memset(mutableBytes! + start, 0, replacementLength)
}
}
if resultingLength < currentLength {
setLength(resultingLength)
}
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
case .mutable(let d):
d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
_backing = .mutable(d)
_length = d.length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
}
}
@inline(__always)
public func resetBytes(in range_: NSRange) {
let range = NSRange(location: range_.location - _offset, length: range_.length)
if range.length == 0 { return }
switch _backing {
case .swift:
if _length < range.location + range.length {
let newLength = range.location + range.length
if _capacity < newLength {
_grow(newLength, false)
}
_length = newLength
}
memset(_bytes!.advanced(by: range.location), 0, range.length)
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.resetBytes(in: range)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
case .mutable(let d):
d.resetBytes(in: range)
_length = d.length
_bytes = d.mutableBytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.resetBytes(in: range)
_backing = .customMutableReference(data)
case .customMutableReference(let d):
d.resetBytes(in: range)
}
}
public convenience init() {
self.init(capacity: 0)
}
public init(length: Int) {
precondition(length < _DataStorage.maxSize)
var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length
if _DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
let clear = _DataStorage.shouldAllocateCleared(length)
_bytes = _DataStorage.allocate(capacity, clear)!
_capacity = capacity
_needToZero = !clear
_length = 0
_offset = 0
setLength(length)
}
public init(capacity capacity_: Int) {
var capacity = capacity_
precondition(capacity < _DataStorage.maxSize)
if _DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = 0
_bytes = _DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
_offset = 0
}
public init(bytes: UnsafeRawPointer?, length: Int) {
precondition(length < _DataStorage.maxSize)
_offset = 0
if length == 0 {
_capacity = 0
_length = 0
_needToZero = false
_bytes = nil
} else if _DataStorage.vmOpsThreshold <= length {
_capacity = length
_length = length
_needToZero = true
_bytes = _DataStorage.allocate(length, false)!
_DataStorage.move(_bytes!, bytes, length)
} else {
var capacity = length
if _DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = length
_bytes = _DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
_DataStorage.move(_bytes!, bytes, length)
}
}
public init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) {
precondition(length < _DataStorage.maxSize)
_offset = offset
if length == 0 {
_capacity = 0
_length = 0
_needToZero = false
_bytes = nil
if let dealloc = deallocator,
let bytes_ = bytes {
dealloc(bytes_, length)
}
} else if !copy {
_capacity = length
_length = length
_needToZero = false
_bytes = bytes
_deallocator = deallocator
} else if _DataStorage.vmOpsThreshold <= length {
_capacity = length
_length = length
_needToZero = true
_bytes = _DataStorage.allocate(length, false)!
_DataStorage.move(_bytes!, bytes, length)
if let dealloc = deallocator {
dealloc(bytes!, length)
}
} else {
var capacity = length
if _DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = length
_bytes = _DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
_DataStorage.move(_bytes!, bytes, length)
if let dealloc = deallocator {
dealloc(bytes!, length)
}
}
}
public init(immutableReference: NSData, offset: Int) {
_offset = offset
_bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes)
_capacity = 0
_needToZero = false
_length = immutableReference.length
_backing = .immutable(immutableReference)
}
public init(mutableReference: NSMutableData, offset: Int) {
_offset = offset
_bytes = mutableReference.mutableBytes
_capacity = 0
_needToZero = false
_length = mutableReference.length
_backing = .mutable(mutableReference)
}
public init(customReference: NSData, offset: Int) {
_offset = offset
_bytes = nil
_capacity = 0
_needToZero = false
_length = 0
_backing = .customReference(customReference)
}
public init(customMutableReference: NSMutableData, offset: Int) {
_offset = offset
_bytes = nil
_capacity = 0
_needToZero = false
_length = 0
_backing = .customMutableReference(customMutableReference)
}
deinit {
switch _backing {
case .swift:
_freeBytes()
default:
break
}
}
@inline(__always)
public func mutableCopy(_ range: Range<Int>) -> _DataStorage {
switch _backing {
case .swift:
return _DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.count, copy: true, deallocator: nil, offset: range.lowerBound)
case .immutable(let d):
if range.lowerBound == 0 && range.upperBound == _length {
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound)
} else {
return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound)
}
case .mutable(let d):
if range.lowerBound == 0 && range.upperBound == _length {
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound)
} else {
return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound)
}
case .customReference(let d):
if range.lowerBound == 0 && range.upperBound == _length {
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound)
} else {
return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound)
}
case .customMutableReference(let d):
if range.lowerBound == 0 && range.upperBound == _length {
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData, offset: range.lowerBound)
} else {
return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData, offset: range.lowerBound)
}
}
}
public func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T {
if range.isEmpty {
return try work(NSData()) // zero length data can be optimized as a singleton
}
switch _backing {
case .swift:
return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false))
case .immutable(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false))
}
return try work(d)
case .mutable(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.count, freeWhenDone: false))
}
return try work(d)
case .customReference(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false))
}
return try work(d)
case .customMutableReference(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: d.bytes.advanced(by: range.lowerBound - _offset)), length: range.count, freeWhenDone: false))
}
return try work(d)
}
}
public func bridgedReference(_ range: Range<Int>) -> NSData {
if range.isEmpty {
return NSData() // zero length data can be optimized as a singleton
}
switch _backing {
case .swift:
return _NSSwiftData(backing: self, range: range)
case .immutable(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return _NSSwiftData(backing: self, range: range)
}
return d
case .mutable(let d):
guard range.lowerBound == 0 && range.upperBound == _length else {
return _NSSwiftData(backing: self, range: range)
}
return d
case .customReference(let d):
guard range.lowerBound == 0 && range.upperBound == d.length else {
return _NSSwiftData(backing: self, range: range)
}
return d
case .customMutableReference(let d):
guard range.lowerBound == 0 && range.upperBound == d.length else {
return d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC()
}
return d.copy() as! NSData
}
}
public func subdata(in range: Range<Data.Index>) -> Data {
switch _backing {
case .customReference(let d):
return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count))
case .customMutableReference(let d):
return d.subdata(with: NSRange(location: range.lowerBound - _offset, length: range.count))
default:
return Data(bytes: _bytes!.advanced(by: range.lowerBound - _offset), count: range.count)
}
}
}
internal class _NSSwiftData : NSData {
var _backing: _DataStorage!
var _range: Range<Data.Index>!
convenience init(backing: _DataStorage, range: Range<Data.Index>) {
self.init()
_backing = backing
_range = range
}
override var length: Int {
return _range.count
}
override var bytes: UnsafeRawPointer {
// NSData's byte pointer methods are not annotated for nullability correctly
// (but assume non-null by the wrapping macro guards). This placeholder value
// is to work-around this bug. Any indirection to the underlying bytes of an NSData
// with a length of zero would have been a programmer error anyhow so the actual
// return value here is not needed to be an allocated value. This is specifically
// needed to live like this to be source compatible with Swift3. Beyond that point
// this API may be subject to correction.
guard let bytes = _backing.bytes else {
return UnsafeRawPointer(bitPattern: 0xBAD0)!
}
return bytes.advanced(by: _range.lowerBound)
}
override func copy(with zone: NSZone? = nil) -> Any {
return self
}
override func mutableCopy(with zone: NSZone? = nil) -> Any {
return NSMutableData(bytes: bytes, length: length)
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@objc override
func _isCompact() -> Bool {
return true
}
#endif
#if DEPLOYMENT_RUNTIME_SWIFT
override func _providesConcreteBacking() -> Bool {
return true
}
#else
@objc(_providesConcreteBacking)
func _providesConcreteBacking() -> Bool {
return true
}
#endif
}
public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection {
public typealias ReferenceType = NSData
public typealias ReadingOptions = NSData.ReadingOptions
public typealias WritingOptions = NSData.WritingOptions
public typealias SearchOptions = NSData.SearchOptions
public typealias Base64EncodingOptions = NSData.Base64EncodingOptions
public typealias Base64DecodingOptions = NSData.Base64DecodingOptions
public typealias Index = Int
public typealias Indices = Range<Int>
@usableFromInline internal var _backing : _DataStorage
@usableFromInline internal var _sliceRange: Range<Index>
// A standard or custom deallocator for `Data`.
///
/// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated.
public enum Deallocator {
/// Use a virtual memory deallocator.
#if !DEPLOYMENT_RUNTIME_SWIFT
case virtualMemory
#endif
/// Use `munmap`.
case unmap
/// Use `free`.
case free
/// Do nothing upon deallocation.
case none
/// A custom deallocator.
case custom((UnsafeMutableRawPointer, Int) -> Void)
fileprivate var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) {
#if DEPLOYMENT_RUNTIME_SWIFT
switch self {
case .unmap:
return { __NSDataInvokeDeallocatorUnmap($0, $1) }
case .free:
return { __NSDataInvokeDeallocatorFree($0, $1) }
case .none:
return { _, _ in }
case .custom(let b):
return { (ptr, len) in
b(ptr, len)
}
}
#else
switch self {
case .virtualMemory:
return { NSDataDeallocatorVM($0, $1) }
case .unmap:
return { NSDataDeallocatorUnmap($0, $1) }
case .free:
return { NSDataDeallocatorFree($0, $1) }
case .none:
return { _, _ in }
case .custom(let b):
return { (ptr, len) in
b(ptr, len)
}
}
#endif
}
}
// MARK: -
// MARK: Init methods
/// Initialize a `Data` with copied memory content.
///
/// - parameter bytes: A pointer to the memory. It will be copied.
/// - parameter count: The number of bytes to copy.
public init(bytes: UnsafeRawPointer, count: Int) {
_backing = _DataStorage(bytes: bytes, length: count)
_sliceRange = 0..<count
}
/// Initialize a `Data` with copied memory content.
///
/// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) {
let count = MemoryLayout<SourceType>.stride * buffer.count
_backing = _DataStorage(bytes: buffer.baseAddress, length: count)
_sliceRange = 0..<count
}
/// Initialize a `Data` with copied memory content.
///
/// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) {
let count = MemoryLayout<SourceType>.stride * buffer.count
_backing = _DataStorage(bytes: buffer.baseAddress, length: count)
_sliceRange = 0..<count
}
/// Initialize a `Data` with the contents of an Array.
///
/// - parameter bytes: An array of bytes to copy.
public init(bytes: Array<UInt8>) {
let count = bytes.count
_backing = bytes.withUnsafeBufferPointer {
return _DataStorage(bytes: $0.baseAddress, length: count)
}
_sliceRange = 0..<count
}
/// Initialize a `Data` with the contents of an Array.
///
/// - parameter bytes: An array of bytes to copy.
public init(bytes: ArraySlice<UInt8>) {
let count = bytes.count
_backing = bytes.withUnsafeBufferPointer {
return _DataStorage(bytes: $0.baseAddress, length: count)
}
_sliceRange = 0..<count
}
/// Initialize a `Data` with a repeating byte pattern
///
/// - parameter repeatedValue: A byte to initialize the pattern
/// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue
public init(repeating repeatedValue: UInt8, count: Int) {
self.init(count: count)
withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> Void in
memset(bytes, Int32(repeatedValue), count)
}
}
/// Initialize a `Data` with the specified size.
///
/// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount.
///
/// This method sets the `count` of the data to 0.
///
/// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page.
///
/// - parameter capacity: The size of the data.
public init(capacity: Int) {
_backing = _DataStorage(capacity: capacity)
_sliceRange = 0..<0
}
/// Initialize a `Data` with the specified count of zeroed bytes.
///
/// - parameter count: The number of bytes the data initially contains.
public init(count: Int) {
_backing = _DataStorage(length: count)
_sliceRange = 0..<count
}
/// Initialize an empty `Data`.
public init() {
_backing = _DataStorage(length: 0)
_sliceRange = 0..<0
}
/// Initialize a `Data` without copying the bytes.
///
/// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed.
/// - parameter bytes: A pointer to the bytes.
/// - parameter count: The size of the bytes.
/// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`.
public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) {
let whichDeallocator = deallocator._deallocator
_backing = _DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0)
_sliceRange = 0..<count
}
/// Initialize a `Data` with the contents of a `URL`.
///
/// - parameter url: The `URL` to read.
/// - parameter options: Options for the read operation. Default value is `[]`.
/// - throws: An error in the Cocoa domain, if `url` cannot be read.
public init(contentsOf url: URL, options: Data.ReadingOptions = []) throws {
let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue))
_backing = _DataStorage(immutableReference: d, offset: 0)
_sliceRange = 0..<d.length
}
/// Initialize a `Data` from a Base-64 encoded String using the given options.
///
/// Returns nil when the input is not recognized as valid Base-64.
/// - parameter base64String: The string to parse.
/// - parameter options: Encoding options. Default value is `[]`.
public init?(base64Encoded base64String: String, options: Data.Base64DecodingOptions = []) {
if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) {
_backing = _DataStorage(immutableReference: d, offset: 0)
_sliceRange = 0..<d.length
} else {
return nil
}
}
/// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`.
///
/// Returns nil when the input is not recognized as valid Base-64.
///
/// - parameter base64Data: Base-64, UTF-8 encoded input data.
/// - parameter options: Decoding options. Default value is `[]`.
public init?(base64Encoded base64Data: Data, options: Data.Base64DecodingOptions = []) {
if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) {
_backing = _DataStorage(immutableReference: d, offset: 0)
_sliceRange = 0..<d.length
} else {
return nil
}
}
/// Initialize a `Data` by adopting a reference type.
///
/// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation.
///
/// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass.
///
/// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`.
public init(referencing reference: NSData) {
#if DEPLOYMENT_RUNTIME_SWIFT
let providesConcreteBacking = reference._providesConcreteBacking()
#else
let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false
#endif
if providesConcreteBacking {
_backing = _DataStorage(immutableReference: reference.copy() as! NSData, offset: 0)
_sliceRange = 0..<reference.length
} else {
_backing = _DataStorage(customReference: reference.copy() as! NSData, offset: 0)
_sliceRange = 0..<reference.length
}
}
// slightly faster paths for common sequences
public init<S: Sequence>(_ elements: S) where S.Iterator.Element == UInt8 {
if elements is Array<UInt8> {
self.init(bytes: _identityCast(elements, to: Array<UInt8>.self))
} else if elements is ArraySlice<UInt8> {
self.init(bytes: _identityCast(elements, to: ArraySlice<UInt8>.self))
} else if elements is UnsafeBufferPointer<UInt8> {
self.init(buffer: _identityCast(elements, to: UnsafeBufferPointer<UInt8>.self))
} else if let buffer = elements as? UnsafeMutableBufferPointer<UInt8> {
self.init(buffer: buffer)
} else if let data = elements as? Data {
let len = data.count
let backing = data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) in
return _DataStorage(bytes: bytes, length: len)
}
self.init(backing: backing, range: 0..<len)
} else {
let underestimatedCount = elements.underestimatedCount
self.init(count: underestimatedCount)
let (endIterator, _) = UnsafeMutableBufferPointer(start: _backing._bytes?.assumingMemoryBound(to: UInt8.self), count: underestimatedCount).initialize(from: elements)
var iter = endIterator
while let byte = iter.next() { self.append(byte) }
}
}
@usableFromInline
internal init(backing: _DataStorage, range: Range<Index>) {
_backing = backing
_sliceRange = range
}
@usableFromInline
internal func _validateIndex(_ index: Int, message: String? = nil) {
precondition(_sliceRange.contains(index), message ?? "Index \(index) is out of bounds of range \(_sliceRange)")
}
@usableFromInline
internal func _validateRange<R: RangeExpression>(_ range: R) where R.Bound == Int {
let lower = R.Bound(_sliceRange.lowerBound)
let upper = R.Bound(_sliceRange.upperBound)
let r = range.relative(to: lower..<upper)
precondition(r.lowerBound >= _sliceRange.lowerBound && r.lowerBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)")
precondition(r.upperBound >= _sliceRange.lowerBound && r.upperBound <= _sliceRange.upperBound, "Range \(r) is out of bounds of range \(_sliceRange)")
}
// -----------------------------------
// MARK: - Properties and Functions
/// The number of bytes in the data.
public var count: Int {
@inline(__always)
get {
return _sliceRange.count
}
@inline(__always)
set {
precondition(count >= 0, "count must not be negative")
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
_backing.length = newValue
_sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + newValue)
}
}
/// Access the bytes in the data.
///
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
@inline(__always)
public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
return try _backing.withUnsafeBytes(in: _sliceRange) {
return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafePointer<ContentType>(bitPattern: 0xBAD0)!)
}
}
/// Mutate the bytes in the data.
///
/// This function assumes that you are mutating the contents.
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
@inline(__always)
public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
return try _backing.withUnsafeMutableBytes(in: _sliceRange) {
return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafeMutablePointer<ContentType>(bitPattern: 0xBAD0)!)
}
}
// MARK: -
// MARK: Copy Bytes
/// Copy the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
/// - parameter count: The number of bytes to copy.
/// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes.
@inline(__always)
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) {
precondition(count >= 0, "count of bytes to copy must not be negative")
if count == 0 { return }
_backing.withUnsafeBytes(in: _sliceRange) {
memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(count, $0.count))
}
}
@inline(__always)
private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: NSRange) {
if range.length == 0 { return }
_backing.withUnsafeBytes(in: range.lowerBound..<range.upperBound) {
memcpy(UnsafeMutableRawPointer(pointer), $0.baseAddress!, Swift.min(range.length, $0.count))
}
}
/// Copy a subset of the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
/// - parameter range: The range in the `Data` to copy.
/// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes.
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) {
_copyBytesHelper(to: pointer, from: NSRange(range))
}
// Copy the contents of the data into a buffer.
///
/// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer.
/// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called.
/// - parameter buffer: A buffer to copy the data into.
/// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied.
/// - returns: Number of bytes copied into the destination buffer.
public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int {
let cnt = count
guard cnt > 0 else { return 0 }
let copyRange : Range<Index>
if let r = range {
guard !r.isEmpty else { return 0 }
copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count))
} else {
copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt)
}
_validateRange(copyRange)
guard !copyRange.isEmpty else { return 0 }
let nsRange = NSRange(location: copyRange.lowerBound, length: copyRange.upperBound - copyRange.lowerBound)
_copyBytesHelper(to: buffer.baseAddress!, from: nsRange)
return copyRange.count
}
// MARK: -
#if !DEPLOYMENT_RUNTIME_SWIFT
@inline(__always)
private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool {
// Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation.
if !options.contains(.atomic) {
#if os(macOS)
return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max)
#else
return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max)
#endif
} else {
return false
}
}
#endif
/// Write the contents of the `Data` to a location.
///
/// - parameter url: The location to write the data into.
/// - parameter options: Options for writing the data. Default value is `[]`.
/// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`.
public func write(to url: URL, options: Data.WritingOptions = []) throws {
try _backing.withInteriorPointerReference(_sliceRange) {
#if DEPLOYMENT_RUNTIME_SWIFT
try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue))
#else
if _shouldUseNonAtomicWriteReimplementation(options: options) {
var error: NSError? = nil
guard __NSDataWriteToURL($0, url, options, &error) else { throw error! }
} else {
try $0.write(to: url, options: options)
}
#endif
}
}
// MARK: -
/// Find the given `Data` in the content of this `Data`.
///
/// - parameter dataToFind: The data to be searched for.
/// - parameter options: Options for the search. Default value is `[]`.
/// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data.
/// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found.
/// - precondition: `range` must be in the bounds of the Data.
public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? {
let nsRange : NSRange
if let r = range {
_validateRange(r)
nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound)
} else {
nsRange = NSRange(location: 0, length: count)
}
let result = _backing.withInteriorPointerReference(_sliceRange) {
$0.range(of: dataToFind, options: options, in: nsRange)
}
if result.location == NSNotFound {
return nil
}
return (result.location + startIndex)..<((result.location + startIndex) + result.length)
}
/// Enumerate the contents of the data.
///
/// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes.
/// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`.
public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) {
_backing.enumerateBytes(in: _sliceRange, block)
}
@inline(__always)
public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) {
if count == 0 { return }
append(UnsafeBufferPointer(start: bytes, count: count))
}
@inline(__always)
public mutating func append(_ other: Data) {
other.enumerateBytes { (buffer, _, _) in
append(buffer)
}
}
/// Append a buffer of bytes to the data.
///
/// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`.
@inline(__always)
public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
if buffer.isEmpty { return }
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
_backing.replaceBytes(in: NSRange(location: _sliceRange.upperBound, length: _backing.length - (_sliceRange.upperBound - _backing._offset)), with: buffer.baseAddress, length: buffer.count * MemoryLayout<SourceType>.stride)
_sliceRange = _sliceRange.lowerBound..<(_sliceRange.upperBound + buffer.count * MemoryLayout<SourceType>.stride)
}
@inline(__always)
public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == Iterator.Element {
let estimatedCount = newElements.underestimatedCount
guard estimatedCount > 0 else {
for byte in newElements {
append(byte)
}
return
}
_withStackOrHeapBuffer(estimatedCount) { allocation in
let buffer = UnsafeMutableBufferPointer(start: allocation.pointee.memory.assumingMemoryBound(to: UInt8.self), count: estimatedCount)
var (iterator, endPoint) = newElements._copyContents(initializing: buffer)
append(buffer.baseAddress!, count: endPoint - buffer.startIndex)
while let byte = iterator.next() {
append(byte)
}
}
}
@inline(__always)
public mutating func append(contentsOf bytes: [UInt8]) {
bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in
append(buffer)
}
}
// MARK: -
/// Set a region of the data to `0`.
///
/// If `range` exceeds the bounds of the data, then the data is resized to fit.
/// - parameter range: The range in the data to set to `0`.
@inline(__always)
public mutating func resetBytes(in range: Range<Index>) {
// it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth)
precondition(range.lowerBound >= 0, "Ranges must not be negative bounds")
precondition(range.upperBound >= 0, "Ranges must not be negative bounds")
let range = NSRange(location: range.lowerBound, length: range.upperBound - range.lowerBound)
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
_backing.resetBytes(in: range)
if _sliceRange.upperBound < range.upperBound {
_sliceRange = _sliceRange.lowerBound..<range.upperBound
}
}
/// Replace a region of bytes in the data with new data.
///
/// This will resize the data if required, to fit the entire contents of `data`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append.
/// - parameter data: The replacement data.
@inline(__always)
public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) {
let cnt = data.count
data.withUnsafeBytes {
replaceSubrange(subrange, with: $0, count: cnt)
}
}
/// Replace a region of bytes in the data with new bytes from a buffer.
///
/// This will resize the data if required, to fit the entire contents of `buffer`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace.
/// - parameter buffer: The replacement bytes.
@inline(__always)
public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) {
guard !buffer.isEmpty else { return }
replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride)
}
/// Replace a region of bytes in the data with new bytes from a collection.
///
/// This will resize the data if required, to fit the entire contents of `newElements`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace.
/// - parameter newElements: The replacement bytes.
@inline(__always)
public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element {
_validateRange(subrange)
let totalCount: Int = numericCast(newElements.count)
_withStackOrHeapBuffer(totalCount) { conditionalBuffer in
let buffer = UnsafeMutableBufferPointer(start: conditionalBuffer.pointee.memory.assumingMemoryBound(to: UInt8.self), count: totalCount)
var (iterator, index) = newElements._copyContents(initializing: buffer)
while let byte = iterator.next() {
buffer[index] = byte
index = buffer.index(after: index)
}
replaceSubrange(subrange, with: conditionalBuffer.pointee.memory, count: totalCount)
}
}
@inline(__always)
public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) {
_validateRange(subrange)
let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound)
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
let upper = _sliceRange.upperBound
_backing.replaceBytes(in: nsRange, with: bytes, length: cnt)
let resultingUpper = upper - nsRange.length + cnt
_sliceRange = _sliceRange.lowerBound..<resultingUpper
}
/// Return a new copy of the data in a specified range.
///
/// - parameter range: The range to copy.
@inline(__always)
public func subdata(in range: Range<Index>) -> Data {
_validateRange(range)
if isEmpty {
return Data()
}
return _backing.subdata(in: range)
}
// MARK: -
//
/// Returns a Base-64 encoded string.
///
/// - parameter options: The options to use for the encoding. Default value is `[]`.
/// - returns: The Base-64 encoded string.
public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String {
return _backing.withInteriorPointerReference(_sliceRange) {
return $0.base64EncodedString(options: options)
}
}
/// Returns a Base-64 encoded `Data`.
///
/// - parameter options: The options to use for the encoding. Default value is `[]`.
/// - returns: The Base-64 encoded data.
public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data {
return _backing.withInteriorPointerReference(_sliceRange) {
return $0.base64EncodedData(options: options)
}
}
// MARK: -
//
/// The hash value for the data.
public var hashValue: Int {
var hashValue = 0
let hashRange: Range<Int> = _sliceRange.lowerBound..<Swift.min(_sliceRange.lowerBound + 80, _sliceRange.upperBound)
_withStackOrHeapBuffer(hashRange.count + 1) { buffer in
if !hashRange.isEmpty {
_backing.withUnsafeBytes(in: hashRange) {
memcpy(buffer.pointee.memory, $0.baseAddress!, hashRange.count)
}
}
hashValue = Int(bitPattern: CFHashBytes(buffer.pointee.memory.assumingMemoryBound(to: UInt8.self), hashRange.count))
}
return hashValue
}
@inline(__always)
public func advanced(by amount: Int) -> Data {
_validateIndex(startIndex + amount)
let length = count - amount
precondition(length > 0)
return withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data in
return Data(bytes: ptr.advanced(by: amount), count: length)
}
}
// MARK: -
// MARK: -
// MARK: Index and Subscript
/// Sets or returns the byte at the specified index.
public subscript(index: Index) -> UInt8 {
@inline(__always)
get {
_validateIndex(index)
return _backing.get(index)
}
@inline(__always)
set {
_validateIndex(index)
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy(_sliceRange)
}
_backing.set(index, to: newValue)
}
}
public subscript(bounds: Range<Index>) -> Data {
@inline(__always)
get {
_validateRange(bounds)
return Data(backing: _backing, range: bounds)
}
@inline(__always)
set {
replaceSubrange(bounds, with: newValue)
}
}
public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data
where R.Bound: FixedWidthInteger, R.Bound.Stride : SignedInteger {
@inline(__always)
get {
let lower = R.Bound(_sliceRange.lowerBound)
let upper = R.Bound(_sliceRange.upperBound)
let range = rangeExpression.relative(to: lower..<upper)
let start: Int = numericCast(range.lowerBound)
let end: Int = numericCast(range.upperBound)
let r: Range<Int> = start..<end
_validateRange(r)
return Data(backing: _backing, range: r)
}
@inline(__always)
set {
let lower = R.Bound(_sliceRange.lowerBound)
let upper = R.Bound(_sliceRange.upperBound)
let range = rangeExpression.relative(to: lower..<upper)
let start: Int = numericCast(range.lowerBound)
let end: Int = numericCast(range.upperBound)
let r: Range<Int> = start..<end
_validateRange(r)
replaceSubrange(r, with: newValue)
}
}
/// The start `Index` in the data.
public var startIndex: Index {
@inline(__always)
get {
return _sliceRange.lowerBound
}
}
/// The end `Index` into the data.
///
/// This is the "one-past-the-end" position, and will always be equal to the `count`.
public var endIndex: Index {
@inline(__always)
get {
return _sliceRange.upperBound
}
}
@inline(__always)
public func index(before i: Index) -> Index {
return i - 1
}
@inline(__always)
public func index(after i: Index) -> Index {
return i + 1
}
public var indices: Range<Int> {
@inline(__always)
get {
return startIndex..<endIndex
}
}
public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) {
guard !isEmpty else { return (makeIterator(), buffer.startIndex) }
guard let p = buffer.baseAddress else {
preconditionFailure("Attempt to copy contents into nil buffer pointer")
}
let cnt = count
precondition(cnt <= buffer.count, "Insufficient space allocated to copy Data contents")
withUnsafeBytes { p.initialize(from: $0, count: cnt) }
return (Iterator(endOf: self), buffer.index(buffer.startIndex, offsetBy: cnt))
}
/// An iterator over the contents of the data.
///
/// The iterator will increment byte-by-byte.
public func makeIterator() -> Data.Iterator {
return Iterator(self)
}
public struct Iterator : IteratorProtocol {
// Both _data and _endIdx should be 'let' rather than 'var'.
// They are 'var' so that the stored properties can be read
// independently of the other contents of the struct. This prevents
// an exclusivity violation when reading '_endIdx' and '_data'
// while simultaneously mutating '_buffer' with the call to
// withUnsafeMutablePointer(). Once we support accessing struct
// let properties independently we should make these variables
// 'let' again.
private var _data: Data
private var _buffer: (
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
private var _idx: Data.Index
private var _endIdx: Data.Index
fileprivate init(_ data: Data) {
_data = data
_buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
_idx = data.startIndex
_endIdx = data.endIndex
}
fileprivate init(endOf data: Data) {
self._data = data
_buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
_idx = data.endIndex
_endIdx = data.endIndex
}
public mutating func next() -> UInt8? {
guard _idx < _endIdx else { return nil }
defer { _idx += 1 }
let bufferSize = MemoryLayout.size(ofValue: _buffer)
return withUnsafeMutablePointer(to: &_buffer) { ptr_ in
let ptr = UnsafeMutableRawPointer(ptr_).assumingMemoryBound(to: UInt8.self)
let bufferIdx = (_idx - _data.startIndex) % bufferSize
if bufferIdx == 0 {
// populate the buffer
_data.copyBytes(to: ptr, from: _idx..<(_endIdx - _idx > bufferSize ? _idx + bufferSize : _endIdx))
}
return ptr[bufferIdx]
}
}
}
// MARK: -
//
@available(*, unavailable, renamed: "count")
public var length: Int {
get { fatalError() }
set { fatalError() }
}
@available(*, unavailable, message: "use withUnsafeBytes instead")
public var bytes: UnsafeRawPointer { fatalError() }
@available(*, unavailable, message: "use withUnsafeMutableBytes instead")
public var mutableBytes: UnsafeMutableRawPointer { fatalError() }
/// Returns `true` if the two `Data` arguments are equal.
public static func ==(d1 : Data, d2 : Data) -> Bool {
let backing1 = d1._backing
let backing2 = d2._backing
if backing1 === backing2 {
if d1._sliceRange == d2._sliceRange {
return true
}
}
let length1 = d1.count
if length1 != d2.count {
return false
}
if backing1.bytes == backing2.bytes {
if d1._sliceRange == d2._sliceRange {
return true
}
}
if length1 > 0 {
return d1.withUnsafeBytes { (b1) in
return d2.withUnsafeBytes { (b2) in
return memcmp(b1, b2, length1) == 0
}
}
}
return true
}
}
extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
/// A human-readable description for the data.
public var description: String {
return "\(self.count) bytes"
}
/// A human-readable debug description for the data.
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
let nBytes = self.count
var children: [(label: String?, value: Any)] = []
children.append((label: "count", value: nBytes))
self.withUnsafeBytes { (bytes : UnsafePointer<UInt8>) in
children.append((label: "pointer", value: bytes))
}
// Minimal size data is output as an array
if nBytes < 64 {
children.append((label: "bytes", value: Array(self[startIndex..<Swift.min(nBytes + startIndex, endIndex)])))
}
let m = Mirror(self, children:children, displayStyle: .struct)
return m
}
}
extension Data {
@available(*, unavailable, renamed: "copyBytes(to:count:)")
public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { }
@available(*, unavailable, renamed: "copyBytes(to:from:)")
public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { }
}
/// Provides bridging functionality for struct Data to class NSData and vice-versa.
extension Data : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSData {
return _backing.bridgedReference(_sliceRange)
}
public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) {
// We must copy the input because it might be mutable; just like storing a value type in ObjC
result = Data(referencing: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool {
// We must copy the input because it might be mutable; just like storing a value type in ObjC
result = Data(referencing: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data {
guard let src = source else { return Data() }
return Data(referencing: src)
}
}
extension NSData : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self))
}
}
extension Data : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
// It's more efficient to pre-allocate the buffer if we can.
if let count = container.count {
self.init(count: count)
// Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space.
// We don't want to write past the end of what we allocated.
for i in 0 ..< count {
let byte = try container.decode(UInt8.self)
self[i] = byte
}
} else {
self.init()
}
while !container.isAtEnd {
var byte = try container.decode(UInt8.self)
self.append(&byte, count: 1)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
// Since enumerateBytes does not rethrow, we need to catch the error, stow it away, and rethrow if we stopped.
var caughtError: Error? = nil
self.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, byteIndex: Data.Index, stop: inout Bool) in
do {
try container.encode(contentsOf: buffer)
} catch {
caughtError = error
stop = true
}
}
if let error = caughtError {
throw error
}
}
}
| apache-2.0 |
place-marker/ios_google_places_autocomplete | GooglePlacesAutocompleteExample/GooglePlacesAutocompleteExampleTests/GooglePlacesAutocompleteExampleTests.swift | 1 | 3053 | //
// GooglePlacesAutocompleteExampleTests.swift
// GooglePlacesAutocompleteExampleTests
//
// Created by Howard Wilson on 15/02/2015.
// Copyright (c) 2015 Howard Wilson. All rights reserved.
//
import Foundation
import UIKit
import XCTest
import GooglePlacesAutocomplete
class GooglePlacesAutocompleteTests: FBSnapshotTestCase, GooglePlacesAutocompleteDelegate {
let gpaViewController = GooglePlacesAutocomplete(apiKey: "APIKEY")
var expectation: XCTestExpectation!
func testGooglePlacesAutocomplete() {
let json: [String : AnyObject] = ["predictions" : [prediction1, prediction2]]
expectation = self.expectationWithDescription("Should return results")
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest!) -> Bool in
return request.URL.absoluteString == "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Paris&key=APIKEY&types="
}, withStubResponse: { (request: NSURLRequest!) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(JSONObject: json, statusCode: 200, headers: nil)
})
self.gpaViewController.placeDelegate = self
UIApplication.sharedApplication().keyWindow!.rootViewController = UIViewController()
let rootVC = UIApplication.sharedApplication().keyWindow!.rootViewController!
rootVC.presentViewController(self.gpaViewController, animated: false, completion: {
self.snapshotVerifyView(self.gpaViewController.view, withIdentifier: "view")
self.gpaViewController.gpaViewController.searchBar(
self.gpaViewController.gpaViewController.searchBar,
textDidChange: "Paris"
)
})
self.waitForExpectationsWithTimeout(2.0, handler: nil)
}
func placesFound(places: [Place]) {
self.snapshotVerifyView(self.gpaViewController.view, withIdentifier: "search")
expectation.fulfill()
}
let prediction1: [String : AnyObject] = [
"description" : "Paris, France",
"id" : "691b237b0322f28988f3ce03e321ff72a12167fd",
"matched_substrings" : [
["length" : 5, "offset" : 0]
],
"place_id" : "ChIJD7fiBh9u5kcRYJSMaMOCCwQ",
"reference" : "CjQlAAAAbHAcwNAV9grGOKRGKz0czmHc_KsFufZ90X7ZhD0aPhWpyTb8-BQqe0GwWGDdGYzbEhBhFHGRSW6t6U8do2RzgUe0GhRZivpe7tNn7ujO7sWz6Vkv9CNyXg",
"terms" : [
["offset" : 0, "value" : "Paris"],
["offset" : 7, "value" : "France"]
],
"types" : [ "locality", "political", "geocode" ]
]
let prediction2: [String : AnyObject] = [
"description" : "Paris 17, Paris, France",
"id" : "126ccd7b36db3990466ee234998f25ab92ce88ac",
"matched_substrings" : [
["length" : 5, "offset" : 0]
],
"place_id" : "ChIJVRQP1aJv5kcRUBuUaMOCCwU",
"reference" : "CjQvAAAAR0bndCO53tJbbUDTclTXN6rgKRDEqCmsoYCDq5qpHCnOnhhrtyXmFSwWx-zVvWi0EhD6G6PPrJTOQEazhy5-JFhVGhRND1R7Or4V3lDaHkBcXt98X8u5mw",
"terms" : [
["offset" : 0, "value" : "Paris 17"],
["offset" : 10, "value" : "Paris"],
["offset" : 17, "value" : "France"]
],
"types" : [ "sublocality_level_1", "sublocality", "political", "geocode" ]
]
}
| mit |
grgcombs/PlayingCards-Swift | Pod/Classes/CardGlyphs.swift | 1 | 2700 | //
// CardGlyphs.swift
// Pods
//
// Created by Gregory Combs on 7/23/15.
// Copyright (c) 2015 PlayingCards (Swift). All rights reserved.
//
import Foundation
internal typealias CardGlyphMap = [CardType : String];
internal typealias SuitGlyphMap = [SuitType : CardGlyphMap];
internal class CardGlyphs {
static func glyphForSuit(suiteType:SuitType, cardType:CardType) -> String? {
if let glyphs = SharedCardGlyphs.cardGlyphs[suiteType] ?? nil {
return glyphs[cardType] ?? nil;
}
return nil;
}
}
/**
* The singleton ensures the (expensive) setup is completed only once,
* no matter how many times you need to access the card glyphs.
*/
private let SharedCardGlyphs : CardGlyphsPrivate = CardGlyphsPrivate();
private class CardGlyphsPrivate {
init() {
var emptyMap : SuitGlyphMap = [:];
cardGlyphs = SuitType.allValues.map({
($0, $0.cardGlyphMap)
}).reduce(emptyMap, combine: {
var map : SuitGlyphMap = $0;
let tuple : GlyphTuple = $1;
map[tuple.suiteType] = tuple.cardGlyphs;
return map;
});
}
private typealias GlyphTuple = (suiteType: SuitType, cardGlyphs: CardGlyphMap);
private let cardGlyphs : SuitGlyphMap;
}
private extension SuitType {
private typealias IndexedCardTypeTuple = (index: Int, element: CardType);
private typealias RangeWithExclusion = (range: Range<Int>, exclude: Int);
private var cardGlyphRange : RangeWithExclusion {
get {
switch self {
case .Spades:
return (0x1F0A1...0x1F0AE, 0x1F0AC);
case .Hearts:
return (0x1F0B1...0x1F0BE, 0x1F0BC);
case .Diamonds:
return (0x1F0C1...0x1F0CE, 0x1F0CC);
case .Clubs:
return (0x1F0D1...0x1F0DE, 0x1F0DC);
}
}
}
private var cardGlyphMap : CardGlyphMap {
get {
var cardTypes = EnumerateGenerator(CardType.allValues.generate())
let range = cardGlyphRange;
var glyphs : CardGlyphMap = [:];
for code in range.range {
if code == range.exclude {
continue;
}
let scalar = UnicodeScalar(code);
let char = Character(scalar);
if let tuple : IndexedCardTypeTuple = cardTypes.next() {
let cardType = tuple.element;
glyphs[cardType] = "\(char)";
continue;
}
break; // no more next()'s, time to quit
}
return glyphs;
}
}
}
| mit |
abunur/quran-ios | UIKitExtension/ActivityIndicator.swift | 1 | 2215 | //
// ActivityIndicator.swift
// RxExample
//
// Created by Krunoslav Zaher on 10/18/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
private struct ActivityToken<E> : ObservableConvertibleType, Disposable {
private let _source: Observable<E>
private let _dispose: Cancelable
init(source: Observable<E>, disposeAction: @escaping () -> ()) {
_source = source
_dispose = Disposables.create(with: disposeAction)
}
func dispose() {
_dispose.dispose()
}
func asObservable() -> Observable<E> {
return _source
}
}
/**
Enables monitoring of sequence computation.
If there is at least one sequence computation in progress, `true` will be sent.
When all activities complete `false` will be sent.
*/
public class ActivityIndicator : SharedSequenceConvertibleType {
public typealias E = Bool
public typealias SharingStrategy = DriverSharingStrategy
private let _lock = NSRecursiveLock()
private let _variable = Variable(0)
private let _loading: SharedSequence<SharingStrategy, Bool>
public init() {
_loading = _variable.asDriver()
.map { $0 > 0 }
.distinctUntilChanged()
}
fileprivate func trackActivityOfObservable<O: ObservableConvertibleType>(_ source: O) -> Observable<O.E> {
return Observable.using({ () -> ActivityToken<O.E> in
self.increment()
return ActivityToken(source: source.asObservable(), disposeAction: self.decrement)
}) { t in
return t.asObservable()
}
}
private func increment() {
_lock.lock()
_variable.value = _variable.value + 1
_lock.unlock()
}
private func decrement() {
_lock.lock()
_variable.value = _variable.value - 1
_lock.unlock()
}
public func asSharedSequence() -> SharedSequence<SharingStrategy, E> {
return _loading
}
}
extension ObservableConvertibleType {
public func trackActivity(_ activityIndicator: ActivityIndicator) -> Observable<E> {
return activityIndicator.trackActivityOfObservable(self)
}
}
| gpl-3.0 |
aiwalle/LiveProject | LiveProject/Tools/NibLoadable.swift | 1 | 424 | //
// NibLoadable.swift
// LiveProject
//
// Created by liang on 2017/8/9.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
protocol NibLoadable {
}
extension NibLoadable where Self : UIView {
static func loadFromNib(_ nibName : String? = nil) -> Self {
let nib = nibName ?? "\(self)"
return Bundle.main.loadNibNamed(nib, owner: nil, options: nil)?.first as! Self
}
}
| mit |
rice-apps/wellbeing-app | app/Pods/Socket.IO-Client-Swift/Source/SocketEngineSpec.swift | 2 | 6919 | //
// SocketEngineSpec.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 10/7/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Specifies a SocketEngine.
@objc public protocol SocketEngineSpec {
/// The client for this engine.
weak var client: SocketEngineClient? { get set }
/// `true` if this engine is closed.
var closed: Bool { get }
/// `true` if this engine is connected. Connected means that the initial poll connect has succeeded.
var connected: Bool { get }
/// The connect parameters sent during a connect.
var connectParams: [String: Any]? { get set }
/// Set to `true` if using the node.js version of socket.io. The node.js version of socket.io
/// handles utf8 incorrectly.
var doubleEncodeUTF8: Bool { get }
/// An array of HTTPCookies that are sent during the connection.
var cookies: [HTTPCookie]? { get }
/// The queue that all engine actions take place on.
var engineQueue: DispatchQueue { get }
/// A dictionary of extra http headers that will be set during connection.
var extraHeaders: [String: String]? { get }
/// When `true`, the engine is in the process of switching to WebSockets.
var fastUpgrade: Bool { get }
/// When `true`, the engine will only use HTTP long-polling as a transport.
var forcePolling: Bool { get }
/// When `true`, the engine will only use WebSockets as a transport.
var forceWebsockets: Bool { get }
/// If `true`, the engine is currently in HTTP long-polling mode.
var polling: Bool { get }
/// If `true`, the engine is currently seeing whether it can upgrade to WebSockets.
var probing: Bool { get }
/// The session id for this engine.
var sid: String { get }
/// The path to engine.io.
var socketPath: String { get }
/// The url for polling.
var urlPolling: URL { get }
/// The url for WebSockets.
var urlWebSocket: URL { get }
/// If `true`, then the engine is currently in WebSockets mode.
var websocket: Bool { get }
/// The WebSocket for this engine.
var ws: WebSocket? { get }
/// Creates a new engine.
///
/// - parameter client: The client for this engine.
/// - parameter url: The url for this engine.
/// - parameter options: The options for this engine.
init(client: SocketEngineClient, url: URL, options: NSDictionary?)
/// Starts the connection to the server.
func connect()
/// Called when an error happens during execution. Causes a disconnection.
func didError(reason: String)
/// Disconnects from the server.
///
/// - parameter reason: The reason for the disconnection. This is communicated up to the client.
func disconnect(reason: String)
/// Called to switch from HTTP long-polling to WebSockets. After calling this method the engine will be in
/// WebSocket mode.
///
/// **You shouldn't call this directly**
func doFastUpgrade()
/// Causes any packets that were waiting for POSTing to be sent through the WebSocket. This happens because when
/// the engine is attempting to upgrade to WebSocket it does not do any POSTing.
///
/// **You shouldn't call this directly**
func flushWaitingForPostToWebSocket()
/// Parses raw binary received from engine.io.
///
/// - parameter data: The data to parse.
func parseEngineData(_ data: Data)
/// Parses a raw engine.io packet.
///
/// - parameter message: The message to parse.
/// - parameter fromPolling: Whether this message is from long-polling.
/// If `true` we might have to fix utf8 encoding.
func parseEngineMessage(_ message: String, fromPolling: Bool)
/// Writes a message to engine.io, independent of transport.
///
/// - parameter msg: The message to send.
/// - parameter withType: The type of this message.
/// - parameter withData: Any data that this message has.
func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data])
}
extension SocketEngineSpec {
var urlPollingWithSid: URL {
var com = URLComponents(url: urlPolling, resolvingAgainstBaseURL: false)!
com.percentEncodedQuery = com.percentEncodedQuery! + "&sid=\(sid.urlEncode()!)"
return com.url!
}
var urlWebSocketWithSid: URL {
var com = URLComponents(url: urlWebSocket, resolvingAgainstBaseURL: false)!
com.percentEncodedQuery = com.percentEncodedQuery! + (sid == "" ? "" : "&sid=\(sid.urlEncode()!)")
return com.url!
}
func createBinaryDataForSend(using data: Data) -> Either<Data, String> {
if websocket {
var byteArray = [UInt8](repeating: 0x4, count: 1)
let mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.append(data)
return .left(mutData as Data)
} else {
let str = "b4" + data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
return .right(str)
}
}
func doubleEncodeUTF8(_ string: String) -> String {
if let latin1 = string.data(using: String.Encoding.utf8),
let utf8 = NSString(data: latin1, encoding: String.Encoding.isoLatin1.rawValue) {
return utf8 as String
} else {
return string
}
}
func fixDoubleUTF8(_ string: String) -> String {
if let utf8 = string.data(using: String.Encoding.isoLatin1),
let latin1 = NSString(data: utf8, encoding: String.Encoding.utf8.rawValue) {
return latin1 as String
} else {
return string
}
}
/// Send an engine message (4)
func send(_ msg: String, withData datas: [Data]) {
write(msg, withType: .message, withData: datas)
}
}
| mit |
rsmoz/swift-corelibs-foundation | TestFoundation/TestNSIndexPath.swift | 1 | 1482 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSIndexPath: XCTestCase {
var allTests: [(String, () throws -> Void)] {
return [
("test_BasicConstruction", test_BasicConstruction)
]
}
func test_BasicConstruction() {
// Test `init()`
do {
let path = NSIndexPath()
XCTAssertEqual(path.length, 0)
}
// Test `init(index:)`
do {
let path = NSIndexPath(index: 8)
XCTAssertEqual(path.length, 1)
let index0 = path.indexAtPosition(0)
XCTAssertEqual(index0, 8)
}
// Test `init(indexes:)`
do {
let path = NSIndexPath(indexes: [1, 2], length: 2)
XCTAssertEqual(path.length, 2)
let index0 = path.indexAtPosition(0)
XCTAssertEqual(index0, 1)
let index1 = path.indexAtPosition(1)
XCTAssertEqual(index1, 2)
}
}
}
| apache-2.0 |
sora0077/iTunesMusicKit | src/Endpoint/GetPreviewUrl.swift | 1 | 1555 | //
// GetPreviewUrl.swift
// iTunesMusicKit
//
// Created by 林達也 on 2015/10/16.
// Copyright © 2015年 jp.sora0077. All rights reserved.
//
import Foundation
import APIKit
public struct GetPreviewUrl {
public let id: String
public let url: String
init(id: String, url: String) {
self.id = id
self.url = url
}
}
public extension GetPreviewUrl {
init(track: Track) {
self.init(id: track.id, url: track.url)
}
}
extension GetPreviewUrl: iTunesRequestToken {
public typealias Response = String
public typealias SerializedObject = [String: AnyObject]
public var method: HTTPMethod {
return .GET
}
public var path: String {
return url
}
public var headers: [String : String]? {
return [
"X-Apple-Store-Front": "143462-9,4",
]
}
public var serializer: Serializer {
return .PropertyList(.Immutable)
}
public func transform(request: NSURLRequest?, response: NSHTTPURLResponse?, object: SerializedObject) throws -> Response {
let items = object["items"] as! [[String: AnyObject]]
// print(items as NSArray)
for item in items {
let id = String(item["item-id"] as! Int)
if self.id == id {
let previewUrl = item["store-offers"]!["PLUS"]!!["preview-url"] as! String
return previewUrl
}
}
throw Error.Unknown
}
}
| mit |
xxxAIRINxxx/Cmg | Sources/Generator.swift | 1 | 14212 | //
// Generator.swift
// Cmg
//
// Created by xxxAIRINxxx on 2016/02/20.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
public struct AztecCodeGenerator: InputImageUnusable, FilterInputCollectionType,
InputMessageAvailable, InputCorrectionLevelAvailable, InputLayersAvailable,
InputCompactStyleAvailable {
public let filter: CIFilter = CIFilter(name: "CIAztecCodeGenerator")!
public let inputMessage: StringInput
public let inputCorrectionLevel: ScalarInput
public let inputLayers: ScalarInput
public let inputCompactStyle: BooleanInput
public init(message: String) {
self.inputMessage = StringInput(filter: self.filter, key: "inputMessage", message)
self.inputCorrectionLevel = ScalarInput(filter: self.filter, key: "inputCorrectionLevel")
self.inputLayers = ScalarInput(filter: self.filter, key: "inputLayers")
self.inputCompactStyle = BooleanInput(filter: self.filter, key: "inputCompactStyle")
}
public func inputs() -> [FilterInputable] {
return [
self.inputMessage,
self.inputCorrectionLevel,
self.inputLayers,
self.inputCompactStyle
]
}
}
public struct CheckerboardGenerator: InputImageUnusable, FilterInputCollectionType,
InputCenterAvailable, InputColor0Available, InputColor1Available,
InputWidthAvailable, InputSharpnessAvailable {
public let filter: CIFilter = CIFilter(name: "CICheckerboardGenerator")!
public let inputCenter: VectorInput
public let inputColor0: ColorInput
public let inputColor1: ColorInput
public let inputWidth: ScalarInput
public let inputSharpness: ScalarInput
public init(imageSize: CGSize) {
self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey)
self.inputColor0 = ColorInput(filter: self.filter, key: "inputColor0")
self.inputColor1 = ColorInput(filter: self.filter, key: "inputColor1")
self.inputWidth = ScalarInput(filter: self.filter, key: kCIInputWidthKey)
self.inputSharpness = ScalarInput(filter: self.filter, key: kCIInputSharpnessKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputCenter,
self.inputColor0,
self.inputColor1,
self.inputWidth,
self.inputSharpness
]
}
}
public struct Code128BarcodeGenerator: InputImageUnusable, FilterInputCollectionType,
InputMessageAvailable, InputQuietSpaceAvailable {
public let filter: CIFilter = CIFilter(name: "CICode128BarcodeGenerator")!
public let inputMessage: StringInput
public let inputQuietSpace: ScalarInput
public init(message: String) {
self.inputMessage = StringInput(filter: self.filter, key: "inputMessage", message, true, String.Encoding.ascii.rawValue)
self.inputQuietSpace = ScalarInput(filter: self.filter, key: "inputQuietSpace")
}
public func inputs() -> [FilterInputable] {
return [
self.inputMessage,
self.inputQuietSpace
]
}
}
public struct ConstantColorGenerator: InputImageUnusable, FilterInputCollectionType,
InputColorAvailable {
public let filter: CIFilter = CIFilter(name: "CIConstantColorGenerator")!
public let inputColor: ColorInput
public init() {
self.inputColor = ColorInput(filter: self.filter, key: kCIInputColorKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputColor
]
}
}
@available(iOS 9.0, *)
public struct LenticularHaloGenerator: InputImageUnusable, FilterInputCollectionType,
InputCenterAvailable, InputColorAvailable, InputHaloRadiusAvailable,
InputHaloWidthAvailable, InputHaloOverlapAvailable, InputStriationStrengthAvailable,
InputStriationContrastAvailable, InputTimeAvailable {
public let filter: CIFilter = CIFilter(name: "CILenticularHaloGenerator")!
public let inputCenter: VectorInput
public let inputColor: ColorInput
public let inputHaloRadius: ScalarInput
public let inputHaloWidth: ScalarInput
public let inputHaloOverlap: ScalarInput
public let inputStriationStrength: ScalarInput
public let inputStriationContrast: ScalarInput
public let inputTime: ScalarInput
public init(imageSize: CGSize) {
self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey)
self.inputColor = ColorInput(filter: self.filter, key: kCIInputColorKey)
self.inputHaloRadius = ScalarInput(filter: self.filter, key: "inputHaloRadius")
self.inputHaloWidth = ScalarInput(filter: self.filter, key: "inputHaloWidth")
self.inputHaloOverlap = ScalarInput(filter: self.filter, key: "inputHaloOverlap")
self.inputStriationStrength = ScalarInput(filter: self.filter, key: "inputStriationStrength")
self.inputStriationContrast = ScalarInput(filter: self.filter, key: "inputStriationContrast")
self.inputTime = ScalarInput(filter: self.filter, key: "inputTime")
}
public func inputs() -> [FilterInputable] {
return [
self.inputCenter,
self.inputColor,
self.inputHaloRadius,
self.inputHaloWidth,
self.inputHaloOverlap,
self.inputStriationStrength,
self.inputStriationContrast,
self.inputTime
]
}
}
@available(iOS 9.0, *)
public struct PDF417BarcodeGenerator: InputImageUnusable, FilterInputCollectionType,
InputMessageAvailable, InputMinWidthAvailable, InputMaxWidthAvailable,
InputMinHeightAvailable, InputMaxHeightAvailable, InputDataColumnsAvailable,
InputRowsAvailable, InputPreferredAspectRatioAvailable, InputCompactionModeAvailable,
InputCompactStyleAvailable, InputCorrectionLevelAvailable, InputAlwaysSpecifyCompactionAvailable {
public let filter: CIFilter = CIFilter(name: "CIPDF417BarcodeGenerator")!
public let inputMessage: StringInput
public let inputMinWidth: VectorInput
public let inputMaxWidth: VectorInput
public let inputMinHeight: VectorInput
public let inputMaxHeight: VectorInput
public let inputDataColumns: ScalarInput
public let inputRows: ScalarInput
public let inputPreferredAspectRatio: ScalarInput
public let inputCompactionMode: ScalarInput
public let inputCompactStyle: BooleanInput
public let inputCorrectionLevel: ScalarInput
public let inputAlwaysSpecifyCompaction: ScalarInput
public init(inputMessage: String, imageSize: CGSize) {
self.inputMessage = StringInput(filter: self.filter, key: "inputMessage", inputMessage, true, String.Encoding.isoLatin1.rawValue)
self.inputMinWidth = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputMinWidth")
self.inputMaxWidth = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputMaxWidth")
self.inputMinHeight = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputMinHeight")
self.inputMaxHeight = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputMaxHeight")
self.inputDataColumns = ScalarInput(filter: self.filter, key: "inputDataColumns")
self.inputRows = ScalarInput(filter: self.filter, key: "inputRows", 45.0)
self.inputPreferredAspectRatio = ScalarInput(filter: self.filter, key: "inputPreferredAspectRatio")
self.inputCompactionMode = ScalarInput(filter: self.filter, key: "inputCompactionMode")
self.inputCompactStyle = BooleanInput(filter: self.filter, key: "inputCompactStyle")
self.inputCorrectionLevel = ScalarInput(filter: self.filter, key: "inputCorrectionLevel")
self.inputAlwaysSpecifyCompaction = ScalarInput(filter: self.filter, key: "inputAlwaysSpecifyCompaction")
}
public func inputs() -> [FilterInputable] {
return [
self.inputMessage,
self.inputMinWidth,
self.inputMaxWidth,
self.inputMinHeight,
self.inputMaxHeight,
self.inputDataColumns,
self.inputRows,
self.inputPreferredAspectRatio,
self.inputCompactionMode,
self.inputCompactStyle,
self.inputCorrectionLevel,
self.inputAlwaysSpecifyCompaction
]
}
}
public struct QRCodeGenerator: InputImageUnusable, FilterInputCollectionType,
InputMessageAvailable, InputStringCorrectionLevelAvailable {
public let filter: CIFilter = CIFilter(name: "CIQRCodeGenerator")!
public let inputMessage: StringInput
public let inputStringCorrectionLevel: StringInput
public init(message: String) {
self.inputMessage = StringInput(filter: self.filter, key: "inputMessage", message)
self.inputStringCorrectionLevel = StringInput(filter: self.filter, key: "inputCorrectionLevel", nil, false)
}
public func inputs() -> [FilterInputable] {
return [
self.inputMessage,
self.inputStringCorrectionLevel
]
}
}
public struct RandomGenerator: InputImageUnusable {
public let filter: CIFilter = CIFilter(name: "CIRandomGenerator")!
public init() {}
}
public struct StarShineGenerator: InputImageUnusable, FilterInputCollectionType,
InputCenterAvailable, InputColorAvailable, InputRadiusAvailable,
InputCrossScaleAvailable, InputCrossAngleAvailable, InputCrossOpacityAvailable,
InputCrossWidthAvailable, InputEpsilonAvailable {
public let filter: CIFilter = CIFilter(name: "CIStarShineGenerator")!
public let inputCenter: VectorInput
public let inputColor: ColorInput
public let inputRadius: ScalarInput
public let inputCrossScale: ScalarInput
public let inputCrossAngle: ScalarInput
public let inputCrossOpacity: ScalarInput
public let inputCrossWidth: ScalarInput
public let inputEpsilon: ScalarInput
public init(imageSize: CGSize) {
self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey)
self.inputColor = ColorInput(filter: self.filter, key: kCIInputColorKey)
self.inputRadius = ScalarInput(filter: self.filter, key: kCIInputRadiusKey)
self.inputCrossScale = ScalarInput(filter: self.filter, key: "inputCrossScale")
self.inputCrossAngle = ScalarInput(filter: self.filter, key: "inputCrossAngle")
self.inputCrossOpacity = ScalarInput(filter: self.filter, key: "inputCrossOpacity")
self.inputCrossWidth = ScalarInput(filter: self.filter, key: "inputCrossWidth")
self.inputEpsilon = ScalarInput(filter: self.filter, key: "inputEpsilon")
}
public func inputs() -> [FilterInputable] {
return [
self.inputCenter,
self.inputColor,
self.inputRadius,
self.inputCrossScale,
self.inputCrossAngle,
self.inputCrossOpacity,
self.inputCrossWidth,
self.inputEpsilon
]
}
}
public struct StripesGenerator: InputImageUnusable, FilterInputCollectionType,
InputCenterAvailable, InputColor0Available, InputColor1Available,
InputWidthAvailable, InputSharpnessAvailable {
public let filter: CIFilter = CIFilter(name: "CIStripesGenerator")!
public let inputCenter: VectorInput
public let inputColor0: ColorInput
public let inputColor1: ColorInput
public let inputWidth: ScalarInput
public let inputSharpness: ScalarInput
public init(imageSize: CGSize) {
self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey)
self.inputColor0 = ColorInput(filter: self.filter, key: "inputColor0")
self.inputColor1 = ColorInput(filter: self.filter, key: "inputColor1")
self.inputWidth = ScalarInput(filter: self.filter, key: kCIInputWidthKey)
self.inputSharpness = ScalarInput(filter: self.filter, key: kCIInputSharpnessKey)
}
public func inputs() -> [FilterInputable] {
return [
self.inputCenter,
self.inputColor0,
self.inputColor1,
self.inputWidth,
self.inputSharpness
]
}
}
@available(iOS 9.0, *)
public struct SunbeamsGenerator: InputImageUnusable, FilterInputCollectionType,
InputCenterAvailable, InputColorAvailable, InputSunRadiusAvailable,
InputMaxStriationRadiusAvailable, InputStriationStrengthAvailable, InputStriationContrastAvailable,
InputTimeAvailable {
public let filter: CIFilter = CIFilter(name: "CISunbeamsGenerator")!
public let inputCenter: VectorInput
public let inputColor: ColorInput
public let inputSunRadius: ScalarInput
public let inputMaxStriationRadius: ScalarInput
public let inputStriationStrength: ScalarInput
public let inputStriationContrast: ScalarInput
public let inputTime: ScalarInput
public init(imageSize: CGSize) {
self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey)
self.inputColor = ColorInput(filter: self.filter, key: kCIInputColorKey)
self.inputSunRadius = ScalarInput(filter: self.filter, key: "inputSunRadius")
self.inputMaxStriationRadius = ScalarInput(filter: self.filter, key: "inputMaxStriationRadius")
self.inputStriationStrength = ScalarInput(filter: self.filter, key: "inputStriationStrength")
self.inputStriationContrast = ScalarInput(filter: self.filter, key: "inputStriationContrast")
self.inputTime = ScalarInput(filter: self.filter, key: "inputTime")
}
public func inputs() -> [FilterInputable] {
return [
self.inputCenter,
self.inputColor,
self.inputSunRadius,
self.inputMaxStriationRadius,
self.inputStriationStrength,
self.inputStriationContrast,
self.inputTime
]
}
}
| mit |
Rahulclaritaz/rahul | ixprez/ixprez/RegistrationViewController.swift | 1 | 23684 | //
// RegistrationViewController.swift
// ixprez
//
// Created by Claritaz Techlabs on 27/04/17.
// Copyright © 2017 Claritaz Techlabs. All rights reserved.
//
import UIKit
import CoreTelephony
import FirebaseAuth
import UserNotifications
import CloudKit
class RegistrationViewController: UIViewController,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource{
@IBOutlet weak var btnTerm: UIButton!
@IBOutlet weak var btnPrivacy: UIButton!
@IBOutlet weak var viewScrollView: UIView!
// @IBOutlet weak var countryPickerView: UIPickerView!
// @IBOutlet weak var languagePickerView: UIPickerView!
@IBOutlet weak var nameTextField : UITextField?
@IBOutlet weak var emailTextField : UITextField?
@IBOutlet weak var mobileNumberTextField : UITextField?
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var countryTextField : UITextField!
@IBOutlet weak var languageTextField : UITextField!
@IBOutlet weak var countryTableView : UITableView!
@IBOutlet weak var languageTableView : UITableView!
var countryData = [[String : Any]]()
var languageData = [[String : Any]]()
var filterCountryData = [[String : Any]]()
var filterLanguageData = [[String:Any]]()
var autoCompleteCountryPossibilities : [NSArray] = []
var autoCompleteLanguagePossibilities : [NSArray] = []
var autoCountryComplete : [NSArray] = []
var autoLanguageComplete : [NSArray] = []
var isCountryTextField : Bool = false
var tap = UITapGestureRecognizer()
var defaults = UserDefaults.standard
var countrySelectedValue = UILabel()
var languageSelectedValue = UILabel()
var countrySelectedPhoneCode = UILabel()
var jsonArrayData = [String]()
var pickerData: [String] = [String]()
var dictValue = NSDictionary()
var countryArrayData = [NSArray]()
var languageArrayData = [NSArray]()
var countryPhoneCode = [NSArray]()
var listData = [String: AnyObject]()
let appdelegate = UIApplication.shared.delegate as! AppDelegate
let getOTPClass = XPWebService()
let getOTPUrl = URLDirectory.RegistrationData()
let getCountryUrl = URLDirectory.Country()
let getLanguageUrl = URLDirectory.Language()
var myCountry : String!
var translated = String()
var country : String!
var countryCode : String!
override func awakeFromNib()
{
let languages = NSLocale.preferredLanguages
for lang in languages
{
let locale = NSLocale(localeIdentifier: lang)
translated = locale.displayName(forKey: NSLocale.Key.identifier, value: lang)!
print("\(lang), \(translated)")
}
// This will set the device country code
let countryLocale : NSLocale = NSLocale.current as NSLocale
let countryCode = countryLocale.object(forKey: NSLocale.Key.countryCode)// as! String
country = countryLocale.displayName(forKey: NSLocale.Key.countryCode, value: countryCode!)
myCountry = String(describing: country!)
print("myCountry", myCountry)
print("Country Locale:\(countryLocale) Code:\(String(describing: countryCode)) Name:\(String(describing: country))")
}
override func viewDidLoad()
{
super.viewDidLoad()
// This will set the device language
languageTextField.text = translated
// This will set the country Mobile prefix code
countryTextField.text = country!
countryTableView.layer.cornerRadius = 10
languageTableView.layer.cornerRadius = 10
self.view.backgroundColor = UIColor(patternImage: UIImage(named:"bg_reg.png")!)
self.viewScrollView.backgroundColor = UIColor(patternImage: UIImage(named:"bg_reg.png")!)
getCountryDataFromTheWebService()
getLanguageNameFromWebService()
UserDefaults.standard.set(true, forKey: "isAppFirstTime")
// This gesture will use to hide the keyboard (tap anywhere inside the screen)
// tap = UITapGestureRecognizer(target: self, action:#selector(dismissKeyboard(rec:)))
//view.addGestureRecognizer(tap)
nameTextField?.delegate = self
saveButton.layer.cornerRadius = 20.0
countryTextField.delegate = self
languageTextField.delegate = self
mobileNumberTextField?.delegate = self
emailTextField?.delegate = self
self.btnTerm.addTarget(self, action: #selector(termsAndCondition(sender:)), for: .touchUpInside)
self.btnPrivacy.addTarget(self, action: #selector(privacyPolicy(sender:)), for: .touchUpInside)
}
override func viewWillAppear(_ animated: Bool) {
countryTableView.isHidden = true
languageTableView.isHidden = true
}
// This will open the browser for term and Conditions.
@IBAction func termsAndCondition (sender : UIButton) {
UIApplication.shared.openURL(NSURL(string: "http://www.quadrupleindia.com/ixprez/page/terms_conditions.html")! as URL)
}
// This will open the browser for Privacy.
@IBAction func privacyPolicy (sender : UIButton) {
UIApplication.shared.openURL(NSURL(string: "http://www.quadrupleindia.com/ixprez/page/privacy_policy.html")! as URL)
}
// TextField Delegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// tap.cancelsTouchesInView = false
var subString = String()
if (textField.tag == 1)
{
subString = (countryTextField.text! as NSString).replacingCharacters(in: range, with: string)
searchAutocompleteCountryEntriesWithSubstring(substring: subString)
if (subString.isEmpty)
{
countryTableView.isHidden = true
}else {
countryTableView.isHidden = false
languageTableView.isHidden = true
isCountryTextField = true
}
} else if (textField.tag == 2)
{
subString = (languageTextField.text! as NSString).replacingCharacters(in: range, with: string)
searchAutocompleteLanguageEntriesWithSubstring(substring: subString)
if (subString.isEmpty) {
languageTableView.isHidden = true
}else {
languageTableView.isHidden = false
countryTableView.isHidden = true
isCountryTextField = false
}
}
return true
}
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
countryTableView.isHidden = true
languageTableView.isHidden = true
}
// This method will serach the autocompleted country name
func searchAutocompleteCountryEntriesWithSubstring (substring : String)
{
filterCountryData.removeAll()
filterCountryData = countryData.filter({
let string = $0["country_name"] as! String
return string.lowercased().range(of : substring.lowercased()) != nil
})
DispatchQueue.main.async
{
self.countryTableView.reloadData()
}
}
// This method will serach the autocompleted language name
func searchAutocompleteLanguageEntriesWithSubstring(substring: String)
{
// autoLanguageComplete.removeAll(keepingCapacity: false)
filterLanguageData.removeAll()
filterLanguageData = languageData.filter({
let string = $0["name"] as! String
return string.lowercased().range(of: substring.lowercased()) != nil
})
DispatchQueue.main.async
{
self.languageTableView.reloadData()
}
}
// tableview Delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == countryTableView
{
return filterCountryData.count
}
else
{
return filterLanguageData.count
}
}
// tableview Delegate
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : UITableViewCell
if (tableView == countryTableView)
{
// countryTableView.isHidden = false
let cellIdentifier = "XPCountryTableViewCell"
let countDic = self.filterCountryData[indexPath.row]
cell = (tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? XPCountryTableViewCell)!
cell.textLabel?.font = UIFont(name: "Mosk", size: 20)
cell.textLabel?.text = countDic["country_name"] as? String
}
else
{
//languageTableView.isHidden = false
let cellIdentifier = "XPLanguageTableViewCell"
cell = (tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? XPLanguageTableViewCell)!
let lanDic = self.filterLanguageData[indexPath.row]
cell.textLabel?.font = UIFont(name: "Mosk", size: 20)
cell.textLabel?.text = lanDic["name"] as? String
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if (tableView == countryTableView)
{
let selectedCell: UITableViewCell = tableView.cellForRow(at: indexPath)!
countryTextField.text = selectedCell.textLabel!.text!
let autoCountryCompleteDic = filterCountryData[indexPath.row]
print("mathan check data",autoCountryCompleteDic)
for i in 0...filterCountryData.count
{
if indexPath.row == i
{
print( autoCountryCompleteDic["ph_code"] as! String)
self.mobileNumberTextField?.text = String(format: "+%@", (autoCountryCompleteDic["ph_code"] as? String)!)
}
}
countryTableView.isHidden = true
}
if tableView == languageTableView
{
let selectedCell: UITableViewCell = tableView.cellForRow(at: indexPath)!
languageTextField.text = selectedCell.textLabel!.text!
}
languageTableView.isHidden = true
}
// This method will dismiss the keyboard
func dismissKeyboard(rec: UIGestureRecognizer)
{
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
countryTableView.isHidden = true
languageTableView.isHidden = true
}
// This method Will call the Web Service to get the country name and passing parameter
func getCountryDataFromTheWebService()
{
/*
self.countryPhoneCode = (countryData.value(forKey: "ph_code") as! NSArray) as! [String]
self.countryArrayData = (countryData.value(forKey: "country_name") as! NSArray) as! [String]
// let delayInSeconds = 1.0
self.autoCompleteCountryPossibilities = self.countryArrayData
*/
let paramsCountry = ["list":"country"] as Dictionary<String, String>
getOTPClass.getCountryDataWebService(urlString: getCountryUrl.url(), dicData: paramsCountry as NSDictionary, callback:
{ ( countryData,needData, error ) in
print("data")
print(countryData)
// self.countryPhoneCode = (countryData.value(forKey: "ph_code") as! NSArray) as! [String]
self.countryArrayData = (needData.value(forKey: "country_name") as! NSArray) as! [NSArray]
self.autoCompleteCountryPossibilities = self.countryArrayData
self.countryData = countryData
DispatchQueue.global(qos: .background).async {
let myData :[[String:Any]] = self.countryData.filter({
let string = $0["country_name"] as? String
let subString = self.myCountry!
print ( "my data",string!)
return string?.lowercased().range(of: subString.lowercased()) != nil
})
for arrData in myData
{
self.mobileNumberTextField?.text = String(format: "+%@", arrData["ph_code"] as! String)
self.countryCode = "+" + (arrData["ph_code"] as! String)
print("The country code for this country is \(self.countryCode)")
self.defaults.set(self.countryCode, forKey: "countryCode")
}
DispatchQueue.main.async
{
self.countryTableView.reloadData()
}
}
})
}
// This method Will call the Web Service to get the language and passing parameter
func getLanguageNameFromWebService() -> Void
{
let paramsLanguage = ["list" : "language"] as Dictionary<String,String>
getOTPClass.getLanguageDataWebService(urlString: getLanguageUrl.url(), dicData: paramsLanguage as NSDictionary, callBack:{(languageData ,needData, error) in
self.languageArrayData = (needData.value(forKey: "name") as! NSArray) as! [NSArray]
self.autoCompleteLanguagePossibilities = self.languageArrayData
self.languageData = languageData
DispatchQueue.main.async
{
self.languageTableView.reloadData()
}
})
}
// This textfield method will hide the keyboard when click on done button.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// This method will store the data into the NSUSerDefaults.
@IBAction func saveButtonAction(_ sender: Any)
{
if (nameTextField?.text == "") {
let alertController = UIAlertController(title: "Alert!", message: "Registration field will not be Blank: Please check your Name.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
} else if (emailTextField?.text == "") {
let alertController = UIAlertController(title: "Alert!", message: "Registration field will not be Blank: Please check your Email.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
} else if (!(emailTextField?.text?.isValidEmail())!) {
let alertController = UIAlertController(title: "Alert", message: "This is not a Valid Email.", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(alertAction)
present(alertController, animated: true, completion: nil)
} else if (countryTextField.text == "") {
let alertController = UIAlertController(title: "Alert!", message: "Registration field will not be Blank: Please select your Country from the list only.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
} else if (languageTextField.text == "") {
let alertController = UIAlertController(title: "Alert!", message: "Registration field will not be Blank: Please select your language from the list only.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
} else if (mobileNumberTextField?.text == "") {
let alertController = UIAlertController(title: "Alert!", message: "Registration field will not be Blank: Please check your Mobile Number.", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
} else if (!(mobileNumberTextField?.text?.isValidPhono())!) {
let alertController = UIAlertController(title: "Alert", message: "This is not a Valid Phone Number. Use only Numeric with your Country Code", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(alertAction)
present(alertController, animated: true, completion: nil)
} else {
print("Good YOU given all the details in Registration Field.")
if (!(countryTextField.text == "")) {
var countryTextFieldString : String = countryTextField.text!
var CountryTextFieldValidate = String ()
for coun in self.countryData {
let countryName : String = coun["country_name"] as! String
print(countryName)
if (countryName == countryTextFieldString) {
CountryTextFieldValidate = countryTextFieldString
break
}
}
if (countryTextFieldString == CountryTextFieldValidate) {
print("The country name is available in the web")
languageFieldValidation()
} else {
let alertView = UIAlertController(title: "Alert", message: "This country is not available, please select from the country list.", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertView.addAction(alertAction)
present(alertView, animated: true, completion: nil)
}
}
}
}// end save function
// This function will validate that language is available in the Server or not
func languageFieldValidation() {
if (!(languageTextField.text == "")) {
let languageTextFieldString : String = languageTextField.text!
var languageTextFieldValidate = String ()
for lang in self.languageData {
let languageName: String = lang["name"] as! String
if (languageName == languageTextFieldString) {
languageTextFieldValidate = languageTextFieldString
break
}
}
if (languageTextFieldString == languageTextFieldValidate) {
print("This Language is available in List")
smsFieldVarification()
} else {
let alertView = UIAlertController(title: "Alert", message: "This language is not available, please select from the language list.", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertView.addAction(alertAction)
present(alertView, animated: true, completion: nil)
}
}
}
// This method will send the OTP from FCM server.
func smsFieldVarification () {
defaults.set(nameTextField?.text, forKey: "userName")
defaults.set(emailTextField?.text, forKey: "emailAddress")
defaults.set(countryTextField.text, forKey: "countryName")
defaults.set(languageTextField.text, forKey: "languageName")
defaults.set(mobileNumberTextField?.text, forKey: "mobileNumber")
PhoneAuthProvider.provider().verifyPhoneNumber((self.mobileNumberTextField?.text)!, completion: { (verificationID, error) in
print("First time verification Id is \(verificationID)")
if error != nil {
print("error \(error?.localizedDescription)")
self.alertViewControllerWithCancel(headerTile: "Error", bodyMessage: (error?.localizedDescription)! + " Add country code with + symbole if not added. ")
} else {
let defaults = UserDefaults.standard.set(verificationID, forKey: "OTPVerificationID")
// print("OTP is \(verificationID)")
let verifyOTPView = self.storyboard?.instantiateViewController(withIdentifier: "OTPVerificationViewController") as! OTPVerificationViewController
self.present(verifyOTPView, animated: true, completion: nil)
}
})
}
} // end class
| mit |
opensourcegit/CustomCollectionViews | Pod/Classes/BaseCollecitonCell.swift | 1 | 537 | //
// BaseCollecitonCell.swift
// Pods
//
// Created by opensourcegit on 18/09/15.
//
//
import Foundation
import UIKit
public class BaseCollecitonCell:UICollectionViewCell,ReactiveView {
public func bindViewModel(viewModel: AnyObject) {
//implement
}
public func horizontalFittingPriority()->UILayoutPriority{
return 1000;
}
public func verticalFittingPriority()-> UILayoutPriority{
return 50;
}
public func sizeForItem()->CGSize{
return CGSizeZero;
}
} | mit |
nameghino/swift-algorithm-club | Singly Linked List/SinglyLinkedList.swift | 1 | 1734 | /* Singly Linked List
Provides O(n) for storage and lookup.
*/
class Node<T> {
var key: T?
var next: Node?
init() {}
init(key: T?) { self.key = key }
init(key: T?, next: Node?) {
self.key = key
self.next = next
}
}
class SinglyLinkedList<T: Equatable> {
var head = Node<T>()
func addLink(key: T) {
guard head.key != nil else { return head.key = key }
var current: Node? = head
FindEmptySpot: while current != nil {
if current?.next == nil {
current?.next = Node<T>(key: key)
break FindEmptySpot
} else {
current = current?.next
}
}
}
func removeLinkAtIndex(index: Int) {
guard index >= 0 && index <= self.count - 1 && head.key != nil else { return }
var current: Node<T>? = head
var trailer: Node<T>?
var listIndex = 0
if index == 0 {
current = current?.next
head = current?.next ?? Node<T>()
return
}
while current != nil {
if listIndex == index {
trailer?.next = current?.next
current = nil
break
}
trailer = current
current = current?.next
listIndex += 1
}
}
var count: Int {
guard head.key != nil else { return 0 }
var current = head
var x = 1
while let next = current.next {
current = next
x += 1
}
return x
}
var isEmpty: Bool {
return head.key == nil
}
}
| mit |
p0dee/PDAlertView | PDAlertView/AlertSelectionControl.swift | 1 | 5506 | //
// AlertSelectionControl.swift
// AlertViewMock
//
// Created by Takeshi Tanaka on 12/23/15.
// Copyright © 2015 Takeshi Tanaka. All rights reserved.
//
import UIKit
internal class AlertSelectionControl: UIControl {
private let stackView = UIStackView()
internal var components = [AlertSelectionComponentView]()
internal var axis: UILayoutConstraintAxis {
return stackView.axis
}
var selectedIndex: Int? {
didSet {
if (selectedIndex != oldValue) {
sendActions(for: .valueChanged)
}
}
}
override var isHighlighted: Bool {
didSet {
selectedIndex = nil
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
setupConstraints()
stackView.distribution = .fillEqually
stackView.spacing = CGFloat(actionButtonLineWidth())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupViews() {
stackView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(stackView)
}
private func setupConstraints() {
let cstrs = NSLayoutConstraint.constraintsToFillSuperview(stackView)
NSLayoutConstraint.activate(cstrs)
}
func addButton(with title: String, style: AlertActionStyle) {
let component = AlertSelectionComponentView(title: title, style: style)
component.isUserInteractionEnabled = false
stackView.addArrangedSubview(component)
components.append(component)
if stackView.axis == .vertical {
//Do nothing.
} else if components.count > 2 || component.preferredLayoutAxis == .vertical {
stackView.axis = .vertical
}
}
private func selectedIndex(with point: CGPoint) -> Int? {
for view in stackView.arrangedSubviews {
if let view = view as? AlertSelectionComponentView, view.frame.contains(point) {
return components.index(of: view)
}
}
return nil
}
//MARK: override
internal override func tintColorDidChange() {
for comp in components {
switch comp.style {
case .default:
comp.tintColor = tintColor
default:
break
}
}
}
internal override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = touch.location(in: self)
selectedIndex = selectedIndex(with: point)
}
}
internal override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = touch.location(in: self)
selectedIndex = selectedIndex(with: point)
}
}
internal override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = touch.location(in: self)
if self.bounds.contains(point) {
sendActions(for: .touchUpInside)
}
}
selectedIndex = nil
}
}
internal class AlertSelectionComponentView: UIView {
private var label = UILabel()
fileprivate var style: AlertActionStyle = .default
fileprivate var preferredLayoutAxis: UILayoutConstraintAxis {
guard let text = label.text else {
return .vertical
}
let attrs = [NSFontAttributeName : label.font]
let size = NSString(string: text).size(attributes: attrs)
return size.width > 115 ? .vertical : .horizontal
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(title: String, style: AlertActionStyle) {
self.init()
self.style = style
if style == .destructive {
self.tintColor = UIColor(red: 255/255.0, green: 0, blue: 33/255.0, alpha: 1.0)
}
label.text = title
switch style {
case .cancel:
label.font = UIFont.boldSystemFont(ofSize: 17.0)
default:
label.font = UIFont.systemFont(ofSize: 17.0)
}
}
private func setupViews() {
self.layoutMargins = UIEdgeInsetsMake(0, 10, 0, 10)
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = tintColor
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.6
label.lineBreakMode = .byTruncatingMiddle
label.baselineAdjustment = .alignCenters
label.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, for: .horizontal)
self.addSubview(label)
}
private func setupConstraints() {
let cstrs = NSLayoutConstraint.constraintsToFillSuperviewMarginsGuide(label)
NSLayoutConstraint.activate(cstrs)
}
//MARK: override
internal override var intrinsicContentSize: CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: 44)
}
internal override func tintColorDidChange() {
label.textColor = tintColor
}
}
| gpl-2.0 |
nathawes/swift | test/SIL/Serialization/perf_inline_without_inline_all.swift | 16 | 616 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module %S/Inputs/nontransparent.swift -O -parse-stdlib -parse-as-library -emit-module -o %t/Swift.swiftmodule -module-name=Swift -module-link-name swiftCore
// RUN: %target-swift-frontend %s -O -I %t -emit-sil -o - | %FileCheck %s
import Swift
// Make sure we inline everything.
// CHECK-LABEL: sil @main
// CHECK: bb0({{.*}}):
// CHECK-NEXT: alloc_global
// CHECK-NEXT: global_addr
// CHECK-NEXT: struct
// CHECK-NEXT: struct
// CHECK-NEXT: store
// CHECK-NEXT: integer_literal
// CHECK-NEXT: return
public var a = doSomething()
a.isBConfused()
| apache-2.0 |
roambotics/swift | test/SILOptimizer/return.swift | 2 | 7244 | // RUN: %target-swift-frontend %s -emit-sil -verify
func singleBlock() -> Int {
_ = 0
} // expected-error {{missing return in global function expected to return 'Int'}}
func singleBlock2() -> Int {
var y = 0
y += 1
} // expected-error {{missing return in global function expected to return 'Int'}}
enum NoCasesButNotNever {}
func diagnoseNoCaseEnumMissingReturn() -> NoCasesButNotNever {
} // expected-error {{function with uninhabited return type 'NoCasesButNotNever' is missing call to another never-returning function on all paths}}
func diagnoseNeverMissingBody() -> Never {
} // expected-error {{function with uninhabited return type 'Never' is missing call to another never-returning function on all paths}}
_ = { () -> Never in
}() // expected-error {{closure with uninhabited return type 'Never' is missing call to another never-returning function on all paths}}-
func diagnoseNeverWithBody(i : Int) -> Never {
if (i == -1) {
print("Oh no!")
} else {
switch i {
case 0:
exit()
case 1:
fatalError()
default:
repeat { } while true
}
}
} // expected-error {{function with uninhabited return type 'Never' is missing call to another never-returning function on all paths}}
class MyClassWithClosure {
var f : (_ s: String) -> String = { (_ s: String) -> String in } // expected-error {{missing return in closure expected to return 'String'}}
}
func multipleBlocksSingleMissing(b: Bool) -> (String, Int) {
var y = 0
if b {
return ("a", 1)
} else if (y == 0) {
y += 1
}
} // expected-error {{missing return in global function expected to return '(String, Int)'}}
func multipleBlocksAllMissing(x: Int) -> Int {
var y : Int = x + 1
while (y > 0 ) {
y -= 1
break
}
var x = 0
x += 1
} // expected-error {{missing return in global function expected to return 'Int'}}
@_silgen_name("exit") func exit () -> Never
func diagnose_missing_return_in_the_else_branch(i: Bool) -> Int {
if (i) {
exit()
}
} // expected-error {{missing return in global function expected to return 'Int'}}
func diagnose_missing_return_no_error_after_noreturn(i: Bool) -> Int {
if (i) {
exit()
} else {
exit()
}
} // no error
class TuringMachine {
func halt() -> Never {
repeat { } while true
}
}
func diagnose_missing_return_no_error_after_noreturn_method() -> Int {
TuringMachine().halt()
} // no error
func whileLoop(flag: Bool) -> Int {
var b = 1
while (flag) {
if b == 3 {
return 3
}
b += 1
}
} //expected-error {{missing return in global function expected to return 'Int'}}
struct S {}
extension S:ExpressibleByStringLiteral {
init!(stringLiteral:String) {
} // no error
}
func whileTrueLoop() -> Int {
var b = 1
while (true) {
if b == 3 {
return 3
}
b += 1
} // no-error
}
func testUnreachableAfterNoReturn(x: Int) -> Int {
exit(); // expected-note{{a call to a never-returning function}}
return x; // expected-warning {{will never be executed}}
}
func testUnreachableAfterNoReturnInADifferentBlock() -> Int {
let x:Int = 5
if true { // expected-note {{condition always evaluates to true}}
exit();
}
return x; // expected-warning {{will never be executed}}
}
func testReachableAfterNoReturnInADifferentBlock(x: Int) -> Int {
if x == 5 {
exit();
}
return x; // no warning
}
func testUnreachableAfterNoReturnFollowedByACall() -> Int {
let x:Int = 5
exit(); // expected-note{{a call to a never-returning function}}
exit(); // expected-warning {{will never be executed}}
return x
}
func testUnreachableAfterNoReturnMethod() -> Int {
TuringMachine().halt(); // expected-note{{a call to a never-returning function}}
return 0; // expected-warning {{will never be executed}}
}
func testCleanupCodeEmptyTuple(fn: @autoclosure () -> Bool = false,
message: String = "",
file: String = #file,
line: Int = #line) {
if true {
exit()
}
} // no warning
protocol InitProtocol {
init(_ x: Int)
}
struct StructWithIUOinit : InitProtocol {
init!(_ x: Int) { } // no missing-return error
}
// https://github.com/apple/swift/issues/56150
func f_56150() {
let _ : () -> Int = {
var x : Int {
get { 0 }
set { }
}
x // expected-error {{missing return in closure expected to return 'Int'}}
// expected-note@-1 {{did you mean to return the last expression?}}{{5-5=return }}
// expected-warning@-2 {{setter argument 'newValue' was never used, but the property was accessed}}
// expected-note@-3 {{did you mean to use 'newValue' instead of accessing the property's current value?}}
// expected-warning@-4 {{variable is unused}}
}
func f() -> Int {
var x : Int {
get { 0 }
set { }
}
x // expected-error {{missing return in local function expected to return 'Int'}}
// expected-note@-1 {{did you mean to return the last expression?}}{{5-5=return }}
// expected-warning@-2 {{setter argument 'newValue' was never used, but the property was accessed}}
// expected-note@-3 {{did you mean to use 'newValue' instead of accessing the property's current value?}}
// expected-warning@-4 {{variable is unused}}
}
let _ : () -> Int = {
var x : UInt {
get { 0 }
set { }
}
x
// expected-warning@-1 {{setter argument 'newValue' was never used, but the property was accessed}}
// expected-note@-2 {{did you mean to use 'newValue' instead of accessing the property's current value?}}
// expected-warning@-3 {{variable is unused}}
} // expected-error {{missing return in closure expected to return 'Int'}}
func f1() -> Int {
var x : UInt {
get { 0 }
set { }
}
x
// expected-warning@-1 {{setter argument 'newValue' was never used, but the property was accessed}}
// expected-note@-2 {{did you mean to use 'newValue' instead of accessing the property's current value?}}
// expected-warning@-3 {{variable is unused}}
} // expected-error {{missing return in local function expected to return 'Int'}}
let _ : () -> Int = {
var x : Int = 0 // expected-warning {{variable 'x' was never mutated; consider changing to 'let' constant}}
var _ : Int = 0
x // expected-error{{missing return in closure expected to return 'Int'}}
// expected-note@-1 {{did you mean to return the last expression?}}{{5-5=return }}
//expected-warning@-2{{variable is unused}}
}
}
// https://github.com/apple/swift/issues/56857
struct S_56857 {
let b = true
var x: Int {
if b {
return 0
}
} // expected-error {{missing return in getter expected to return 'Int'}}
var y: Int {
get {
if b {
return 0
}
} // expected-error {{missing return in getter expected to return 'Int'}}
set {}
}
}
class C_56857 {
static let a = false
let b = true
func method() -> Int {
if b {
return 0
}
} // expected-error {{missing return in instance method expected to return 'Int'}}
class func method1() -> Int {
if a {
return 0
}
} // expected-error {{missing return in class method expected to return 'Int'}}
}
| apache-2.0 |
Brightify/ReactantUI | Sources/Tokenizer/Properties/Types/XSD/XSDType.swift | 1 | 615 | //
// XSDType.swift
// Tokenizer
//
// Created by Matouš Hýbl on 23/03/2018.
//
import Foundation
public enum XSDType {
case builtin(BuiltinXSDType)
case enumeration(EnumerationXSDType)
case union(UnionXSDType)
case pattern(PatternXSDType)
public var name: String {
switch self {
case .builtin(let builtin):
return builtin.xsdName
case .enumeration(let enumeration):
return enumeration.name
case .union(let union):
return union.name
case .pattern(let pattern):
return pattern.name
}
}
}
| mit |
xedin/swift | test/stmt/statements.swift | 1 | 20255 | // RUN: %target-typecheck-verify-swift
/* block comments */
/* /* nested too */ */
func markUsed<T>(_ t: T) {}
func f1(_ a: Int, _ y: Int) {}
func f2() {}
func f3() -> Int {}
func invalid_semi() {
; // expected-error {{';' statements are not allowed}} {{3-5=}}
}
func nested1(_ x: Int) {
var y : Int
func nested2(_ z: Int) -> Int {
return x+y+z
}
_ = nested2(1)
}
func funcdecl5(_ a: Int, y: Int) {
var x : Int
// a few statements
if (x != 0) {
if (x != 0 || f3() != 0) {
// while with and without a space after it.
while(true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}}
while (true) { 4; 2; 1 } // expected-warning 3 {{integer literal is unused}}
}
}
// Assignment statement.
x = y
(x) = y
1 = x // expected-error {{cannot assign to a literal value}}
(1) = x // expected-error {{cannot assign to a literal value}}
"string" = "other" // expected-error {{cannot assign to a literal value}}
[1, 1, 1, 1] = [1, 1] // expected-error {{cannot assign to immutable expression of type '[Int]}}
1.0 = x // expected-error {{cannot assign to a literal value}}
nil = 1 // expected-error {{cannot assign to a literal value}}
(x:1).x = 1 // expected-error {{cannot assign to immutable expression of type 'Int'}}
var tup : (x:Int, y:Int)
tup.x = 1
_ = tup
let B : Bool
// if/then/else.
if (B) {
} else if (y == 2) {
}
// This diagnostic is terrible - rdar://12939553
if x {} // expected-error {{'Int' is not convertible to 'Bool'}}
if true {
if (B) {
} else {
}
}
if (B) {
f1(1,2)
} else {
f2()
}
if (B) {
if (B) {
f1(1,2)
} else {
f2()
}
} else {
f2()
}
// while statement.
while (B) {
}
// It's okay to leave out the spaces in these.
while(B) {}
if(B) {}
}
struct infloopbool {
var boolValue: infloopbool {
return self
}
}
func infloopbooltest() {
if (infloopbool()) {} // expected-error {{'infloopbool' is not convertible to 'Bool'}}
}
// test "builder" API style
extension Int {
static func builder() -> Int { }
var builderProp: Int { return 0 }
func builder2() {}
}
Int
.builder()
.builderProp
.builder2()
struct SomeGeneric<T> {
static func builder() -> SomeGeneric<T> { }
var builderProp: SomeGeneric<T> { return .builder() }
func builder2() {}
}
SomeGeneric<Int>
.builder()
.builderProp
.builder2()
break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}}
continue // expected-error {{'continue' is only allowed inside a loop}}
while true {
func f() {
break // expected-error {{'break' is only allowed inside a loop}}
continue // expected-error {{'continue' is only allowed inside a loop}}
}
// Labeled if
MyIf: if 1 != 2 {
break MyIf
continue MyIf // expected-error {{'continue' cannot be used with if statements}}
break // break the while
continue // continue the while.
}
}
// Labeled if
MyOtherIf: if 1 != 2 {
break MyOtherIf
continue MyOtherIf // expected-error {{'continue' cannot be used with if statements}}
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if}}
continue // expected-error {{'continue' is only allowed inside a loop}}
}
do {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
func tuple_assign() {
var a,b,c,d : Int
(a,b) = (1,2)
func f() -> (Int,Int) { return (1,2) }
((a,b), (c,d)) = (f(), f())
}
func missing_semicolons() {
var w = 321
func g() {}
g() w += 1 // expected-error{{consecutive statements}} {{6-6=;}}
var z = w"hello" // expected-error{{consecutive statements}} {{12-12=;}} expected-warning {{string literal is unused}}
class C {}class C2 {} // expected-error{{consecutive statements}} {{14-14=;}}
struct S {}struct S2 {} // expected-error{{consecutive statements}} {{14-14=;}}
func j() {}func k() {} // expected-error{{consecutive statements}} {{14-14=;}}
}
//===--- Return statement.
return 42 // expected-error {{return invalid outside of a func}}
return // expected-error {{return invalid outside of a func}}
func NonVoidReturn1() -> Int {
_ = 0
return // expected-error {{non-void function should return a value}}
}
func NonVoidReturn2() -> Int {
return + // expected-error {{unary operator cannot be separated from its operand}} {{11-1=}} expected-error {{expected expression in 'return' statement}}
}
func VoidReturn1() {
if true { return }
// Semicolon should be accepted -- rdar://11344875
return; // no-error
}
func VoidReturn2() {
return () // no-error
}
func VoidReturn3() {
return VoidReturn2() // no-error
}
//===--- If statement.
func IfStmt1() {
if 1 > 0 // expected-error {{expected '{' after 'if' condition}}
_ = 42
}
func IfStmt2() {
if 1 > 0 {
} else // expected-error {{expected '{' or 'if' after 'else'}}
_ = 42
}
func IfStmt3() {
if 1 > 0 {
} else 1 < 0 { // expected-error {{expected '{' or 'if' after 'else'; did you mean to write 'if'?}} {{9-9= if}}
_ = 42
} else {
}
}
//===--- While statement.
func WhileStmt1() {
while 1 > 0 // expected-error {{expected '{' after 'while' condition}}
_ = 42
}
//===-- Do statement.
func DoStmt() {
// This is just a 'do' statement now.
do {
}
}
func DoWhileStmt() {
do { // expected-error {{'do-while' statement is not allowed; use 'repeat-while' instead}} {{3-5=repeat}}
} while true
}
//===--- Repeat-while statement.
func RepeatWhileStmt1() {
repeat {} while true
repeat {} while false
repeat { break } while true
repeat { continue } while true
}
func RepeatWhileStmt2() {
repeat // expected-error {{expected '{' after 'repeat'}} expected-error {{expected 'while' after body of 'repeat' statement}}
}
func RepeatWhileStmt4() {
repeat {
} while + // expected-error {{unary operator cannot be separated from its operand}} {{12-1=}} expected-error {{expected expression in 'repeat-while' condition}}
}
func brokenSwitch(_ x: Int) -> Int {
switch x {
case .Blah(var rep): // expected-error{{pattern cannot match values of type 'Int'}}
return rep
}
}
func switchWithVarsNotMatchingTypes(_ x: Int, y: Int, z: String) -> Int {
switch (x,y,z) {
case (let a, 0, _), (0, let a, _): // OK
return a
case (let a, _, _), (_, _, let a): // expected-error {{pattern variable bound to type 'String', expected type 'Int'}}
// expected-warning@-1 {{case is already handled by previous patterns; consider removing it}}
return a
}
}
func breakContinue(_ x : Int) -> Int {
Outer:
for _ in 0...1000 {
Switch: // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}}
switch x {
case 42: break Outer
case 97: continue Outer
case 102: break Switch
case 13: continue
case 139: break // <rdar://problem/16563853> 'break' should be able to break out of switch statements
}
}
// <rdar://problem/16692437> shadowing loop labels should be an error
Loop: // expected-note {{previously declared here}}
for _ in 0...2 {
Loop: // expected-error {{label 'Loop' cannot be reused on an inner statement}}
for _ in 0...2 {
}
}
// <rdar://problem/16798323> Following a 'break' statement by another statement on a new line result in an error/fit-it
switch 5 {
case 5:
markUsed("before the break")
break
markUsed("after the break") // 'markUsed' is not a label for the break.
default:
markUsed("")
}
let x : Int? = 42
// <rdar://problem/16879701> Should be able to pattern match 'nil' against optionals
switch x { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.some(_)'}}
case .some(42): break
case nil: break
}
}
enum MyEnumWithCaseLabels {
case Case(one: String, two: Int)
}
func testMyEnumWithCaseLabels(_ a : MyEnumWithCaseLabels) {
// <rdar://problem/20135489> Enum case labels are ignored in "case let" statements
switch a {
case let .Case(one: _, two: x): break // ok
case let .Case(xxx: _, two: x): break // expected-error {{tuple pattern element label 'xxx' must be 'one'}}
// TODO: In principle, reordering like this could be supported.
case let .Case(two: _, one: x): break // expected-error {{tuple pattern element label}}
}
}
// "defer"
func test_defer(_ a : Int) {
defer { VoidReturn1() }
defer { breakContinue(1)+42 } // expected-warning {{result of operator '+' is unused}}
// Ok:
defer { while false { break } }
// Not ok.
while false { defer { break } } // expected-error {{'break' cannot transfer control out of a defer statement}}
// expected-warning@-1 {{'defer' statement at end of scope always executes immediately}}{{17-22=do}}
defer { return } // expected-error {{'return' cannot transfer control out of a defer statement}}
// expected-warning@-1 {{'defer' statement at end of scope always executes immediately}}{{3-8=do}}
}
class SomeTestClass {
var x = 42
func method() {
defer { x = 97 } // self. not required here!
// expected-warning@-1 {{'defer' statement at end of scope always executes immediately}}{{5-10=do}}
}
}
enum DeferThrowError: Error {
case someError
}
func throwInDefer() {
defer { throw DeferThrowError.someError } // expected-error {{'throw' cannot transfer control out of a defer statement}}
print("Foo")
}
func throwingFuncInDefer1() throws {
defer { try throwingFunctionCalledInDefer() } // expected-error {{errors cannot be thrown out of a defer body}}
print("Bar")
}
func throwingFuncInDefer2() throws {
defer { throwingFunctionCalledInDefer() } // expected-error {{errors cannot be thrown out of a defer body}}
print("Bar")
}
func throwingFuncInDefer3() {
defer { try throwingFunctionCalledInDefer() } // expected-error {{errors cannot be thrown out of a defer body}}
print("Bar")
}
func throwingFuncInDefer4() {
defer { throwingFunctionCalledInDefer() } // expected-error {{errors cannot be thrown out of a defer body}}
print("Bar")
}
func throwingFunctionCalledInDefer() throws {
throw DeferThrowError.someError
}
class SomeDerivedClass: SomeTestClass {
override init() {
defer {
super.init() // expected-error {{initializer chaining ('super.init') cannot be nested in another expression}}
}
}
}
func test_guard(_ x : Int, y : Int??, cond : Bool) {
// These are all ok.
guard let a = y else {}
markUsed(a)
guard let b = y, cond else {}
guard case let c = x, cond else {}
guard case let Optional.some(d) = y else {}
guard x != 4, case _ = x else { }
guard let e, cond else {} // expected-error {{variable binding in a condition requires an initializer}}
guard case let f? : Int?, cond else {} // expected-error {{variable binding in a condition requires an initializer}}
guard let g = y else {
markUsed(g) // expected-error {{variable declared in 'guard' condition is not usable in its body}}
}
guard let h = y, cond {} // expected-error {{expected 'else' after 'guard' condition}} {{25-25=else }}
guard case _ = x else {} // expected-warning {{'guard' condition is always true, body is unreachable}}
// SR-7567
guard let outer = y else {
guard true else {
print(outer) // expected-error {{variable declared in 'guard' condition is not usable in its body}}
}
}
}
func test_is_as_patterns() {
switch 4 {
case is Int: break // expected-warning {{'is' test is always true}}
case _ as Int: break // expected-warning {{'as' test is always true}}
// expected-warning@-1 {{case is already handled by previous patterns; consider removing it}}
case _: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
}
}
// <rdar://problem/21387308> Fuzzing SourceKit: crash in Parser::parseStmtForEach(...)
func matching_pattern_recursion() {
switch 42 {
case { // expected-error {{expression pattern of type '() -> ()' cannot match values of type 'Int'}}
for i in zs {
}
}: break
}
}
// <rdar://problem/18776073> Swift's break operator in switch should be indicated in errors
func r18776073(_ a : Int?) {
switch a {
case nil: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{14-14= break}}
case _?: break
}
}
// <rdar://problem/22491782> unhelpful error message from "throw nil"
func testThrowNil() throws {
throw nil // expected-error {{cannot infer concrete Error for thrown 'nil' value}}
}
// rdar://problem/23684220
// Even if the condition fails to typecheck, save it in the AST anyway; the old
// condition may have contained a SequenceExpr.
func r23684220(_ b: Any) {
if let _ = b ?? b {} // expected-error {{initializer for conditional binding must have Optional type, not 'Any'}}
// expected-warning@-1 {{left side of nil coalescing operator '??' has non-optional type 'Any', so the right side is never used}}
}
// <rdar://problem/21080671> QoI: try/catch (instead of do/catch) creates silly diagnostics
func f21080671() {
try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}}
} catch { }
try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}}
f21080671()
} catch let x as Int {
} catch {
}
}
// <rdar://problem/24467411> QoI: Using "&& #available" should fixit to comma
// https://twitter.com/radexp/status/694561060230184960
func f(_ x : Int, y : Int) {
if x == y && #available(iOS 52, *) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}}
if #available(iOS 52, *) && x == y {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{27-30=,}}
// https://twitter.com/radexp/status/694790631881883648
if x == y && let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-15=,}}
if x == y&&let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{12-14=,}}
}
// <rdar://problem/25178926> QoI: Warn about cases where switch statement "ignores" where clause
enum Type {
case Foo
case Bar
}
func r25178926(_ a : Type) {
switch a { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Bar'}}
case .Foo, .Bar where 1 != 100:
// expected-warning @-1 {{'where' only applies to the second pattern match in this case}}
// expected-note @-2 {{disambiguate by adding a line break between them if this is desired}} {{14-14=\n }}
// expected-note @-3 {{duplicate the 'where' on both patterns to check both patterns}} {{12-12= where 1 != 100}}
break
}
switch a { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Bar'}}
case .Foo: break
case .Bar where 1 != 100: break
}
switch a { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Bar'}}
case .Foo, // no warn
.Bar where 1 != 100:
break
}
switch a { // expected-error {{switch must be exhaustive}}
// expected-note@-1 {{missing case: '.Foo'}}
// expected-note@-2 {{missing case: '.Bar'}}
case .Foo where 1 != 100, .Bar where 1 != 100:
break
}
}
do {
guard 1 == 2 else {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
}
func fn(a: Int) {
guard a < 1 else {
break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}}
}
}
func fn(x: Int) {
if x >= 0 {
guard x < 1 else {
guard x < 2 else {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
return
}
}
}
func bad_if() {
if 1 {} // expected-error {{'Int' is not convertible to 'Bool'}}
if (x: false) {} // expected-error {{'(x: Bool)' is not convertible to 'Bool'}}
if (x: 1) {} // expected-error {{'(x: Int)' is not convertible to 'Bool'}}
}
// Typo correction for loop labels
for _ in [1] {
break outerloop // expected-error {{use of unresolved label 'outerloop'}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'}}
}
while true {
break outerloop // expected-error {{use of unresolved label 'outerloop'}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'}}
}
repeat {
break outerloop // expected-error {{use of unresolved label 'outerloop'}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'}}
} while true
outerLoop: for _ in [1] { // expected-note {{'outerLoop' declared here}}
break outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{9-18=outerLoop}}
}
outerLoop: for _ in [1] { // expected-note {{'outerLoop' declared here}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{12-21=outerLoop}}
}
outerLoop: while true { // expected-note {{'outerLoop' declared here}}
break outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{9-18=outerLoop}}
}
outerLoop: while true { // expected-note {{'outerLoop' declared here}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{12-21=outerLoop}}
}
outerLoop: repeat { // expected-note {{'outerLoop' declared here}}
break outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{9-18=outerLoop}}
} while true
outerLoop: repeat { // expected-note {{'outerLoop' declared here}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'; did you mean 'outerLoop'?}} {{12-21=outerLoop}}
} while true
outerLoop1: for _ in [1] { // expected-note {{did you mean 'outerLoop1'?}} {{11-20=outerLoop1}}
outerLoop2: for _ in [1] { // expected-note {{did you mean 'outerLoop2'?}} {{11-20=outerLoop2}}
break outerloop // expected-error {{use of unresolved label 'outerloop'}}
}
}
outerLoop1: for _ in [1] { // expected-note {{did you mean 'outerLoop1'?}} {{14-23=outerLoop1}}
outerLoop2: for _ in [1] { // expected-note {{did you mean 'outerLoop2'?}} {{14-23=outerLoop2}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'}}
}
}
outerLoop1: while true { // expected-note {{did you mean 'outerLoop1'?}} {{11-20=outerLoop1}}
outerLoop2: while true { // expected-note {{did you mean 'outerLoop2'?}} {{11-20=outerLoop2}}
break outerloop // expected-error {{use of unresolved label 'outerloop'}}
}
}
outerLoop1: while true { // expected-note {{did you mean 'outerLoop1'?}} {{14-23=outerLoop1}}
outerLoop2: while true { // expected-note {{did you mean 'outerLoop2'?}} {{14-23=outerLoop2}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'}}
}
}
outerLoop1: repeat { // expected-note {{did you mean 'outerLoop1'?}} {{11-20=outerLoop1}}
outerLoop2: repeat { // expected-note {{did you mean 'outerLoop2'?}} {{11-20=outerLoop2}}
break outerloop // expected-error {{use of unresolved label 'outerloop'}}
} while true
} while true
outerLoop1: repeat { // expected-note {{did you mean 'outerLoop1'?}} {{14-23=outerLoop1}}
outerLoop2: repeat { // expected-note {{did you mean 'outerLoop2'?}} {{14-23=outerLoop2}}
continue outerloop // expected-error {{use of unresolved label 'outerloop'}}
} while true
} while true
// Errors in case syntax
class
case, // expected-error {{expected identifier in enum 'case' declaration}} expected-error {{expected pattern}}
case // expected-error {{expected identifier after comma in enum 'case' declaration}} expected-error {{expected identifier in enum 'case' declaration}} expected-error {{enum 'case' is not allowed outside of an enum}} expected-error {{expected pattern}}
// NOTE: EOF is important here to properly test a code path that used to crash the parser
| apache-2.0 |
xedin/swift | test/SILOptimizer/devirt_speculate.swift | 5 | 2452 | // RUN: %target-swift-frontend %/s -parse-as-library -O -emit-sil -save-optimization-record-path %t.opt.yaml | %FileCheck %s
// RUN: %FileCheck -check-prefix=YAML -input-file=%t.opt.yaml %s
// RUN: %target-swift-frontend %/s -parse-as-library -Osize -emit-sil | %FileCheck %s --check-prefix=OSIZE
//
// Test speculative devirtualization.
// Test MaxNumSpeculativeTargets.
// rdar:23228386
public class Base {
public init() {}
public func foo() {}
}
class Sub1 : Base {
override func foo() {}
}
class Sub2 : Base {
override func foo() {}
}
class Sub3 : Base {
override func foo() {}
}
class Sub4 : Base {
override func foo() {}
}
class Sub5 : Base {
override func foo() {}
}
class Sub6 : Base {
override func foo() {}
}
class Sub7 : Base {
override func foo() {}
}
// CHECK: @$s16devirt_speculate28testMaxNumSpeculativeTargetsyyAA4BaseCF
// CHECK: checked_cast_br [exact] %0 : $Base to $Base
// CHECK: checked_cast_br [exact] %0 : $Base to $Sub1
// CHECK: checked_cast_br [exact] %0 : $Base to $Sub2
// CHECK: checked_cast_br [exact] %0 : $Base to $Sub3
// CHECK: checked_cast_br [exact] %0 : $Base to $Sub4
// CHECK: checked_cast_br [exact] %0 : $Base to $Sub5
// CHECK: checked_cast_br [exact] %0 : $Base to $Sub6
// CHECK-NOT: checked_cast_br
// CHECK: %[[CM:[0-9]+]] = class_method %0 : $Base, #Base.foo!1 : (Base) -> () -> (), $@convention(method) (@guaranteed Base) -> ()
// CHECK: apply %[[CM]](%0) : $@convention(method) (@guaranteed Base) -> ()
// YAML: Pass: sil-speculative-devirtualizer
// YAML-NEXT: Name: sil.PartialSpecDevirt
// YAML-NEXT: DebugLoc:
// YAML-NEXT: File: {{.*}}/devirt_speculate.swift
// YAML-NEXT: Line: 66
// YAML-NEXT: Column: 5
// YAML-NEXT: Function: 'testMaxNumSpeculativeTargets(_:)'
// YAML-NEXT: Args:
// YAML-NEXT: - String: 'Partially devirtualized call with run-time checks for '
// YAML-NEXT: - NumSubTypesChecked: '6'
// YAML-NEXT: - String: ' subclasses of '
// YAML-NEXT: - ClassType: Base
// YAML-NEXT: - String: ', number of subclasses not devirtualized: '
// YAML-NEXT: - NotHandledSubsNum: '1'
// YAML-NEXT: ...
// OSIZE: @$s16devirt_speculate28testMaxNumSpeculativeTargetsyyAA4BaseCF
// OSIZE-NOT: checked_cast_br [exact] %0 : $Base to $Base
// OSIZE-NOT: checked_cast_br [exact] %0 : $Base to $Sub
public func testMaxNumSpeculativeTargets(_ b: Base) {
b.foo()
}
| apache-2.0 |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/记忆题 - 只需要记住最优解/268_Missing Number.swift | 1 | 1460 | // 268_Missing Number
// https://leetcode.com/problems/missing-number/
//
// Created by Honghao Zhang on 10/16/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
//
//Example 1:
//
//Input: [3,0,1]
//Output: 2
//Example 2:
//
//Input: [9,6,4,2,3,5,7,0,1]
//Output: 8
//Note:
//Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
//
// 给出1-n的数字,但是其中缺1个,乱序状态。
// 找出这个missing number
import Foundation
class Num268 {
// MARK: - Sort and find the first gap
// O(n log n)
// O(1)
// MARK: - Set and iterate
// 通过数组大小,我们可以退出全部值的范围
// 然后可以循环一遍找到这个missing number
// O(n)
// MARK: - Bit manipulation
// MARK: - Gauss's Formula
func missingNumber_gauss(_ nums: [Int]) -> Int {
// 0, 1, 2, 3
// 可以求expect的sum和actual sum。
// actual sum会比expect sum大,这是因为这个sum少加了缺掉的数字,但是多加了最后一个数字
// 多加的最后一个数字一定是nums.count,那么nums.count减去这个差值就是缺掉的数字
let expectedSum = (nums.count - 1) * nums.count / 2
let actualSum = nums.reduce(0, +)
return nums.count - (actualSum - expectedSum)
}
}
| mit |
soapyigu/LeetCode_Swift | Stack/PreorderTraversal.swift | 1 | 968 | /**
* Question Link: https://leetcode.com/problems/binary-tree-preorder-traversal/
* Primary idea: Use a stack to help iterate the tree
* Time Complexity: O(n), Space Complexity: O(n)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class PreorderTraversal {
func preorderTraversal(root: TreeNode?) -> [Int] {
var res = [Int]()
var stack = [TreeNode]()
var node = root
while !stack.isEmpty || node != nil {
if node != nil {
res.append(node!.val)
stack.append(node!)
node = node!.left
} else {
node = stack.removeLast().right
}
}
return res
}
} | mit |
OpenStack-mobile/aerogear-ios-oauth2 | AeroGearOAuth2Tests/TimeZone.swift | 1 | 731 | //
// TimeZone.swift
// OpenStackSummit
//
// Created by Alsey Coleman Miller on 6/1/16.
// Copyright © 2016 OpenStack. All rights reserved.
//
public struct TimeZone: Equatable {
public var name: String
public var countryCode: String
public var latitude: Double
public var longitude: Double
public var comments: String
public var offset: Int
}
// MARK: - Equatable
public func == (lhs: TimeZone, rhs: TimeZone) -> Bool {
return lhs.name == rhs.name
&& lhs.countryCode == rhs.countryCode
&& lhs.latitude == rhs.latitude
&& lhs.longitude == rhs.longitude
&& lhs.comments == rhs.comments
&& lhs.offset == rhs.offset
}
| apache-2.0 |
johnno1962d/swift | benchmark/single-source/StringInterpolation.swift | 3 | 1426 | //===--- StringInterpolation.swift ----------------------------------------===//
//
// 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 TestsUtils
class RefTypePrintable : CustomStringConvertible {
var description: String {
return "01234567890123456789012345678901234567890123456789"
}
}
@inline(never)
public func run_StringInterpolation(_ N: Int) {
let reps = 100
let refResult = reps
let anInt: Int64 = 0x1234567812345678
let aRefCountedObject = RefTypePrintable()
for _ in 1...100*N {
var result = 0
for _ in 1...reps {
let s = "\(anInt) abcdefdhijklmn \(aRefCountedObject) abcdefdhijklmn \u{01}"
// FIXME: if String is not stored as UTF-16 on this platform, then the
// following operation has a non-trivial cost and needs to be replaced
// with an operation on the native storage type.
result = result &+ Int(s.utf16[s.utf16.endIndex.predecessor()])
}
CheckResults(result == refResult, "IncorrectResults in StringInterpolation: \(result) != \(refResult)")
}
}
| apache-2.0 |
iossocket/DBDemo | DBDemoUITests/DBDemoUITests.swift | 1 | 1243 | //
// DBDemoUITests.swift
// DBDemoUITests
//
// Created by XueliangZhu on 12/19/16.
// Copyright © 2016 ThoughtWorks. All rights reserved.
//
import XCTest
class DBDemoUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/02231-swift-nominaltypedecl-getdeclaredtypeincontext.swift | 11 | 479 | // 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
// RUN: not %target-swift-frontend %s -parse
struct B<T: d where B : a {
typealias e = d
typealias A = { func n: l: A {
"))
class d
| apache-2.0 |
kostiakoval/Swift-Speed | SpeedTest/Model/MesureHelper.swift | 1 | 714 | //
// MesureHelper.swift
// SpeedTest
//
// Created by Konstantin Koval on 11/11/14.
// Copyright (c) 2014 konstanntn Koval. All rights reserved.
//
import Foundation
import QuartzCore
var mesureNumber = 100000000
func iterate(call: () -> Void ) {
for i in 1...mesureNumber {
call()
}
}
func measure(title: String!, call: () -> Void) {
let startTime = CACurrentMediaTime()
call()
let endTime = CACurrentMediaTime()
if let title = title {
print("\(title): ")
}
println("Time - \(endTime - startTime)")
}
func iterateAndMesure(title: String!, call: () -> Void ) {
measure(title) {
iterate(call)
}
}
func iterateAndMesure(call: () -> Void ) {
iterateAndMesure(nil, call)
}
| mit |
mleiv/MEGameTracker | MEGameTracker/Views/Group Tab/Search Group Split View/SearchGroupSplitViewController.swift | 1 | 770 | //
// SearchGroupSplitViewController.swift
// MEGameTracker
//
// Created by Emily Ivie on 3/29/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import UIKit
final public class SearchGroupSplitViewController: UIViewController, MESplitViewController {
@IBOutlet weak public var mainPlaceholder: IBIncludedSubThing?
@IBOutlet weak public var detailBorderLeftView: UIView?
@IBOutlet weak public var detailPlaceholder: IBIncludedSubThing?
public var ferriedSegue: FerriedPrepareForSegueClosure?
public var dontSplitViewInPage = false
@IBAction public func closeDetailStoryboard(_ sender: AnyObject?) {
closeDetailStoryboard()
}
override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
ferriedSegue?(segue.destination)
}
}
| mit |
fireunit/login | Pods/Material/Sources/iOS/MaterialEdgeInset.swift | 3 | 4117 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* 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 Material 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 UIKit
public enum MaterialEdgeInset {
case None
// square
case Square1
case Square2
case Square3
case Square4
case Square5
case Square6
case Square7
case Square8
case Square9
// rectangle
case WideRectangle1
case WideRectangle2
case WideRectangle3
case WideRectangle4
case WideRectangle5
case WideRectangle6
case WideRectangle7
case WideRectangle8
case WideRectangle9
// flipped rectangle
case TallRectangle1
case TallRectangle2
case TallRectangle3
case TallRectangle4
case TallRectangle5
case TallRectangle6
case TallRectangle7
case TallRectangle8
case TallRectangle9
}
/// Converts the MaterialEdgeInset to a UIEdgeInsets value.
public func MaterialEdgeInsetToValue(inset: MaterialEdgeInset) -> UIEdgeInsets {
switch inset {
case .None:
return UIEdgeInsetsZero
// square
case .Square1:
return UIEdgeInsetsMake(4, 4, 4, 4)
case .Square2:
return UIEdgeInsetsMake(8, 8, 8, 8)
case .Square3:
return UIEdgeInsetsMake(16, 16, 16, 16)
case .Square4:
return UIEdgeInsetsMake(24, 24, 24, 24)
case .Square5:
return UIEdgeInsetsMake(32, 32, 32, 32)
case .Square6:
return UIEdgeInsetsMake(40, 40, 40, 40)
case .Square7:
return UIEdgeInsetsMake(48, 48, 48, 48)
case .Square8:
return UIEdgeInsetsMake(56, 56, 56, 56)
case .Square9:
return UIEdgeInsetsMake(64, 64, 64, 64)
// rectangle
case .WideRectangle1:
return UIEdgeInsetsMake(2, 4, 2, 4)
case .WideRectangle2:
return UIEdgeInsetsMake(4, 8, 4, 8)
case .WideRectangle3:
return UIEdgeInsetsMake(8, 16, 8, 16)
case .WideRectangle4:
return UIEdgeInsetsMake(12, 24, 12, 24)
case .WideRectangle5:
return UIEdgeInsetsMake(16, 32, 16, 32)
case .WideRectangle6:
return UIEdgeInsetsMake(20, 40, 20, 40)
case .WideRectangle7:
return UIEdgeInsetsMake(24, 48, 24, 48)
case .WideRectangle8:
return UIEdgeInsetsMake(28, 56, 28, 56)
case .WideRectangle9:
return UIEdgeInsetsMake(32, 64, 32, 64)
// flipped rectangle
case .TallRectangle1:
return UIEdgeInsetsMake(4, 2, 4, 2)
case .TallRectangle2:
return UIEdgeInsetsMake(8, 4, 8, 4)
case .TallRectangle3:
return UIEdgeInsetsMake(16, 8, 16, 8)
case .TallRectangle4:
return UIEdgeInsetsMake(24, 12, 24, 12)
case .TallRectangle5:
return UIEdgeInsetsMake(32, 16, 32, 16)
case .TallRectangle6:
return UIEdgeInsetsMake(40, 20, 40, 20)
case .TallRectangle7:
return UIEdgeInsetsMake(48, 24, 48, 24)
case .TallRectangle8:
return UIEdgeInsetsMake(56, 28, 56, 28)
case .TallRectangle9:
return UIEdgeInsetsMake(64, 32, 64, 32)
}
}
| mit |
dduan/swift | stdlib/public/core/Reflection.swift | 1 | 16910 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Customizes the result of `_reflect(x)`, where `x` is a conforming
/// type.
public protocol _Reflectable {
// The runtime has inappropriate knowledge of this protocol and how its
// witness tables are laid out. Changing this protocol requires a
// corresponding change to Reflection.cpp.
/// Returns a mirror that reflects `self`.
@warn_unused_result
func _getMirror() -> _Mirror
}
/// A unique identifier for a class instance or metatype.
///
/// In Swift, only class instances and metatypes have unique identities. There
/// is no notion of identity for structs, enums, functions, or tuples.
public struct ObjectIdentifier : Hashable, Comparable {
internal let _value: Builtin.RawPointer
// FIXME: Better hashing algorithm
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`.
///
/// - Note: The hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return Int(Builtin.ptrtoint_Word(_value))
}
/// Construct an instance that uniquely identifies the class instance `x`.
public init(_ x: AnyObject) {
self._value = Builtin.bridgeToRawPointer(x)
}
/// Construct an instance that uniquely identifies the metatype `x`.
public init(_ x: Any.Type) {
self._value = unsafeBitCast(x, to: Builtin.RawPointer.self)
}
}
@warn_unused_result
public func <(lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool {
return UInt(lhs) < UInt(rhs)
}
@warn_unused_result
public func ==(x: ObjectIdentifier, y: ObjectIdentifier) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(x._value, y._value))
}
extension UInt {
/// Create a `UInt` that captures the full value of `objectID`.
public init(_ objectID: ObjectIdentifier) {
self.init(Builtin.ptrtoint_Word(objectID._value))
}
}
extension Int {
/// Create an `Int` that captures the full value of `objectID`.
public init(_ objectID: ObjectIdentifier) {
self.init(bitPattern: UInt(objectID))
}
}
/// How children of this value should be presented in the IDE.
public enum _MirrorDisposition {
/// As a struct.
case `struct`
/// As a class.
case `class`
/// As an enum.
case `enum`
/// As a tuple.
case tuple
/// As a miscellaneous aggregate with a fixed set of children.
case aggregate
/// As a container that is accessed by index.
case indexContainer
/// As a container that is accessed by key.
case keyContainer
/// As a container that represents membership of its values.
case membershipContainer
/// As a miscellaneous container with a variable number of children.
case container
/// An Optional which can have either zero or one children.
case optional
/// An Objective-C object imported in Swift.
case objCObject
}
/// The type returned by `_reflect(x)`; supplies an API for runtime
/// reflection on `x`.
public protocol _Mirror {
/// The instance being reflected.
var value: Any { get }
/// Identical to `value.dynamicType`.
var valueType: Any.Type { get }
/// A unique identifier for `value` if it is a class instance; `nil`
/// otherwise.
var objectIdentifier: ObjectIdentifier? { get }
/// The count of `value`'s logical children.
var count: Int { get }
/// Get a name and mirror for the `i`th logical child.
subscript(i: Int) -> (String, _Mirror) { get }
/// A string description of `value`.
var summary: String { get }
/// A rich representation of `value` for an IDE, or `nil` if none is supplied.
var quickLookObject: PlaygroundQuickLook? { get }
/// How `value` should be presented in an IDE.
var disposition: _MirrorDisposition { get }
}
/// An entry point that can be called from C++ code to get the summary string
/// for an arbitrary object. The memory pointed to by "out" is initialized with
/// the summary string.
@warn_unused_result
@_silgen_name("swift_getSummary")
public // COMPILER_INTRINSIC
func _getSummary<T>(out: UnsafeMutablePointer<String>, x: T) {
out.initialize(with: String(reflecting: x))
}
/// Produce a mirror for any value. If the value's type conforms to
/// `_Reflectable`, invoke its `_getMirror()` method; otherwise, fall back
/// to an implementation in the runtime that structurally reflects values
/// of any type.
@warn_unused_result
@_silgen_name("swift_reflectAny")
public func _reflect<T>(x: T) -> _Mirror
/// Dump an object's contents using its mirror to the specified output stream.
public func dump<T, TargetStream : OutputStream>(
value: T,
to target: inout TargetStream,
name: String? = nil,
indent: Int = 0,
maxDepth: Int = .max,
maxItems: Int = .max
) -> T {
var maxItemCounter = maxItems
var visitedItems = [ObjectIdentifier : Int]()
target._lock()
defer { target._unlock() }
_dump_unlocked(
value,
to: &target,
name: name,
indent: indent,
maxDepth: maxDepth,
maxItemCounter: &maxItemCounter,
visitedItems: &visitedItems)
return value
}
/// Dump an object's contents using its mirror to standard output.
public func dump<T>(
value: T,
name: String? = nil,
indent: Int = 0,
maxDepth: Int = .max,
maxItems: Int = .max
) -> T {
var stdoutStream = _Stdout()
return dump(
value,
to: &stdoutStream,
name: name,
indent: indent,
maxDepth: maxDepth,
maxItems: maxItems)
}
/// Dump an object's contents. User code should use dump().
internal func _dump_unlocked<TargetStream : OutputStream>(
value: Any,
to target: inout TargetStream,
name: String?,
indent: Int,
maxDepth: Int,
maxItemCounter: inout Int,
visitedItems: inout [ObjectIdentifier : Int]
) {
guard maxItemCounter > 0 else { return }
maxItemCounter -= 1
for _ in 0..<indent { target.write(" ") }
let mirror = Mirror(reflecting: value)
let count = mirror.children.count
let bullet = count == 0 ? "-"
: maxDepth <= 0 ? "▹" : "▿"
target.write(bullet)
target.write(" ")
if let nam = name {
target.write(nam)
target.write(": ")
}
// This takes the place of the old mirror API's 'summary' property
_dumpPrint_unlocked(value, mirror, &target)
let id: ObjectIdentifier?
if let classInstance = value as? AnyObject where value.dynamicType is AnyObject.Type {
// Object is a class (but not an ObjC-bridged struct)
id = ObjectIdentifier(classInstance)
} else if let metatypeInstance = value as? Any.Type {
// Object is a metatype
id = ObjectIdentifier(metatypeInstance)
} else {
id = nil
}
if let theId = id {
if let previous = visitedItems[theId] {
target.write(" #")
_print_unlocked(previous, &target)
target.write("\n")
return
}
let identifier = visitedItems.count
visitedItems[theId] = identifier
target.write(" #")
_print_unlocked(identifier, &target)
}
target.write("\n")
guard maxDepth > 0 else { return }
if let superclassMirror = mirror.superclassMirror {
_dumpSuperclass_unlocked(
mirror: superclassMirror,
to: &target,
indent: indent + 2,
maxDepth: maxDepth - 1,
maxItemCounter: &maxItemCounter,
visitedItems: &visitedItems)
}
var currentIndex = mirror.children.startIndex
for i in 0..<count {
if maxItemCounter <= 0 {
for _ in 0..<(indent+4) {
_print_unlocked(" ", &target)
}
let remainder = count - i
target.write("(")
_print_unlocked(remainder, &target)
if i > 0 { target.write(" more") }
if remainder == 1 {
target.write(" child)\n")
} else {
target.write(" children)\n")
}
return
}
let (name, child) = mirror.children[currentIndex]
currentIndex = currentIndex.successor()
_dump_unlocked(
child,
to: &target,
name: name,
indent: indent + 2,
maxDepth: maxDepth - 1,
maxItemCounter: &maxItemCounter,
visitedItems: &visitedItems)
}
}
/// Dump information about an object's superclass, given a mirror reflecting
/// that superclass.
internal func _dumpSuperclass_unlocked<TargetStream : OutputStream>(
mirror mirror: Mirror,
to target: inout TargetStream,
indent: Int,
maxDepth: Int,
maxItemCounter: inout Int,
visitedItems: inout [ObjectIdentifier : Int]
) {
guard maxItemCounter > 0 else { return }
maxItemCounter -= 1
for _ in 0..<indent { target.write(" ") }
let count = mirror.children.count
let bullet = count == 0 ? "-"
: maxDepth <= 0 ? "▹" : "▿"
target.write(bullet)
target.write(" super: ")
_debugPrint_unlocked(mirror.subjectType, &target)
target.write("\n")
guard maxDepth > 0 else { return }
if let superclassMirror = mirror.superclassMirror {
_dumpSuperclass_unlocked(
mirror: superclassMirror,
to: &target,
indent: indent + 2,
maxDepth: maxDepth - 1,
maxItemCounter: &maxItemCounter,
visitedItems: &visitedItems)
}
var currentIndex = mirror.children.startIndex
for i in 0..<count {
if maxItemCounter <= 0 {
for _ in 0..<(indent+4) {
target.write(" ")
}
let remainder = count - i
target.write("(")
_print_unlocked(remainder, &target)
if i > 0 { target.write(" more") }
if remainder == 1 {
target.write(" child)\n")
} else {
target.write(" children)\n")
}
return
}
let (name, child) = mirror.children[currentIndex]
currentIndex = currentIndex.successor()
_dump_unlocked(
child,
to: &target,
name: name,
indent: indent + 2,
maxDepth: maxDepth - 1,
maxItemCounter: &maxItemCounter,
visitedItems: &visitedItems)
}
}
// -- Implementation details for the runtime's _Mirror implementation
@_silgen_name("swift_MagicMirrorData_summary")
func _swift_MagicMirrorData_summaryImpl(
metadata: Any.Type, _ result: UnsafeMutablePointer<String>
)
public struct _MagicMirrorData {
let owner: Builtin.NativeObject
let ptr: Builtin.RawPointer
let metadata: Any.Type
var value: Any {
@_silgen_name("swift_MagicMirrorData_value")get
}
var valueType: Any.Type {
@_silgen_name("swift_MagicMirrorData_valueType")get
}
public var objcValue: Any {
@_silgen_name("swift_MagicMirrorData_objcValue")get
}
public var objcValueType: Any.Type {
@_silgen_name("swift_MagicMirrorData_objcValueType")get
}
var summary: String {
let (_, result) = _withUninitializedString {
_swift_MagicMirrorData_summaryImpl(self.metadata, $0)
}
return result
}
public func _loadValue<T>() -> T {
return Builtin.load(ptr) as T
}
}
struct _OpaqueMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int { return 0 }
subscript(i: Int) -> (String, _Mirror) {
_preconditionFailure("no children")
}
var summary: String { return data.summary }
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .aggregate }
}
internal struct _TupleMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
@_silgen_name("swift_TupleMirror_count")get
}
subscript(i: Int) -> (String, _Mirror) {
return _subscript_get(i)
}
@_silgen_name("swift_TupleMirror_subscript")
func _subscript_get<T>(i: Int) -> (T, _Mirror)
var summary: String { return "(\(count) elements)" }
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .tuple }
}
struct _StructMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
@_silgen_name("swift_StructMirror_count")get
}
subscript(i: Int) -> (String, _Mirror) {
return _subscript_get(i)
}
@_silgen_name("swift_StructMirror_subscript")
func _subscript_get<T>(i: Int) -> (T, _Mirror)
var summary: String {
return _typeName(valueType)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .`struct` }
}
struct _EnumMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? { return nil }
var count: Int {
@_silgen_name("swift_EnumMirror_count")get
}
var caseName: UnsafePointer<CChar> {
@_silgen_name("swift_EnumMirror_caseName")get
}
subscript(i: Int) -> (String, _Mirror) {
return _subscript_get(i)
}
@_silgen_name("swift_EnumMirror_subscript")
func _subscript_get<T>(i: Int) -> (T, _Mirror)
var summary: String {
let maybeCaseName = String(validatingUTF8: self.caseName)
let typeName = _typeName(valueType)
if let caseName = maybeCaseName {
return typeName + "." + caseName
}
return typeName
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .`enum` }
}
@warn_unused_result
@_silgen_name("swift_ClassMirror_count")
func _getClassCount(_: _MagicMirrorData) -> Int
// Like the other swift_*Mirror_subscript functions declared here and
// elsewhere, this is implemented in the runtime. The Swift CC would
// normally require the String to be returned directly and the _Mirror
// indirectly. However, Clang isn't currently capable of doing that
// reliably because the size of String exceeds the normal direct-return
// ABI rules on most platforms. Therefore, we make this function generic,
// which has the disadvantage of passing the String type metadata as an
// extra argument, but does force the string to be returned indirectly.
@warn_unused_result
@_silgen_name("swift_ClassMirror_subscript")
func _getClassChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror)
#if _runtime(_ObjC)
@warn_unused_result
@_silgen_name("swift_ClassMirror_quickLookObject")
public func _getClassPlaygroundQuickLook(
data: _MagicMirrorData
) -> PlaygroundQuickLook?
#endif
struct _ClassMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? {
return data._loadValue() as ObjectIdentifier
}
var count: Int {
return _getClassCount(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getClassChild(i, data)
}
var summary: String {
return _typeName(valueType)
}
var quickLookObject: PlaygroundQuickLook? {
#if _runtime(_ObjC)
return _getClassPlaygroundQuickLook(data)
#else
return nil
#endif
}
var disposition: _MirrorDisposition { return .`class` }
}
struct _ClassSuperMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
// Suppress the value identifier for super mirrors.
var objectIdentifier: ObjectIdentifier? {
return nil
}
var count: Int {
return _getClassCount(data)
}
subscript(i: Int) -> (String, _Mirror) {
return _getClassChild(i, data)
}
var summary: String {
return _typeName(data.metadata)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
var disposition: _MirrorDisposition { return .`class` }
}
struct _MetatypeMirror : _Mirror {
let data: _MagicMirrorData
var value: Any { return data.value }
var valueType: Any.Type { return data.valueType }
var objectIdentifier: ObjectIdentifier? {
return data._loadValue() as ObjectIdentifier
}
var count: Int {
return 0
}
subscript(i: Int) -> (String, _Mirror) {
_preconditionFailure("no children")
}
var summary: String {
return _typeName(data._loadValue() as Any.Type)
}
var quickLookObject: PlaygroundQuickLook? { return nil }
// Special disposition for types?
var disposition: _MirrorDisposition { return .aggregate }
}
extension ObjectIdentifier {
@available(*, unavailable, message: "use the 'UInt(_:)' initializer")
public var uintValue: UInt {
fatalError("unavailable function can't be called")
}
}
| apache-2.0 |
ps2/rileylink_ios | MinimedKitTests/PumpEvents/ResumePumpEventTests.swift | 1 | 658 | //
// ResumePumpEventTests.swift
// MinimedKitTests
//
// Created by Pete Schwamb on 11/10/19.
// Copyright © 2019 Pete Schwamb. All rights reserved.
//
import XCTest
@testable import MinimedKit
class ResumePumpEventTests: XCTestCase {
func testRemotelyTriggeredFlag() {
let localResume = ResumePumpEvent(availableData: Data(hexadecimalString: "1f20a4e30e0a13")!, pumpModel: .model523)!
XCTAssert(!localResume.wasRemotelyTriggered)
let remoteResume = ResumePumpEvent(availableData: Data(hexadecimalString: "1f209de40e4a13")!, pumpModel: .model523)!
XCTAssert(remoteResume.wasRemotelyTriggered)
}
}
| mit |
vakoc/particle-swift | Examples/TVExample/TVExample/DevicesCollectionViewController.swift | 1 | 4510 | // This source file is part of the vakoc.com open source project(s)
//
// Copyright © 2018 Mark Vakoc. All rights reserved.
// Licensed under Apache License v2.0
//
// See http://www.vakoc.com/LICENSE.txt for license information
import UIKit
import ParticleSwift
private let reuseIdentifier = "device"
class DeviceCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var nameLabel: UILabel!
}
class DevicesCollectionViewController: UICollectionViewController {
var deviceListResult = [DeviceInformation]() {
didSet {
collectionView?.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
collectionView!.register(UINib(nibName: "DeviceCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshDevices(nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func refreshDevices(_ sender: Any?) {
(UIApplication.shared.delegate as! AppDelegate).particleCloud.devices { [weak self] (result) in
/// If we are still around save the results of the call on the main thread
if let this = self {
DispatchQueue.main.async {
switch result {
case .success(let devices):
this.deviceListResult = devices.sorted(by: { (a, b) -> Bool in
return a.name < b.name
})
case .failure( _):
// Handle the error
this.deviceListResult = []
}
}
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return deviceListResult.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! DeviceCollectionViewCell
cell.nameLabel.text = deviceListResult[indexPath.row].name
return cell
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
}
*/
}
| apache-2.0 |
laurentVeliscek/AudioKit | AudioKit/Common/Operations/Effects/Filters/dcBlock.swift | 2 | 510 | //
// dcBlock.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
extension AKComputedParameter {
/// Implements the DC blocking filter Y[i] = X[i] - X[i-1] + (igain * Y[i-1])
/// Based on work by Perry Cook.
///
/// - parameter input: Input audio signal
///
public func dcBlock() -> AKOperation {
return AKOperation(module: "dcblock", inputs: self.toMono())
}
}
| mit |
duliodenis/slappylock | Slappy Lock/Slappy Lock/Extensions.swift | 1 | 357 | //
// Extensions.swift
// Slappy Lock
//
// Created by Dulio Denis on 11/16/15.
// Copyright © 2015 Dulio Denis. All rights reserved.
//
import Foundation
import SpriteKit
extension CGFloat {
static func random(min: CGFloat, max: CGFloat) -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF) * (max - min) + min
}
} | mit |
kickstarter/ios-ksapi | KsApi/models/lenses/ConfigLenses.swift | 1 | 2590 | import Prelude
extension Config {
public enum lens {
public static let applePayCountries = Lens<Config, [String]>(
view: { $0.applePayCountries },
set: { Config(abExperiments: $1.abExperiments, appId: $1.appId, applePayCountries: $0,
countryCode: $1.countryCode, features: $1.features, iTunesLink: $1.iTunesLink,
launchedCountries: $1.launchedCountries, locale: $1.locale,
stripePublishableKey: $1.stripePublishableKey) }
)
public static let countryCode = Lens<Config, String>(
view: { $0.countryCode },
set: { Config(abExperiments: $1.abExperiments, appId: $1.appId, applePayCountries: $1.applePayCountries,
countryCode: $0, features: $1.features, iTunesLink: $1.iTunesLink,
launchedCountries: $1.launchedCountries, locale: $1.locale,
stripePublishableKey: $1.stripePublishableKey) }
)
public static let features = Lens<Config, [String:Bool]>(
view: { $0.features },
set: { Config(abExperiments: $1.abExperiments, appId: $1.appId, applePayCountries: $1.applePayCountries,
countryCode: $1.countryCode, features: $0, iTunesLink: $1.iTunesLink,
launchedCountries: $1.launchedCountries, locale: $1.locale,
stripePublishableKey: $1.stripePublishableKey) }
)
public static let launchedCountries = Lens<Config, [Project.Country]>(
view: { $0.launchedCountries },
set: { Config(abExperiments: $1.abExperiments, appId: $1.appId, applePayCountries: $1.applePayCountries,
countryCode: $1.countryCode, features: $1.features, iTunesLink: $1.iTunesLink, launchedCountries: $0,
locale: $1.locale, stripePublishableKey: $1.stripePublishableKey) }
)
public static let locale = Lens<Config, String>(
view: { $0.locale },
set: { Config(abExperiments: $1.abExperiments, appId: $1.appId, applePayCountries: $1.applePayCountries,
countryCode: $1.countryCode, features: $1.features, iTunesLink: $1.iTunesLink,
launchedCountries: $1.launchedCountries, locale: $0, stripePublishableKey: $1.stripePublishableKey) }
)
public static let stripePublishableKey = Lens<Config, String>(
view: { $0.stripePublishableKey },
set: { Config(abExperiments: $1.abExperiments, appId: $1.appId, applePayCountries: $1.applePayCountries,
countryCode: $1.countryCode, features: $1.features, iTunesLink: $1.iTunesLink,
launchedCountries: $1.launchedCountries, locale: $1.locale, stripePublishableKey: $0) }
)
}
}
| apache-2.0 |
joshua-d-miller/macOSLAPS | macOSLAPS/main.swift | 1 | 11200 | /// ------------------------
/// LAPS for macOS Devices
/// ------------------------
/// Command line executable that handles automatic
/// generation and rotation of the local administrator
/// password.
///
/// Current Usage:
/// - Active Directory (Similar to Windows functionality)
/// - Local (Password stored in Keychain Only)
/// -------------------------
/// Joshua D. Miller - josh.miller@outlook.com
///
/// Last Updated June 20, 2022
/// -------------------------
import Foundation
struct Constants {
// Begin by tying date_formatter() to a variable
static let dateFormatter = date_formatter()
// Read Command Line Arugments into array to use later
static let arguments : Array = CommandLine.arguments
// Retrieve our configuration for the application or use the
// default values
static let local_admin = GetPreference(preference_key: "LocalAdminAccount") as! String
static let password_length = GetPreference(preference_key: "PasswordLength") as! Int
static let days_till_expiration = GetPreference(preference_key: "DaysTillExpiration") as! Int
static let remove_keychain = GetPreference(preference_key: "RemoveKeychain") as! Bool
static let characters_to_remove = GetPreference(preference_key: "RemovePassChars") as! String
static let character_exclusion_sets = GetPreference(preference_key: "ExclusionSets") as? Array<String>
static let preferred_domain_controller = GetPreference(preference_key: "PreferredDC") as! String
static var first_password = GetPreference(preference_key: "FirstPass") as! String
static let method = GetPreference(preference_key: "Method") as! String
static let passwordrequirements = GetPreference(preference_key: "PasswordRequirements") as! Dictionary<String, Any>
// Constant values if triggering a password reset / specifying a First Password
static var pw_reset : Bool = false
static var use_firstpass : Bool = false
}
func macOSLAPS() {
// Check if running as root
let current_running_User = NSUserName()
if current_running_User != "root" {
laps_log.print("macOSLAPS needs to be run as root to ensure the password change for \(Constants.local_admin) if needed.", .error)
exit(77)
}
let output_dir = "/var/root/Library/Application Support"
// Remove files from extracting password if they exist
if FileManager.default.fileExists(atPath: "\(output_dir)/macOSLAPS-password") {
do {
try FileManager.default.removeItem(atPath: "/var/root/Library/Application Support/macOSLAPS-password")
try FileManager.default.removeItem(atPath: "/var/root/Library/Application Support/macOSLAPS-expiration")
} catch {
laps_log.print("Unable to remove files used for extraction of password for MDM. Please delete manually", .warn)
}
}
// Iterate through supported Arguments
for argument in Constants.arguments {
switch argument {
case "-version":
let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
print(appVersion)
exit(0)
case "-getPassword":
if Constants.method == "Local" {
let (current_password, keychain_item_check) = KeychainService.loadPassword(service: "macOSLAPS")
if current_password == nil && keychain_item_check == nil {
laps_log.print("Unable to retrieve password from macOSLAPS Keychain entry.", .error)
exit(1)
} else if current_password == nil && keychain_item_check == "Not Found" {
laps_log.print("There does not appear to be a macOSLAPS Keychain Entry. Most likely, a password change has never been performed or the first password change has failed due to an incorrect password", .error)
exit(1)
} else {
do {
// Verify Password
let password_verify_status = Shell.run(launchPath: "/usr/bin/dscl", arguments: [".", "-authonly", Constants.local_admin, current_password!])
if password_verify_status == "" {
laps_log.print("Password has been verified to work. Extracting...", .info)
} else {
laps_log.print("Password cannot be verified. The password is out of sync. Please run sysadminctl to perform a reset to restart rottation", .error)
exit(1)
}
let current_expiration_date = LocalTools.get_expiration_date()
let current_expiration_string = Constants.dateFormatter.string(for: current_expiration_date)
// Verify our output Directory exists and if not create it
var isDir:ObjCBool = true
// Write contents to file
if !FileManager.default.fileExists(atPath: output_dir, isDirectory: &isDir) {
do {
laps_log.print("Creating directory \(output_dir) as it does not currently exist. This issue was first present in macOS 12.2.1 on Apple Silicon", .warn)
try FileManager.default.createDirectory(atPath: output_dir, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o755, .ownerAccountID: 0, .groupOwnerAccountID: 0])
laps_log.print("Directory \(output_dir) has been created. Continuing...")
} catch {
laps_log.print("An error occured attempting to create the directory \(output_dir). Unable to extract password. Exiting...")
exit(0)
}
}
try current_password!.write(toFile: "/var/root/Library/Application Support/macOSLAPS-password", atomically: true, encoding: String.Encoding.utf8)
try current_expiration_string!.write(toFile: "/var/root/Library/Application Support/macOSLAPS-expiration", atomically: true, encoding: String.Encoding.utf8)
exit(0)
}
catch let error as NSError {
laps_log.print("Unable to extract password from keychain. Error: \(error)", .error)
}
exit(1)
}
} else {
laps_log.print("Will not display password as our current method is Active Directory", .warn)
exit(0)
}
case "-resetPassword":
Constants.pw_reset = true
case "-help":
print("""
macOSLAPS Help
==============
These are the arguments that you can use with macOSLAPS. You may only use one argument at a time.
-version Prints Current Version of macOSLAPS and gracefully exits
-getPassword If using the Local method, the password will be outputted
to the filesystem temporarily. Password is deleted upon
next automated or manual run
-resetPassword Forces a password reset no matter the expiration date
-firstPass Performs a password reset using the FirstPass Configuration
Profile key or the password you specify after this flag.
The password of the admin MUST be this password or the
change WILL FAIL.
-help Displays this screen
""")
exit(0)
case "-firstPass":
Constants.pw_reset = true
Constants.use_firstpass = true
if Constants.first_password == "" {
Constants.first_password = CommandLine.arguments[2]
}
if Constants.first_password == "" {
laps_log.print("No password is specified via the FirstPass key OR in the command line. Exiting...", .error)
exit(1)
}
laps_log.print("the -firstPass argument was invoked. Using the Configuration Profile specified password or the argument password that was specified.", .info)
default:
continue
}
}
switch Constants.method {
case "AD":
// Active Directory Password Change Function
let ad_computer_record = ADTools.connect()
// Get Expiration Time from Active Directory
var ad_exp_time = ""
if Constants.pw_reset == true {
ad_exp_time = "126227988000000000"
} else {
ad_exp_time = ADTools.check_pw_expiration(computer_record: ad_computer_record)!
}
// Convert that time into a date
let exp_date = TimeConversion.epoch(exp_time: ad_exp_time)
// Compare that newly calculated date against now to see if a change is required
if exp_date! < Date() {
// Check if the domain controller that we are connected to is writable
ADTools.verify_dc_writability(computer_record: ad_computer_record)
// Performs Password Change for local admin account
laps_log.print("Password Change is required as the LAPS password for \(Constants.local_admin), has expired", .info)
ADTools.password_change(computer_record: ad_computer_record)
}
else {
let actual_exp_date = Constants.dateFormatter.string(from: exp_date!)
laps_log.print("Password change is not required as the password for \(Constants.local_admin) does not expire until \(actual_exp_date)", .info)
exit(0)
}
case "Local":
// Local method to perform passwords changes locally vs relying on Active Directory.
// It is assumed that users will be using either an MDM or some reporting method to store
// the password somewhere
// Load the Keychain Item and compare the date
var exp_date : Date?
if Constants.pw_reset == true {
exp_date = Calendar.current.date(byAdding: .day, value: -7, to: Date())
} else {
exp_date = LocalTools.get_expiration_date()
}
if exp_date! < Date() {
LocalTools.password_change()
let new_exp_date = LocalTools.get_expiration_date()
laps_log.print("Password change has been completed for the local admin \(Constants.local_admin). New expiration date is \(Constants.dateFormatter.string(from: new_exp_date!))", .info)
exit(0)
}
else {
laps_log.print("Password change is not required as the password for \(Constants.local_admin) does not expire until \(Constants.dateFormatter.string(from: exp_date!))", .info)
exit(0)
}
default:
exit(0)
}
}
macOSLAPS()
| mit |
benlangmuir/swift | test/Concurrency/Runtime/async_initializer.swift | 7 | 3914 | // RUN: %target-run-simple-swift(-parse-as-library -Xfrontend -disable-availability-checking) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
@available(SwiftStdlib 5.1, *)
actor NameGenerator {
private var counter = 0
private var prefix : String
init(_ title: String) { self.prefix = title }
func getName() -> String {
counter += 1
return "\(prefix) \(counter)"
}
}
@available(SwiftStdlib 5.1, *)
protocol Person {
init() async
var name : String { get set }
}
@available(SwiftStdlib 5.1, *)
class EarthPerson : Person {
private static let oracle = NameGenerator("Earthling")
var name : String
required init() async {
self.name = await EarthPerson.oracle.getName()
}
init(name: String) async {
self.name = await (detach { name }).get()
}
}
@available(SwiftStdlib 5.1, *)
class NorthAmericaPerson : EarthPerson {
private static let oracle = NameGenerator("NorthAmerican")
required init() async {
await super.init()
self.name = await NorthAmericaPerson.oracle.getName()
}
override init(name: String) async {
await super.init(name: name)
}
}
@available(SwiftStdlib 5.1, *)
class PrecariousClass {
init?(nilIt : Int) async {
let _ : Optional<Int> = await (detach { nil }).get()
return nil
}
init(throwIt : Double) async throws {
if await (detach { 0 }).get() != 1 {
throw Something.bogus
}
}
init?(nilOrThrowIt shouldThrow: Bool) async throws {
let flag = await (detach { shouldThrow }).get()
if flag {
throw Something.bogus
}
return nil
}
init!(crashOrThrowIt shouldThrow: Bool) async throws {
let flag = await (detach { shouldThrow }).get()
if flag {
throw Something.bogus
}
return nil
}
}
enum Something : Error {
case bogus
}
@available(SwiftStdlib 5.1, *)
struct PrecariousStruct {
init?(nilIt : Int) async {
let _ : Optional<Int> = await (detach { nil }).get()
return nil
}
init(throwIt : Double) async throws {
if await (detach { 0 }).get() != 1 {
throw Something.bogus
}
}
}
// CHECK: Earthling 1
// CHECK-NEXT: Alice
// CHECK-NEXT: Earthling 2
// CHECK-NEXT: Bob
// CHECK-NEXT: Earthling 3
// CHECK-NEXT: Alex
// CHECK-NEXT: NorthAmerican 1
// CHECK-NEXT: NorthAmerican 2
// CHECK-NEXT: Earthling 6
// CHECK-NEXT: class was nil
// CHECK-NEXT: class threw
// CHECK-NEXT: nilOrThrowIt init was nil
// CHECK-NEXT: nilOrThrowIt init threw
// CHECK-NEXT: crashOrThrowIt init threw
// CHECK-NEXT: struct was nil
// CHECK-NEXT: struct threw
// CHECK: done
@available(SwiftStdlib 5.1, *)
@main struct RunIt {
static func main() async {
let people : [Person] = [
await EarthPerson(),
await NorthAmericaPerson(name: "Alice"),
await EarthPerson(),
await NorthAmericaPerson(name: "Bob"),
await EarthPerson(),
await NorthAmericaPerson(name: "Alex"),
await NorthAmericaPerson(),
await NorthAmericaPerson(),
await EarthPerson()
]
for p in people {
print(p.name)
}
// ----
if await PrecariousClass(nilIt: 0) == nil {
print("class was nil")
}
do { let _ = try await PrecariousClass(throwIt: 0.0) } catch {
print("class threw")
}
if try! await PrecariousClass(nilOrThrowIt: false) == nil {
print("nilOrThrowIt init was nil")
}
do { let _ = try await PrecariousClass(nilOrThrowIt: true) } catch {
print("nilOrThrowIt init threw")
}
do { let _ = try await PrecariousClass(crashOrThrowIt: true) } catch {
print("crashOrThrowIt init threw")
}
if await PrecariousStruct(nilIt: 0) == nil {
print("struct was nil")
}
do { let _ = try await PrecariousStruct(throwIt: 0.0) } catch {
print("struct threw")
}
print("done")
}
}
| apache-2.0 |
JeffESchmitz/RideNiceRide | RideNiceRide/ViewControllers/SlideMenu/FavoritesViewController.swift | 1 | 5798 | //
// FavoritesViewController.swift
// RideNiceRide
//
// Created by Jeff Schmitz on 11/12/16.
// Copyright © 2016 Jeff Schmitz. All rights reserved.
//
import UIKit
import GoogleMaps
import GooglePlaces
import Willow
import Cent
import CoreData
import DATAStack
import MapKit
class FavoritesViewController: UIViewController {
// MARK: - Properties (public)
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var emptyTableMessage: UILabel!
lazy var hubwayAPI: HubwayAPI = HubwayAPI(dataStack: self.dataStack)
unowned var dataStack: DATAStack
var tableData: [FavoriteStation] = []
// MARK: - View Life Cycle
required init?(coder aDecoder: NSCoder) {
//swiftlint:disable force_cast
let appdelegate = UIApplication.shared.delegate as! AppDelegate
self.dataStack = appdelegate.dataStack
//swiftlint:enable force_cast
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Favorites"
self.emptyTableMessage.text = "You don't have any Favorites yet.\n\nYou can add one by tapping on a pin and then 'Add Favorite'."
self.emptyTableMessage.sizeToFit()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.setNavigationBarItem()
let mainContext = dataStack.mainContext
let objects = self.fetch(forEntityName: String(describing: FavoriteStation.self), in: mainContext)
log.info("objects.count: \(objects.count)")
self.tableData.removeAll()
if let stations = objects as? [FavoriteStation] {
self.tableData = stations
}
self.tableView.reloadData()
}
// MARK: - Helper/utility functions
//swiftlint:disable force_cast
//swiftlint:disable force_try
func fetch(forEntityName entityName: String, in context: NSManagedObjectContext) -> [NSManagedObject] {
let request = NSFetchRequest<NSManagedObject>(entityName: entityName)
let objects = try! context.fetch(request)
return objects
}
func clearOutFavoriteData(in context: NSManagedObjectContext) {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: FavoriteStation.self))
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try context.execute(deleteRequest)
} catch let error as NSError {
print(":: ERROR: \(error.localizedDescription)")
}
}
//swiftlint:enable force_cast
//swiftlint:enable force_try
}
// MARK: - UITableViewDataSource
extension FavoritesViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.tableData.count
}
func numberOfSections(in tableView: UITableView) -> Int {
if tableData.isNotEmpty {
emptyTableMessage.isHidden = true
return 1
} else {
emptyTableMessage.isHidden = false
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//swiftlint:disable force_cast
let cell = self.tableView.dequeueReusableCell(withIdentifier: FavoritesTableViewCell.identifier) as! FavoritesTableViewCell
// swiftlint:enable force_cast
cell.favoriteStation = self.tableData[indexPath.row]
return cell
}
}
// MARK: - UITableViewDelegate
extension FavoritesViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let stationToRemove = self.tableData[indexPath.row]
if let stationId = stationToRemove.id {
hubwayAPI.removeFavorite(forStationId: stationId, in: dataStack.mainContext)
}
guard let favoriteStations = hubwayAPI.fetch(forEntityName: "FavoriteStation", in: dataStack.mainContext) as? [FavoriteStation] else {
log.error("Error occured while fetching FavoriteStations after deleting a row.")
return
}
self.tableData = favoriteStations
// delete the row from the UITableView
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// For v1 of app, just open iOS Maps application with selected favorite.
// For v2, send these coordinates back to the mapView, and center and select the pin tapped.
let selectedFavoriteStation = self.tableData[indexPath.row]
print("Favorite lat: \(selectedFavoriteStation.latitude), long: \(selectedFavoriteStation.longitude)")
print("")
openMapForFavorite(favoriteStation: selectedFavoriteStation)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let deselectedCell = tableView.cellForRow(at: indexPath)!
deselectedCell.backgroundColor = UIColor.clear
}
func openMapForFavorite(favoriteStation: FavoriteStation) {
let latitude: CLLocationDegrees = Double(favoriteStation.latitude!)!
let longitude: CLLocationDegrees = Double(favoriteStation.longitude!)!
let regionDistance: CLLocationDistance = 10000
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
let options = [
MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = favoriteStation.stationName
mapItem.openInMaps(launchOptions: options)
}
}
| mit |
bitjammer/swift | test/SILGen/dynamic_lookup.swift | 3 | 15622 | // RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
// REQUIRES: objc_interop
class X {
@objc func f() { }
@objc class func staticF() { }
@objc var value: Int {
return 17
}
@objc subscript (i: Int) -> Int {
get {
return i
}
set {}
}
}
@objc protocol P {
func g()
}
// CHECK-LABEL: sil hidden @_T014dynamic_lookup15direct_to_class{{[_0-9a-zA-Z]*}}F
func direct_to_class(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : $AnyObject):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[OPENED_ARG:%[0-9]+]] = open_existential_ref [[BORROWED_ARG]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OPENED_ARG_COPY]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign : (X) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: apply [[METHOD]]([[OPENED_ARG_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: destroy_value [[OPENED_ARG_COPY]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
obj.f!()
}
// CHECK: } // end sil function '_T014dynamic_lookup15direct_to_class{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @_T014dynamic_lookup18direct_to_protocol{{[_0-9a-zA-Z]*}}F
func direct_to_protocol(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : $AnyObject):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[OPENED_ARG:%[0-9]+]] = open_existential_ref [[BORROWED_ARG]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OPENED_ARG_COPY]] : $@opened({{.*}}) AnyObject, #P.g!1.foreign : <Self where Self : P> (Self) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: apply [[METHOD]]([[OPENED_ARG_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: destroy_value [[OPENED_ARG_COPY]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
obj.g!()
}
// CHECK: } // end sil function '_T014dynamic_lookup18direct_to_protocol{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @_T014dynamic_lookup23direct_to_static_method{{[_0-9a-zA-Z]*}}F
func direct_to_static_method(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : $AnyObject):
var obj = obj
// CHECK: [[OBJBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]]
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: [[OBJCOPY:%[0-9]+]] = load_borrow [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject
// CHECK-NEXT: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened([[UUID:".*"]]) AnyObject).Type
// CHECK-NEXT: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OPENMETA]] : $@thick (@opened([[UUID]]) AnyObject).Type, #X.staticF!1.foreign : (X.Type) -> () -> (), $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> ()
// CHECK: apply [[METHOD]]([[OPENMETA]]) : $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> ()
// CHECK: destroy_value [[OBJBOX]]
// CHECK: destroy_value [[ARG]]
type(of: obj).staticF!()
}
// } // end sil function '_TF14dynamic_lookup23direct_to_static_method{{.*}}'
// CHECK-LABEL: sil hidden @_T014dynamic_lookup12opt_to_class{{[_0-9a-zA-Z]*}}F
func opt_to_class(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : $AnyObject):
var obj = obj
// CHECK: [[EXISTBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[EXISTBOX]]
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[PBOBJ]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: [[OPTBOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_owned () -> ()> }
// CHECK: [[PBOPT:%.*]] = project_box [[OPTBOX]]
// CHECK: [[EXISTVAL:%[0-9]+]] = load [copy] [[PBOBJ]] : $*AnyObject
// CHECK: [[OBJ_SELF:%[0-9]*]] = open_existential_ref [[EXISTVAL]]
// CHECK: [[OPT_TMP:%.*]] = alloc_stack $Optional<@callee_owned () -> ()>
// CHECK: dynamic_method_br [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign, [[HASBB:[a-zA-z0-9]+]], [[NOBB:[a-zA-z0-9]+]]
// Has method BB:
// CHECK: [[HASBB]]([[UNCURRIED:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()):
// CHECK: [[OBJ_SELF_COPY:%.*]] = copy_value [[OBJ_SELF]]
// CHECK: [[PARTIAL:%[0-9]+]] = partial_apply [[UNCURRIED]]([[OBJ_SELF_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: [[THUNK_PAYLOAD:%.*]] = init_enum_data_addr [[OPT_TMP]]
// CHECK: store [[PARTIAL]] to [init] [[THUNK_PAYLOAD]]
// CHECK: inject_enum_addr [[OPT_TMP]] : $*Optional<@callee_owned () -> ()>, #Optional.some!enumelt.1
// CHECK: br [[CONTBB:[a-zA-Z0-9]+]]
// No method BB:
// CHECK: [[NOBB]]:
// CHECK: inject_enum_addr [[OPT_TMP]] : {{.*}}, #Optional.none!enumelt
// CHECK: br [[CONTBB]]
// Continuation block
// CHECK: [[CONTBB]]:
// CHECK: [[OPT:%.*]] = load [take] [[OPT_TMP]]
// CHECK: store [[OPT]] to [init] [[PBOPT]] : $*Optional<@callee_owned () -> ()>
// CHECK: dealloc_stack [[OPT_TMP]]
var of: (() -> ())! = obj.f
// Exit
// CHECK: destroy_value [[OBJ_SELF]] : $@opened({{".*"}}) AnyObject
// CHECK: destroy_value [[OPTBOX]] : ${ var Optional<@callee_owned () -> ()> }
// CHECK: destroy_value [[EXISTBOX]] : ${ var AnyObject }
// CHECK: destroy_value %0
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
}
// CHECK-LABEL: sil hidden @_T014dynamic_lookup20forced_without_outer{{[_0-9a-zA-Z]*}}F
func forced_without_outer(_ obj: AnyObject) {
// CHECK: dynamic_method_br
var f = obj.f!
}
// CHECK-LABEL: sil hidden @_T014dynamic_lookup20opt_to_static_method{{[_0-9a-zA-Z]*}}F
func opt_to_static_method(_ obj: AnyObject) {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject):
// CHECK: [[OBJBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]]
// CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[BORROWED_OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: end_borrow [[BORROWED_OBJ]] from [[OBJ]]
// CHECK: [[OPTBOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_owned () -> ()> }
// CHECK: [[PBO:%.*]] = project_box [[OPTBOX]]
// CHECK: [[OBJCOPY:%[0-9]+]] = load_borrow [[PBOBJ]] : $*AnyObject
// CHECK: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject
// CHECK: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened
// CHECK: [[OBJCMETA:%[0-9]+]] = thick_to_objc_metatype [[OPENMETA]]
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<@callee_owned () -> ()>
// CHECK: dynamic_method_br [[OBJCMETA]] : $@objc_metatype (@opened({{".*"}}) AnyObject).Type, #X.staticF!1.foreign, [[HASMETHOD:[A-Za-z0-9_]+]], [[NOMETHOD:[A-Za-z0-9_]+]]
var optF: (() -> ())! = type(of: obj).staticF
}
// CHECK-LABEL: sil hidden @_T014dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F
func opt_to_property(_ obj: AnyObject) {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[BORROWED_OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: end_borrow [[BORROWED_OBJ]] from [[OBJ]]
// CHECK: [[INT_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: project_box [[INT_BOX]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[PBOBJ]] : $*AnyObject
// CHECK: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.1.foreign, bb1, bb2
// CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int):
// CHECK: [[RAWOBJ_SELF_COPY:%.*]] = copy_value [[RAWOBJ_SELF]]
// CHECK: [[BOUND_METHOD:%[0-9]+]] = partial_apply [[METHOD]]([[RAWOBJ_SELF_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int
// CHECK: [[VALUE:%[0-9]+]] = apply [[BOUND_METHOD]]() : $@callee_owned () -> Int
// CHECK: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[VALUE]] to [trivial] [[VALUETEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]{{.*}}some
// CHECK: br bb3
var i: Int = obj.value!
}
// CHECK: } // end sil function '_T014dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @_T014dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F
func direct_to_subscript(_ obj: AnyObject, i: Int) {
var obj = obj
var i = i
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[BORROWED_OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: end_borrow [[BORROWED_OBJ]] from [[OBJ]]
// CHECK: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBI:%.*]] = project_box [[I_BOX]]
// CHECK: store [[I]] to [trivial] [[PBI]] : $*Int
// CHECK: alloc_box ${ var Int }
// CHECK: project_box
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[PBOBJ]] : $*AnyObject
// CHECK: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[I:%[0-9]+]] = load [trivial] [[PBI]] : $*Int
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// CHECK: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [[GETTER]]([[OBJ_REF_COPY]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int
// CHECK: [[RESULT:%[0-9]+]] = apply [[GETTER_WITH_SELF]]([[I]]) : $@callee_owned (Int) -> Int
// CHECK: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]{{.*}}some
// CHECK: br bb3
var x: Int = obj[i]!
}
// CHECK: } // end sil function '_T014dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden @_T014dynamic_lookup16opt_to_subscript{{[_0-9a-zA-Z]*}}F
func opt_to_subscript(_ obj: AnyObject, i: Int) {
var obj = obj
var i = i
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[BORROWED_OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: end_borrow [[BORROWED_OBJ]] from [[OBJ]]
// CHECK: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBI:%.*]] = project_box [[I_BOX]]
// CHECK: store [[I]] to [trivial] [[PBI]] : $*Int
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[PBOBJ]] : $*AnyObject
// CHECK: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[I:%[0-9]+]] = load [trivial] [[PBI]] : $*Int
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// CHECK: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [[GETTER]]([[OBJ_REF_COPY]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int
// CHECK: [[RESULT:%[0-9]+]] = apply [[GETTER_WITH_SELF]]([[I]]) : $@callee_owned (Int) -> Int
// CHECK: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]
// CHECK: br bb3
obj[i]
}
// CHECK-LABEL: sil hidden @_T014dynamic_lookup8downcast{{[_0-9a-zA-Z]*}}F
func downcast(_ obj: AnyObject) -> X {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[BORROWED_OBJ:%.*]] = begin_borrow [[OBJ]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[BORROWED_OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: end_borrow [[BORROWED_OBJ]] from [[OBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[PBOBJ]] : $*AnyObject
// CHECK: [[X:%[0-9]+]] = unconditional_checked_cast [[OBJ]] : $AnyObject to $X
// CHECK: destroy_value [[OBJ_BOX]] : ${ var AnyObject }
// CHECK: destroy_value %0
// CHECK: return [[X]] : $X
return obj as! X
}
@objc class Juice { }
@objc protocol Fruit {
@objc optional var juice: Juice { get }
}
// CHECK-LABEL: sil hidden @_T014dynamic_lookup7consumeyAA5Fruit_pF
// CHECK: bb0(%0 : $Fruit):
// CHECK: [[BOX:%.*]] = alloc_stack $Optional<Juice>
// CHECK: dynamic_method_br [[SELF:%.*]] : $@opened("{{.*}}") Fruit, #Fruit.juice!getter.1.foreign, bb1, bb2
// CHECK: bb1([[FN:%.*]] : $@convention(objc_method) (@opened("{{.*}}") Fruit) -> @autoreleased Juice):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[METHOD:%.*]] = partial_apply [[FN]]([[SELF_COPY]]) : $@convention(objc_method) (@opened("{{.*}}") Fruit) -> @autoreleased Juice
// CHECK: [[RESULT:%.*]] = apply [[METHOD]]() : $@callee_owned () -> @owned Juice
// CHECK: [[PAYLOAD:%.*]] = init_enum_data_addr [[BOX]] : $*Optional<Juice>, #Optional.some!enumelt.1
// CHECK: store [[RESULT]] to [init] [[PAYLOAD]]
// CHECK: inject_enum_addr [[BOX]] : $*Optional<Juice>, #Optional.some!enumelt.1
// CHECK: br bb3
// CHECK: bb2:
// CHECK: inject_enum_addr [[BOX]] : $*Optional<Juice>, #Optional.none!enumelt
// CHECK: br bb3
// CHECK: bb3:
// CHECK: return
func consume(_ fruit: Fruit) {
_ = fruit.juice
}
// rdar://problem/29249513 -- looking up an IUO member through AnyObject
// produces a Foo!? type. The SIL verifier did not correctly consider Optional
// to be the lowering of IUO (which is now eliminated by SIL lowering).
@objc protocol IUORequirement {
var iuoProperty: AnyObject! { get }
}
func getIUOPropertyDynamically(x: AnyObject) -> Any {
return x.iuoProperty
}
| apache-2.0 |
Pocketbrain/nativeadslib-ios | PocketMediaNativeAds/Core/Caching.swift | 1 | 4561 | //
// Caching.swift
// PocketMediaNativeAds
//
// Created by Iain Munro on 16/09/16.
//
//
import Foundation
import UIKit
/**
This class contains the sharedCache used for the images.
*/
class Caching {
/// Static constant variable with our cache.
static let sharedCache: NSCache = { () -> NSCache<AnyObject, AnyObject> in
let cache = NSCache<AnyObject, AnyObject>()
cache.name = "PocketMediaCache"
// cache.countLimit = 1000 // Max 20 images in memory.
// cache.totalCostLimit = 100 * 1024 * 1024 // Max 100MB used.
return cache
}()
}
/**
This extension is used to cache the ad images.
*/
extension URL {
/// Defines the method signature of the on completion methods.
typealias ImageCacheCompletion = (UIImage) -> Void
/// Holds the callbacks. URI as key.
fileprivate static var callbacks = [String: [ImageCacheCompletion]]()
/// Returns the cache key of a URL instance.
func getCacheKey() -> String {
return self.absoluteString // self.lastPathComponent!
}
/// Retrieves a pre-cached image, or nil if it isn't cached.
/// You should call this before calling fetchImage.
var cachedImage: UIImage? {
return Caching.sharedCache.object(
forKey: getCacheKey() as AnyObject) as? UIImage
}
/**
Fetches the image from the network.
Stores it in the cache if successful.
Only calls completion on successful image download.
Completion is called on the main thread.
*/
func fetchImage(_ completion: @escaping ImageCacheCompletion) {
if URL.callbacks[self.getCacheKey()] == nil {
// create it.
URL.callbacks[self.getCacheKey()] = [ImageCacheCompletion]()
let task = URLSession.shared.dataTask(with: self, completionHandler: {
data, response, error in
if error == nil {
if let data = data, let image = UIImage(data: data) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
Caching.sharedCache.setObject(image, forKey: self.getCacheKey() as AnyObject, cost: data.count)
for callback in URL.callbacks[self.getCacheKey()]! {
callback(image)
}
// Reset it. So that if the Cache decides the remove this image. We'll be able to download it again.
URL.callbacks[self.getCacheKey()] = nil
}
}
}
})
task.resume()
}
// Add to the list of images we need to call when we have the requested result.
URL.callbacks[self.getCacheKey()]!.append(completion)
}
}
/**
This extension is used to cache the ad images.
*/
public extension UIImageView {
/// The last url that an instance of the imageView has asked for.
fileprivate static var currentUrl = [UIImageView: URL]()
/**
This method will kick off the caching process. It will start fetching the image if it isn't already being downloaded or in the cache and eventually call set the self.image.
*/
func nativeSetImageFromURL(_ url: URL, completion handler: ((Bool) -> Swift.Void)? = nil) {
if UIImageView.currentUrl[self] == url {
return
}
if let campaignImage = url.cachedImage {
// Cached
self.image = campaignImage
// Clear up after ourselves.
UIImageView.currentUrl[self] = nil
} else {
// Set this url as the last url we've asked for.
UIImageView.currentUrl[self] = url
url.fetchImage({ downloadedImage in
// In some cases this fetchImage call gets called very quickly if people scroll very quickly.
// This check here, makes sure that the response we are getting for this image, is actually the one he has last requested.
if UIImageView.currentUrl[self] != url {
return
}
self.image = downloadedImage
handler?(true)
// Check the cell hasn't recycled while loading.
// UIView.transition(with: self, duration: 0.3, options: .transitionCrossDissolve, animations: {
// self.image = downloadedImage
// }, completion: handler)
})
}
}
}
| mit |
firebase/firebase-ios-sdk | FirebaseStorage/Tests/Unit/StorageAuthorizerTests.swift | 1 | 9512 | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
@testable import FirebaseStorage
import GTMSessionFetcherCore
import SharedTestUtilities
import XCTest
class StorageAuthorizerTests: StorageTestHelpers {
var appCheckTokenSuccess: FIRAppCheckTokenResultFake!
var appCheckTokenError: FIRAppCheckTokenResultFake!
var fetcher: GTMSessionFetcher!
var fetcherService: GTMSessionFetcherService!
var auth: FIRAuthInteropFake!
var appCheck: FIRAppCheckFake!
let StorageTestAuthToken = "1234-5678-9012-3456-7890"
override func setUp() {
super.setUp()
appCheckTokenSuccess = FIRAppCheckTokenResultFake(token: "token", error: nil)
appCheckTokenError = FIRAppCheckTokenResultFake(token: "dummy token",
error: NSError(
domain: "testAppCheckError",
code: -1,
userInfo: nil
))
let fetchRequest = URLRequest(url: StorageTestHelpers().objectURL())
fetcher = GTMSessionFetcher(request: fetchRequest)
fetcherService = GTMSessionFetcherService()
auth = FIRAuthInteropFake(token: StorageTestAuthToken, userID: nil, error: nil)
appCheck = FIRAppCheckFake()
fetcher?.authorizer = StorageTokenAuthorizer(googleAppID: "dummyAppID",
fetcherService: fetcherService!,
authProvider: auth, appCheck: appCheck)
}
override func tearDown() {
fetcher = nil
fetcherService = nil
auth = nil
appCheck = nil
appCheckTokenSuccess = nil
super.tearDown()
}
func testSuccessfulAuth() {
let expectation = self.expectation(description: #function)
setFetcherTestBlock(with: 200) { fetcher in
self.checkAuthorizer(fetcher: fetcher, trueFalse: true)
}
fetcher?.beginFetch { data, error in
let headers = self.fetcher!.request?.allHTTPHeaderFields
XCTAssertEqual(headers!["Authorization"], "Firebase \(self.StorageTestAuthToken)")
expectation.fulfill()
}
waitForExpectation(test: self)
}
func testUnsuccessfulAuth() {
let expectation = self.expectation(description: #function)
let authError = NSError(domain: "FIRStorageErrorDomain",
code: StorageErrorCode.unauthenticated.rawValue, userInfo: nil)
let failedAuth = FIRAuthInteropFake(token: nil, userID: nil, error: authError)
fetcher?.authorizer = StorageTokenAuthorizer(
googleAppID: "dummyAppID",
fetcherService: fetcherService!,
authProvider: failedAuth,
appCheck: nil
)
setFetcherTestBlock(with: 401) { fetcher in
self.checkAuthorizer(fetcher: fetcher, trueFalse: false)
}
fetcher?.beginFetch { data, error in
let headers = self.fetcher!.request?.allHTTPHeaderFields
XCTAssertNil(headers)
let nsError = error as? NSError
XCTAssertEqual(nsError?.domain, "FIRStorageErrorDomain")
XCTAssertEqual(nsError?.code, StorageErrorCode.unauthenticated.rawValue)
XCTAssertEqual(nsError?.localizedDescription, "User is not authenticated, please " +
"authenticate using Firebase Authentication and try again.")
expectation.fulfill()
}
waitForExpectation(test: self)
}
func testSuccessfulUnauthenticatedAuth() {
let expectation = self.expectation(description: #function)
// Simulate Auth not being included at all
fetcher?.authorizer = StorageTokenAuthorizer(
googleAppID: "dummyAppID",
fetcherService: fetcherService!,
authProvider: nil,
appCheck: nil
)
setFetcherTestBlock(with: 200) { fetcher in
self.checkAuthorizer(fetcher: fetcher, trueFalse: false)
}
fetcher?.beginFetch { data, error in
let headers = self.fetcher!.request?.allHTTPHeaderFields
XCTAssertNil(headers!["Authorization"])
XCTAssertNil(error)
expectation.fulfill()
}
waitForExpectation(test: self)
}
func testSuccessfulAppCheckNoAuth() {
let expectation = self.expectation(description: #function)
appCheck?.tokenResult = appCheckTokenSuccess!
// Simulate Auth not being included at all
fetcher?.authorizer = StorageTokenAuthorizer(
googleAppID: "dummyAppID",
fetcherService: fetcherService!,
authProvider: nil,
appCheck: appCheck
)
setFetcherTestBlock(with: 200) { fetcher in
self.checkAuthorizer(fetcher: fetcher, trueFalse: false)
}
fetcher?.beginFetch { data, error in
let headers = self.fetcher!.request?.allHTTPHeaderFields
XCTAssertEqual(headers!["X-Firebase-AppCheck"], self.appCheckTokenSuccess?.token)
XCTAssertNil(error)
expectation.fulfill()
}
waitForExpectation(test: self)
}
func testSuccessfulAppCheckAndAuth() {
let expectation = self.expectation(description: #function)
appCheck?.tokenResult = appCheckTokenSuccess!
setFetcherTestBlock(with: 200) { fetcher in
self.checkAuthorizer(fetcher: fetcher, trueFalse: true)
}
fetcher?.beginFetch { data, error in
let headers = self.fetcher!.request?.allHTTPHeaderFields
XCTAssertEqual(headers!["Authorization"], "Firebase \(self.StorageTestAuthToken)")
XCTAssertEqual(headers!["X-Firebase-AppCheck"], self.appCheckTokenSuccess?.token)
XCTAssertNil(error)
expectation.fulfill()
}
waitForExpectation(test: self)
}
func testAppCheckError() {
let expectation = self.expectation(description: #function)
appCheck?.tokenResult = appCheckTokenError!
setFetcherTestBlock(with: 200) { fetcher in
self.checkAuthorizer(fetcher: fetcher, trueFalse: true)
}
fetcher?.beginFetch { data, error in
let headers = self.fetcher!.request?.allHTTPHeaderFields
XCTAssertEqual(headers!["Authorization"], "Firebase \(self.StorageTestAuthToken)")
XCTAssertEqual(headers!["X-Firebase-AppCheck"], self.appCheckTokenError?.token)
XCTAssertNil(error)
expectation.fulfill()
}
waitForExpectation(test: self)
}
func testIsAuthorizing() {
let expectation = self.expectation(description: #function)
setFetcherTestBlock(with: 200) { fetcher in
do {
let authorizer = try XCTUnwrap(fetcher.authorizer)
XCTAssertFalse(authorizer.isAuthorizingRequest(fetcher.request!))
} catch {
XCTFail("Failed to get authorizer: \(error)")
}
}
fetcher?.beginFetch { data, error in
XCTAssertNil(error)
expectation.fulfill()
}
waitForExpectation(test: self)
}
func testStopAuthorizingNoop() {
let expectation = self.expectation(description: #function)
setFetcherTestBlock(with: 200) { fetcher in
do {
let authorizer = try XCTUnwrap(fetcher.authorizer)
// Since both of these are noops, we expect that invoking them
// will still result in successful authenticatio
authorizer.stopAuthorization()
authorizer.stopAuthorization(for: fetcher.request!)
} catch {
XCTFail("Failed to get authorizer: \(error)")
}
}
fetcher?.beginFetch { data, error in
XCTAssertNil(error)
let headers = self.fetcher!.request?.allHTTPHeaderFields
XCTAssertEqual(headers!["Authorization"], "Firebase \(self.StorageTestAuthToken)")
expectation.fulfill()
}
waitForExpectation(test: self)
}
func testEmail() {
let expectation = self.expectation(description: #function)
setFetcherTestBlock(with: 200) { fetcher in
do {
let authorizer = try XCTUnwrap(fetcher.authorizer)
XCTAssertNil(authorizer.userEmail)
} catch {
XCTFail("Failed to get authorizer: \(error)")
}
}
fetcher?.beginFetch { data, error in
XCTAssertNil(error)
expectation.fulfill()
}
waitForExpectation(test: self)
}
// MARK: Helpers
private func setFetcherTestBlock(with statusCode: Int,
_ validationBlock: @escaping (GTMSessionFetcher) -> Void) {
fetcher?.testBlock = { (fetcher: GTMSessionFetcher,
response: GTMSessionFetcherTestResponse) in
validationBlock(fetcher)
let httpResponse = HTTPURLResponse(url: (fetcher.request?.url)!,
statusCode: statusCode,
httpVersion: "HTTP/1.1",
headerFields: nil)
response(httpResponse, nil, nil)
}
}
private func checkAuthorizer(fetcher: GTMSessionFetcher, trueFalse: Bool) {
do {
let authorizer = try XCTUnwrap(fetcher.authorizer)
XCTAssertEqual(authorizer.isAuthorizedRequest(fetcher.request!), trueFalse)
} catch {
XCTFail("Failed to get authorizer: \(error)")
}
}
}
| apache-2.0 |
Constructor-io/constructorio-client-swift | AutocompleteClient/FW/API/Data/TaskResponse.swift | 1 | 554 | //
// TaskResponse.swift
// Constructor.io
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
/**
Task response must be constructed through one of the two constructors so it's impossible to have a response
that has no data and no error
*/
public class TaskResponse<T, E> {
public let data: T?
public let error: E?
public init(data: T) {
self.data = data
self.error = nil
}
public init(error: E) {
self.data = nil
self.error = error
}
}
| mit |
ACChe/eidolon | Kiosk/Auction Listings/MasonryCollectionViewCell.swift | 1 | 4759 | import UIKit
let MasonryCollectionViewCellWidth: CGFloat = 254
class MasonryCollectionViewCell: ListingsCollectionViewCell {
private lazy var bidView: UIView = {
let view = UIView()
for subview in [self.currentBidLabel, self.numberOfBidsLabel] {
view.addSubview(subview)
subview.alignTopEdgeWithView(view, predicate:"13")
subview.alignBottomEdgeWithView(view, predicate:"0")
subview.constrainHeight("18")
}
self.currentBidLabel.alignLeadingEdgeWithView(view, predicate: "0")
self.numberOfBidsLabel.alignTrailingEdgeWithView(view, predicate: "0")
return view
}()
private lazy var cellSubviews: [UIView] = [self.artworkImageView, self.lotNumberLabel, self.artistNameLabel, self.artworkTitleLabel, self.estimateLabel, self.bidView, self.bidButton, self.moreInfoLabel]
private var artworkImageViewHeightConstraint: NSLayoutConstraint?
override func setup() {
super.setup()
contentView.constrainWidth("\(MasonryCollectionViewCellWidth)")
// Add subviews
for subview in cellSubviews {
self.contentView.addSubview(subview)
subview.alignLeading("0", trailing: "0", toView: self.contentView)
}
// Constrain subviews
artworkImageView.alignTop("0", bottom: nil, toView: contentView)
let lotNumberTopConstraint = lotNumberLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artworkImageView, predicate: "20").first as! NSLayoutConstraint
let artistNameTopConstraint = artistNameLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: lotNumberLabel, predicate: "10").first as! NSLayoutConstraint
artistNameLabel.constrainHeight("20")
artworkTitleLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artistNameLabel, predicate: "10")
artworkTitleLabel.constrainHeight("16")
estimateLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: artworkTitleLabel, predicate: "10")
estimateLabel.constrainHeight("16")
bidView.alignAttribute(.Top, toAttribute: .Bottom, ofView: estimateLabel, predicate: "13")
bidButton.alignAttribute(.Top, toAttribute: .Bottom, ofView: currentBidLabel, predicate: "13")
moreInfoLabel.alignAttribute(.Top, toAttribute: .Bottom, ofView: bidButton, predicate: "0")
moreInfoLabel.constrainHeight("44")
moreInfoLabel.alignAttribute(.Bottom, toAttribute: .Bottom, ofView: contentView, predicate: "12")
RACObserve(lotNumberLabel, "text").subscribeNext { (text) -> Void in
switch text as! String? {
case .Some(let text) where text.isEmpty:
fallthrough
case .None:
lotNumberTopConstraint.constant = 0
artistNameTopConstraint.constant = 20
default:
lotNumberTopConstraint.constant = 20
artistNameTopConstraint.constant = 10
}
}
// Bind subviews
viewModelSignal.subscribeNext { [weak self] (viewModel) -> Void in
let viewModel = viewModel as! SaleArtworkViewModel
if let artworkImageViewHeightConstraint = self?.artworkImageViewHeightConstraint {
self?.artworkImageView.removeConstraint(artworkImageViewHeightConstraint)
}
let imageHeight = heightForImageWithAspectRatio(viewModel.thumbnailAspectRatio)
self?.artworkImageViewHeightConstraint = self?.artworkImageView.constrainHeight("\(imageHeight)").first as? NSLayoutConstraint
self?.layoutIfNeeded()
}
}
override func layoutSubviews() {
super.layoutSubviews()
bidView.drawTopDottedBorderWithColor(.artsyMediumGrey())
}
}
extension MasonryCollectionViewCell {
class func heightForCellWithImageAspectRatio(aspectRatio: CGFloat?) -> CGFloat {
let imageHeight = heightForImageWithAspectRatio(aspectRatio)
let remainingHeight =
20 + // padding
20 + // artist name
10 + // padding
16 + // artwork name
10 + // padding
16 + // estimate
13 + // padding
13 + // padding
16 + // bid
13 + // padding
44 + // more info button
12 // padding
return imageHeight + ButtonHeight + CGFloat(remainingHeight)
}
}
private func heightForImageWithAspectRatio(aspectRatio: CGFloat?) -> CGFloat {
if let ratio = aspectRatio {
if ratio != 0 {
return CGFloat(MasonryCollectionViewCellWidth) / ratio
}
}
return CGFloat(MasonryCollectionViewCellWidth)
}
| mit |
rpitting/LGLinearFlow | Example/LGMagnifyingLinearFlowLayout/ViewController.swift | 1 | 4775 | //
// ViewController.swift
// LGLinearFlowViewSwift
//
// Created by Luka Gabric on 16/08/15.
// Copyright © 2015 Luka Gabric. All rights reserved.
//
import UIKit
import LGMagnifyingLinearFlowLayout
class ViewController: UIViewController {
// MARK: Vars
private var collectionViewLayout: LGMagnifyingLinearFlowLayout!
private var dataSource: Array<String>!
@IBOutlet private var collectionView: UICollectionView!
@IBOutlet private var nextButton: UIButton!
@IBOutlet private var previousButton: UIButton!
@IBOutlet private var pageControl: UIPageControl!
private var animationsCount = 0
private var pageWidth: CGFloat {
return self.collectionViewLayout.itemSize.width + self.collectionViewLayout.minimumLineSpacing
}
private var contentOffset: CGFloat {
return self.collectionView.contentOffset.x + self.collectionView.contentInset.left
}
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.configureDataSource()
self.configureCollectionView()
self.configurePageControl()
self.configureButtons()
}
// MARK: Configuration
private func configureDataSource() {
self.dataSource = Array()
for index in 1...10 {
self.dataSource.append("Page \(index)")
}
}
private func configureCollectionView() {
self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast
self.collectionView.registerNib(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionViewCell")
let layout = LGMagnifyingLinearFlowLayout()
layout.minimumLineSpacing = 0
layout.itemSize = CGSizeMake(180, 180)
self.collectionViewLayout = layout
self.collectionView.collectionViewLayout = layout
}
private func configurePageControl() {
self.pageControl.numberOfPages = self.dataSource.count
}
private func configureButtons() {
self.nextButton.enabled = self.dataSource.count > 0 && self.pageControl.currentPage < self.dataSource.count - 1
self.previousButton.enabled = self.pageControl.currentPage > 0
}
// MARK: Actions
@IBAction private func pageControlValueChanged(sender: AnyObject) {
self.scrollToPage(self.pageControl.currentPage, animated: true)
}
@IBAction private func nextButtonAction(sender: AnyObject) {
self.scrollToPage(self.pageControl.currentPage + 1, animated: true)
}
@IBAction private func previousButtonAction(sender: AnyObject) {
self.scrollToPage(self.pageControl.currentPage - 1, animated: true)
}
private func scrollToPage(page: Int, animated: Bool) {
self.collectionView.userInteractionEnabled = false
self.animationsCount += 1
let pageOffset = CGFloat(page) * self.pageWidth - self.collectionView.contentInset.left
self.collectionView.setContentOffset(CGPointMake(pageOffset, 0), animated: true)
self.pageControl.currentPage = page
self.configureButtons()
}
}
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataSource.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let collectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
collectionViewCell.pageLabel.text = self.dataSource[indexPath.row]
return collectionViewCell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if collectionView.dragging || collectionView.decelerating || collectionView.tracking {
return
}
let selectedPage = indexPath.row
if selectedPage == self.pageControl.currentPage {
NSLog("Did select center item")
}
else {
self.scrollToPage(selectedPage, animated: true)
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
self.pageControl.currentPage = Int(self.contentOffset / self.pageWidth)
self.configureButtons()
}
func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
self.animationsCount -= 1
if self.animationsCount == 0 {
self.collectionView.userInteractionEnabled = true
}
}
}
| mit |
thomasvl/swift-protobuf | Tests/SwiftProtobufTests/unittest_swift_extension4.pb.swift | 4 | 11998 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: unittest_swift_extension4.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
// Protos/unittest_swift_extension4.proto - test proto
//
// 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
//
// -----------------------------------------------------------------------------
///
/// Test naming of extensions that differ only in proto package. This is a
/// clone of unittest_swift_extension[23].proto, but with a different proto
/// package, different extension numbers, and a Swift prefix option.
///
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobufCore
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobufCore.ProtobufAPIVersionCheck {
struct _3: SwiftProtobufCore.ProtobufAPIVersion_3 {}
typealias Version = _3
}
struct Ext4MyMessage {
// SwiftProtobufCore.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobufCore.UnknownStorage()
struct C {
// SwiftProtobufCore.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var c: Int64 {
get {return _c ?? 0}
set {_c = newValue}
}
/// Returns true if `c` has been explicitly set.
var hasC: Bool {return self._c != nil}
/// Clears the value of `c`. Subsequent reads from it will return its default value.
mutating func clearC() {self._c = nil}
var unknownFields = SwiftProtobufCore.UnknownStorage()
init() {}
fileprivate var _c: Int64? = nil
}
init() {}
}
struct Ext4C {
// SwiftProtobufCore.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var c: Int64 {
get {return _c ?? 0}
set {_c = newValue}
}
/// Returns true if `c` has been explicitly set.
var hasC: Bool {return self._c != nil}
/// Clears the value of `c`. Subsequent reads from it will return its default value.
mutating func clearC() {self._c = nil}
var unknownFields = SwiftProtobufCore.UnknownStorage()
init() {}
fileprivate var _c: Int64? = nil
}
#if swift(>=5.5) && canImport(_Concurrency)
extension Ext4MyMessage: @unchecked Sendable {}
extension Ext4MyMessage.C: @unchecked Sendable {}
extension Ext4C: @unchecked Sendable {}
#endif // swift(>=5.5) && canImport(_Concurrency)
// MARK: - Extension support defined in unittest_swift_extension4.proto.
// MARK: - Extension Properties
// Swift Extensions on the exteneded Messages to add easy access to the declared
// extension fields. The names are based on the extension field name from the proto
// declaration. To avoid naming collisions, the names are prefixed with the name of
// the scope where the extend directive occurs.
extension ProtobufUnittest_Extend_Foo.Bar.Baz {
var Ext4b: String {
get {return getExtensionValue(ext: Ext4Extensions_b) ?? String()}
set {setExtensionValue(ext: Ext4Extensions_b, value: newValue)}
}
/// Returns true if extension `Ext4Extensions_b`
/// has been explicitly set.
var hasExt4b: Bool {
return hasExtensionValue(ext: Ext4Extensions_b)
}
/// Clears the value of extension `Ext4Extensions_b`.
/// Subsequent reads from it will return its default value.
mutating func clearExt4b() {
clearExtensionValue(ext: Ext4Extensions_b)
}
var Ext4c: Ext4C {
get {return getExtensionValue(ext: Ext4Extensions_C) ?? Ext4C()}
set {setExtensionValue(ext: Ext4Extensions_C, value: newValue)}
}
/// Returns true if extension `Ext4Extensions_C`
/// has been explicitly set.
var hasExt4c: Bool {
return hasExtensionValue(ext: Ext4Extensions_C)
}
/// Clears the value of extension `Ext4Extensions_C`.
/// Subsequent reads from it will return its default value.
mutating func clearExt4c() {
clearExtensionValue(ext: Ext4Extensions_C)
}
var Ext4MyMessage_b: String {
get {return getExtensionValue(ext: Ext4MyMessage.Extensions.b) ?? String()}
set {setExtensionValue(ext: Ext4MyMessage.Extensions.b, value: newValue)}
}
/// Returns true if extension `Ext4MyMessage.Extensions.b`
/// has been explicitly set.
var hasExt4MyMessage_b: Bool {
return hasExtensionValue(ext: Ext4MyMessage.Extensions.b)
}
/// Clears the value of extension `Ext4MyMessage.Extensions.b`.
/// Subsequent reads from it will return its default value.
mutating func clearExt4MyMessage_b() {
clearExtensionValue(ext: Ext4MyMessage.Extensions.b)
}
var Ext4MyMessage_c: Ext4MyMessage.C {
get {return getExtensionValue(ext: Ext4MyMessage.Extensions.C) ?? Ext4MyMessage.C()}
set {setExtensionValue(ext: Ext4MyMessage.Extensions.C, value: newValue)}
}
/// Returns true if extension `Ext4MyMessage.Extensions.C`
/// has been explicitly set.
var hasExt4MyMessage_c: Bool {
return hasExtensionValue(ext: Ext4MyMessage.Extensions.C)
}
/// Clears the value of extension `Ext4MyMessage.Extensions.C`.
/// Subsequent reads from it will return its default value.
mutating func clearExt4MyMessage_c() {
clearExtensionValue(ext: Ext4MyMessage.Extensions.C)
}
}
// MARK: - File's ExtensionMap: Ext4UnittestSwiftExtension4_Extensions
/// A `SwiftProtobuf.SimpleExtensionMap` that includes all of the extensions defined by
/// this .proto file. It can be used any place an `SwiftProtobuf.ExtensionMap` is needed
/// in parsing, or it can be combined with other `SwiftProtobuf.SimpleExtensionMap`s to create
/// a larger `SwiftProtobuf.SimpleExtensionMap`.
let Ext4UnittestSwiftExtension4_Extensions: SwiftProtobufCore.SimpleExtensionMap = [
Ext4Extensions_b,
Ext4Extensions_C,
Ext4MyMessage.Extensions.b,
Ext4MyMessage.Extensions.C
]
// Extension Objects - The only reason these might be needed is when manually
// constructing a `SimpleExtensionMap`, otherwise, use the above _Extension Properties_
// accessors for the extension fields on the messages directly.
let Ext4Extensions_b = SwiftProtobufCore.MessageExtension<SwiftProtobufCore.OptionalExtensionField<SwiftProtobufCore.ProtobufString>, ProtobufUnittest_Extend_Foo.Bar.Baz>(
_protobuf_fieldNumber: 420,
fieldName: "protobuf_unittest.extend4.b"
)
let Ext4Extensions_C = SwiftProtobufCore.MessageExtension<SwiftProtobufCore.OptionalGroupExtensionField<Ext4C>, ProtobufUnittest_Extend_Foo.Bar.Baz>(
_protobuf_fieldNumber: 421,
fieldName: "protobuf_unittest.extend4.c"
)
extension Ext4MyMessage {
enum Extensions {
static let b = SwiftProtobufCore.MessageExtension<SwiftProtobufCore.OptionalExtensionField<SwiftProtobufCore.ProtobufString>, ProtobufUnittest_Extend_Foo.Bar.Baz>(
_protobuf_fieldNumber: 410,
fieldName: "protobuf_unittest.extend4.MyMessage.b"
)
static let C = SwiftProtobufCore.MessageExtension<SwiftProtobufCore.OptionalGroupExtensionField<Ext4MyMessage.C>, ProtobufUnittest_Extend_Foo.Bar.Baz>(
_protobuf_fieldNumber: 411,
fieldName: "protobuf_unittest.extend4.MyMessage.c"
)
}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "protobuf_unittest.extend4"
extension Ext4MyMessage: SwiftProtobufCore.Message, SwiftProtobufCore._MessageImplementationBase, SwiftProtobufCore._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MyMessage"
static let _protobuf_nameMap = SwiftProtobufCore._NameMap()
mutating func decodeMessage<D: SwiftProtobufCore.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobufCore.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Ext4MyMessage, rhs: Ext4MyMessage) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Ext4MyMessage.C: SwiftProtobufCore.Message, SwiftProtobufCore._MessageImplementationBase, SwiftProtobufCore._ProtoNameProviding {
static let protoMessageName: String = Ext4MyMessage.protoMessageName + ".C"
static let _protobuf_nameMap: SwiftProtobufCore._NameMap = [
1410: .same(proto: "c"),
]
mutating func decodeMessage<D: SwiftProtobufCore.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1410: try { try decoder.decodeSingularInt64Field(value: &self._c) }()
default: break
}
}
}
func traverse<V: SwiftProtobufCore.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
try { if let v = self._c {
try visitor.visitSingularInt64Field(value: v, fieldNumber: 1410)
} }()
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Ext4MyMessage.C, rhs: Ext4MyMessage.C) -> Bool {
if lhs._c != rhs._c {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Ext4C: SwiftProtobufCore.Message, SwiftProtobufCore._MessageImplementationBase, SwiftProtobufCore._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".C"
static let _protobuf_nameMap: SwiftProtobufCore._NameMap = [
1420: .same(proto: "c"),
]
mutating func decodeMessage<D: SwiftProtobufCore.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1420: try { try decoder.decodeSingularInt64Field(value: &self._c) }()
default: break
}
}
}
func traverse<V: SwiftProtobufCore.Visitor>(visitor: inout V) throws {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every if/case branch local when no optimizations
// are enabled. https://github.com/apple/swift-protobuf/issues/1034 and
// https://github.com/apple/swift-protobuf/issues/1182
try { if let v = self._c {
try visitor.visitSingularInt64Field(value: v, fieldNumber: 1420)
} }()
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Ext4C, rhs: Ext4C) -> Bool {
if lhs._c != rhs._c {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| apache-2.0 |
michaelvu812/MVFetchedResultsController | MVFetchedResultsController/MVFetchedResultsController.swift | 1 | 6260 | //
// MVFetchedResultsController.swift
// MVFetchedResultsController
//
// Created by Michael on 1/7/14.
// Copyright (c) 2014 Michael Vu. All rights reserved.
//
import UIKit
import CoreData
class MVFetchedResultsController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {
var context: NSManagedObjectContext = AppDelegate().managedObjectContext
var fetchSize: Int = 5
var sortDescriptor: NSSortDescriptor = NSSortDescriptor()
var entityName: String = String() {
didSet {
initFetchedResultsController()
}
}
var tableView: UITableView = UITableView()
var tableFrame: CGRect = CGRectZero {
didSet {
tableView.frame = tableFrame
}
}
var tableBackgroundColor: UIColor = UIColor.clearColor() {
didSet {
tableView.backgroundColor = tableBackgroundColor
}
}
var separatorColor: UIColor = UIColor.colorWithHexString("#bbbbbb") {
didSet {
tableView.separatorColor = separatorColor
}
}
var fetchedResultsController: NSFetchedResultsController = NSFetchedResultsController() {
didSet {
if (fetchedResultsController != oldValue) {
fetchedResultsController.delegate = self;
if (fetchedResultsController.isKindOfClass(NSFetchedResultsController)) {
self.performFetchResults()
} else {
self.tableView.reloadData()
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
self.tableView.backgroundColor = tableBackgroundColor
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.showsHorizontalScrollIndicator = false
self.tableView.showsVerticalScrollIndicator = false
self.tableView.separatorColor = self.separatorColor
self.tableView.separatorStyle = .SingleLine
self.tableView.separatorInset = UIEdgeInsetsZero
self.view.addSubview(self.tableView)
self.tableView.reloadData()
}
override func loadView() {
super.loadView()
if CGRectEqualToRect(self.tableView.frame, CGRectZero) {
if CGRectEqualToRect(self.tableFrame, CGRectZero) {
self.tableView.frame = self.view.frame
} else {
self.tableView.frame = self.tableFrame
}
}
}
func initFetchedResultsController() {
var fetchRequest: NSFetchRequest = NSFetchRequest(entityName: entityName)
fetchRequest.fetchBatchSize = fetchSize
if sortDescriptor != nil {
fetchRequest.sortDescriptors = [sortDescriptor]
}
self.fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
}
func performFetchResults() {
if (self.fetchedResultsController.isKindOfClass(NSFetchedResultsController)) {
var error: NSError?
self.fetchedResultsController.performFetch(&error)
}
self.tableView.reloadData()
}
func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
if fetchedResultsController.sections != nil {
return fetchedResultsController.sections.count
}
return 1
}
func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
var rows = 0
if (fetchedResultsController.sections != nil && fetchedResultsController.sections.count > 0) {
rows = fetchedResultsController.sections[section].numberOfObjects
}
return rows
}
func tableView(tableView:UITableView!, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! {
return nil
}
func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
return true
}
func controllerWillChangeContent(controller: NSFetchedResultsController!) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController!, didChangeSection sectionInfo: NSFetchedResultsSectionInfo!, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case NSFetchedResultsChangeInsert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Fade)
break
case NSFetchedResultsChangeDelete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: UITableViewRowAnimation.Fade)
break
default:
break
}
}
func controller(controller: NSFetchedResultsController!, didChangeObject anObject: AnyObject!, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath : NSIndexPath!) {
switch type {
case NSFetchedResultsChangeInsert:
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
break
case NSFetchedResultsChangeDelete:
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
break
case NSFetchedResultsChangeUpdate:
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
break
case NSFetchedResultsChangeMove:
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
break
default:
break
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController!) {
self.tableView.endUpdates()
}
}
| mit |
spromicky/UICollectionViewAnimatedTransition | CollectionTransitions/src/transition/TransitionAnimator.swift | 1 | 3152 | //
// TransitionAnimator.swift
// CollectionTransitions
//
// Created by Nick on 1/7/16.
// Copyright © 2016 spromicky. All rights reserved.
//
import Foundation
import UIKit
class TransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
let reverse: Bool
init(reverse: Bool) {
self.reverse = reverse
super.init()
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
let defaultTime = 0.32
guard reverse else { return defaultTime }
guard let transitionContext = transitionContext else { return defaultTime }
guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as? DetailViewController else { return defaultTime }
guard let collectionView = fromVC.collectionView else { return defaultTime }
let containFirstItem = collectionView.visibleCells().lazy.map { collectionView.indexPathForCell($0) }.contains { $0?.item == 0 }
return containFirstItem ? defaultTime : 0.82
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) else { return }
guard let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else { return }
guard let masterVC = (reverse ? toVC : fromVC) as? MasterViewController else { return }
guard let detailVC = (reverse ? fromVC : toVC) as? DetailViewController else { return }
guard let containerView = transitionContext.containerView() else { return }
containerView.addSubview(toVC.view)
if reverse {
containerView.addSubview(fromVC.view)
} else {
toVC.view.frame = transitionContext.finalFrameForViewController(toVC)
toVC.view.layoutIfNeeded()
}
if !reverse {
detailVC.collectionView?.backgroundColor = .clearColor()
}
let cell = masterVC.collectionView?.cellForItemAtIndexPath(masterVC.selectedIndex) as! MasterCell
cell.colorViews.forEach { $0.alpha = 0 }
detailVC.flowLayout.toStartPosition = reverse
detailVC.collectionView?.performBatchUpdates({
detailVC.collectionView?.collectionViewLayout.invalidateLayout()
}, completion:nil)
let invalidateTime = 0.32
UIView.animateWithDuration(invalidateTime, animations: {
detailVC.collectionView?.backgroundColor = self.reverse ? .clearColor() : masterVC.collectionView?.backgroundColor
}) { _ in
cell.colorViews.forEach { $0.alpha = 1 }
UIView.animateWithDuration(self.transitionDuration(transitionContext) - invalidateTime, animations: {
guard self.reverse else { return }
fromVC.view.alpha = 0
}) { _ in
fromVC.view.removeFromSuperview()
transitionContext.completeTransition(true)
}
}
}
}
| mit |
noppefoxwolf/TVUploader-iOS | TVUploader/STTwitter/Classes/Video.swift | 1 | 246 | //
// Video.swift
// Pods
//
// Created by Tomoya Hirano on 2016/08/30.
//
//
import Foundation
import Unbox
internal struct Video: Unboxable {
var videoType = ""
init(unboxer: Unboxer) {
videoType = unboxer.unbox("video_type")
}
} | mit |
loudnate/LoopKit | LoopKitTests/CarbStoreTests.swift | 1 | 18751 | //
// CarbStoreTests.swift
// LoopKitTests
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import XCTest
import HealthKit
import CoreData
@testable import LoopKit
class CarbStoreTests: PersistenceControllerTestCase, CarbStoreSyncDelegate {
var carbStore: CarbStore!
var healthStore: HKHealthStoreMock!
override func setUp() {
super.setUp()
healthStore = HKHealthStoreMock()
carbStore = CarbStore(healthStore: healthStore, cacheStore: cacheStore)
carbStore.testQueryStore = healthStore
carbStore.syncDelegate = self
}
override func tearDown() {
carbStore.syncDelegate = nil
carbStore = nil
healthStore = nil
uploadMessages = []
deleteMessages = []
uploadHandler = nil
deleteHandler = nil
super.tearDown()
}
// MARK: - CarbStoreSyncDelegate
var uploadMessages: [(entries: [StoredCarbEntry], completion: ([StoredCarbEntry]) -> Void)] = []
var uploadHandler: ((_: [StoredCarbEntry], _: ([StoredCarbEntry]) -> Void) -> Void)?
func carbStore(_ carbStore: CarbStore, hasEntriesNeedingUpload entries: [StoredCarbEntry], completion: @escaping ([StoredCarbEntry]) -> Void) {
uploadMessages.append((entries: entries, completion: completion))
uploadHandler?(entries, completion)
}
var deleteMessages: [(entries: [DeletedCarbEntry], completion: ([DeletedCarbEntry]) -> Void)] = []
var deleteHandler: ((_: [DeletedCarbEntry], _: ([DeletedCarbEntry]) -> Void) -> Void)?
func carbStore(_ carbStore: CarbStore, hasDeletedEntries entries: [DeletedCarbEntry], completion: @escaping ([DeletedCarbEntry]) -> Void) {
deleteMessages.append((entries: entries, completion: completion))
deleteHandler?(entries, completion)
}
// MARK: -
/// Adds a new entry, validates its uploading/uploaded transition
func testAddAndSyncSuccessful() {
let entry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3))
let addCarb = expectation(description: "Add carb entry")
let uploading = expectation(description: "Sync delegate: upload")
let uploaded = expectation(description: "Sync delegate: completed")
// 2. assert sync delegate called
uploadHandler = { (entries, completion) in
XCTAssertEqual(1, entries.count)
// 3. assert entered in db as uploading
self.cacheStore.managedObjectContext.performAndWait {
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(1, objects.count)
XCTAssertEqual(.uploading, objects.first!.uploadState)
}
uploading.fulfill()
var entry = entries.first!
entry.externalID = "1234"
entry.isUploaded = true
completion([entry])
// 4. call delegate completion
self.cacheStore.managedObjectContext.performAndWait {
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
// 5. assert entered in db as uploaded
XCTAssertEqual(.uploaded, objects.first!.uploadState)
uploaded.fulfill()
}
}
// 1. Add carb
carbStore.addCarbEntry(entry) { (result) in
addCarb.fulfill()
}
wait(for: [addCarb, uploading, uploaded], timeout: 2, enforceOrder: true)
}
/// Adds a new entry, validates its uploading/notUploaded transition
func testAddAndSyncFailed() {
let entry = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3))
let addCarb = expectation(description: "Add carb entry")
let uploading = expectation(description: "Sync delegate: upload")
let uploaded = expectation(description: "Sync delegate: completed")
// 2. assert sync delegate called
uploadHandler = { (entries, completion) in
XCTAssertEqual(1, entries.count)
// 3. assert entered in db as uploading
self.cacheStore.managedObjectContext.performAndWait {
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(1, objects.count)
XCTAssertEqual(.uploading, objects.first!.uploadState)
}
uploading.fulfill()
completion(entries) // Not uploaded
// 4. call delegate completion
self.cacheStore.managedObjectContext.performAndWait {
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
// 5. assert entered in db as not uploaded
XCTAssertEqual(.notUploaded, objects.first!.uploadState)
uploaded.fulfill()
}
}
// 1. Add carb
carbStore.addCarbEntry(entry) { (result) in
addCarb.fulfill()
}
wait(for: [addCarb, uploading, uploaded], timeout: 2, enforceOrder: true)
}
/// Adds two entries, validating their transition as the delegate calls completion out-of-order
func testAddAndSyncInterleve() {
let entry1 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3))
let entry2 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3))
let addCarb1 = expectation(description: "Add carb entry")
let addCarb2 = expectation(description: "Add carb entry")
let uploading1 = expectation(description: "Sync delegate: upload")
let uploading2 = expectation(description: "Sync delegate: upload")
let uploaded = expectation(description: "Sync delegate: completed")
uploaded.expectedFulfillmentCount = 2
// 2. assert sync delegate called
uploadHandler = { (entries, completion) in
XCTAssertEqual(1, entries.count)
// 3. assert entered in db as uploading
self.cacheStore.managedObjectContext.performAndWait {
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(self.uploadMessages.count, objects.count)
for object in objects {
XCTAssertEqual(.uploading, object.uploadState)
}
}
switch self.uploadMessages.count {
case 1:
uploading1.fulfill()
self.carbStore.addCarbEntry(entry2) { (result) in
addCarb2.fulfill()
}
case 2:
uploading2.fulfill()
for index in (0...1).reversed() {
var entry = self.uploadMessages[index].entries.first!
entry.externalID = "\(index)"
entry.isUploaded = true
self.uploadMessages[index].completion([entry])
// 4. call delegate completion
self.cacheStore.managedObjectContext.performAndWait {
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
for object in objects {
if object.externalID == "\(index)" {
XCTAssertEqual(.uploaded, object.uploadState)
}
}
uploaded.fulfill()
}
}
default:
XCTFail()
}
}
// 1. Add carb 1
carbStore.addCarbEntry(entry1) { (result) in
addCarb1.fulfill()
}
wait(for: [addCarb1, uploading1, addCarb2, uploading2, uploaded], timeout: 2, enforceOrder: true)
}
/// Adds an entry with a failed upload, validates its requested again for sync on next entry
func testAddAndSyncMultipleCallbacks() {
let entry1 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3))
let entry2 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3))
let addCarb1 = expectation(description: "Add carb entry")
let addCarb2 = expectation(description: "Add carb entry")
let uploading1 = expectation(description: "Sync delegate: upload")
let uploading2 = expectation(description: "Sync delegate: upload")
let uploaded = expectation(description: "Sync delegate: completed")
uploaded.expectedFulfillmentCount = 2
// 2. assert sync delegate called
uploadHandler = { (entries, completion) in
// 3. assert entered in db as uploading
self.cacheStore.managedObjectContext.performAndWait {
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(self.uploadMessages.count, objects.count)
for object in objects {
XCTAssertEqual(.uploading, object.uploadState)
}
}
switch self.uploadMessages.count {
case 1:
XCTAssertEqual(1, entries.count)
uploading1.fulfill()
completion(entries) // Not uploaded
self.carbStore.addCarbEntry(entry2) { (result) in
addCarb2.fulfill()
}
case 2:
XCTAssertEqual(2, entries.count)
uploading2.fulfill()
for index in (0...1).reversed() {
var entry = self.uploadMessages[index].entries.first!
entry.externalID = "\(index)"
entry.isUploaded = true
self.uploadMessages[index].completion([entry])
// 4. call delegate completion
self.cacheStore.managedObjectContext.performAndWait {
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
for object in objects {
if object.externalID == "\(index)" {
XCTAssertEqual(.uploaded, object.uploadState)
}
}
uploaded.fulfill()
}
}
default:
XCTFail()
}
}
// 1. Add carb 1
carbStore.addCarbEntry(entry1) { (result) in
addCarb1.fulfill()
}
wait(for: [addCarb1, uploading1, addCarb2, uploading2, uploaded], timeout: 2, enforceOrder: true)
}
/// Adds and uploads an entry, then modifies it and validates its re-upload
func testModifyUploadedCarb() {
let entry1 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3))
let entry2 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 15), startDate: Date(), foodType: nil, absorptionTime: .hours(3))
let sample2 = HKQuantitySample(type: carbStore.sampleType as! HKQuantityType, quantity: entry2.quantity, start: entry2.startDate, end: entry2.endDate)
let addCarb1 = expectation(description: "Add carb entry")
let addCarb2 = expectation(description: "Add carb entry")
let uploading1 = expectation(description: "Sync delegate: upload")
let uploading2 = expectation(description: "Sync delegate: upload")
let uploaded = expectation(description: "Sync delegate: completed")
var lastUUID: UUID?
// 2. assert sync delegate called
uploadHandler = { (entries, completion) in
// 3. assert entered in db as uploading
self.cacheStore.managedObjectContext.performAndWait {
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(1, objects.count)
XCTAssertEqual(.uploading, objects[0].uploadState)
if let lastUUID = lastUUID {
XCTAssertNotEqual(lastUUID, objects[0].uuid)
}
lastUUID = objects[0].uuid
}
switch self.uploadMessages.count {
case 1:
XCTAssertEqual(1, entries.count)
uploading1.fulfill()
var entry = entries.first!
entry.externalID = "1234"
entry.isUploaded = true
completion([entry])
self.healthStore.queryResults = (samples: [sample2], error: nil)
self.carbStore.replaceCarbEntry(entries.first!, withEntry: entry2) { (result) in
addCarb2.fulfill()
self.healthStore.queryResults = nil
}
case 2:
XCTAssertEqual(1, entries.count)
XCTAssertEqual("1234", entries.first!.externalID)
XCTAssertFalse(entries.first!.isUploaded)
uploading2.fulfill()
var entry = entries.first!
entry.isUploaded = true
completion([entry])
// 4. call delegate completion
self.cacheStore.managedObjectContext.performAndWait {
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(1, objects.count)
for object in objects {
XCTAssertEqual(.uploaded, object.uploadState)
}
uploaded.fulfill()
}
default:
XCTFail()
}
}
deleteHandler = { (entries, completion) in
XCTFail()
}
// 1. Add carb 1
carbStore.addCarbEntry(entry1) { (result) in
addCarb1.fulfill()
}
wait(for: [addCarb1, uploading1, addCarb2, uploading2, uploaded], timeout: 2, enforceOrder: true)
}
/// Adds an entry, modifying it before upload completes, validating the delegate is then asked to delete it
func testModifyNotUploadedCarb() {
let entry1 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 10), startDate: Date(), foodType: nil, absorptionTime: .hours(3))
let entry2 = NewCarbEntry(quantity: HKQuantity(unit: .gram(), doubleValue: 15), startDate: Date(), foodType: nil, absorptionTime: .hours(3))
let sample2 = HKQuantitySample(type: carbStore.sampleType as! HKQuantityType, quantity: entry2.quantity, start: entry2.startDate, end: entry2.endDate)
let addCarb1 = expectation(description: "Add carb entry")
let addCarb2 = expectation(description: "Add carb entry")
let uploading1 = expectation(description: "Sync delegate: upload")
let uploading2 = expectation(description: "Sync delegate: upload")
let uploaded = expectation(description: "Sync delegate: completed")
let deleted = expectation(description: "Sync delegate: deleted")
// 2. assert sync delegate called
uploadHandler = { (entries, completion) in
// 3. assert entered in db as uploading
self.cacheStore.managedObjectContext.performAndWait {
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(1, objects.count)
for object in objects {
XCTAssertEqual(.uploading, object.uploadState)
}
}
switch self.uploadMessages.count {
case 1:
XCTAssertEqual(1, entries.count)
uploading1.fulfill()
self.healthStore.queryResults = (samples: [sample2], error: nil)
self.carbStore.replaceCarbEntry(entries.first!, withEntry: entry2) { (result) in
addCarb2.fulfill()
self.healthStore.queryResults = nil
}
case 2:
XCTAssertEqual(1, entries.count)
XCTAssertNil(entries.first!.externalID)
XCTAssertFalse(entries.first!.isUploaded)
uploading2.fulfill()
var entry = entries.first!
entry.externalID = "1234"
entry.isUploaded = true
completion([entry])
entry = self.uploadMessages[0].entries.first!
entry.externalID = "5678"
entry.isUploaded = true
self.uploadMessages[0].completion([entry])
// 4. call delegate completion
self.cacheStore.managedObjectContext.performAndWait {
let objects: [CachedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(1, objects.count)
for object in objects {
XCTAssertEqual("1234", object.externalID)
XCTAssertEqual(.uploaded, object.uploadState)
}
uploaded.fulfill()
}
default:
XCTFail()
}
}
deleteHandler = { (entries, completion) in
XCTAssertEqual(1, entries.count)
var entry = entries[0]
XCTAssertEqual("5678", entry.externalID)
XCTAssertFalse(entry.isUploaded)
self.cacheStore.managedObjectContext.performAndWait {
let objects: [DeletedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(1, objects.count)
for object in objects {
XCTAssertEqual("5678", object.externalID)
XCTAssertEqual(.uploading, object.uploadState)
}
}
entry.isUploaded = true
completion([entry])
self.cacheStore.managedObjectContext.performAndWait {
let objects: [DeletedCarbObject] = self.cacheStore.managedObjectContext.all()
XCTAssertEqual(0, objects.count)
}
deleted.fulfill()
}
// 1. Add carb 1
carbStore.addCarbEntry(entry1) { (result) in
addCarb1.fulfill()
}
wait(for: [addCarb1, uploading1, addCarb2, uploading2, uploaded, deleted], timeout: 2, enforceOrder: true)
}
}
| mit |
blitzagency/amigo-swift | Amigo/Compiler.swift | 1 | 676 | //
// Compiler.swift
// Amigo
//
// Created by Adam Venturella on 7/7/15.
// Copyright © 2015 BLITZ. All rights reserved.
//
import Foundation
public protocol Compiler{
func compile(expression: CreateTable) -> String
func compile(expression: CreateColumn) -> String
func compile(expression: CreateIndex) -> String
func compile(expression: Join) -> String
func compile(expression: Select) -> String
func compile(expression: Insert) -> String
func compile(expression: Update) -> String
func compile(expression: Delete) -> String
func compile(expression: NSPredicate, table: Table, models: [String: ORMModel]) -> (String, [AnyObject])
} | mit |
phatblat/realm-cocoa | RealmSwift/ObjectiveCSupport+Sync.swift | 2 | 2381 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// 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 Realm
/**
:nodoc:
**/
public extension ObjectiveCSupport {
/// Convert a `SyncConfiguration` to a `RLMSyncConfiguration`.
static func convert(object: SyncConfiguration) -> RLMSyncConfiguration {
return object.asConfig()
}
/// Convert a `RLMSyncConfiguration` to a `SyncConfiguration`.
static func convert(object: RLMSyncConfiguration) -> SyncConfiguration {
return SyncConfiguration(config: object)
}
/// Convert a `Credentials` to a `RLMCredentials`
static func convert(object: Credentials) -> RLMCredentials {
switch object {
case .facebook(let accessToken):
return RLMCredentials(facebookToken: accessToken)
case .google(let serverAuthCode):
return RLMCredentials(googleAuthCode: serverAuthCode)
case .googleId(let token):
return RLMCredentials(googleIdToken: token)
case .apple(let idToken):
return RLMCredentials(appleToken: idToken)
case .emailPassword(let email, let password):
return RLMCredentials(email: email, password: password)
case .jwt(let token):
return RLMCredentials(jwt: token)
case .function(let payload):
return RLMCredentials(functionPayload: ObjectiveCSupport.convert(object: AnyBSON(payload)) as! [String: RLMBSON])
case .userAPIKey(let APIKey):
return RLMCredentials(userAPIKey: APIKey)
case .serverAPIKey(let serverAPIKey):
return RLMCredentials(serverAPIKey: serverAPIKey)
case .anonymous:
return RLMCredentials.anonymous()
}
}
}
| apache-2.0 |
lindydonna/azure-mobile-apps-quickstarts | client/iOS-Swift/ZUMOAPPNAME/ZUMOAPPNAME/ToDoTableViewController.swift | 1 | 10811 | // ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
import CoreData
class ToDoTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, ToDoItemDelegate {
var table : MSSyncTable?
var store : MSCoreDataStore?
lazy var fetchedResultController: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest(entityName: "TodoItem")
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
// show only non-completed items
fetchRequest.predicate = NSPredicate(format: "complete != true")
// sort by item text
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)]
// Note: if storing a lot of data, you should specify a cache for the last parameter
// for more information, see Apple's documentation: http://go.microsoft.com/fwlink/?LinkId=524591&clcid=0x409
let resultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
resultsController.delegate = self;
return resultsController
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let client = MSClient(applicationURLString: "ZUMOAPPURL")
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
self.store = MSCoreDataStore(managedObjectContext: managedObjectContext)
client.syncContext = MSSyncContext(delegate: nil, dataSource: self.store, callback: nil)
self.table = client.syncTableWithName("TodoItem")
self.refreshControl?.addTarget(self, action: "onRefresh:", forControlEvents: UIControlEvents.ValueChanged)
var error : NSError? = nil
do {
try self.fetchedResultController.performFetch()
} catch let error1 as NSError {
error = error1
print("Unresolved error \(error), \(error?.userInfo)")
abort()
}
// Refresh data on load
self.refreshControl?.beginRefreshing()
self.onRefresh(self.refreshControl)
}
func onRefresh(sender: UIRefreshControl!) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.table!.pullWithQuery(self.table?.query(), queryId: "AllRecords") {
(error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error != nil {
// A real application would handle various errors like network conditions,
// server conflicts, etc via the MSSyncContextDelegate
print("Error: \(error!.description)")
// We will just discard our changes and keep the servers copy for simplicity
if let opErrors = error!.userInfo[MSErrorPushResultKey] as? Array<MSTableOperationError> {
for opError in opErrors {
print("Attempted operation to item \(opError.itemId)")
if (opError.operation == .Insert || opError.operation == .Delete) {
print("Insert/Delete, failed discarding changes")
opError.cancelOperationAndDiscardItemWithCompletion(nil)
} else {
print("Update failed, reverting to server's copy")
opError.cancelOperationAndUpdateItem(opError.serverItem!, completion: nil)
}
}
}
}
self.refreshControl?.endRefreshing()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Table Controls
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle
{
return UITableViewCellEditingStyle.Delete
}
override func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String?
{
return "Complete"
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
let record = self.fetchedResultController.objectAtIndexPath(indexPath) as! NSManagedObject
var item = self.store!.tableItemFromManagedObject(record)
item["complete"] = true
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.table!.update(item) { (error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error != nil {
print("Error: \(error!.description)")
return
}
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if let sections = self.fetchedResultController.sections {
return sections[section].numberOfObjects
}
return 0;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellIdentifier = "Cell"
var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath)
cell = configureCell(cell, indexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) -> UITableViewCell {
let item = self.fetchedResultController.objectAtIndexPath(indexPath) as! NSManagedObject
// Set the label on the cell and make sure the label color is black (in case this cell
// has been reused and was previously greyed out
if let text = item.valueForKey("text") as? String {
cell.textLabel!.text = text
} else {
cell.textLabel!.text = "?"
}
cell.textLabel!.textColor = UIColor.blackColor()
return cell
}
// MARK: Navigation
@IBAction func addItem(sender : AnyObject) {
self.performSegueWithIdentifier("addItem", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
{
if segue.identifier == "addItem" {
let todoController = segue.destinationViewController as! ToDoItemViewController
todoController.delegate = self
}
}
// MARK: - ToDoItemDelegate
func didSaveItem(text: String)
{
if text.isEmpty {
return
}
// We set created at to now, so it will sort as we expect it to post the push/pull
let itemToInsert = ["text": text, "complete": false, "__createdAt": NSDate()]
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.table!.insert(itemToInsert) {
(item, error) in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
if error != nil {
print("Error: " + error!.description)
}
}
}
// MARK: - NSFetchedResultsDelegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.beginUpdates()
});
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let indexSectionSet = NSIndexSet(index: sectionIndex)
if type == .Insert {
self.tableView.insertSections(indexSectionSet, withRowAnimation: .Fade)
} else if type == .Delete {
self.tableView.deleteSections(indexSectionSet, withRowAnimation: .Fade)
}
})
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
switch type {
case .Insert:
self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Move:
self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Update:
// note: Apple samples show a call to configureCell here; this is incorrect--it can result in retrieving the
// wrong index when rows are reordered. For more information, see:
// http://go.microsoft.com/fwlink/?LinkID=524590&clcid=0x409
self.tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
}
})
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.endUpdates()
});
}
}
| apache-2.0 |
eggswift/ESTabBarController | Sources/ESTabBarItemContentView.swift | 1 | 16255 | //
// ESTabBarContentView.swift
//
// Created by Vincent Li on 2017/2/8.
// Copyright (c) 2013-2020 ESTabBarController (https://github.com/eggswift/ESTabBarController)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
public enum ESTabBarItemContentMode : Int {
case alwaysOriginal // Always set the original image size
case alwaysTemplate // Always set the image as a template image size
}
open class ESTabBarItemContentView: UIView {
// MARK: - PROPERTY SETTING
/// The title displayed on the item, default is `nil`
open var title: String? {
didSet {
self.titleLabel.text = title
self.updateLayout()
}
}
/// The image used to represent the item, default is `nil`
open var image: UIImage? {
didSet {
if !selected { self.updateDisplay() }
}
}
/// The image displayed when the tab bar item is selected, default is `nil`.
open var selectedImage: UIImage? {
didSet {
if selected { self.updateDisplay() }
}
}
/// A Boolean value indicating whether the item is enabled, default is `YES`.
open var enabled = true
/// A Boolean value indicating whether the item is selected, default is `NO`.
open var selected = false
/// A Boolean value indicating whether the item is highlighted, default is `NO`.
open var highlighted = false
/// Text color, default is `UIColor(white: 0.57254902, alpha: 1.0)`.
open var textColor = UIColor(white: 0.57254902, alpha: 1.0) {
didSet {
if !selected { titleLabel.textColor = textColor }
}
}
/// Text color when highlighted, default is `UIColor(red: 0.0, green: 0.47843137, blue: 1.0, alpha: 1.0)`.
open var highlightTextColor = UIColor(red: 0.0, green: 0.47843137, blue: 1.0, alpha: 1.0) {
didSet {
if selected { titleLabel.textColor = highlightTextColor }
}
}
/// Icon color, default is `UIColor(white: 0.57254902, alpha: 1.0)`.
open var iconColor = UIColor(white: 0.57254902, alpha: 1.0) {
didSet {
if !selected { imageView.tintColor = iconColor }
}
}
/// Icon color when highlighted, default is `UIColor(red: 0.0, green: 0.47843137, blue: 1.0, alpha: 1.0)`.
open var highlightIconColor = UIColor(red: 0.0, green: 0.47843137, blue: 1.0, alpha: 1.0) {
didSet {
if selected { imageView.tintColor = highlightIconColor }
}
}
/// Background color, default is `UIColor.clear`.
open var backdropColor = UIColor.clear {
didSet {
if !selected { backgroundColor = backdropColor }
}
}
/// Background color when highlighted, default is `UIColor.clear`.
open var highlightBackdropColor = UIColor.clear {
didSet {
if selected { backgroundColor = highlightBackdropColor }
}
}
/// Icon imageView renderingMode, default is `.alwaysTemplate`.
open var renderingMode: UIImage.RenderingMode = .alwaysTemplate {
didSet {
self.updateDisplay()
}
}
/// Item content mode, default is `.alwaysTemplate`
open var itemContentMode: ESTabBarItemContentMode = .alwaysTemplate {
didSet {
self.updateDisplay()
}
}
/// The offset to use to adjust the title position, default is `UIOffset.zero`.
open var titlePositionAdjustment: UIOffset = UIOffset.zero {
didSet {
self.updateLayout()
}
}
/// The insets that you use to determine the insets edge for contents, default is `UIEdgeInsets.zero`
open var insets = UIEdgeInsets.zero
{
didSet {
self.updateLayout()
}
}
open var imageView: UIImageView = {
let imageView = UIImageView.init(frame: CGRect.zero)
imageView.backgroundColor = .clear
return imageView
}()
open var titleLabel: UILabel = {
let titleLabel = UILabel.init(frame: CGRect.zero)
titleLabel.backgroundColor = .clear
titleLabel.textColor = .clear
titleLabel.textAlignment = .center
return titleLabel
}()
/// Badge value, default is `nil`.
open var badgeValue: String? {
didSet {
if let _ = badgeValue {
self.badgeView.badgeValue = badgeValue
self.addSubview(badgeView)
self.updateLayout()
} else {
// Remove when nil.
self.badgeView.removeFromSuperview()
}
badgeChanged(animated: true, completion: nil)
}
}
/// Badge color, default is `nil`.
open var badgeColor: UIColor? {
didSet {
if let _ = badgeColor {
self.badgeView.badgeColor = badgeColor
} else {
self.badgeView.badgeColor = ESTabBarItemBadgeView.defaultBadgeColor
}
}
}
/// Badge view, default is `ESTabBarItemBadgeView()`.
open var badgeView: ESTabBarItemBadgeView = ESTabBarItemBadgeView() {
willSet {
if let _ = badgeView.superview {
badgeView.removeFromSuperview()
}
}
didSet {
if let _ = badgeView.superview {
self.updateLayout()
}
}
}
/// Badge offset, default is `UIOffset(horizontal: 6.0, vertical: -22.0)`.
open var badgeOffset: UIOffset = UIOffset(horizontal: 6.0, vertical: -22.0) {
didSet {
if badgeOffset != oldValue {
self.updateLayout()
}
}
}
// MARK: -
public override init(frame: CGRect) {
super.init(frame: frame)
self.isUserInteractionEnabled = false
addSubview(imageView)
addSubview(titleLabel)
titleLabel.textColor = textColor
imageView.tintColor = iconColor
backgroundColor = backdropColor
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open func updateDisplay() {
imageView.image = (selected ? (selectedImage ?? image) : image)?.withRenderingMode(renderingMode)
imageView.tintColor = selected ? highlightIconColor : iconColor
titleLabel.textColor = selected ? highlightTextColor : textColor
backgroundColor = selected ? highlightBackdropColor : backdropColor
}
open func updateLayout() {
let w = self.bounds.size.width
let h = self.bounds.size.height
imageView.isHidden = (imageView.image == nil)
titleLabel.isHidden = (titleLabel.text == nil)
if self.itemContentMode == .alwaysTemplate {
var s: CGFloat = 0.0 // image size
var f: CGFloat = 0.0 // font
var isLandscape = false
if let keyWindow = UIApplication.shared.keyWindow {
isLandscape = keyWindow.bounds.width > keyWindow.bounds.height
}
let isWide = isLandscape || traitCollection.horizontalSizeClass == .regular // is landscape or regular
if #available(iOS 11.0, *), isWide {
s = UIScreen.main.scale == 3.0 ? 23.0 : 20.0
f = UIScreen.main.scale == 3.0 ? 13.0 : 12.0
} else {
s = 23.0
f = 10.0
}
if !imageView.isHidden && !titleLabel.isHidden {
titleLabel.font = UIFont.systemFont(ofSize: f)
titleLabel.sizeToFit()
if #available(iOS 11.0, *), isWide {
titleLabel.frame = CGRect.init(x: (w - titleLabel.bounds.size.width) / 2.0 + (UIScreen.main.scale == 3.0 ? 14.25 : 12.25) + titlePositionAdjustment.horizontal,
y: (h - titleLabel.bounds.size.height) / 2.0 + titlePositionAdjustment.vertical,
width: titleLabel.bounds.size.width,
height: titleLabel.bounds.size.height)
imageView.frame = CGRect.init(x: titleLabel.frame.origin.x - s - (UIScreen.main.scale == 3.0 ? 6.0 : 5.0),
y: (h - s) / 2.0,
width: s,
height: s)
} else {
titleLabel.frame = CGRect.init(x: (w - titleLabel.bounds.size.width) / 2.0 + titlePositionAdjustment.horizontal,
y: h - titleLabel.bounds.size.height - 1.0 + titlePositionAdjustment.vertical,
width: titleLabel.bounds.size.width,
height: titleLabel.bounds.size.height)
imageView.frame = CGRect.init(x: (w - s) / 2.0,
y: (h - s) / 2.0 - 6.0,
width: s,
height: s)
}
} else if !imageView.isHidden {
imageView.frame = CGRect.init(x: (w - s) / 2.0,
y: (h - s) / 2.0,
width: s,
height: s)
} else if !titleLabel.isHidden {
titleLabel.font = UIFont.systemFont(ofSize: f)
titleLabel.sizeToFit()
titleLabel.frame = CGRect.init(x: (w - titleLabel.bounds.size.width) / 2.0 + titlePositionAdjustment.horizontal,
y: (h - titleLabel.bounds.size.height) / 2.0 + titlePositionAdjustment.vertical,
width: titleLabel.bounds.size.width,
height: titleLabel.bounds.size.height)
}
if let _ = badgeView.superview {
let size = badgeView.sizeThatFits(self.frame.size)
if #available(iOS 11.0, *), isWide {
badgeView.frame = CGRect.init(origin: CGPoint.init(x: imageView.frame.midX - 3 + badgeOffset.horizontal, y: imageView.frame.midY + 3 + badgeOffset.vertical), size: size)
} else {
badgeView.frame = CGRect.init(origin: CGPoint.init(x: w / 2.0 + badgeOffset.horizontal, y: h / 2.0 + badgeOffset.vertical), size: size)
}
badgeView.setNeedsLayout()
}
} else {
if !imageView.isHidden && !titleLabel.isHidden {
titleLabel.sizeToFit()
imageView.sizeToFit()
titleLabel.frame = CGRect.init(x: (w - titleLabel.bounds.size.width) / 2.0 + titlePositionAdjustment.horizontal,
y: h - titleLabel.bounds.size.height - 1.0 + titlePositionAdjustment.vertical,
width: titleLabel.bounds.size.width,
height: titleLabel.bounds.size.height)
imageView.frame = CGRect.init(x: (w - imageView.bounds.size.width) / 2.0,
y: (h - imageView.bounds.size.height) / 2.0 - 6.0,
width: imageView.bounds.size.width,
height: imageView.bounds.size.height)
} else if !imageView.isHidden {
imageView.sizeToFit()
imageView.center = CGPoint.init(x: w / 2.0, y: h / 2.0)
} else if !titleLabel.isHidden {
titleLabel.sizeToFit()
titleLabel.center = CGPoint.init(x: w / 2.0, y: h / 2.0)
}
if let _ = badgeView.superview {
let size = badgeView.sizeThatFits(self.frame.size)
badgeView.frame = CGRect.init(origin: CGPoint.init(x: w / 2.0 + badgeOffset.horizontal, y: h / 2.0 + badgeOffset.vertical), size: size)
badgeView.setNeedsLayout()
}
}
}
// MARK: - INTERNAL METHODS
internal final func select(animated: Bool, completion: (() -> ())?) {
selected = true
if enabled && highlighted {
highlighted = false
dehighlightAnimation(animated: animated, completion: { [weak self] in
self?.updateDisplay()
self?.selectAnimation(animated: animated, completion: completion)
})
} else {
updateDisplay()
selectAnimation(animated: animated, completion: completion)
}
}
internal final func deselect(animated: Bool, completion: (() -> ())?) {
selected = false
updateDisplay()
self.deselectAnimation(animated: animated, completion: completion)
}
internal final func reselect(animated: Bool, completion: (() -> ())?) {
if selected == false {
select(animated: animated, completion: completion)
} else {
if enabled && highlighted {
highlighted = false
dehighlightAnimation(animated: animated, completion: { [weak self] in
self?.reselectAnimation(animated: animated, completion: completion)
})
} else {
reselectAnimation(animated: animated, completion: completion)
}
}
}
internal final func highlight(animated: Bool, completion: (() -> ())?) {
if !enabled {
return
}
if highlighted == true {
return
}
highlighted = true
self.highlightAnimation(animated: animated, completion: completion)
}
internal final func dehighlight(animated: Bool, completion: (() -> ())?) {
if !enabled {
return
}
if !highlighted {
return
}
highlighted = false
self.dehighlightAnimation(animated: animated, completion: completion)
}
internal func badgeChanged(animated: Bool, completion: (() -> ())?) {
self.badgeChangedAnimation(animated: animated, completion: completion)
}
// MARK: - ANIMATION METHODS
open func selectAnimation(animated: Bool, completion: (() -> ())?) {
completion?()
}
open func deselectAnimation(animated: Bool, completion: (() -> ())?) {
completion?()
}
open func reselectAnimation(animated: Bool, completion: (() -> ())?) {
completion?()
}
open func highlightAnimation(animated: Bool, completion: (() -> ())?) {
completion?()
}
open func dehighlightAnimation(animated: Bool, completion: (() -> ())?) {
completion?()
}
open func badgeChangedAnimation(animated: Bool, completion: (() -> ())?) {
completion?()
}
}
| mit |
SocialObjects-Software/AMSlideMenu | AMSlideMenuExample/AMSlideMenuExample/MainContainerViewController.swift | 1 | 565 | //
// MainContainerViewController.swift
// AMSlideMenuExample
//
// Created by Artur Mkrtchyan on 5/20/20.
// Copyright © 2020 Artur Mkrtchyan. All rights reserved.
//
import UIKit
import AMSlideMenu
class MainContainerViewController: AMSlideMenuMainViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
}
| mit |
Limon-O-O/Convex | Example/TabBarControllerConfig.swift | 1 | 1254 | //
// TabBarControllerConfig.swift
// Example
//
// Created by Limon on 3/19/16.
// Copyright © 2016 Convex. All rights reserved.
//
import UIKit
import Convex
class TabBarControllerConfig: NSObject {
let tabBarController: TabBarController
override init() {
let dict1 = [Constant.TabbarItemsTitleKey: "首页", Constant.TabbarItemsImageKey: "home_normal", Constant.TabbarItemsSelectedImageKey: "home_highlight"]
let dict2 = [Constant.TabbarItemsTitleKey: "设置", Constant.TabbarItemsImageKey: "message_normal", Constant.TabbarItemsSelectedImageKey: "message_highlight"]
let firstVC = ViewController()
let secondVC = ViewController()
secondVC.view.backgroundColor = UIColor.blueColor()
tabBarController = TabBarController(button: PlusCenterButton())
tabBarController.tabBarItemsAttributes = [dict1, dict2]
tabBarController.viewControllers = [firstVC, secondVC]
}
}
class BaseNavigationController: UINavigationController {
override func pushViewController(viewController: UIViewController, animated: Bool) {
viewController.hidesBottomBarWhenPushed = !viewControllers.isEmpty
super.pushViewController(viewController, animated: animated)
}
}
| mit |
sharkspeed/dororis | languages/swift/guide/20-nested-types.swift | 1 | 25843 | // import Foundation
// import os
// 20. Nested Types
// define utility classes and structures purely for use within the context of a more complex type
// Swift enables you to define nested types, whereby you nest supporting enumerations, classes, and structures within the definition of the type they support
// BlackJack 汉语名称是梅花杰克又名,又名“二十一点”
// 么点可当做1或11点,端看持有人如何运用;有人头的牌一律算10点;其他点与牌面所示相同。
// 20.1 Nested Types in Action
// The BlackJack structure contains two nested enumeration types called Suit and Rank.
struct BlackJackCard {
enum Suit: Character {
case spades = "♠", hearts = "♡", diamonds = "♢", clubs = "♣"
}
enum Rank: Int {
case two = 2, three, four, five, six, seven, eight, nine, ten
case jack, queen, king, ace
struct Values {
let first: Int, second: Int?
}
var values: Values { // A computed property with a getter but no setter is known as a read-only computed property.
switch self {
case .ace:
return Values(first: 1, second: 11)
case .jack, .queen, .king:
return Values(first: 10, second: nil)
default:
return Values(first: self.rawValue, second: nil) // the rank’s raw Int value
}
}
}
// properties and methods
let rank: Rank, suit: Suit // Memberwise Initializers for Structure Types.
var description: String {
var output = "suit is \(suit.rawValue),"
output += " value is \(rank.values.first)"
if let second = rank.values.second {
output += " or \(second)"
}
return output
}
}
let theAceOfSpades = BlackJackCard(rank: .ace, suit: .spades)
// Even though Rank and Suit are nested within BlackjackCard, their type can be inferred from context, and so the initialization of this instance is able to refer to the enumeration cases by their case names (.ace and .spades) alone
print("theAceOfSpades: \(theAceOfSpades.description)")
// 20.2 Referring to Nested Types
// use a nested type outside of its definition context
let heartsSymbol = BlackJackCard.Suit.hearts.rawValue
print("heartsSymbol is \(heartsSymbol)")
// 21. Extensions
// Extensions add new functionality to an existing class, structure, enumeration, or protocol type. include the ability to extend types for which you do not have access to the original source code
// Extensions in Swift can:
// Add computed instance properties and computed type properties
// Define instance methods and type methods
// Provide new initializers
// Define subscripts
// Define and use new nested types
// Make an existing type conform to a protocol
// can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of.
// Extensions can add new functionality to a type, but they cannot override existing functionality.
// 21.1 Extension Syntax
/*
extension SomeType {
new functionality to add to SomeType
}
*/
// An extension can extend an existing type to make it adopt one or more protocols.
/*
extension SomeType: SomeProtocol, AnotherProtocol {
implementation of protocol requirements
}
*/
// An extension can be used to extend an existing generic type or extend a generic type to conditionally add functionality
// 对一个类的扩展会影响已经创建的实例
// 21.2 Computed Properties
// add computed instance properties and computed type properties to existing types
// * adds five computed instance properties to Swift’s built-in Double type
extension Double {
// a Double value of 1.0 is considered to represent “one meter”
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
print("one inch is \(oneInch) meters")
let aMarathon = 42.km + 195.m
print("A marathon is \(aMarathon) meters long")
// Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.
// 21.3 Initializers
// to extend other types to accept your own custom types as initializer parameters, or to provide additional initialization options that were not included as part of the type’s original implementation
// can add new convenience initializers to a class, but they cannot add new designated initializers or deinitializers to a class
struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
}
// Rect 有默认初始化参数 Swift provides a default initializer for any structure or class that provides default values for all of its properties and does not provide at least one initializer itself
let defaultRect = Rect()
let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0), size: Size(width: 5.0, height: 5.0))
// extend the Rect structure to provide an additional initializer takes a specific center point and size
extension Rect {
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
let centerRect = Rect(center: Point(x: 4.0, y: 4.0), size: Size(width: 3.0, height: 3.0)) // 需要保证每个实例完全初始化
// 21.4 Methods
// add new instance methods and type methods to existing types 添加实例方法和类方法
// 给 Int 类型添加
extension Int {
func repetitions(task: () -> Void) {
for _ in 0..<self {
task()
}
}
}
// repetions(task:) takes a single argument of type() -> Void => a function that has no parameters and does not return a value
3.repetitions {
print("Hello!")
}
// 21.4.1 Mutating Instance Methods
// Structure and enumeration methods that modify self or its properties must mark the instance method as mutating, just like mutating methods from an original implementation.
extension Int {
mutating func square() {
self = self * self
}
}
var myInt = 3
myInt.square()
print("myInt square is \(myInt)")
// 21.5 Subscripts
// add new subscripts to an existing type
// 123456789[0] returns 9
// 123456789[1] returns 8
extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 0..<digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
print("271828[0] is \(271828[0])")
print("271828[3] is \(271828[3])")
print("271828[5] is \(271828[15])")
// 21.6 Nested Types
// add new nested types
extension Int {
enum Kind {
case negative, zero, positive
}
var kind: Kind {
switch self {
case 0:
return .zero
case let x where x > 0:
return .positive
default:
return .negative
}
}
}
func printIntegerKinds(_ numbers: [Int]) {
for number in numbers {
switch number.kind {
case .negative:
print("- ", terminator: "")
case .zero:
print("0 ", terminator: "")
case .positive:
print("+ ", terminator: "")
}
}
}
let intArray = [3, 12, -10, 0, -19]
printIntegerKinds(intArray)
// number.kind is already known to be of type Int.Kind. Because of this, all of the Int.Kind case values can be written in shorthand form inside the switch statement, such as .negative rather than Int.Kind.negative.
// 22. Protocols
// A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.
// The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to CONFORM to that protocol.
// extend a protocol to implement some of these requirements or to implement additional functionality that conforming types can take advantage of
// 22.1 Protocol Syntax
// protocol SomeProtocol {
// protocol definition goes here
// }
// Custom types 实现协议
// struct SomeStructure: FirstProtocol, AnotherProtocol {
// structure definition goes here
// }
// 对于有父类的类
// class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
// class definition goes here
// }
// 22.2 Property Requirements
// 可以要求任意类型提供 instance property 实例属性 或者 type property 类属性 不指定该属性是 stored property 还是 computed property 只要求类型和名字
// 还可以指定属性是 只读的 还是 可读写的
// 如果要求是 可读写的, 就无法使用 constant stored property 或 a read-only computed property
// 如果只要求 可读, 就可以使用任意类型 (同时这些属性自己可以是 可读写的)
// property requirements 常用 variable properties 声明 var
// Gettable 和 settable 使用 {get set} 和 { get }
// protocol SomeProtocol {
// var mustSettable: Int { get set }
// var doesNotNeedToBeSettable: Int { get }
// }
// 限制类属性统一用 static 实现可以用 class 或 static
// You define type properties with the static keyword. For computed type properties for class types, you can use the class keyword instead to allow subclasses to override the superclass’s implementation 可以被子类复写的计算属性用 class 关键字
// protocol SomeProtocol {
// static var someTypeProperty: Int { get set }
// }
protocol FullyNamed {
var fullName: String { get }
}
// any FullyNamed type must have a gettable instance property called fullName, which is of type String.
struct Person: FullyNamed {
var fullName: String
}
let johnInfo = Person(fullName: "John Carmack")
print(johnInfo)
class Starship: FullyNamed {
var prefix: String?
var name: String
init(name: String, prefix: String? = nil) {
self.name = name
self.prefix = prefix
}
var fullName: String {
return (prefix != nil ? prefix! + " " : "") + name
}
}
var cc = Starship(name: "Peace", prefix: "Mars")
print(cc.fullName)
// 22.3 Method Requirements
// Protocols can require specific instance methods and type methods to be implemented by conforming types
// 方法作为协议定义的一部分 和正常的实例或类方法定义一致,但是没有大括号和方法体。可以有可变参数,但没有默认参数
// 在协议中对类方法进行限定需要添加 static。
// protocol SomeProtocol {
// static func someTypeMethod() // 类方法
// }
protocol RandomNumberGenerator {
func random() -> Double
}
// a pseudorandom number generator algorithm known as a linear congruential generator
class LinearCongruentialGenerator: RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0
let a = 3877.0
let c = 29573.0
func random() -> Double {
lastRandom = ((lastRandom * a + c).truncatingRemainder(dividingBy:m))
return lastRandom / m
}
}
let generator = LinearCongruentialGenerator()
print("Here's a random number: \(generator.random())")
print("Another one random number: \(generator.random())")
// 22.4 Mutating Method Requirements
// 有些修改值类型(structures enumerations)的内部方法 要在协议条件中的方法前加 mutating 在structures enumerations里要加 mutating 不用在实现协议的class内部写这个关键字
protocol Togglable {
mutating func toggle()
}
enum OnOffSwitch: Togglable {
case off, on
mutating func toggle() {
switch self {
case .off:
self = .on
case .on:
self = .off
}
}
}
var lightSwitch = OnOffSwitch.off
lightSwitch.toggle()
print(lightSwitch)
lightSwitch.toggle()
print(lightSwitch)
// 22.5 Initializer Requirements
// 协议可以规定一些类型方法必须实现特定初始化方法 协议条件的初始化方法和正常初始化方法一样,只是没有大括号和方法体。
protocol SomeProtocol {
init(someParameter: Int)
}
// 22.5.1 Class Implementations of Protocol Initializer Requirements
// Rule 1
// A designated initializer must call a designated initializer from its immediate superclass.
// Rule 2
// A convenience initializer must call another initializer from the same class.
// Rule 3
// A convenience initializer must ultimately call a designated initializer.
// A simple way to remember this is:
// Designated initializers must always delegate up.
// Convenience initializers must always delegate across.
// 协议中的初始化方法可以用 designated 或 convenience 初始化方法。但都要在实现中在初始化方法前加关键字 required
// 当然 final 修饰的初始化方法不用加 required
// 如果子类 override 父类初始化方法并要实现协议的初始化方法, 要在初始化方法前加 required override
// class SomeSubClass: SomeSuperClass, SomeProtocol {
// // "required" from SomeProtocol conformance; "override" from SomeSuperClass
// required override init() {
// // initializer implementation goes here
// }
// }
// 22.5.2 Failable Initializer Requirements
// A failable initializer requirement can be satisfied by a failable or nonfailable initializer on a conforming type. A nonfailable initializer requirement can be satisfied by a nonfailable initializer or an implicitly unwrapped failable initializer.
// 22.6 Protocols as Types
// 可以将协议用在 类型 可以使用的地方
// 作为参数类型 或 函数/方法返回类型
// 作为 constant variable property 的类型
// 作为数组字典和其他容器的元素类型
class Dice {
let sides: Int
let generator: RandomNumberGenerator
init(sides: Int, generator: RandomNumberGenerator) {
self.sides = sides
self.generator = generator
}
func roll() -> Int {
return Int(generator.random() * Double(sides)) + 1
}
}
var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator())
for _ in 1...5 {
print("Random dice roll is \(d6.roll())")
}
// 22.7 Delegation
// 设计模式 使得一个类或结构可以将一些对其他类型的响应 hand off / delegate。
// 通过定义一个封装delegated响应的协议完成
// 可用于响应特殊行动, 从外部接受数据不用知道数据源内部类型
protocol DiceGame {
var dice: Dice { get }
func play()
}
protocol DiceGameDelegate {
func gameDidStart(_ game: DiceGame)
func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
func gameDidEnd(_ game: DiceGame)
}
// a version of the Snakes and Ladders game originally introduced in Control Flow
class SnakesAndLadders: DiceGame {
let finalSquare = 25
let dice = Dice(sides: 6, generator: LinearCongruentialGenerator())
var square = 0
var board: [Int]
init() {
board = Array(repeating: 0, count: finalSquare + 1)
board[03] = +08
board[06] = +11
board[09] = +09
board[10] = +02
board[14] = -10
board[19] = -11
board[22] = -02
board[24] = -08
}
var delegate: DiceGameDelegate?
func play() {
square = 0
delegate?.gameDidStart(self)
gameLoop: while square != finalSquare {
let diceRoll = dice.roll()
delegate?.game(self, didStartNewTurnWithDiceRoll: diceRoll)
switch square + diceRoll {
case finalSquare:
break gameLoop
case let newSquare where newSquare > finalSquare:
continue gameLoop
default:
square += diceRoll
square += board[square]
}
}
delegate?.gameDidEnd(self)
}
}
// play() 调用一个 optional chain 在 delegate 上调用一个方法,如果 delegate 是 nil 那么这个 delegate 会默默失败而不报错 如果不是 nil 就执行 gameLoop 并将 实例 self 作为参数传入 于是我们需要一个 adopt DiceGameDelegate 的 class 如下
class DiceGameTracker: DiceGameDelegate {
var numberOfTurns = 0
func gameDidStart(_ game: DiceGame) {
numberOfTurns = 0
if game is SnakesAndLadders {
print("Started a new game of Snakes and Ladders")
}
print("The game is using a \(game.dice.sides)-sides dice")
}
func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int) {
numberOfTurns += 1
print("Rolled a \(diceRoll)")
}
func gameDidEnd(_ game: DiceGame) {
print("The game lasted for \(numberOfTurns) turns")
}
}
let tracker = DiceGameTracker()
let game = SnakesAndLadders()
game.delegate = tracker
game.play()
// 22.8 Adding Protocol Conformance with an Extension
// 可以扩展已有类型使其遵守某个协议, 甚至你无法访问源代码也可以做到。 Extension 可以添加 新 properties , method, 和 subscripts
// 给类型添加这些扩展会立即作用于类型实例上
// TextRepresentable 给任意类型添加显示文本功能
protocol TextRepresentable {
var textualDescription: String { get }
}
// 给 Dice class 添加这个功能
extension Dice: TextRepresentable {
var textualDescription: String {
return "A \(sides)-sided dice"
}
}
let d12 = Dice(sides: 12, generator: LinearCongruentialGenerator())
print(d12.textualDescription)
// 给 SnakesAndLadders 添加显示功能
extension SnakesAndLadders: TextRepresentable {
var textualDescription: String {
return "A game of Snakes and Ladders with \(finalSquare) squares"
}
}
print(game.textualDescription)
// 22.8.1 Declaring Protocol Adoption with an Extension
// 1. 类型已经实现了一个协议的所有要求 2. 还没有声明其实现了哪个协议 -> 你可以用一个空 extension 来声明这一点
struct Hamster {
var name: String
var textualDescription: String {
return "A hamster named \(name)"
}
}
extension Hamster: TextRepresentable {} // 声明实现了哪个协议
// Types do not automatically adopt a protocol just by satisfying its requirements. They must always explicitly declare their adoption of the protocol. 仅实现要求不够,还要声明自己实现了哪个协议的要求
let simonTheHamster = Hamster(name: "Simon")
let somethingTextRepresentable: TextRepresentable = simonTheHamster
print(somethingTextRepresentable.textualDescription)
// 22.9 Collections of Protocol Types
// 作为元素的 protocol 类型
let things : [TextRepresentable] = [game, d12, simonTheHamster]
for thing in things {
print(thing.textualDescription)
}
// 注意 thing 的类型是 TextRepresentable 不是 Dice DiceGame 或 Hamster
// 22.10 Protocol Inheritance
// 协议可以继承一个或多个其他协议 语法类似 类继承
// protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
// }
protocol PrettyTextRepresentable: TextRepresentable {
var prettyTextualDescription: String { get }
}
// 实现 PrettyTextRepresentable 要求的类型必须同时满足 TextRepresentable 的要求
extension SnakesAndLadders: PrettyTextRepresentable {
var prettyTextualDescription: String {
var output = textualDescription + ":\n"
for index in 1...finalSquare {
switch board[index] {
case let ladder where ladder > 0:
output += "▲ "
case let snake where snake < 0:
output += "▼ "
default:
output += "○ "
}
}
return output
}
}
// 22.11 Class-Only Protocols
// 限制只能由 class 实现本协议
// protocol SomeClassOnlyProtocol: class, SomeInheritedProtocol {
// }
// structure enumeration 来实现会导致 compile-time error 在要求实现类型为 引用类型时使用这个语法
// 22.12 Protocol Composition
// 可以要求一个类型实现多个协议 多个协议组成的类型写成 SomeProtocol & AnotherProtocol & ThirdProtocol & ...
// 实现多个协议写为 SomeProtocol, AnotherProtocol, ThirdProtocol...
protocol Named {
var name: String { get }
}
protocol Aged {
var age: Int { get }
}
struct Person1: Named, Aged {
var name: String
var age: Int
}
func wishHappyBirthday(to celebrator: Named & Aged) {
print("Happy Birthday, \(celebrator.name), you're \(celebrator.age)!")
}
let birthdayPerson = Person1(name: "Jim", age: 22)
wishHappyBirthday(to: birthdayPerson)
// 22.12 Checking for Protocol Conformance
// check for protocol conformance 用 is 操作符
// cast 到一个类型 用 as 操作符 as? 如果转失败就返回 nil as! 假定不出错,如果出错就 runtime error
protocol HasArea {
var area: Double { get }
}
class Circle: HasArea {
let pi = 3.1415927
var radius: Double
var area: Double { return pi * radius * radius } // 用计算属性初始化
init(radius: Double) { self.radius = radius }
}
class Country: HasArea {
var area: Double // 用存储属性初始化
init(area: Double) { self.area = area }
}
class Animal {
var legs: Int
init(legs: Int) { self.legs = legs }
}
// Circle Conuntry Animal 没有共享的基类 但都是 class 可以用 AnyObject 标识
let objects: [AnyObject] = [
Circle(radius: 2.0),
Country(area: 243_610),
Animal(legs: 8)
]
for object in objects {
if let objectWithArea = object as? HasArea {
print("Area is \(objectWithArea.area)")
} else {
print("Something that doesn't have an area")
}
}
// Whenever an object in the array conforms to the HasArea protocol, the optional value returned by the as? operator is unwrapped with optional binding into a constant called objectWithArea (unwrapped 动作如何完成的?)
// 22.13 Optional Protocol Requirements
// 可以在协议里定义 可选要求 即部分要求可以不实现 这些要求要用 optional 做修饰符
// the protocol and the optional requirement must MUST be marked with the @objc attribute
// @objc protocols can be adopted only by classes that inherit from Objective-C classes or other @objc classes. 只能由继承自 Objective-C 类的类实现或其他 @objc 类实现。
// 使用一个 optional 协议 它的 optional 方法或属性会自动变为 optional 的。 整个方法变为 optional 而不是返回值变为 optional
// 在方法后加 ? 可以检测一个类型实现了一个协议的 optional 要求 someOptionalMethod?(someArgument)
// Need import Foundation ...
// @objc protocol CounterDataSource {
// @objc optional func increment(forCount count: Int) -> Int
// @objc optional var fixedIncrement: Int { get }
// }
/*
class Counter {
var count = 0
var dataSource: CounterDataSource?
func increment() {
// dataSource? 保证 dataSource 不为 nil 才调用 increment?
// increment? 保证 dataSource 中有 increment 才调用 increment? => 返回 一个 optional 值 (不管实际返回什么类型)
// let -> optional binding
if let amount = dataSource?.increment?(forCount: count) {
count += amount
} else if let amount = dataSource?.fixedIncrement {
// dataSource?.fixedIncrement 也是 optional 类型
count += amount
}
}
}
*/
/*
class ThreeSource: NSObject, CounterDataSource {
let fixedIncrement = 3
}
var counter = Counter()
counter.dataSource = ThreeSource()
for _ in 1...4 {
counter.increment()
print(counter.count)
}
@objc class TowardsZeroSource: NSObject, CounterDataSource {
func increment(forCount count: Int) -> Int {
if count == 0{
return 0
} else if count < 0 {
return 1
} else {
return -1
}
}
counter.count = -4
counter.dataSource = TowardsZeroSource()
for _ in 1...5 {
counter.increment()
print(counter.count)
}
}
*/
// Optional requirements are available so that you can write code that interoperates with Objective-C.
// 22.14 Protocol Extensions
// 协议可以被扩展来给遵守协议的类型添加method property 这允许你在协议里定义行为
extension RandomNumberGenerator {
func randomBool() -> Bool {
return random() > 0.5
}
}
let generator1 = LinearCongruentialGenerator()
print("Here's a random number: \(generator1.random())")
print("And here's a random Boolean: \(generator1.randomBool())")
// 22.14.1 Providing Default Implementations
// 可以用扩展来给协议添加默认的条件(方法 或 计算属性)实现
// Although conforming types don’t have to provide their own implementation of either, requirements with default implementations can be called without optional chaining.
extension PrettyTextRepresentable {
var prettyTextualDescription: String {
return textualDescription
}
}
// 22.14.2 Adding Constraints to Protocol Extensions
// 在实现协议的类型调用扩展方法或属性前可以对这些类型进行限定
extension Collection where Iterator.Element: TextRepresentable {
var textualDescription: String {
let itemAsText = self.map { $0.textualDescription }
return "[" + itemAsText.joined(separator: ", ") + "]"
}
}
let m1TheHamster = Hamster(name: "m1")
let m2TheHamster = Hamster(name: "m2")
let m3TheHamster = Hamster(name: "m3")
let myHamsters = [m1TheHamster, m2TheHamster, m3TheHamster]
print(myHamsters.textualDescription)
// 多个限制条件选最严格的那个。。。 | bsd-2-clause |
trill-lang/LLVMSwift | Sources/LLVM/VoidType.swift | 1 | 799 | #if SWIFT_PACKAGE
import cllvm
#endif
/// The `Void` type represents any value and has no size.
public struct VoidType: IRType {
/// Returns the context associated with this type.
public let context: Context
/// Creates an instance of the `Void` type.
///
/// - parameter context: The context to create this type in
/// - SeeAlso: http://llvm.org/docs/ProgrammersManual.html#achieving-isolation-with-llvmcontext
public init(in context: Context = Context.global) {
self.context = context
}
/// Retrieves the underlying LLVM type object.
public func asLLVM() -> LLVMTypeRef {
return LLVMVoidTypeInContext(context.llvm)
}
}
extension VoidType: Equatable {
public static func == (lhs: VoidType, rhs: VoidType) -> Bool {
return lhs.asLLVM() == rhs.asLLVM()
}
}
| mit |
MoonCoders/SpeechMaster | Example/SpeechMaster/AppDelegate.swift | 1 | 1411 | //
// AppDelegate.swift
// SpeechMaster
//
import UIKit
import SpeechMaster
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
SpeechMaster.shared.setAudioSession(active: false)
}
func applicationDidEnterBackground(_ application: UIApplication) {
SpeechMaster.shared.setAudioSession(active: false)
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
bradwoo8621/Swift-Study | Instagram/Instagram/FollowerCell.swift | 1 | 2063 | //
// FollowerCell.swift
// Instagram
//
// Created by brad.wu on 2017/4/17.
// Copyright © 2017年 bradwoo8621. All rights reserved.
//
import UIKit
import AVOSCloud
class FollowerCell: UITableViewCell {
@IBOutlet weak var avaImg: UIImageView!
@IBOutlet weak var usernameLbl: UILabel!
@IBOutlet weak var followBtn: UIButton!
var user:AVUser!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
avaImg.layer.cornerRadius = avaImg.frame.width / 2
avaImg.clipsToBounds = true
let width = UIScreen.main.bounds.width
avaImg.frame = CGRect(x: 10,
y: 10,
width: width / 5.3,
height: width / 5.3)
usernameLbl.frame = CGRect(x: avaImg.frame.width + 20,
y: 30,
width: width / 3.2,
height: 30)
followBtn.frame = CGRect(x: width - width / 3.5 - 20,
y: 30,
width: width / 3.5,
height: 30)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func followBtnClicked(_ sender: UIButton) {
let title = followBtn.title(for: .normal)
if title == "关注" {
guard user != nil else {return}
AVUser.current()?.follow(user.objectId!, andCallback: { (success: Bool, error: Error?) in
if success {
self.followBtn.setTitle("已关注", for: .normal)
self.followBtn.backgroundColor = .green
} else {
print(error?.localizedDescription as Any)
}
})
} else {
guard user != nil else {return}
AVUser.current()?.unfollow(user.objectId!, andCallback: {(success: Bool, error: Error?) in
if success {
self.followBtn.setTitle("关注", for: .normal)
self.followBtn.backgroundColor = .lightGray
} else {
print(error?.localizedDescription as Any)
}
})
}
}
}
| mit |
maximbilan/SwiftlySlider | SwiftlySlider/AppDelegate.swift | 1 | 2088 | //
// AppDelegate.swift
// SwiftlyVolumeSlider
//
// Created by Maxim Bilan on 6/6/16.
// Copyright © 2016 Maxim Bilan. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
augmify/ModelRocket | ModelRocket/Property.swift | 6 | 4022 | // Property.swift
//
// Copyright (c) 2015 Oven Bits, LLC
//
// 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
final public class Property<T : JSONTransformable>: PropertyDescription {
typealias PropertyType = T
/// Backing store for property data
public var value: PropertyType?
/// Post-processing closure.
public var postProcess: ((PropertyType?) -> Void)?
/// JSON parameter key
public var key: String
/// Type information
public var type: String {
return "\(PropertyType.self)"
}
/// Specify whether value is required
public var required = false
public subscript() -> PropertyType? {
return value
}
// MARK: Initialization
/// Initialize with JSON property key
public init(key: String, defaultValue: PropertyType? = nil, required: Bool = false, postProcess: ((PropertyType?) -> Void)? = nil) {
self.key = key
self.value = defaultValue
self.required = required
self.postProcess = postProcess
}
// MARK: Transform
/// Extract object from JSON and return whether or not the value was extracted
public func fromJSON(json: JSON) -> Bool {
var jsonValue = json
let keyPaths = key.componentsSeparatedByString(".")
for key in keyPaths {
jsonValue = jsonValue[key]
}
if let newValue = PropertyType.fromJSON(jsonValue) as? PropertyType {
value = newValue
}
return (value != nil)
}
/// Convert object to JSON
public func toJSON() -> AnyObject? {
return value?.toJSON()
}
/// Perform initialization post-processing
public func initPostProcess() {
postProcess?(value)
}
// MARK: Coding
/// Encode
public func encode(coder: NSCoder) {
if let object: AnyObject = value as? AnyObject {
coder.encodeObject(object, forKey: key)
}
}
public func decode(decoder: NSCoder) {
if let decodedValue = decoder.decodeObjectForKey(key) as? PropertyType {
value = decodedValue
}
}
}
// MARK:- Printable
extension Property: Printable {
public var description: String {
var string = "Property<\(type)> (key: \(key), value: "
if let value = value {
string += "\(value)"
}
else {
string += "nil"
}
string += ", required: \(required))"
return string
}
}
// MARK:- DebugPrintable
extension Property: DebugPrintable {
public var debugDescription: String {
return description
}
}
// MARK:- Hashable
extension Property: Hashable {
public var hashValue: Int {
return key.hashValue
}
}
// MARK:- Equatable
extension Property: Equatable {}
public func ==<T>(lhs: Property<T>, rhs: Property<T>) -> Bool {
return lhs.key == rhs.key
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.