repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
universeiscool/MediaPickerController | MediaPickerController/MomentsCollectionViewFlowLayout.swift | 1 | 11456 | //
// MomentsCollectionViewFlowLayout.swift
// MediaPickerController
//
// Created by Malte Schonvogel on 24.11.15.
// Copyright © 2015 universeiscool UG (haftungsbeschränkt). All rights reserved.
//
import UIKit
let kDecorationReuseIdentifier = "MomentsCollectionViewDecoration"
class MomentsCollectionViewFlowLayout: UICollectionViewFlowLayout
{
var headerAttributes = [NSIndexPath:UICollectionViewLayoutAttributes]()
var footerAttributes = [NSIndexPath:UICollectionViewLayoutAttributes]()
var backgroundAttributes = [NSIndexPath:MediaPickerCollectionViewLayoutAttributes]()
var cellAttributes = [NSIndexPath:UICollectionViewLayoutAttributes]()
private var contentSize = CGSizeZero
var viewPortWidth: CGFloat {
get {
return self.collectionView!.frame.width - self.collectionView!.contentInset.left - self.collectionView!.contentInset.right
}
}
var viewPortAvailableSize: CGFloat {
get {
return self.viewPortWidth - self.sectionInset.left - self.sectionInset.right
}
}
weak var delegate: MomentsCollectionViewFlowLayoutDelegate? {
get{
return self.collectionView!.delegate as? MomentsCollectionViewFlowLayoutDelegate
}
}
// Caution! This prevents layout calculations
var sizeOfViewsNeverChange:Bool = false
override init()
{
super.init()
setup()
}
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
setup()
}
private func setup()
{
registerClass(MomentsCollectionDecorationView.self, forDecorationViewOfKind: kDecorationReuseIdentifier)
}
override class func layoutAttributesClass() -> AnyClass
{
return MediaPickerCollectionViewLayoutAttributes.self
}
private func clearVariables()
{
headerAttributes.removeAll()
cellAttributes.removeAll()
footerAttributes.removeAll()
backgroundAttributes.removeAll()
contentSize = CGSizeZero
}
override func prepareLayout()
{
guard let sectionAmount = collectionView?.numberOfSections() else {
return
}
if sectionAmount == 0 || (sizeOfViewsNeverChange && sectionAmount == backgroundAttributes.count && contentSize.width == viewPortWidth) {
return
}
let itemsPerRow = Int(viewPortWidth / itemSize.width)
// Initialize variables
clearVariables()
// Shortcut
let viewWidth = collectionView!.bounds.width
for section in 0..<sectionAmount {
let indexPath = NSIndexPath(forItem: 0, inSection: section)
// HeaderSize
let headerSize = referenceSizeForHeaderInSection(section)
let hLa = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withIndexPath: indexPath)
hLa.frame = CGRect(x: 0, y: contentSize.height, width: viewWidth, height: headerSize.height)
headerAttributes[indexPath] = hLa
// SectionSize
let sectionOffset = CGPoint(x: 0, y: contentSize.height + headerSize.height)
let itemsAmount:Int = collectionView!.numberOfItemsInSection(section)
let fractions = fractionize(itemsAmount, itemsAmountPerRow: itemsPerRow, section: section)
let sectionSize = setFramesForItems(fractions: fractions, section: section, sectionOffset: sectionOffset)
// FooterSize
let footerSize = referenceSizeForFooterInSection(section)
let fLa = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withIndexPath: indexPath)
fLa.frame = CGRect(x: 0, y: contentSize.height + headerSize.height + sectionSize.height, width: viewWidth, height: footerSize.height)
footerAttributes[indexPath] = fLa
// BackgroundSize
let bLa = MediaPickerCollectionViewLayoutAttributes(forDecorationViewOfKind: kDecorationReuseIdentifier, withIndexPath: indexPath)
bLa.frame = CGRect(x: 0, y: contentSize.height, width: viewWidth, height: headerSize.height + sectionSize.height - sectionInset.bottom)
if let selected = delegate?.sectionIsSelected(section) {
bLa.selected = selected
}
backgroundAttributes[indexPath] = bLa
// ContentSize
contentSize = CGSize(width: sectionSize.width, height: contentSize.height + headerSize.height + sectionSize.height + footerSize.height)
}
}
private func fractionize(let amount:Int, itemsAmountPerRow:Int, section:Int) -> [[Int]]
{
var result = [[Int]]()
if amount == 0 {
return result
}
let rest:Int = amount % itemsAmountPerRow
// Quick & Dirty
if amount == rest {
result.append((0..<amount).map({ $0 }))
} else if rest > 0 && rest <= Int(ceil(Float(itemsAmountPerRow/2))) && amount >= rest + itemsAmountPerRow {
let newRest = rest + itemsAmountPerRow
let divider = Int(ceil(Float(newRest) / Float(itemsAmountPerRow/2)))
result += (0..<newRest).map({$0}).splitBy(divider).reverse()
result += (newRest..<amount).map({$0}).splitBy(itemsAmountPerRow)
} else {
let first = (0..<rest).map({ $0 })
if !first.isEmpty {
result.append(first)
}
let second = (rest..<amount).map({ $0 }).splitBy(itemsAmountPerRow)
if !second.isEmpty {
result += second
}
}
return result
}
private func setFramesForItems(fractions fractions:[[Int]], section:Int, sectionOffset: CGPoint) -> CGSize
{
var contentMaxValueInScrollDirection = CGFloat(0)
var offset = CGPoint(x: sectionOffset.x + sectionInset.left, y: sectionOffset.y + sectionInset.top)
for fraction in fractions {
let itemsPerRow = fraction.count
let itemWidthHeight:CGFloat = (viewPortAvailableSize - minimumInteritemSpacing * CGFloat(itemsPerRow-1)) / CGFloat(itemsPerRow)
offset.x = sectionOffset.x + sectionInset.left
for itemIndex in fraction {
let indexPath = NSIndexPath(forItem: itemIndex, inSection: section)
let frame = CGRectMake(offset.x, offset.y, itemWidthHeight, itemWidthHeight)
let la = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
la.frame = frame
cellAttributes[indexPath] = la
contentMaxValueInScrollDirection = CGRectGetMaxY(frame)
offset.x += itemWidthHeight + minimumInteritemSpacing
}
offset.y += itemWidthHeight + minimumLineSpacing
}
return CGSize(width: viewPortWidth, height: contentMaxValueInScrollDirection - sectionOffset.y + sectionInset.bottom)
}
// MARK: Delegate Helpers
private func referenceSizeForHeaderInSection(section:Int) -> CGSize
{
if let headerSize = self.delegate?.collectionView?(collectionView!, layout: self, referenceSizeForHeaderInSection: section){
return headerSize
}
return headerReferenceSize
}
private func referenceSizeForFooterInSection(section:Int) -> CGSize
{
if let footerSize = self.delegate?.collectionView?(collectionView!, layout: self, referenceSizeForFooterInSection: section){
return footerSize
}
return footerReferenceSize
}
override func collectionViewContentSize() -> CGSize
{
return contentSize
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]?
{
var lA = [UICollectionViewLayoutAttributes]()
for section in 0..<collectionView!.numberOfSections() {
let sectionIndexPath = NSIndexPath(forItem: 0, inSection: section)
// HeaderAttributes
if let hA = layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionHeader, atIndexPath: sectionIndexPath) where !CGSizeEqualToSize(hA.frame.size, CGSizeZero) && CGRectIntersectsRect(hA.frame, rect) {
lA.append(hA)
}
// ItemAttributes
for item in 0..<collectionView!.numberOfItemsInSection(section) {
if let la = cellAttributes[NSIndexPath(forItem: item, inSection: section)] where CGRectIntersectsRect(rect, la.frame) {
lA.append(la)
}
}
// FooterAttributes
if let fA = layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionFooter, atIndexPath: sectionIndexPath) where !CGSizeEqualToSize(fA.frame.size, CGSizeZero) && CGRectIntersectsRect(fA.frame, rect) {
lA.append(fA)
}
// BackgroundAttributes
if let bA = layoutAttributesForDecorationViewOfKind(kDecorationReuseIdentifier, atIndexPath: sectionIndexPath) where !CGSizeEqualToSize(bA.frame.size, CGSizeZero) && CGRectIntersectsRect(bA.frame, rect) {
lA.append(bA)
}
}
return lA
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?
{
return cellAttributes[indexPath]
}
override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?
{
switch elementKind {
case UICollectionElementKindSectionHeader:
return headerAttributes[indexPath]
case UICollectionElementKindSectionFooter:
return footerAttributes[indexPath]
default:
return nil
}
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool
{
let oldBounds = collectionView!.bounds
if CGRectGetWidth(newBounds) != CGRectGetWidth(oldBounds) || CGRectGetHeight(newBounds) != CGRectGetHeight(oldBounds) {
return true
}
return false
}
override func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
let la = backgroundAttributes[indexPath]
if let selected = delegate?.sectionIsSelected(indexPath.section) {
la?.selected = selected
}
return la
}
}
public protocol MomentsCollectionViewFlowLayoutDelegate: UICollectionViewDelegateFlowLayout
{
func sectionIsSelected(section:Int) -> Bool
}
class MediaPickerCollectionViewLayoutAttributes: UICollectionViewLayoutAttributes
{
var selected = false
}
extension Array {
func splitBy(subSize: Int) -> [[Element]] {
return 0.stride(to: self.count, by: subSize).map { startIndex in
let endIndex = startIndex.advancedBy(subSize, limit: self.count)
return Array(self[startIndex ..< endIndex])
}
}
} | mit | 647ed8a29e4be989dc55256279afd5d0 | 38.229452 | 229 | 0.647197 | 5.690015 | false | false | false | false |
nguyenantinhbk77/practice-swift | CoreData/CoreData2/CoreData2/AppDelegate.swift | 3 | 7056 | //
// AppDelegate.swift
// CoreData2
//
// Created by Domenico Solazzo on 7/16/14.
// Copyright (c) 2014 Domenico Solazzo. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication!) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication!) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication!) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication!) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication!) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
func saveContext () {
var error: NSError? = nil
let managedObjectContext = self.managedObjectContext
if managedObjectContext != nil {
if managedObjectContext.hasChanges && !managedObjectContext.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
// #pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
var managedObjectContext: NSManagedObjectContext {
if !_managedObjectContext {
let coordinator = self.persistentStoreCoordinator
if coordinator != nil {
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = coordinator
}
}
return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
var managedObjectModel: NSManagedObjectModel {
if !_managedObjectModel {
let modelURL = NSBundle.mainBundle().URLForResource("CoreData2", withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
}
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
if !_persistentStoreCoordinator {
let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreData2.sqlite")
var error: NSError? = nil
_persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil)
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
//println("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
return _persistentStoreCoordinator!
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil
// #pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}
}
| mit | a8c7448c9512e6aabc0ff9f5ef441ece | 51.266667 | 285 | 0.700964 | 6.184049 | false | false | false | false |
LoopKit/LoopKit | LoopKit/TemporaryScheduleOverridePreset.swift | 1 | 2376 | //
// TemporaryScheduleOverridePreset.swift
// Loop
//
// Created by Michael Pangburn on 1/2/19.
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import Foundation
public struct TemporaryScheduleOverridePreset: Hashable {
public let id: UUID
public var symbol: String
public var name: String
public var settings: TemporaryScheduleOverrideSettings
public var duration: TemporaryScheduleOverride.Duration
public init(id: UUID = UUID(), symbol: String, name: String, settings: TemporaryScheduleOverrideSettings, duration: TemporaryScheduleOverride.Duration) {
self.id = id
self.symbol = symbol
self.name = name
self.settings = settings
self.duration = duration
}
public func createOverride(enactTrigger: TemporaryScheduleOverride.EnactTrigger, beginningAt date: Date = Date()) -> TemporaryScheduleOverride {
return TemporaryScheduleOverride(
context: .preset(self),
settings: settings,
startDate: date,
duration: duration,
enactTrigger: enactTrigger,
syncIdentifier: UUID()
)
}
}
extension TemporaryScheduleOverridePreset: RawRepresentable {
public typealias RawValue = [String: Any]
public init?(rawValue: RawValue) {
guard
let idString = rawValue["id"] as? String,
let id = UUID(uuidString: idString),
let symbol = rawValue["symbol"] as? String,
let name = rawValue["name"] as? String,
let settingsRawValue = rawValue["settings"] as? TemporaryScheduleOverrideSettings.RawValue,
let settings = TemporaryScheduleOverrideSettings(rawValue: settingsRawValue),
let durationRawValue = rawValue["duration"] as? TemporaryScheduleOverride.Duration.RawValue,
let duration = TemporaryScheduleOverride.Duration(rawValue: durationRawValue)
else {
return nil
}
self.init(id: id, symbol: symbol, name: name, settings: settings, duration: duration)
}
public var rawValue: RawValue {
return [
"id": id.uuidString,
"symbol": symbol,
"name": name,
"settings": settings.rawValue,
"duration": duration.rawValue
]
}
}
extension TemporaryScheduleOverridePreset: Codable {}
| mit | 5ea48a7e6b8f1bb8998f07db3fbc3bf0 | 32.928571 | 157 | 0.654316 | 5.074786 | false | false | false | false |
PureSwift/GATT | Sources/GATT/ManufacturerSpecificData.swift | 1 | 1735 | //
// ManufacturerSpecificData.swift
//
//
// Created by Alsey Coleman Miller on 10/23/20.
//
import Foundation
@_exported import Bluetooth
#if canImport(BluetoothGAP)
@_exported import BluetoothGAP
public typealias ManufacturerSpecificData = GAPManufacturerSpecificData
#else
/// GATT Manufacturer Specific Data
public struct ManufacturerSpecificData: Equatable, Hashable {
internal let data: Data // Optimize for CoreBluetooth / iOS
public init?(data: Data) {
guard data.count >= 2
else { return nil }
self.data = data
}
}
public extension ManufacturerSpecificData {
/// Company Identifier
var companyIdentifier: CompanyIdentifier {
get {
assert(data.count >= 2, "Invalid manufacturer data")
return CompanyIdentifier(rawValue: UInt16(littleEndian: unsafeBitCast((data[0], data[1]), to: UInt16.self)))
}
set { self = ManufacturerSpecificData(companyIdentifier: newValue, additionalData: additionalData) }
}
var additionalData: Data {
get {
if data.count > 2 {
return Data(data.suffix(from: 2))
} else {
return Data()
}
}
set { self = ManufacturerSpecificData(companyIdentifier: companyIdentifier, additionalData: newValue) }
}
init(companyIdentifier: CompanyIdentifier,
additionalData: Data = Data()) {
var data = Data(capacity: 2 + additionalData.count)
withUnsafeBytes(of: companyIdentifier.rawValue.littleEndian) { data.append(contentsOf: $0) }
data.append(additionalData)
self.data = data
}
}
#endif
| mit | e648e060b39ce8c7fd80366dd2ca7971 | 26.983871 | 120 | 0.626513 | 4.915014 | false | false | false | false |
bradwoo8621/Swift-Study | Instagram/Instagram/EditViewController.swift | 1 | 8435 | //
// EditViewController.swift
// Instagram
//
// Created by brad.wu on 2017/4/20.
// Copyright © 2017年 bradwoo8621. All rights reserved.
//
import UIKit
import AVOSCloud
class EditViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var avaImg: UIImageView!
@IBOutlet weak var fullnameTxt: UITextField!
@IBOutlet weak var usernameTxt: UITextField!
@IBOutlet weak var webTxt: UITextField!
@IBOutlet weak var bioTxt: UITextView!
@IBOutlet weak var titleLbl: UILabel!
@IBOutlet weak var emailTxt: UITextField!
@IBOutlet weak var telTxt: UITextField!
@IBOutlet weak var genderTxt: UITextField!
var genderPicker: UIPickerView!
let genders = ["男", "女"]
var keyboard = CGRect()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
genderPicker = UIPickerView()
genderPicker.dataSource = self
genderPicker.delegate = self
genderPicker.backgroundColor = UIColor.groupTableViewBackground
genderPicker.showsSelectionIndicator = true
genderTxt.inputView = genderPicker
NotificationCenter.default.addObserver(self, selector: #selector(showKeyboard), name: Notification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(hideKeyboard), name: Notification.Name.UIKeyboardWillHide, object: nil)
let hideTap = UITapGestureRecognizer(target: self, action: #selector(hideKeyboardTap))
hideTap.numberOfTapsRequired = 1
self.view.isUserInteractionEnabled = true
self.view.addGestureRecognizer(hideTap)
let imgTap = UITapGestureRecognizer(target: self, action: #selector(loadImg))
imgTap.numberOfTapsRequired = 1
avaImg.isUserInteractionEnabled = true
avaImg.addGestureRecognizer(imgTap)
alignment()
information()
}
func alignment() {
let width = self.view.frame.width
let height = self.view.frame.height
scrollView.frame = CGRect(x: 0, y: 0, width: width, height: height)
avaImg.frame = CGRect(x: width - 68 - 10, y: 15, width: 68, height: 68)
avaImg.layer.cornerRadius = avaImg.frame.width / 2
avaImg.clipsToBounds = true
fullnameTxt.frame = CGRect(x: 10, y: avaImg.frame.origin.y, width: width - avaImg.frame.width - 30, height: 30)
usernameTxt.frame = CGRect(x: 10, y: fullnameTxt.frame.origin.y + 40, width: width - avaImg.frame.width - 30, height: 30)
webTxt.frame = CGRect(x: 10, y: usernameTxt.frame.origin.y + 40, width: width - 20, height: 30)
bioTxt.frame = CGRect(x: 10, y: webTxt.frame.origin.y + 40, width: width - 20, height: 60)
bioTxt.layer.borderWidth = 1
bioTxt.layer.borderColor = UIColor(red: 230 / 255.0, green: 230 / 255.0, blue: 230 / 255.0, alpha: 1).cgColor
bioTxt.layer.cornerRadius = bioTxt.frame.width / 50
bioTxt.clipsToBounds = true
titleLbl.frame = CGRect(x: 10, y: bioTxt.frame.origin.y + 100, width: width - 20, height: 30)
emailTxt.frame = CGRect(x: 10, y: titleLbl.frame.origin.y + 40, width: width - 20, height: 30)
telTxt.frame = CGRect(x: 10, y: emailTxt.frame.origin.y + 40, width: width - 20, height: 30)
genderTxt.frame = CGRect(x: 10, y: telTxt.frame.origin.y + 40, width: width - 20, height: 30)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func information() {
let ava = AVUser.current()?.object(forKey: "ava") as! AVFile
ava.getDataInBackground({ (data: Data?, error: Error?) in
if error == nil {
self.avaImg.image = UIImage(data: data!)
} else {
print(error?.localizedDescription as Any)
}
})
usernameTxt.text = AVUser.current()?.username
fullnameTxt.text = AVUser.current()?.object(forKey: "fullname") as? String
bioTxt.text = AVUser.current()?.object(forKey: "bio") as? String
webTxt.text = AVUser.current()?.object(forKey: "web") as? String
emailTxt.text = AVUser.current()?.email
telTxt.text = AVUser.current()?.mobilePhoneNumber
genderTxt.text = AVUser.current()?.object(forKey: "gender") as? String
}
func hideKeyboardTap(recogziner: UITapGestureRecognizer) {
self.view.endEditing(true)
}
func showKeyboard(notification: Notification) {
let rect = notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
keyboard = rect.cgRectValue
UIView.animate(withDuration: 0.4) {
self.scrollView.contentSize.height = self.view.frame.height + self.keyboard.height / 2
}
}
func hideKeyboard(notification: Notification) {
UIView.animate(withDuration: 0.4) {
self.scrollView.contentSize.height = 0
}
}
func loadImg(recognizer: UITapGestureRecognizer) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
avaImg.image = info[UIImagePickerControllerEditedImage] as? UIImage
self.dismiss(animated: true, completion: nil)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return genders.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return genders[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
genderTxt.text = genders[row]
self.view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func cancelClicked(_ sender: UIBarButtonItem) {
self.view.endEditing(true)
self.dismiss(animated: true, completion: nil)
}
@IBAction func saveClicked(_ sender: UIBarButtonItem) {
if !validateEmail(email: emailTxt.text!) {
alert(error: "错误的邮件地址", message: "请输入正确的邮件地址")
return
}
if !validateWeb(web: webTxt.text!) {
alert(error: "错误的网页链接", message: "请输入正确的网页链接地址")
return
}
if !validateMobilePhoneNumber(mobilePhoneNumber: telTxt.text!) {
alert(error: "错误的手机号码", message: "请输入正确的手机号码")
return
}
let user = AVUser.current()
user?.username = usernameTxt.text?.lowercased()
user?.email = emailTxt.text?.lowercased()
user?["fullname"] = fullnameTxt.text?.lowercased()
user?["web"] = webTxt.text?.lowercased()
user?["bio"] = bioTxt.text
if telTxt.text!.isEmpty {
user?.mobilePhoneNumber = ""
} else {
user?.mobilePhoneNumber = telTxt.text
}
if genderTxt.text!.isEmpty {
user?["gender"] = ""
} else {
user?["gender"] = genderTxt.text
}
user?.saveInBackground({ (success: Bool, error: Error?) in
if success {
self.view.endEditing(true)
self.dismiss(animated: true, completion: nil)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "reload"), object: nil)
} else {
print(error?.localizedDescription as Any)
}
})
}
func validateEmail(email: String) -> Bool {
let regex = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}"
let range = email.range(of: regex, options: .regularExpression)
let result = range != nil ? true : false
return result
}
func validateWeb(web: String) -> Bool {
let regex = "www\\.[A-Za-z0-9._%+-]+\\.[A-Za-z]{2,14}"
let range = web.range(of: regex, options: .regularExpression)
return range != nil ? true : false
}
func validateMobilePhoneNumber(mobilePhoneNumber: String) -> Bool {
return mobilePhoneNumber.range(of: "0?(13|14|15|18)[0-9]{9}", options: .regularExpression) != nil ? true : false
}
func alert(error: String, message: String) {
let alert = UIAlertController(title: error, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
}
| mit | b4c910863c14200ed9a7c20895af04d4 | 35.5 | 155 | 0.71341 | 3.585523 | false | false | false | false |
swojtyna/starsview | StarsView/StarsView/BaseOperation.swift | 1 | 1570 | //
// BaseOperation.swift
// StarsView
//
// Created by Sebastian Wojtyna on 04/09/16.
// Copyright © 2016 Sebastian Wojtyna. All rights reserved.
//
import Foundation
class BaseOperation: NSOperation {
//MARK: Properties
private var _executing: Bool
override var executing: Bool {
get { return _executing }
set { update({ self._executing = newValue }, key: "isExecuting") }
}
private var _finished: Bool
override var finished: Bool {
get { return _finished }
set { update({ self._finished = newValue }, key: "isFinished") }
}
private func update(change: Void -> Void, key: String) {
willChangeValueForKey(key)
change()
didChangeValueForKey(key)
}
override var asynchronous: Bool {
return true
}
//MARK: Initializers method
override init() {
_executing = false
_finished = false
}
//MARK: NSOperation method
override final func start() {
guard cancelled == false else {
finished = true
return
}
super.start()
}
override func main() {
assert(!NSThread.isMainThread(), "Probably you don't want to block main thread for operation \(self)")
if !cancelled {
execute()
} else {
finish()
}
}
func finish() {
executing = false
finished = true
}
//MARK: methods to ovveride
func execute() {
print("\(self.dynamicType) must override `execute()`.")
}
}
| agpl-3.0 | 2decd34ab179053fa9da85689db86f7c | 19.376623 | 110 | 0.568515 | 4.655786 | false | false | false | false |
surfandneptune/CommandCougar | Sources/CommandCougar/Command.swift | 1 | 9454 | //
// Command.swift
// CommandCougar
//
// Copyright (c) 2017 Surf & Neptune LLC (http://surfandneptune.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A struct used to describe a command entry for evaluation and help menu
public struct Command: CommandIndexable {
/// A callback type used to notify after evaluation
public typealias Callback = ((CommandEvaluation) throws -> Void)
/// The name of this command
public var name: String
/// The overview of this command used in the help menu
public var overview: String
/// The options this command is allowed to take in
public var options: [Option]
/// The parameters this command is allowd to take in
public var parameters: [Parameter]
/// The subCommands this parameter is allowd to take in
public var subCommands: [Command]
/// The callback used by PerformCallbacks when this command is evaulated
public var callback: Callback?
/// How much padding the help menu uses
public var helpPadding: Int = 30
/// The minimum number of parameters allowed
internal var minParameterCount: Int {
return parameters.filter{ $0.isRequired }.count
}
/// The maximum number of parameters allowed
internal var maxParameterCount: Int {
return parameters.count
}
/// Command Init. This init allows for parameters and not
/// subcommands since a command can not have both subcommands and parameters
///
/// - Parameters:
/// - name: The name of this command
/// - overview: The overview used in the help menu
/// - callback: The callback which is called when the command evaluates to true
/// - options: Possible options this command is allow to take in
/// - parameters: Possible parameters this command is allowed to take in
public init(
name: String,
overview: String,
callback: Callback?,
options: [Option],
parameters: [Parameter]) {
self.name = name
self.overview = overview
self.callback = callback
self.options = options + [Option.help]
self.subCommands = []
self.parameters = parameters
}
/// Command Init. This init allows for subCommands and not
/// parameters since a command can not have both subcommands and parameters
///
/// - Parameters:
/// - name: The name of this command
/// - overview: The overview used in the help menu
/// - callback: The callback which is called when the command evaluates to true
/// - options: Possible options this command is allow to take in
/// - subCommands: Possible subCommands this command is allowed to take in
public init(
name: String,
overview: String,
callback: Callback?,
options: [Option],
subCommands: [Command]) {
self.name = name
self.overview = overview
self.callback = callback
self.options = options + [Option.help]
self.parameters = []
self.subCommands = subCommands
}
/// Creates the usage string for this command given an array of supercommands. A Command does not
/// keep a link to its supercommands, so it is dynamically generated at run time.
///
/// - Parameter superCommands: The array of super commands
/// - Returns: The usage string for this command
public func usage(superCommands: [Command] = []) -> String {
let fullCommandName = superCommands.reduce("", { $0 + "\($1.name) " } ).appending(name)
let optionString = options.isEmpty ? "" : " [options] "
let parameterString = parameters.isEmpty ? "" : parameters.reduce("", { $0 + "\($1.formattedValue) " })
let subCommandString = subCommands.isEmpty ? "" : "subcommand"
return "\(fullCommandName)\(optionString)\(parameterString)\(subCommandString)"
}
/// Creates the help text string for this command given an array of supercommands. The supercommands
/// are used to dynamcially generate the usuage text.
///
/// - Parameter superCommands: The array of super commands
/// - Returns: The help text string for this command
public func help(superCommands: [Command] = []) -> String {
let commandHelp = subCommands.isEmpty ? "" :
subCommands
.map {
"\($0.name.padding(toLength: helpPadding, withPad: " ", startingAt: 0))" +
"\($0.overview)"
}
.reduce("SUBCOMMANDS:", { "\($0)\n \($1)" }) + "\n\n"
let optionHelp = options.isEmpty ? "" :
options
.map { $0.helpText }
.reduce("OPTIONS:", { "\($0)\n \($1)" })
return "OVERVIEW: \(overview)\n\nUSAGE: \(usage(superCommands: superCommands))\n\n\(commandHelp)\(optionHelp)"
}
/// Ensures that the Command structure is valid
///
/// - Throws: Error if the Command structure is not valid
public func validate() throws {
// A command can not have both subcommands and parameters
if parameters.count > 0 && subCommands.count > 0 {
throw CommandCougar.Errors.validate("A command can not have both subcommands and parameters.")
}
// Subcommand names must be unique
let subCommandNames = subCommands.map { $0.name }
if subCommandNames.count != Set(subCommandNames).count {
throw CommandCougar.Errors.validate("Duplicate subCommand(s) for command \(name). Subcommand names must be unique.")
}
// Option flags must be unique i.e. they can't have the same shortNames or longNames
let shorts = options.compactMap ({ $0.flag.shortName })
let longs = options.compactMap ({ $0.flag.longName })
if shorts.count != Set(shorts).count, longs.count != Set(longs).count {
throw CommandCougar.Errors.validate("Duplicate option flag(s) for command \(name). Option flags must be unique.")
}
}
/// Strip the first arg and subevaluate. Prints help text if help option is present.
///
/// - Parameter args: The command line arugments usually from CommandLine.arguments
/// - Returns: An evaluated command. The evaluation contains a subevaluation for any subCommand parsed
/// - Throws: Error if arguments are malformed or this command does not support option / parameter
public func evaluate(arguments: [String]) throws -> CommandEvaluation {
let commandEvaluation = try subEvaluate(arguments:arguments.dropFirst().map { $0 })
// If help option is present in the command evaluation, print help.
if commandEvaluation.options.contains(where: { $0.flag == Option.help.flag }) {
print(help(superCommands: []))
return commandEvaluation
}
// If help options is present in a subcommand evaluation, print help. Keep track of the supercommands
// so that the usasge in the help text can be dynamically generated.
var current = commandEvaluation
var superCommands = [Command]()
superCommands.append(current.describer)
while let next = current.subEvaluation {
current = next
if current.options.contains(where: { $0.flag == Option.help.flag }) {
print(current.describer.help(superCommands: superCommands))
}
superCommands.append(current.describer)
}
return commandEvaluation
}
/// Evaluates this command and all subcommands againts a set of arguments.
/// This will generate a evaluation filled out with the options and parameters
/// passed into each
///
/// - Parameter args: The command line arugments usually from CommandLine.arguments
/// - Returns: A evaulated command. The evaluation contains a subevaluation for any subCommand parsed
/// - Throws: Error if arguments is malformed or this command does not support option / parameter
private func subEvaluate(arguments: [String]) throws -> CommandEvaluation {
try validate()
var evaluation = CommandEvaluation(describer: self)
var argsList = arguments
while !argsList.isEmpty {
let next = argsList.removeFirst()
if let subCommand = subCommands.first(where: { $0.name == next }) {
evaluation.subEvaluation = try subCommand.subEvaluate(arguments: argsList)
try evaluation.validate()
return evaluation
}
else if
let option = OptionEvaluation(string: next) {
// If option is help, stop evaluating
if option.flag == Option.help.flag {
evaluation.options.append(option)
return evaluation
}
evaluation.options.append(option)
}
else {
evaluation.parameters.append(next)
}
}
try evaluation.validate()
return evaluation
}
/// A subscript to access this commands subcommand by name
///
/// - Parameter commandName: The name of the subcommand
public subscript(subCommand: String) -> Command? {
get {
return subCommands[subCommand]
} set {
subCommands[subCommand] = newValue
}
}
}
| mit | 9d9277e4110fbcd2a599a760bef0f067 | 35.501931 | 119 | 0.709224 | 3.92445 | false | false | false | false |
JAlblas/portfolio-project | Portfolio Project/MapViewController.swift | 1 | 10422 | //
// ViewController.swift
// Portfolio Project
//
// Created by Jasper Alblas on 05/05/16.
// Copyright © 2016 Jasper Alblas. All rights reserved.
//
import UIKit
import MapKit
import Alamofire
import CoreData
class MapViewController: UIViewController {
@IBOutlet weak var airQualityMapView: MKMapView!
var activityIndicator: UIActivityIndicatorView!
let dataController = DataController()
var appDelegate: AppDelegate!
var sharedContext: NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
sharedContext = appDelegate.managedObjectContext
title = "Air Quality US"
setupMapview()
//addActivityIndicator()
//plotCountryData()
// Fetch all current measurements from core data if available
if let measurements = fetchAllMeasurements() {
airQualityMapView.addAnnotations(measurements)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupMapview() {
// Set mapview to cover US
airQualityMapView.region = MKCoordinateRegionMakeWithDistance(
CLLocationCoordinate2DMake(39.50, -98.35), 8000000, 8000000);
airQualityMapView.delegate = self
// Add gestureRecognizer to mapview
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(MapViewController.dropPin(_:)))
longPress.minimumPressDuration = 0.5
airQualityMapView.addGestureRecognizer(longPress)
airQualityMapView.delegate = self
}
func addActivityIndicator() {
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
activityIndicator.center = self.view.center
activityIndicator.startAnimating()
self.view.addSubview(activityIndicator)
}
func loadCityList() -> [String]? {
// Loads up csv file from assets folder
if let asset = NSDataAsset(name: "cities") {
let data = asset.data
if let content = NSString(data: data, encoding: NSUTF8StringEncoding) {
let cityArray = content.componentsSeparatedByString("\n")
return cityArray
} else {
return nil
}
} else {
return nil
}
}
func plotCountryData() {
if let cityList = loadCityList() {
for city in cityList {
let cityData = city.componentsSeparatedByString(",")
if (cityData.count == 3) {
let latitude = Double(cityData[1])!
let longitude = Double(cityData[2])!
print("\(latitude) \(longitude)")
// Fetch data for each city in array
dataController.fetchAirQualityData(latitude, longitude: longitude, completionHandler: { (object) in
if let area = object["ReportingArea"].string, AQI = object["AQI"].int, category = object["Category"].dictionaryObject, measuredLat = object["Latitude"].double, measuredLong = object["Longitude"].double, rank = category["Number"] {
// Add annontation on map for measurement
let measurement = Measurement(areaName: area, airQuality: AQI, rank: rank as! Int, coordinate: CLLocationCoordinate2D(latitude: measuredLat, longitude: measuredLong), insertIntoManagedObjectContext: self.sharedContext)
dispatch_async(dispatch_get_main_queue(),{
// Add annotation on map on main thread
self.airQualityMapView.addAnnotation(measurement)
})
}
})
appDelegate.saveContext()
}
}
} else {
let alert = UIAlertController(title: "Error", message: "There was an error fetching the data", preferredStyle: .Alert)
presentViewController(alert, animated: true, completion: nil)
}
//activityIndicator.stopAnimating()
}
func dropPin(gestureRecognizer: UIGestureRecognizer) {
let tapPoint: CGPoint = gestureRecognizer.locationInView(airQualityMapView)
let touchMapCoordinate: CLLocationCoordinate2D = airQualityMapView.convertPoint(tapPoint, toCoordinateFromView: airQualityMapView)
if UIGestureRecognizerState.Began == gestureRecognizer.state {
// Fetch data from webservice //TODO
// Fetch data for each city in array
dataController.fetchAirQualityData(touchMapCoordinate.latitude, longitude: touchMapCoordinate.longitude, completionHandler: { (object) in
if let area = object["ReportingArea"].string, AQI = object["AQI"].int, category = object["Category"].dictionaryObject, measuredLat = object["Latitude"].double, measuredLong = object["Longitude"].double, rank = category["Number"] {
// Add annontation on map for measurement
let measurement = Measurement(areaName: area, airQuality: AQI, rank: rank as! Int, coordinate: CLLocationCoordinate2D(latitude: measuredLat, longitude: measuredLong), insertIntoManagedObjectContext: self.sharedContext)
dispatch_async(dispatch_get_main_queue(),{
// Add annotation on map on main thread
self.airQualityMapView.addAnnotation(measurement)
})
}
})
appDelegate.saveContext()
}
}
// MARK: Navigation methods
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetails" {
let annotationView : MKAnnotationView = sender as! MKAnnotationView
let measurement = annotationView.annotation as! Measurement
let destinationVC = segue.destinationViewController as! DetailViewController
destinationVC.measurement = measurement
}
}
// MARK: Core Graphics functionality
func drawCircleAnnotation(color: UIColor, AQI : Int) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: 25, height: 25), false, 0)
let context = UIGraphicsGetCurrentContext()
let rectangle = CGRect(x: 0, y: 0, width: 25, height: 25)
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
CGContextSetLineWidth(context, 1)
CGContextAddEllipseInRect(context, rectangle)
CGContextDrawPath(context, .FillStroke)
// Add text to circle
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .Center
let attrs = [NSFontAttributeName: UIFont(name: "HelveticaNeue", size: 12)!, NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName : UIColor.whiteColor()]
let string = "\(AQI)"
string.drawWithRect(CGRect(x: 5, y: 5, width: 15, height: 15), options: .UsesLineFragmentOrigin, attributes: attrs, context: nil)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
// MARK: MapViewDelegate methods
extension MapViewController : MKMapViewDelegate {
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "Measurement"
let measurement = annotation as! Measurement
// Reuse the annotation if possible
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
if annotationView == nil {
//4
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView!.canShowCallout = true
// 5
let button = UIButton(type: .DetailDisclosure)
button.frame = CGRectMake(0, 0, 23, 23);
annotationView!.rightCalloutAccessoryView = button
// Set background color based on rank
var color: UIColor
switch measurement.rank!.integerValue {
case 1:
color = UIColor.blueColor()
case 2:
color = UIColor.greenColor()
case 3:
color = UIColor.yellowColor()
case 4:
color = UIColor.orangeColor()
case 5:
color = UIColor.redColor()
default:
color = UIColor.whiteColor()
}
let img = drawCircleAnnotation(color, AQI: measurement.airQuality!.integerValue)
annotationView!.image = img
}
return annotationView
}
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
performSegueWithIdentifier("showDetails", sender: view)
}
// MARK: Fetch results
// Probably should gets its own class
func fetchAllMeasurements() -> [Measurement]? {
let fetchRequest = NSFetchRequest(entityName: "Measurement")
var results : [Measurement]
do {
results = try sharedContext.executeFetchRequest(fetchRequest) as! [Measurement]
return results
}
catch {
print("Error in fectchAllMeasurements(): \(error)")
return nil
}
}
}
| mit | 58e3d3a8ee19f9d9a5c011ba2a2ceec3 | 37.032847 | 254 | 0.588523 | 6.18457 | false | false | false | false |
mdznr/Keyboard | KeyboardExtension/KeyboardViewController.swift | 1 | 8005 | //
// KeyboardViewController.swift
// KeyboardExtension
//
// Created by Matt Zanchelli on 6/15/14.
// Copyright (c) 2014 Matt Zanchelli. All rights reserved.
//
import UIKit
// Some constants to use.
let APPEAR_ANIMATION_DURATION = 0.3
class KeyboardViewController: UIInputViewController, TyperDelegate {
// MARK: Typer
let typer = Typer()
var textualContext: UITextDocumentProxy {
get {
return self.textDocumentProxy as UITextDocumentProxy
}
}
func shouldUpdateShiftState(shiftState: KeyboardShiftState) {
self.shiftState = shiftState
}
var shiftState: KeyboardShiftState = .Disabled {
didSet {
typer.shiftState = shiftState
shiftKey.shiftState = shiftState
if shiftState != oldValue {
let capitalized = shiftState != .Disabled
for letterKey in letterKeys {
letterKey.capitalized = capitalized
}
}
}
}
// MARK: Keyboard
let keyboard = Keyboard()
// MARK: Letter Keys
var letterKeys = [LetterKey]()
// MARK: Special Keys
// TODO: Shouldn't harcode frame.
let shiftKey: ShiftKey = ShiftKey(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
let deleteKey: MetaKey = {
let key = MetaKey()
key.imageView.image = UIImage(named: "Delete")
return key
}()
let symbolKeyboardKey: MetaKey = {
let key = MetaKey()
key.imageView.image = UIImage(named: "Symbols")
return key
}()
let nextKeyboardKey: MetaKey = {
let key = MetaKey()
key.imageView.image = UIImage(named: "Globe")
return key
}()
let returnKey = ReturnKey()
let spacebar = Spacebar()
// MARK: Initialization
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
typer.delegate = self
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init() {
super.init()
}
// MARK: UIViewController
override func updateViewConstraints() {
super.updateViewConstraints()
// Add custom view sizing constraints here
}
override func viewDidLoad() {
super.viewDidLoad()
self.inputView.addSubview(keyboard)
keyboard.rowHeights = [59/216, 55/216, 54/216, 48/216]
keyboard.edgeInsets = [
UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0),
UIEdgeInsets(top: 0, left: 7, bottom: 0, right: 7),
UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 1),
UIEdgeInsets(top: 0, left: 1, bottom: 0, right: 1)
]
var keys = [[KeyboardKey]]()
let row1Letters = ["Q","W","E","R","T","Y","U","I","O","P"]
let row2Letters = ["A","S","D","F","G","H","J","K","L"]
let row3Letters = ["Z","X","C","V","B","N","M"]
var row1Keys = [KeyboardKey]()
for letter in row1Letters {
let letterKey = self.letterKeyWithLetter(letter)
row1Keys.append(letterKey)
letterKeys.append(letterKey)
}
keys.append(row1Keys)
var row2Keys = [KeyboardKey]()
for letter in row2Letters {
let letterKey = self.letterKeyWithLetter(letter)
row2Keys.append(letterKey)
letterKeys.append(letterKey)
}
keys.append(row2Keys)
var row3Keys = [KeyboardKey]()
row3Keys.append(shiftKey)
shiftKey.action = {
self.shiftState = self.shiftKey.shiftState
}
for letter in row3Letters {
let letterKey = self.letterKeyWithLetter(letter)
row3Keys.append(letterKey)
letterKeys.append(letterKey)
}
row3Keys.append(deleteKey)
deleteKey.action = {
self.typer.deleteCharacter()
}
keys.append(row3Keys)
var row4Keys = [KeyboardKey]()
row4Keys.append(symbolKeyboardKey)
symbolKeyboardKey.action = {
}
row4Keys.append(nextKeyboardKey)
nextKeyboardKey.action = {
self.advanceToNextInputMode()
}
row4Keys.append(spacebar)
spacebar.action = {
self.typer.typeString(" ")
}
row4Keys.append(returnKey)
returnKey.action = {
self.createNewline()
}
keys.append(row4Keys)
keyboard.keys = keys
// Gestures
let swipeLeft = UISwipeGestureRecognizer(target: self, action: "didSwipeLeft:")
swipeLeft.direction = .Left
self.inputView.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action: "didSwipeRight:")
swipeRight.direction = .Right
self.inputView.addGestureRecognizer(swipeRight)
let swipeDown = UISwipeGestureRecognizer(target: self, action: "didSwipeDown:")
swipeDown.direction = .Down
self.inputView.addGestureRecognizer(swipeDown)
let swipeDownWithTwoFingers = UISwipeGestureRecognizer(target: self, action: "didSwipeDownWithTwoFingers:")
swipeDownWithTwoFingers.direction = .Down
swipeDownWithTwoFingers.numberOfTouchesRequired = 2
self.inputView.addGestureRecognizer(swipeDownWithTwoFingers)
}
func letterKeyWithLetter(letter: String) -> LetterKey {
let letterKey = LetterKey(letter: letter)
letterKey.action = {
self.typer.typeAutocapitalizedString(letterKey.letter)
}
return letterKey
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
// MARK: UITextInputDelegate
override func textWillChange(textInput: UITextInput) {
super.textWillChange(textInput)
// The app is about to change the document's contents. Perform any preparation here.
}
override func textDidChange(textInput: UITextInput) {
super.textDidChange(textInput)
// The app has just changed the document's contents, the document context has been updated.
NSLog("Text Did Change!")
typer.textDidChange(textInput)
self.updateAppearance()
}
// MARK: -
func updateAppearance() {
returnKey.type = self.returnKeyType()
let appearance = self.keyboardAppearance()
self.inputView.backgroundColor = KeyboardAppearance.keyboardBackgroundColorForAppearance(appearance)
KeyboardDivider.appearance().backgroundColor = KeyboardAppearance.dividerColorForAppearance(appearance)
// LetterKey.appearance().textColor = KeyboardAppearance.primaryButtonColorForAppearance(appearance)
// Spacebar.appearance().disabledTintColor = KeyboardAppearance.primaryButtonColorForAppearance(appearance)
// Spacebar.appearance().enabledTintColor = KeyboardAppearance.primaryButtonColorForAppearance(appearance)
// ShiftKey.appearance().disabledTintColor = KeyboardAppearance.secondaryButtonColorForApperance(appearance)
// ShiftKey.appearance().enabledTintColor = KeyboardAppearance.enabledButtonColorForAppearance(appearance)
// ReturnKey.appearance().disabledTintColor = KeyboardAppearance.enabledButtonColorForAppearance(appearance)
// ReturnKey.appearance().enabledTintColor = KeyboardAppearance.enabledButtonColorForAppearance(appearance).colorWithAlphaComponent(0.7)
// UIButton.appearance().tintColor = KeyboardAppearance.secondaryButtonColorForApperance(appearance)
}
// MARK: Gestures
/// TODO: Fix this once `documentContextBeforeInput` stops always returning nil.
/// Did a swipe left gesture. Delete until previous chunk of whitespace.
func didSwipeLeft(sender: UIGestureRecognizer) {
if sender.state == .Ended {
typer.deleteWord()
}
}
/// Did a swipe right gesture. End the sentence.
func didSwipeRight(sender: UIGestureRecognizer) {
if sender.state == .Ended {
endSentence()
}
}
/// Did a swipe down gesture. Add a newline character.
func didSwipeDown(sender: UIGestureRecognizer) {
if sender.state == .Ended {
createNewline()
}
}
/// Did a swipe down gesture with two fingers. Dismiss the keyboard.
func didSwipeDownWithTwoFingers(sender: UIGestureRecognizer) {
if sender.state == .Ended {
dismissKeyboard()
}
}
/// End the sentence by adding a period and enabling capitalization.
/// TODO: Insert newline (if possible), if at the start of a sentence. (double-swipe)
func endSentence() {
typer.typeString(". ")
}
/// Create a newline or act as return
func createNewline() {
typer.typeString("\n")
}
}
| mit | 43a06271043ceeb6774c8c528d8eb3d5 | 27.087719 | 137 | 0.7203 | 3.821002 | false | false | false | false |
grandiere/box | box/Model/GridMap/MGridMapDetailItemDistance.swift | 1 | 2399 | import UIKit
import CoreLocation
class MGridMapDetailItemDistance:MGridMapDetailItem
{
private let kMaxDecimals:Int = 0
private let kMinIntegers:Int = 1
init?(
userLocation:CLLocation,
annotation:MGridMapAnnotation)
{
guard
let location:CLLocation = annotation.algo?.location,
let distanceMetrics:MDistanceProtocol = MSession.sharedInstance.settings?.currentDistance()
else
{
return nil
}
let rawDistance:CLLocationDistance = location.distance(from:userLocation)
let convertDistance:Double = distanceMetrics.convertFromStandard(standard:rawDistance)
let rawDistanceNumber:NSNumber = convertDistance as NSNumber
let numberFormatter:NumberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
numberFormatter.maximumFractionDigits = kMaxDecimals
numberFormatter.minimumIntegerDigits = kMinIntegers
guard
let rawDistanceString:String = numberFormatter.string(
from:rawDistanceNumber)
else
{
return nil
}
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
let attributesTitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.bold(size:14),
NSForegroundColorAttributeName:UIColor(white:0, alpha:0.3)]
let attributesSubtitle:[String:AnyObject] = [
NSFontAttributeName:UIFont.numeric(size:14),
NSForegroundColorAttributeName:UIColor.black]
let stringTitle:NSAttributedString = NSAttributedString(
string:NSLocalizedString("MGridMapDetailItemDistance_stringTitle", comment:""),
attributes:attributesTitle)
let stringDistance:NSAttributedString = NSAttributedString(
string:rawDistanceString,
attributes:attributesSubtitle)
let stringMetrics:NSAttributedString = NSAttributedString(
string:" \(distanceMetrics.name)",
attributes:attributesSubtitle)
mutableString.append(stringTitle)
mutableString.append(stringDistance)
mutableString.append(stringMetrics)
super.init(attributedString:mutableString)
}
}
| mit | cc07b741ecba55070b19615f65e4d64e | 35.348485 | 103 | 0.660692 | 6.088832 | false | false | false | false |
rocketmade/rockauth-ios | RockauthiOS/UI/RockauthNavigationController.swift | 1 | 2669 | //
// RockauthNavigationController.swift
// RockauthiOS
//
// Created by Cody Mace on 11/16/15.
// Copyright © 2015 Daniel Gubler. All rights reserved.
//
import UIKit
public class RockauthNavigationController: UINavigationController {
var logo: UIImage?
var providers: [SocialProvider?]!
var connected: loginSuccess!
var failed: loginFailure!
var useEmailAuthentication: Bool!
public var themeColor: UIColor?
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit(self.providers, connected: nil, failed: nil)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nil, bundle: nil)
commonInit([], connected: nil, failed: nil)
}
public init(themeColor: UIColor, logo: UIImage?, useEmailAuthentication: Bool, providers: [SocialProvider?]) {
let splash = UIViewController(nibName: nil, bundle: nil)
super.init(rootViewController: splash)
self.navigationBar.backgroundColor = themeColor
self.navigationBar.barStyle = .Black
self.navigationBar.barTintColor = themeColor
self.navigationBar.tintColor = UIColor.whiteColor()
self.navigationBar.translucent = false
self.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.useEmailAuthentication = useEmailAuthentication
self.logo = logo
self.providers = providers
self.themeColor = themeColor
}
func commonInit(providers: [SocialProvider?], connected: loginSuccess?, failed: loginFailure?) {
self.providers = providers
if let connected = connected {
self.connected = connected
} else {
self.connected = {(session: RockAuthSession) -> () in
print(session)
}
}
if let failed = failed {
self.failed = failed
} else {
self.failed = {(error: ErrorType) -> () in
print(error)
}
}
}
public func showUI(presenter: UIViewController, connected: loginSuccess, failed: loginFailure) {
self.connected = connected
self.failed = failed
let splash = SplashViewController(showCancelButton: true, logo: self.logo, useEmailAuthentication: self.useEmailAuthentication, providers: self.providers, connected: self.connected, failed: self.failed)
self.viewControllers = [splash]
// self.modalPresentationStyle = .Custom
presenter.presentViewController(self, animated: true) { () -> Void in
}
}
}
| mit | 5e14cf48bfe9d6c7511474a2843089f8 | 35.054054 | 210 | 0.66042 | 4.904412 | false | false | false | false |
mseemann/D2Layers | Pod/Classes/Layer/PieSliceLayer.swift | 1 | 4016 | //
// PieSliceLayer.swift
// TestGraphics
//
// Created by Michael Seemann on 06.11.15.
// Copyright © 2015 Michael Seemann. All rights reserved.
//
import Foundation
public class PieSliceLayer: CustomAnimPieLayer {
private static let animProps = ["startAngle", "endAngle", "innerRadius", "outerRadius", "fillColor", "strokeColor", "strokeWidth"]
public override init() {
super.init()
self.fillColor = UIColor.grayColor().CGColor
self.strokeColor = UIColor.blackColor().CGColor
self.strokeWidth = 1.0
//
// self.shadowRadius = 10.0
// self.shadowOffset = CGSize(width: 0, height: 0)
// self.shadowColor = UIColor.grayColor().CGColor
// self.masksToBounds = false
// self.shadowOpacity = 1.0
self.setNeedsDisplay()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override init(layer: AnyObject) {
super.init(layer:layer)
if let slice = layer as? PieSliceLayer {
self.startAngle = slice.startAngle;
self.endAngle = slice.endAngle;
self.fillColor = slice.fillColor;
self.innerRadius = slice.innerRadius;
self.outerRadius = slice.outerRadius;
self.strokeColor = slice.strokeColor;
self.strokeWidth = slice.strokeWidth;
}
}
override static public func needsDisplayForKey(key: String) -> Bool{
if animProps.contains(key) {
return true
}
return super.needsDisplayForKey(key)
}
override public func actionForKey(event: String) -> CAAction? {
if PieSliceLayer.animProps.contains(event){
return createAnimationForKey(event)
}
return super.actionForKey(event)
}
override public func drawInContext(ctx: CGContext) {
let center = CGPoint(x:self.bounds.size.width/2, y:self.bounds.size.height/2)
let radius = Float(outerRadius)
let iRadius = Float(innerRadius)
CGContextSetFillColorWithColor(ctx, fillColor)
CGContextSetStrokeColorWithColor(ctx, strokeColor)
CGContextSetLineWidth(ctx, CGFloat(strokeWidth))
CGContextBeginPath(ctx)
let p0 = CGPoint(x:CGFloat(Float(center.x) + iRadius * cosf(Float(startAngle))), y:CGFloat(Float(center.y) + iRadius * sinf(Float(startAngle))))
CGContextMoveToPoint(ctx, p0.x, p0.y)
let p1 = CGPoint(x:CGFloat(Float(center.x) + radius * cosf(Float(startAngle))), y:CGFloat(Float(center.y) + radius * sinf(Float(startAngle))))
CGContextAddLineToPoint(ctx, p1.x, p1.y)
let clockwise = self.startAngle > self.endAngle ? 1 : 0
CGContextAddArc(ctx, center.x, center.y, CGFloat(radius), CGFloat(startAngle), CGFloat(endAngle), Int32(clockwise))
let p3 = CGPoint(x:CGFloat(Float(center.x) + iRadius * cosf(Float(endAngle))), y:CGFloat(Float(center.y) + iRadius * sinf(Float(endAngle))))
CGContextAddLineToPoint(ctx, p3.x, p3.y)
CGContextAddArc(ctx, center.x, center.y, CGFloat(iRadius), CGFloat(endAngle), CGFloat(startAngle), Int32(clockwise == 0 ? 1: 0))
CGContextClosePath(ctx)
CGContextDrawPath(ctx, CGPathDrawingMode.FillStroke)
}
func createAnimationForKey(key: String) -> CAAnimation? {
let anim = CABasicAnimation(keyPath: key)
anim.fromValue = self.presentationLayer()?.valueForKey(key)
if anim.fromValue == nil {
anim.fromValue = self.valueForKey(key)
}
anim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
anim.duration = 0.3
return anim
}
override public func layoutSublayers() {
self.frame = (superlayer?.bounds)!
super.layoutSublayers()
}
}
| mit | a9db7adb72b22cf5704a2c9db82e1771 | 34.530973 | 152 | 0.62391 | 4.476031 | false | false | false | false |
hungtruong/TouchFart | TouchFart/WindowController.swift | 1 | 1695 | //
// WindowController.swift
// TouchFart
//
// Created by Hung Truong on 10/27/16.
// Copyright © 2016 Hung Truong. All rights reserved.
//
import Cocoa
fileprivate extension NSTouchBar.CustomizationIdentifier {
static let touchBar = NSTouchBar.CustomizationIdentifier("com.hung-truong.touchfart")
}
fileprivate extension NSTouchBarItem.Identifier {
static let 💩 = NSTouchBarItem.Identifier("💩")
static let 💨 = NSTouchBarItem.Identifier("💨")
static let fart = NSTouchBarItem.Identifier("fart")
static let dry = NSTouchBarItem.Identifier("dry")
static let creamy = NSTouchBarItem.Identifier("creamy")
}
class WindowController: NSWindowController, NSTouchBarDelegate {
@objc func handleFart(sender: NSButton) {
let title = sender.title
guard let sound = NSSound(named: NSSound.Name(rawValue: title)) else {
return
}
sound.play()
}
@available(OSX 10.12.2, *)
override func makeTouchBar() -> NSTouchBar? {
let touchBar = NSTouchBar()
touchBar.delegate = self
touchBar.customizationIdentifier = .touchBar
touchBar.defaultItemIdentifiers = [.💩, .💨, .fixedSpaceSmall, .fart, .dry, .creamy]
return touchBar
}
@available(OSX 10.12.2, *)
func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
let touchBarItem = NSCustomTouchBarItem(identifier: identifier)
touchBarItem.view = NSButton(title: identifier.rawValue, target: self, action: #selector(handleFart))
return touchBarItem
}
}
| mit | 33e22f392cb1972bd558288acf1ef1fa | 31.862745 | 123 | 0.666468 | 4.445623 | false | false | false | false |
ranacquat/fish | Carthage/Checkouts/Fusuma/Sources/FusumaViewController.swift | 1 | 17358 | //
// FusumaViewController.swift
// Fusuma
//
// Created by Yuta Akizuki on 2015/11/14.
// Copyright © 2015年 ytakzk. All rights reserved.
//
import UIKit
import Photos
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
@objc public protocol FusumaDelegate: class {
func fusumaImageSelected(_ image: UIImage)
@objc optional func fusumaDismissedWithImage(_ image: UIImage)
func fusumaVideoCompleted(withFileURL fileURL: URL)
func fusumaCameraRollUnauthorized()
@objc optional func fusumaClosed()
}
public var fusumaBaseTintColor = UIColor.hex("#FFFFFF", alpha: 1.0)
public var fusumaTintColor = UIColor.hex("#009688", alpha: 1.0)
public var fusumaBackgroundColor = UIColor.hex("#212121", alpha: 1.0)
public var fusumaAlbumImage : UIImage? = nil
public var fusumaCameraImage : UIImage? = nil
public var fusumaVideoImage : UIImage? = nil
public var fusumaCheckImage : UIImage? = nil
public var fusumaCloseImage : UIImage? = nil
public var fusumaFlashOnImage : UIImage? = nil
public var fusumaFlashOffImage : UIImage? = nil
public var fusumaFlipImage : UIImage? = nil
public var fusumaShotImage : UIImage? = nil
public var fusumaVideoStartImage : UIImage? = nil
public var fusumaVideoStopImage : UIImage? = nil
public var fusumaCropImage: Bool = true
public var fusumaCameraRollTitle = "CAMERA ROLL"
public var fusumaCameraTitle = "PHOTO"
public var fusumaVideoTitle = "VIDEO"
public var fusumaTitleFont = UIFont(name: "AvenirNext-DemiBold", size: 15)
public var fusumaTintIcons : Bool = true
public enum FusumaModeOrder {
case cameraFirst
case libraryFirst
}
//@objc public class FusumaViewController: UIViewController, FSCameraViewDelegate, FSAlbumViewDelegate {
public final class FusumaViewController: UIViewController {
enum Mode {
case camera
case library
case video
}
public var hasVideo = false
var mode: Mode = .camera
public var modeOrder: FusumaModeOrder = .libraryFirst
var willFilter = true
@IBOutlet weak var photoLibraryViewerContainer: UIView!
@IBOutlet weak var cameraShotContainer: UIView!
@IBOutlet weak var videoShotContainer: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var menuView: UIView!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var libraryButton: UIButton!
@IBOutlet weak var cameraButton: UIButton!
@IBOutlet weak var videoButton: UIButton!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet var libraryFirstConstraints: [NSLayoutConstraint]!
@IBOutlet var cameraFirstConstraints: [NSLayoutConstraint]!
lazy var albumView = FSAlbumView.instance()
lazy var cameraView = FSCameraView.instance()
lazy var videoView = FSVideoCameraView.instance()
fileprivate var hasGalleryPermission: Bool {
return PHPhotoLibrary.authorizationStatus() == .authorized
}
public weak var delegate: FusumaDelegate? = nil
override public func loadView() {
if let view = UINib(nibName: "FusumaViewController", bundle: Bundle(for: self.classForCoder)).instantiate(withOwner: self, options: nil).first as? UIView {
self.view = view
}
}
override public func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = fusumaBackgroundColor
cameraView.delegate = self
albumView.delegate = self
videoView.delegate = self
menuView.backgroundColor = fusumaBackgroundColor
menuView.addBottomBorder(UIColor.black, width: 1.0)
let bundle = Bundle(for: self.classForCoder)
// Get the custom button images if they're set
let albumImage = fusumaAlbumImage != nil ? fusumaAlbumImage : UIImage(named: "ic_insert_photo", in: bundle, compatibleWith: nil)
let cameraImage = fusumaCameraImage != nil ? fusumaCameraImage : UIImage(named: "ic_photo_camera", in: bundle, compatibleWith: nil)
let videoImage = fusumaVideoImage != nil ? fusumaVideoImage : UIImage(named: "ic_videocam", in: bundle, compatibleWith: nil)
let checkImage = fusumaCheckImage != nil ? fusumaCheckImage : UIImage(named: "ic_check", in: bundle, compatibleWith: nil)
let closeImage = fusumaCloseImage != nil ? fusumaCloseImage : UIImage(named: "ic_close", in: bundle, compatibleWith: nil)
if fusumaTintIcons {
libraryButton.setImage(albumImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
libraryButton.setImage(albumImage?.withRenderingMode(.alwaysTemplate), for: .highlighted)
libraryButton.setImage(albumImage?.withRenderingMode(.alwaysTemplate), for: .selected)
libraryButton.tintColor = fusumaTintColor
libraryButton.adjustsImageWhenHighlighted = false
cameraButton.setImage(cameraImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
cameraButton.setImage(cameraImage?.withRenderingMode(.alwaysTemplate), for: .highlighted)
cameraButton.setImage(cameraImage?.withRenderingMode(.alwaysTemplate), for: .selected)
cameraButton.tintColor = fusumaTintColor
cameraButton.adjustsImageWhenHighlighted = false
closeButton.setImage(closeImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
closeButton.setImage(closeImage?.withRenderingMode(.alwaysTemplate), for: .highlighted)
closeButton.setImage(closeImage?.withRenderingMode(.alwaysTemplate), for: .selected)
closeButton.tintColor = fusumaBaseTintColor
videoButton.setImage(videoImage, for: UIControlState())
videoButton.setImage(videoImage, for: .highlighted)
videoButton.setImage(videoImage, for: .selected)
videoButton.tintColor = fusumaTintColor
videoButton.adjustsImageWhenHighlighted = false
doneButton.setImage(checkImage?.withRenderingMode(.alwaysTemplate), for: UIControlState())
doneButton.tintColor = fusumaBaseTintColor
} else {
libraryButton.setImage(albumImage, for: UIControlState())
libraryButton.setImage(albumImage, for: .highlighted)
libraryButton.setImage(albumImage, for: .selected)
libraryButton.tintColor = nil
cameraButton.setImage(cameraImage, for: UIControlState())
cameraButton.setImage(cameraImage, for: .highlighted)
cameraButton.setImage(cameraImage, for: .selected)
cameraButton.tintColor = nil
videoButton.setImage(videoImage, for: UIControlState())
videoButton.setImage(videoImage, for: .highlighted)
videoButton.setImage(videoImage, for: .selected)
videoButton.tintColor = nil
closeButton.setImage(closeImage, for: UIControlState())
doneButton.setImage(checkImage, for: UIControlState())
}
cameraButton.clipsToBounds = true
libraryButton.clipsToBounds = true
videoButton.clipsToBounds = true
changeMode(Mode.library)
photoLibraryViewerContainer.addSubview(albumView)
cameraShotContainer.addSubview(cameraView)
videoShotContainer.addSubview(videoView)
titleLabel.textColor = fusumaBaseTintColor
titleLabel.font = fusumaTitleFont
// if modeOrder != .LibraryFirst {
// libraryFirstConstraints.forEach { $0.priority = 250 }
// cameraFirstConstraints.forEach { $0.priority = 1000 }
// }
if !hasVideo {
videoButton.removeFromSuperview()
self.view.addConstraint(NSLayoutConstraint(
item: self.view,
attribute: .trailing,
relatedBy: .equal,
toItem: cameraButton,
attribute: .trailing,
multiplier: 1.0,
constant: 0
)
)
self.view.layoutIfNeeded()
}
if fusumaCropImage {
cameraView.fullAspectRatioConstraint.isActive = false
cameraView.croppedAspectRatioConstraint.isActive = true
} else {
cameraView.fullAspectRatioConstraint.isActive = true
cameraView.croppedAspectRatioConstraint.isActive = false
}
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
albumView.frame = CGRect(origin: CGPoint.zero, size: photoLibraryViewerContainer.frame.size)
albumView.layoutIfNeeded()
cameraView.frame = CGRect(origin: CGPoint.zero, size: cameraShotContainer.frame.size)
cameraView.layoutIfNeeded()
albumView.initialize()
cameraView.initialize()
if hasVideo {
videoView.frame = CGRect(origin: CGPoint.zero, size: videoShotContainer.frame.size)
videoView.layoutIfNeeded()
videoView.initialize()
}
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.stopAll()
}
override public var prefersStatusBarHidden : Bool {
return true
}
@IBAction func closeButtonPressed(_ sender: UIButton) {
self.dismiss(animated: true, completion: {
self.delegate?.fusumaClosed?()
})
}
@IBAction func libraryButtonPressed(_ sender: UIButton) {
changeMode(Mode.library)
}
@IBAction func photoButtonPressed(_ sender: UIButton) {
changeMode(Mode.camera)
}
@IBAction func videoButtonPressed(_ sender: UIButton) {
changeMode(Mode.video)
}
@IBAction func doneButtonPressed(_ sender: UIButton) {
let view = albumView.imageCropView
if fusumaCropImage {
let normalizedX = (view?.contentOffset.x)! / (view?.contentSize.width)!
let normalizedY = (view?.contentOffset.y)! / (view?.contentSize.height)!
let normalizedWidth = (view?.frame.width)! / (view?.contentSize.width)!
let normalizedHeight = (view?.frame.height)! / (view?.contentSize.height)!
let cropRect = CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight)
DispatchQueue.global(qos: .default).async(execute: {
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.isNetworkAccessAllowed = true
options.normalizedCropRect = cropRect
options.resizeMode = .exact
let targetWidth = floor(CGFloat(self.albumView.phAsset.pixelWidth) * cropRect.width)
let targetHeight = floor(CGFloat(self.albumView.phAsset.pixelHeight) * cropRect.height)
let dimension = max(min(targetHeight, targetWidth), 1024 * UIScreen.main.scale)
let targetSize = CGSize(width: dimension, height: dimension)
PHImageManager.default().requestImage(for: self.albumView.phAsset, targetSize: targetSize,
contentMode: .aspectFill, options: options) {
result, info in
DispatchQueue.main.async(execute: {
self.delegate?.fusumaImageSelected(result!)
self.dismiss(animated: true, completion: {
self.delegate?.fusumaDismissedWithImage?(result!)
})
})
}
})
} else {
print("no image crop ")
delegate?.fusumaImageSelected((view?.image)!)
self.dismiss(animated: true, completion: {
self.delegate?.fusumaDismissedWithImage?((view?.image)!)
})
}
}
}
extension FusumaViewController: FSAlbumViewDelegate, FSCameraViewDelegate, FSVideoCameraViewDelegate {
// MARK: FSCameraViewDelegate
func cameraShotFinished(_ image: UIImage) {
delegate?.fusumaImageSelected(image)
self.dismiss(animated: true, completion: {
self.delegate?.fusumaDismissedWithImage?(image)
})
}
public func albumViewCameraRollAuthorized() {
// in the case that we're just coming back from granting photo gallery permissions
// ensure the done button is visible if it should be
self.updateDoneButtonVisibility()
}
// MARK: FSAlbumViewDelegate
public func albumViewCameraRollUnauthorized() {
delegate?.fusumaCameraRollUnauthorized()
}
func videoFinished(withFileURL fileURL: URL) {
delegate?.fusumaVideoCompleted(withFileURL: fileURL)
self.dismiss(animated: true, completion: nil)
}
}
private extension FusumaViewController {
func stopAll() {
if hasVideo {
self.videoView.stopCamera()
}
self.cameraView.stopCamera()
}
func changeMode(_ mode: Mode) {
if self.mode == mode {
return
}
//operate this switch before changing mode to stop cameras
switch self.mode {
case .library:
break
case .camera:
self.cameraView.stopCamera()
case .video:
self.videoView.stopCamera()
}
self.mode = mode
dishighlightButtons()
updateDoneButtonVisibility()
switch mode {
case .library:
titleLabel.text = NSLocalizedString(fusumaCameraRollTitle, comment: fusumaCameraRollTitle)
highlightButton(libraryButton)
self.view.bringSubview(toFront: photoLibraryViewerContainer)
case .camera:
titleLabel.text = NSLocalizedString(fusumaCameraTitle, comment: fusumaCameraTitle)
highlightButton(cameraButton)
self.view.bringSubview(toFront: cameraShotContainer)
cameraView.startCamera()
case .video:
titleLabel.text = fusumaVideoTitle
highlightButton(videoButton)
self.view.bringSubview(toFront: videoShotContainer)
videoView.startCamera()
}
doneButton.isHidden = !hasGalleryPermission
self.view.bringSubview(toFront: menuView)
}
func updateDoneButtonVisibility() {
// don't show the done button without gallery permission
if !hasGalleryPermission {
self.doneButton.isHidden = true
return
}
switch self.mode {
case .library:
self.doneButton.isHidden = false
default:
self.doneButton.isHidden = true
}
}
func dishighlightButtons() {
cameraButton.tintColor = fusumaBaseTintColor
libraryButton.tintColor = fusumaBaseTintColor
if cameraButton.layer.sublayers?.count > 1 {
for layer in cameraButton.layer.sublayers! {
if let borderColor = layer.borderColor , UIColor(cgColor: borderColor) == fusumaTintColor {
layer.removeFromSuperlayer()
}
}
}
if libraryButton.layer.sublayers?.count > 1 {
for layer in libraryButton.layer.sublayers! {
if let borderColor = layer.borderColor , UIColor(cgColor: borderColor) == fusumaTintColor {
layer.removeFromSuperlayer()
}
}
}
if let videoButton = videoButton {
videoButton.tintColor = fusumaBaseTintColor
if videoButton.layer.sublayers?.count > 1 {
for layer in videoButton.layer.sublayers! {
if let borderColor = layer.borderColor , UIColor(cgColor: borderColor) == fusumaTintColor {
layer.removeFromSuperlayer()
}
}
}
}
}
func highlightButton(_ button: UIButton) {
button.tintColor = fusumaTintColor
button.addBottomBorder(fusumaTintColor, width: 3)
}
}
| mit | 150a825ed61bd9df21367046c965bda5 | 33.571713 | 163 | 0.611121 | 5.528831 | false | false | false | false |
0xfeedface1993/Xs8-Safari-Block-Extension-Mac | Sex8BlockExtension/Sex8BlockExtension/DownloadView/ContentCellView.swift | 1 | 6156 | //
// ContentCellView.swift
// PopverTest
//
// Created by virus1993 on 2018/2/27.
// Copyright © 2018年 ascp. All rights reserved.
//
import Cocoa
import WebShell
enum DownloadStatus : String {
case downloading = "下载中"
case downloaded = "完成"
case waitting = "等待中"
case cancel = "已取消"
case errors = "失败"
case abonden = "失效"
static let statusColorPacks : [DownloadStatus:NSColor] = [.downloading:.green,
.downloaded:.blue,
.waitting:.lightGray,
.cancel:.darkGray,
.errors:.red,
.abonden:.brown]
}
extension WebHostSite {
static let hostImagePack : [WebHostSite:NSImage] = [.feemoo:NSImage(named: "mofe_feemoo")!,
.pan666:NSImage(named: "mofe_666pan")!,
.cchooo:NSImage(named: "mofe_ccchooo")!,
.yousuwp:NSImage(named: "mofe_yousu")!,
.v2file:NSImage(named: "mofe_v4")!,
.xunniu:NSImage(named: "mofe_xunniu")!,
.xi:NSImage(named: "mofe_xi")!,
.bus:NSImage(named: "mofe_bus")!,
.color:NSImage(named: "mofe_color")!,
.unknowsite:NSImage(named: "mofe_feemoo")!,
.kuyun:NSImage(named: "mofe_kuyun")!]
}
/// 下载状态数据模型,用于视图数据绑定
class DownloadStateInfo : NSObject {
var uuid = UUID()
var status : DownloadStatus {
didSet {
update(newStatus: status)
}
}
var hostType : WebHostSite {
didSet {
update(newSite: hostType)
}
}
var originTask: PCDownloadTask?
var mainURL : URL?
weak var riffle: PCWebRiffle?
@objc dynamic var name = ""
@objc dynamic var progress = ""
@objc dynamic var totalBytes = ""
@objc dynamic var site = ""
@objc dynamic var state = ""
@objc dynamic var stateColor = NSColor.black
@objc dynamic var isCanCancel : Bool = false
@objc dynamic var isCanRestart : Bool = false
@objc dynamic var isHiddenPrograss : Bool = false
@objc dynamic var siteIcon : NSImage?
override init() {
status = .waitting
hostType = .unknowsite
super.init()
}
init(task: PCDownloadTask) {
status = .downloading
if let url = task.request.riffle?.mainURL {
hostType = siteType(url: url)
} else {
hostType = .unknowsite
}
super.init()
name = task.request.friendName
let pros = task.pack.progress * 100.0
let guts = Float(task.pack.totalBytes) / 1024.0 / 1024.0
progress = String(format: "%.2f", pros)
totalBytes = String(format: "%.2fM", guts)
originTask = task
mainURL = task.request.mainURL
uuid = task.request.uuid
update(newSite: hostType)
update(newStatus: status)
}
init(riffle: PCWebRiffle) {
status = .waitting
hostType = riffle.host
super.init()
name = riffle.friendName.count <= 0 ? (riffle.mainURL?.absoluteString ?? "no url"):riffle.friendName
mainURL = riffle.mainURL
progress = "0"
totalBytes = "0M"
self.riffle = riffle
uuid = riffle.uuid
update(newSite: hostType)
update(newStatus: status)
}
func update(newStatus: DownloadStatus) {
state = newStatus.rawValue
stateColor = DownloadStatus.statusColorPacks[status]!
isCanCancel = status == .downloading || status == .waitting
isCanRestart = status != .abonden && status != .waitting && status != .downloading
isHiddenPrograss = status != .downloading
}
func update(newSite: WebHostSite) {
siteIcon = WebHostSite.hostImagePack[newSite]!
}
override var description: String {
return "status: \(status)\n hostType: \(hostType)\n name: \(name)\n uuid: \(uuid)\n progress: \(progress)\n" + "site: \(site)\n state: \(state)\n stateColor: \(stateColor)\n isCanCancel: \(isCanCancel)\n isCanRestart: \(isCanRestart)\n" + "isHiddenPrograss: \(isHiddenPrograss)\n siteIcon: \(String(describing: siteIcon))"
}
}
class ContentCellView: NSTableCellView {
@IBOutlet weak var thumbImage: NSImageView!
@IBOutlet weak var fileName: NSTextField!
@IBOutlet weak var prograssText: NSTextField!
@IBOutlet weak var progressBar: NSProgressIndicator!
@IBOutlet weak var status: NSTextField!
@IBOutlet weak var restart: NSButton!
@IBOutlet weak var cancel: NSButton!
weak var info : DownloadStateInfo?
var restartAction : (()->())?
var cancelAction : (()->())?
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
override func awakeFromNib() {
super.awakeFromNib()
restart.isHidden = true
cancel.isHidden = true
// restart.addGestureRecognizer(NSClickGestureRecognizer(target: self, action: #selector(tap(sender:))))
// cancel.addGestureRecognizer(NSClickGestureRecognizer(target: self, action: #selector(tap(sender:))))
}
@objc func tap(sender: NSClickGestureRecognizer) {
guard let v = sender.view as? NSButton, v.isEnabled else { return }
switch v {
case self.restart:
self.restartAction?()
break
case self.cancel:
self.cancelAction?()
break
default:
break
}
}
}
| apache-2.0 | a110be4bfe878771b2900559f812ddfd | 36.355828 | 330 | 0.534406 | 4.467351 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Extensions/UILabelExtension.swift | 2 | 590 | //
// UILabelExtension.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 8/4/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
extension UILabel {
static func heightForView(_ text: String, font: UIFont, width: CGFloat) -> CGFloat {
let label: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = .byClipping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
}
| mit | eb80c85cbb07d4bac198484fb8cb1864 | 24.608696 | 118 | 0.645161 | 3.926667 | false | false | false | false |
ben-ng/swift | stdlib/public/SDK/Foundation/Data.swift | 1 | 64224 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
@_silgen_name("__NSDataInvokeDeallocatorVM")
internal func __NSDataInvokeDeallocatorVM(_ mem: UnsafeMutableRawPointer, _ length: Int) -> Void
@_silgen_name("__NSDataInvokeDeallocatorUnmap")
internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) -> Void
@_silgen_name("__NSDataInvokeDeallocatorFree")
internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) -> Void
@_silgen_name("_NSWriteDataToFile_Swift")
internal func _NSWriteDataToFile_Swift(url: NSURL, data: NSData, options: UInt, error: NSErrorPointer) -> Bool
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 foregin sources where neither Swift nor Foundation are fully certain whom they belong
// to from a 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) | unsafeBitCast(dest, to: Int.self)) & (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)? = nil
public var _backing: Backing = .swift
public var bytes: UnsafeRawPointer? {
@inline(__always)
get {
switch _backing {
case .swift:
return UnsafeRawPointer(_bytes)
case .immutable:
return UnsafeRawPointer(_bytes)
case .mutable:
return UnsafeRawPointer(_bytes)
case .customReference(let d):
return d.bytes
case .customMutableReference(let d):
return d.bytes
}
}
}
public var mutableBytes: UnsafeMutableRawPointer? {
@inline(__always)
get {
switch _backing {
case .swift:
return _bytes
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .mutable(data)
_bytes = data.mutableBytes
return data.mutableBytes
case .mutable:
return _bytes
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .customMutableReference(data)
_bytes = data.mutableBytes
return data.mutableBytes
case .customMutableReference(let d):
return d.mutableBytes
}
}
}
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(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) {
var stop: Bool = false
switch _backing {
case .swift:
block(UnsafeBufferPointer<UInt8>(start: _bytes?.assumingMemoryBound(to: UInt8.self), count: _length), 0, &stop)
break
case .immutable:
block(UnsafeBufferPointer<UInt8>(start: _bytes?.assumingMemoryBound(to: UInt8.self), count: _length), 0, &stop)
break
case .mutable:
block(UnsafeBufferPointer<UInt8>(start: _bytes?.assumingMemoryBound(to: UInt8.self), count: _length), 0, &stop)
break
case .customReference(let d):
d.enumerateBytes { (ptr, range, stop) in
var stopv = false
let bytePtr = ptr.bindMemory(to: UInt8.self, capacity: range.length)
block(UnsafeBufferPointer(start: bytePtr, count: range.length), range.length, &stopv)
if stopv {
stop.pointee = true
}
}
break
case .customMutableReference(let d):
d.enumerateBytes { (ptr, range, stop) in
var stopv = false
let bytePtr = ptr.bindMemory(to: UInt8.self, capacity: range.length)
block(UnsafeBufferPointer(start: bytePtr, count: range.length), range.length, &stopv)
if stopv {
stop.pointee = true
}
}
break
}
}
@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 newBytes != nil {
_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 newBytes != nil {
_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 newBytes != nil {
_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
break
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .mutable(data)
_length = length
_bytes = data.mutableBytes
break
case .mutable(let d):
d.length = length
_length = length
_bytes = d.mutableBytes
break
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.length = length
_backing = .customMutableReference(data)
break
case .customMutableReference(let d):
d.length = length
break
}
}
@inline(__always)
public func append(_ bytes: UnsafeRawPointer, length: Int) {
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)
break
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.append(bytes, length: length)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
break
case .mutable(let d):
d.append(bytes, length: length)
_length = d.length
_bytes = d.mutableBytes
break
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.append(bytes, length: length)
_backing = .customReference(data)
break
case .customMutableReference(let d):
d.append(bytes, length: length)
break
}
}
// fast-path for appending directly from another data storage
@inline(__always)
public func append(_ otherData: _DataStorage) {
let otherLength = otherData.length
if otherLength == 0 { return }
if let bytes = otherData.bytes {
append(bytes, length: otherLength)
}
}
@inline(__always)
public func append(_ otherData: Data) {
otherData.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, location: Data.Index, stop: inout Bool) 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
break
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.increaseLength(by: extraLength)
_backing = .mutable(data)
_length += extraLength
_bytes = data.mutableBytes
break
case .mutable(let d):
d.increaseLength(by: extraLength)
_length += extraLength
_bytes = d.mutableBytes
break
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.increaseLength(by: extraLength)
_backing = .customReference(data)
break
case .customMutableReference(let d):
d.increaseLength(by: extraLength)
break
}
}
@inline(__always)
public func set(_ index: Int, to value: UInt8) {
switch _backing {
case .swift:
fallthrough
case .mutable:
_bytes!.advanced(by: index).assumingMemoryBound(to: UInt8.self).pointee = value
break
default:
var theByte = value
let range = NSRange(location: index, length: 1)
replaceBytes(in: range, with: &theByte, length: 1)
break
}
}
@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), bytes!, range.length)
break
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: range, withBytes: bytes!)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
break
case .mutable(let d):
d.replaceBytes(in: range, withBytes: bytes!)
_length = d.length
_bytes = d.mutableBytes
break
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: range, withBytes: bytes!)
_backing = .customMutableReference(data)
break
case .customMutableReference(let d):
d.replaceBytes(in: range, withBytes: bytes!)
break
}
}
@inline(__always)
public func replaceBytes(in range: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) {
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 replacementBytes != nil {
memmove(mutableBytes! + start, replacementBytes, replacementLength)
} else {
memset(mutableBytes! + start, 0, replacementLength)
}
}
if resultingLength < currentLength {
setLength(resultingLength)
}
break
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
_backing = .mutable(data)
_length = replacementLength
_bytes = data.mutableBytes
break
case .mutable(let d):
d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
_backing = .mutable(d)
_length = replacementLength
_bytes = d.mutableBytes
break
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
_backing = .customMutableReference(data)
break
case .customMutableReference(let d):
d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength)
break
}
}
@inline(__always)
public func resetBytes(in range: NSRange) {
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)
break
case .immutable(let d):
let data = d.mutableCopy() as! NSMutableData
data.resetBytes(in: range)
_backing = .mutable(data)
_length = data.length
_bytes = data.mutableBytes
break
case .mutable(let d):
d.resetBytes(in: range)
_length = d.length
_bytes = d.mutableBytes
break
case .customReference(let d):
let data = d.mutableCopy() as! NSMutableData
data.resetBytes(in: range)
_backing = .customMutableReference(data)
break
case .customMutableReference(let d):
d.resetBytes(in: range)
break
}
}
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
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
}
public init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?) {
precondition(length < _DataStorage.maxSize)
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) {
_bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes)
_capacity = 0
_needToZero = false
_length = immutableReference.length
_backing = .immutable(immutableReference)
}
public init(mutableReference: NSMutableData) {
_bytes = mutableReference.mutableBytes
_capacity = 0
_needToZero = false
_length = mutableReference.length
_backing = .mutable(mutableReference)
}
public init(customReference: NSData) {
_bytes = nil
_capacity = 0
_needToZero = false
_length = 0
_backing = .customReference(customReference)
}
public init(customMutableReference: NSMutableData) {
_bytes = nil
_capacity = 0
_needToZero = false
_length = 0
_backing = .customMutableReference(customMutableReference)
}
deinit {
switch _backing {
case .swift:
_freeBytes()
break
default:
break
}
}
@inline(__always)
public func mutableCopy() -> _DataStorage {
switch _backing {
case .swift:
return _DataStorage(bytes: _bytes, length: _length, copy: true, deallocator: nil)
case .immutable(let d):
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData)
case .mutable(let d):
return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData)
case .customReference(let d):
return _DataStorage(customMutableReference: d.mutableCopy() as! NSMutableData)
case .customMutableReference(let d):
return _DataStorage(customMutableReference: d.mutableCopy() as! NSMutableData)
}
}
public func withInteriorPointerReference<T>(_ work: (NSData) throws -> T) rethrows -> T {
switch _backing {
case .swift:
return try work(NSData(bytesNoCopy: _bytes!, length: _length, freeWhenDone: false))
case .immutable(let d):
return try work(d)
case .mutable(let d):
return try work(d)
case .customReference(let d):
return try work(d)
case .customMutableReference(let d):
return try work(d)
}
}
public func bridgedReference() -> NSData {
switch _backing {
case .swift:
return _NSSwiftData(backing: self)
case .immutable(let d):
return d
case .mutable(let d):
return d
case .customReference(let d):
return d
case .customMutableReference(let d):
// Because this is returning an object that may be mutated in the future it needs to create a copy to prevent
// any further mutations out from under the reciever
return d.copy() as! NSData
}
}
public static func ==(_ lhs: _DataStorage, _ rhs: _DataStorage) -> Bool {
switch (lhs._backing, rhs._backing) {
case (.swift, .customReference(let d)):
return lhs.withInteriorPointerReference {
return $0.isEqual(d)
}
case (.swift, .customMutableReference(let d)):
return lhs.withInteriorPointerReference {
return $0.isEqual(d)
}
case (.immutable(let d1), .customReference(let d2)):
return d1.isEqual(d2)
case (.immutable(let d1), .customMutableReference(let d2)):
return d1.isEqual(d2)
case (.mutable(let d1), .customReference(let d2)):
return d1.isEqual(d2)
case (.mutable(let d1), .customMutableReference(let d2)):
return d1.isEqual(d2)
case (.customReference(let d), .swift):
return rhs.withInteriorPointerReference {
return d.isEqual($0)
}
case (.customReference(let d1), .immutable):
return rhs.withInteriorPointerReference {
return d1.isEqual($0)
}
case (.customReference(let d1), .mutable):
return rhs.withInteriorPointerReference {
return d1.isEqual($0)
}
case (.customReference(let d1), .customReference(let d2)):
return d1.isEqual(d2)
case (.customReference(let d1), .customMutableReference(let d2)):
return d1.isEqual(d2)
case (.customMutableReference(let d), .swift):
return rhs.withInteriorPointerReference {
return d.isEqual($0)
}
case (.customMutableReference(let d1), .immutable):
return rhs.withInteriorPointerReference {
return d1.isEqual($0)
}
case (.customMutableReference(let d1), .mutable):
return rhs.withInteriorPointerReference {
return d1.isEqual($0)
}
case (.customMutableReference(let d1), .customReference(let d2)):
return d1.isEqual(d2)
case (.customMutableReference(let d1), .customMutableReference(let d2)):
return d1.isEqual(d2)
default:
let length1 = lhs.length
if length1 != rhs.length {
return false
}
if lhs.bytes == rhs.bytes {
return true
}
return memcmp(lhs._bytes, rhs._bytes, length1) == 0
}
}
public var hashValue: Int {
switch _backing {
case .customReference(let d):
return d.hash
case .customMutableReference(let d):
return d.hash
default:
let len = _length
return Int(bitPattern: CFHashBytes(_bytes?.assumingMemoryBound(to: UInt8.self), Swift.min(len, 80)))
}
}
public func subdata(in range: Range<Data.Index>) -> Data {
switch _backing {
case .customReference(let d):
return d.subdata(with: NSRange(location: range.lowerBound, length: range.count))
case .customMutableReference(let d):
return d.subdata(with: NSRange(location: range.lowerBound, length: range.count))
default:
return Data(bytes: _bytes!.advanced(by: range.lowerBound), count: range.count)
}
}
}
internal class _NSSwiftData : NSData {
var _backing: _DataStorage!
convenience init(backing: _DataStorage) {
self.init()
_backing = backing
}
override var length: Int {
return _backing.length
}
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 a 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.
return _backing.bytes ?? UnsafeRawPointer(bitPattern: 0xBAD0)!
}
override func copy(with zone: NSZone? = nil) -> Any {
return NSData(bytes: _backing.bytes, length: _backing.length)
}
@objc
func _isCompact() -> Bool {
return true
}
@objc(_providesConcreteBacking)
func _providesConcreteBacking() -> Bool {
return true
}
}
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 = CountableRange<Int>
internal var _backing : _DataStorage
// 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.
case virtualMemory
/// 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)? {
switch self {
case .virtualMemory:
return { __NSDataInvokeDeallocatorVM($0, $1) }
case .unmap:
return { __NSDataInvokeDeallocatorUnmap($0, $1) }
case .free:
return { __NSDataInvokeDeallocatorFree($0, $1) }
case .none:
return nil
case .custom(let b):
return { (ptr, len) in
b(ptr, len)
}
}
}
}
// 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: UnsafeMutableRawPointer(mutating: bytes), length: count, copy: true, deallocator: nil)
}
/// 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>) {
_backing = _DataStorage(bytes: UnsafeMutableRawPointer(mutating: buffer.baseAddress), length: MemoryLayout<SourceType>.stride * buffer.count, copy: true, deallocator: nil)
}
/// 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>) {
_backing = _DataStorage(bytes: buffer.baseAddress, length: MemoryLayout<SourceType>.stride * buffer.count, copy: true, deallocator: nil)
}
/// Initialize a `Data` with the contents of an Array.
///
/// - parameter bytes: An array of bytes to copy.
public init(bytes: Array<UInt8>) {
_backing = bytes.withUnsafeBufferPointer {
return _DataStorage(bytes: UnsafeMutableRawPointer(mutating: $0.baseAddress), length: $0.count, copy: true, deallocator: nil)
}
}
/// Initialize a `Data` with the contents of an Array.
///
/// - parameter bytes: An array of bytes to copy.
public init(bytes: ArraySlice<UInt8>) {
_backing = bytes.withUnsafeBufferPointer {
return _DataStorage(bytes: UnsafeMutableRawPointer(mutating: $0.baseAddress), length: $0.count, copy: true, deallocator: nil)
}
}
/// 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)
}
/// 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)
}
/// Initialize an empty `Data`.
public init() {
_backing = _DataStorage(length: 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(immutableReference: NSData(bytesNoCopy: bytes, length: count, deallocator: whichDeallocator))
}
/// 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 {
_backing = _DataStorage(immutableReference: try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue)))
}
/// 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)
} 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)
} 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) {
let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false
if providesConcreteBacking {
_backing = _DataStorage(immutableReference: reference.copy() as! NSData)
} else {
_backing = _DataStorage(customReference: reference.copy() as! NSData)
}
}
// -----------------------------------
// MARK: - Properties and Functions
/// The number of bytes in the data.
public var count: Int {
@inline(__always)
get {
return _backing.length
}
@inline(__always)
set {
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy()
}
_backing.length = 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 {
let bytes = _backing.bytes!
defer { _fixLifetime(self)}
let contentPtr = bytes.bindMemory(to: ContentType.self, capacity: count / MemoryLayout<ContentType>.stride)
return try body(contentPtr)
}
/// 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()
}
let mutableBytes = _backing.mutableBytes!
defer { _fixLifetime(self)}
let contentPtr = mutableBytes.bindMemory(to: ContentType.self, capacity: count / MemoryLayout<ContentType>.stride)
return try body(UnsafeMutablePointer(contentPtr))
}
// 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) {
memcpy(UnsafeMutableRawPointer(pointer), _backing.bytes!, count)
}
@inline(__always)
private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: NSRange) {
memcpy(UnsafeMutableRawPointer(pointer), _backing.bytes!.advanced(by: range.location), range.length)
}
/// 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 }
precondition(r.lowerBound >= 0)
precondition(r.lowerBound < cnt, "The range is outside the bounds of the data")
precondition(r.upperBound >= 0)
precondition(r.upperBound <= cnt, "The range is outside the bounds of the data")
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)
}
guard !copyRange.isEmpty else { return 0 }
let nsRange = NSMakeRange(copyRange.lowerBound, copyRange.upperBound - copyRange.lowerBound)
_copyBytesHelper(to: buffer.baseAddress!, from: nsRange)
return copyRange.count
}
// MARK: -
@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(OSX)
return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max)
#else
return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max)
#endif
} else {
return false
}
}
/// 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 {
if _shouldUseNonAtomicWriteReimplementation(options: options) {
var error : NSError?
if !_NSWriteDataToFile_Swift(url: url._bridgeToObjectiveC(), data: $0, options: options.rawValue, error: &error) {
throw error!
}
} else {
try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue))
}
}
}
// 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 {
nsRange = NSMakeRange(r.lowerBound, r.upperBound - r.lowerBound)
} else {
nsRange = NSMakeRange(0, _backing.length)
}
let result = _backing.withInteriorPointerReference {
$0.range(of: dataToFind, options: options, in: nsRange)
}
if result.location == NSNotFound {
return nil
}
return result.location..<(result.location + 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(block)
}
@inline(__always)
public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) {
if count == 0 { return }
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy()
}
_backing.append(bytes, length: count)
}
@inline(__always)
public mutating func append(_ other: Data) {
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy()
}
_backing.append(other._backing)
}
/// 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.count == 0 { return }
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy()
}
_backing.append(buffer.baseAddress!, length: buffer.count * MemoryLayout<SourceType>.stride)
}
@inline(__always)
public mutating func append(_ other: MutableRangeReplaceableRandomAccessSlice<Data>) {
let count = other.count
if count == 0 { return }
other.base.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in
append(bytes, count: count)
}
}
@inline(__always)
public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == Iterator.Element {
let estimatedCount = newElements.underestimatedCount
var idx = count
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy()
}
count += estimatedCount
for byte in newElements {
self[idx] = byte
idx += 1
count = idx
}
}
@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>) {
let range = NSMakeRange(range.lowerBound, range.upperBound - range.lowerBound)
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy()
}
_backing.resetBytes(in: range)
}
/// 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 nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound)
let cnt = data.count
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy()
}
data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in
_backing.replaceBytes(in: nsRange, with: bytes, length: 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>) {
let nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound)
let bufferCount = buffer.count * MemoryLayout<SourceType>.stride
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy()
}
_backing.replaceBytes(in: nsRange, with: buffer.baseAddress, length: bufferCount)
}
/// 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 {
// Calculate this once, it may not be O(1)
let replacementCount: Int = numericCast(newElements.count)
let currentCount = self.count
let subrangeCount = subrange.count
if currentCount < subrange.lowerBound + subrangeCount {
if subrangeCount == 0 {
preconditionFailure("location \(subrange.lowerBound) exceeds data count \(currentCount)")
} else {
preconditionFailure("range \(subrange) exceeds data count \(currentCount)")
}
}
let resultCount = currentCount - subrangeCount + replacementCount
if resultCount != currentCount {
// This may realloc.
// In the future, if we keep the malloced pointer and count inside this struct/ref instead of deferring to NSData, we may be able to do this more efficiently.
self.count = resultCount
}
let shift = resultCount - currentCount
let start = subrange.lowerBound
self.withUnsafeMutableBytes { (bytes : UnsafeMutablePointer<UInt8>) -> () in
if shift != 0 {
let destination = bytes + start + replacementCount
let source = bytes + start + subrangeCount
memmove(destination, source, currentCount - start - subrangeCount)
}
if replacementCount != 0 {
newElements._copyContents(initializing: bytes + start)
}
}
}
@inline(__always)
public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) {
let nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound)
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy()
}
_backing.replaceBytes(in: nsRange, with: bytes, length: cnt)
}
/// 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 {
let length = count
if count == 0 {
return Data()
}
precondition(length >= range.upperBound)
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 {
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 {
return $0.base64EncodedData(options: options)
}
}
// MARK: -
//
/// The hash value for the data.
public var hashValue: Int {
return _backing.hashValue
}
@inline(__always)
public func advanced(by amount: Int) -> Data {
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 {
return withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> UInt8 in
return bytes.advanced(by: index).pointee
}
}
@inline(__always)
set {
if !isKnownUniquelyReferenced(&_backing) {
_backing = _backing.mutableCopy()
}
_backing.set(index, to: newValue)
}
}
public subscript(bounds: Range<Index>) -> MutableRangeReplaceableRandomAccessSlice<Data> {
@inline(__always)
get {
return MutableRangeReplaceableRandomAccessSlice(base: self, bounds: bounds)
}
@inline(__always)
set {
replaceSubrange(bounds, with: newValue.base)
}
}
/// The start `Index` in the data.
public var startIndex: Index {
@inline(__always)
get {
return 0
}
}
/// 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 count
}
}
@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: CountableRange<Int> {
@inline(__always)
get {
return startIndex..<endIndex
}
}
/// An iterator over the contents of the data.
///
/// The iterator will increment byte-by-byte.
public func makeIterator() -> Data.Iterator {
return Iterator(_data: self)
}
public struct Iterator : IteratorProtocol {
private let _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 let _endIdx: Data.Index
fileprivate init(_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 = 0
_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 % 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 {
return true
}
let length1 = backing1.length
if length1 != backing2.length {
return false
}
if backing1.bytes == backing2.bytes {
return true
}
return memcmp(backing1.bytes, backing2.bytes, length1) == 0
}
}
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: self[0..<nBytes].map { $0 }))
}
let m = Mirror(self, children:children, displayStyle: Mirror.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()
}
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 {
var result: Data?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension NSData : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self))
}
}
| apache-2.0 | 3da401370907c2132145e3da07a713e9 | 38.351716 | 352 | 0.587618 | 5.007173 | false | false | false | false |
pawanpoudel/CompositeValidation | CompositeValidationTests/Validators/EmptyPhoneNumberValidatorSpec.swift | 1 | 2256 | import Quick
import Nimble
class EmptyPhoneNumberValidatorSpec: QuickSpec {
override func spec() {
var validator: EmptyPhoneNumberValidator!
var phoneNumber: String!
var error: NSError?
var isPhoneNumberValid: Bool!
beforeEach {
validator = EmptyPhoneNumberValidator()
}
afterEach {
error = nil
}
context("when phone number is nil") {
beforeEach {
phoneNumber = nil
isPhoneNumberValid = validator.validateValue(phoneNumber, error: &error)
}
it("it is invalid") {
expect(isPhoneNumberValid).to(beFalse())
}
it("correct error domain is set") {
expect(error?.domain).to(equal(PhoneNumberValidatorErrorDomain))
}
it("correct error code is set") {
expect(error?.code).to(equal(PhoneNumberValidatorErrorCode.EmptyPhoneNumber.rawValue))
}
}
context("when phone number is empty") {
beforeEach {
phoneNumber = ""
isPhoneNumberValid = validator.validateValue(phoneNumber, error: &error)
}
it("it is invalid") {
expect(isPhoneNumberValid).to(beFalse())
}
it("correct error domain is set") {
expect(error?.domain).to(equal(PhoneNumberValidatorErrorDomain))
}
it("correct error code is set") {
expect(error?.code).to(equal(PhoneNumberValidatorErrorCode.EmptyPhoneNumber.rawValue))
}
}
context("when phone number is not empty") {
beforeEach {
phoneNumber = "[email protected]"
isPhoneNumberValid = validator.validateValue(phoneNumber, error: &error)
}
it("it is valid") {
expect(isPhoneNumberValid).to(beTrue())
}
it("error should be nil") {
expect(error).to(beNil())
}
}
}
}
| mit | e11be77afc6949c8b97567585c79f2c4 | 29.90411 | 102 | 0.499113 | 5.69697 | false | false | false | false |
darrarski/SwipeToReveal-iOS | ExampleTests/UI/MainMenuViewModelSpec.swift | 1 | 2132 | import Quick
import Nimble
@testable import SwipeToRevealExample
class MainMenuViewModelSpec: QuickSpec {
override func spec() {
describe("MainMenuViewModel") {
var sut: MainMenuViewModel!
var assembly: Assembly!
var delegate: Delegate!
beforeEach {
assembly = Assembly()
delegate = Delegate()
sut = MainMenuViewModel(assembly: assembly)
sut.delegate = delegate
}
it("should have one item") {
expect(sut.items.count).to(equal(1))
}
context("first item did select") {
beforeEach {
sut.menuItemViewModelDidSelect(sut.items.first!)
}
it("should call delegate") {
expect(delegate._menuViewModelDidPresentViewController?.viewModel).to(be(sut))
}
it("should present correct view controller") {
expect(delegate._menuViewModelDidPresentViewController?.viewController)
.to(be(assembly.tableExampleViewController))
}
}
context("unknown item did select") {
it("should throw assertion") {
expect { () -> Void in
sut.menuItemViewModelDidSelect(MainMenuItemViewModel(title: "Unknown"))
}.to(throwAssertion())
}
}
}
}
struct Assembly: MenuAssembly {
var viewModel: MenuViewModel { fatalError() }
let tableExampleViewController = UIViewController(nibName: nil, bundle: nil)
}
class Delegate: MenuViewModelDelegate {
func menuViewModel(_ viewModel: MenuViewModel,
presentViewController viewController: UIViewController) {
_menuViewModelDidPresentViewController = (viewModel, viewController)
}
private(set) var _menuViewModelDidPresentViewController:
(viewModel: MenuViewModel, viewController: UIViewController)?
}
}
| mit | c392095ea7c195cba01eaa0bea484fdc | 31.30303 | 98 | 0.558161 | 5.971989 | false | false | false | false |
nextcloud/ios | iOSClient/Extensions/UIColor+Extensions.swift | 1 | 5328 | //
// UIColor+adjust.swift
// Nextcloud
//
// Created by Marino Faggiana on 04/02/2020.
// Copyright © 2020 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
import UIKit
extension UIColor {
var hexString: String {
let cgColorInRGB = cgColor.converted(to: CGColorSpace(name: CGColorSpace.sRGB)!, intent: .defaultIntent, options: nil)!
let colorRef = cgColorInRGB.components
let r = colorRef?[0] ?? 0
let g = colorRef?[1] ?? 0
let b = ((colorRef?.count ?? 0) > 2 ? colorRef?[2] : g) ?? 0
let a = cgColor.alpha
var color = String(
format: "#%02lX%02lX%02lX",
lroundf(Float(r * 255)),
lroundf(Float(g * 255)),
lroundf(Float(b * 255))
)
if a < 1 {
color += String(format: "%02lX", lroundf(Float(a * 255)))
}
return color
}
@objc convenience init?(hex: String) {
let r, g, b, a: CGFloat
if hex.hasPrefix("#") {
let start = hex.index(hex.startIndex, offsetBy: 1)
let hexColor = String(hex[start...])
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if hexColor.count == 6 && scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff0000) >> 16) / 255.0
g = CGFloat((hexNumber & 0x00ff00) >> 8) / 255.0
b = CGFloat(hexNumber & 0x0000ff) / 255.0
self.init(red: r, green: g, blue: b, alpha: 1)
return
} else if hexColor.count == 7 && scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
a = CGFloat(hexNumber & 0x000000ff) / 255
self.init(red: r, green: g, blue: b, alpha: a)
return
}
}
return nil
}
@objc func lighter(by percentage: CGFloat = 30.0) -> UIColor? {
return self.adjust(by: abs(percentage) )
}
@objc func darker(by percentage: CGFloat = 30.0) -> UIColor? {
return self.adjust(by: -1 * abs(percentage) )
}
func adjust(by percentage: CGFloat = 30.0) -> UIColor? {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
if self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
return UIColor(red: min(red + percentage/100, 1.0),
green: min(green + percentage/100, 1.0),
blue: min(blue + percentage/100, 1.0),
alpha: alpha)
} else {
return nil
}
}
@objc func isTooLight() -> Bool {
var white: CGFloat = 0.0
self.getWhite(&white, alpha: nil)
if white == 1 { return true }
guard let components = cgColor.components, components.count > 2 else {return false}
let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000
return (brightness > 0.95)
}
@objc func isTooDark() -> Bool {
var white: CGFloat = 0.0
self.getWhite(&white, alpha: nil)
if white == 0 { return true }
guard let components = cgColor.components, components.count > 2 else {return false}
let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000
return (brightness < 0.05)
}
func isLight(threshold: Float = 0.7) -> Bool {
let originalCGColor = self.cgColor
// Now we need to convert it to the RGB colorspace. UIColor.white / UIColor.black are greyscale and not RGB.
// If you don't do this then you will crash when accessing components index 2 below when evaluating greyscale colors.
let RGBCGColor = originalCGColor.converted(to: CGColorSpaceCreateDeviceRGB(), intent: .defaultIntent, options: nil)
guard let components = RGBCGColor?.components else { return false }
guard components.count >= 3 else { return false }
let brightness = Float(((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000)
return (brightness > threshold)
}
func image(_ size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { rendererContext in
self.setFill()
rendererContext.fill(CGRect(origin: .zero, size: size))
}
}
}
| gpl-3.0 | 2e756b32059208f7149e7c2f1ed536e1 | 34.993243 | 127 | 0.582317 | 4.002254 | false | false | false | false |
google/JacquardSDKiOS | Example/JacquardSDK/GestureView/GesturesViewController.swift | 1 | 4380 | // Copyright 2021 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 Combine
import JacquardSDK
import UIKit
private typealias GesturesDataSource =
UITableViewDiffableDataSource<GesturesViewController.Section, GestureModel>
private typealias GesturesSnapshot =
NSDiffableDataSourceSnapshot<GesturesViewController.Section, GestureModel>
private class GestureCell: UITableViewCell {
static let reuseIdentifier = "GesuterCell"
func configure(_ gestureName: String) {
textLabel?.text = gestureName
}
}
private struct GestureModel: Hashable {
let name: String
let uuid = UUID()
}
final class GesturesViewController: UIViewController {
fileprivate enum Section {
case feed
}
private enum Constants {
static let cellHeight: CGFloat = 30.0
static let gesturesNibName = "GesturesViewController"
static let infoButtonImage = UIImage(named: "info.png")
}
// MARK: Instance vars
private var observers = [Cancellable]()
private var dataSource = [GestureModel]()
private var diffableDataSource: UITableViewDiffableDataSource<Section, GestureModel>!
/// Convenience stream that only contains the tag.
private var tagPublisher: AnyPublisher<ConnectedTag, Never>
@IBOutlet weak var tableView: UITableView!
// MARK: View life cycle
init(tagPublisher: AnyPublisher<ConnectedTag, Never>) {
self.tagPublisher = tagPublisher
super.init(nibName: Constants.gesturesNibName, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(GestureCell.self, forCellReuseIdentifier: GestureCell.reuseIdentifier)
tagPublisher.sink { tag in
tag.registerSubscriptions(self.createGestureSubscription)
}.addTo(&observers)
let infoButton = UIBarButtonItem(
image: Constants.infoButtonImage, style: .plain, target: self,
action: #selector(self.infoButtonTapped))
navigationItem.rightBarButtonItem = infoButton
navigationItem.rightBarButtonItem?.tintColor = .black
configureDataSource()
}
@objc private func infoButtonTapped() {
let gestureVC = GestureListViewController()
gestureVC.modalPresentationStyle = .fullScreen
present(gestureVC, animated: true)
}
// Gestures subscription could be use to get most recently executed gesture.
private func createGestureSubscription(_ tag: SubscribableTag) {
tag.subscribe(GestureNotificationSubscription())
.sink { [weak self] notification in
guard let self = self else { return }
self.dataSource.insert(GestureModel(name: "\(notification.name)"), at: 0)
self.createSnapshot(from: self.dataSource)
self.view.showBlurView(image: notification.image, gestureName: notification.name)
}.addTo(&observers)
}
}
/// Handle diffableDataSource , gesturesSnapshot, tableviewDelegate methods.
extension GesturesViewController: UITableViewDelegate {
private func configureDataSource() {
diffableDataSource = GesturesDataSource(tableView: tableView) {
(tableView, indexPath, gesture) -> UITableViewCell in
guard
let cell = tableView.dequeueReusableCell(
withIdentifier: GestureCell.reuseIdentifier, for: indexPath
) as? GestureCell
else {
return UITableViewCell()
}
cell.textLabel?.font = UIFont.system14Medium
cell.textLabel?.text = "\(gesture.name) logged"
return cell
}
}
private func createSnapshot(from gesture: [GestureModel]) {
var snapshot = GesturesSnapshot()
snapshot.appendSections([.feed])
snapshot.appendItems(gesture)
diffableDataSource.apply(snapshot, animatingDifferences: false)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return Constants.cellHeight
}
}
| apache-2.0 | 32e892ac6edf8e8a6c70a214bc9b8d1d | 32.953488 | 93 | 0.740639 | 4.855876 | false | false | false | false |
GuiBayma/PasswordVault | PasswordVault/Scenes/Add Group/AddGroupViewController.swift | 1 | 2503 | //
// AddGroupViewController.swift
// PasswordVault
//
// Created by Guilherme Bayma on 7/26/17.
// Copyright © 2017 Bayma. All rights reserved.
//
import UIKit
class AddGroupViewController: UIViewController, UITextFieldDelegate {
// MARK: - Variables
fileprivate let addGroupView = AddGroupView()
weak var delegate: NewDataDelegate?
// MARK: - Initializing
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
// MARK: - View lifecycle
override func loadView() {
self.view = addGroupView
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel,
target: self,
action: #selector(self.cancelPressed(_:)))
addGroupView.labeledTextField.textField.delegate = self
addGroupView.labeledTextField.textField.becomeFirstResponder()
addGroupView.buttonAction = donePressed
}
// MARK: - Bar button items
func cancelPressed(_ sender: UIBarButtonItem) {
dismiss(animated: true) {}
}
// MARK: - Text field delegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
saveNewGroupAndDismiss()
return true
}
// MARK: - Button action
func donePressed() {
addGroupView.labeledTextField.textField.resignFirstResponder()
saveNewGroupAndDismiss()
}
// MARK: - Save new group
func saveNewGroupAndDismiss() {
guard
let text = addGroupView.labeledTextField.textField.text
else {
fatalError("\(String(describing: type(of: self))): Error retrieving text from textfield")
}
if text == "" {
dismiss(animated: true) {}
} else {
let newGroup = GroupManager.sharedInstance.newGroup()
newGroup?.name = text
if let group = newGroup {
_ = GroupManager.sharedInstance.save()
self.delegate?.addNewDataAndDismiss(self, data: group)
} else {
dismiss(animated: true) {}
}
}
}
}
| mit | 47441073c670750d2406636de9633546 | 27.11236 | 106 | 0.59952 | 5.357602 | false | false | false | false |
qxuewei/XWSwiftWB | XWSwiftWB/XWSwiftWB/AppDelegate.swift | 1 | 1463 | //
// AppDelegate.swift
// XWSwiftWB
//
// Created by 邱学伟 on 16/10/25.
// Copyright © 2016年 邱学伟. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var defaultVC : UIViewController? {
let isLogin = UserAccountViewModel.shareInstance.isLogin
// if let access_token = UserAccountViewModel.shareInstance.account?.access_token {
// XWLog("access_token有值:\(access_token)")
// }else{
// XWLog("access_token没有有值")
// }
return isLogin ? WelcomeVC() : UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()!
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = defaultVC
window?.makeKeyAndVisible()
//设置全局
UITabBar.appearance().tintColor = UIColor.orange
UINavigationBar.appearance().tintColor = UIColor.orange
return true
}
}
//自定义打印
func XWLog<T>(_ messsage : T, file : String = #file, funcName : String = #function, lineNum : Int = #line) {
#if DEBUG
let fileName = (file as NSString).lastPathComponent
print("\(fileName):(\(lineNum))-\(messsage)")
#endif
}
| apache-2.0 | 2f7989bd4860c2850c2f9177f7ca033c | 29.170213 | 144 | 0.648801 | 4.664474 | false | false | false | false |
vladrusu-3pillar/JSON-fork | Source/JSONParser.swift | 1 | 16200 | // JSONParser.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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.
//
// This file has been modified from its original project Swift-JsonSerializer
public enum JSONParseError: ErrorProtocol, CustomStringConvertible {
case unexpectedTokenError(reason: String, lineNumber: Int, columnNumber: Int)
case insufficientTokenError(reason: String, lineNumber: Int, columnNumber: Int)
case extraTokenError(reason: String, lineNumber: Int, columnNumber: Int)
case nonStringKeyError(reason: String, lineNumber: Int, columnNumber: Int)
case invalidStringError(reason: String, lineNumber: Int, columnNumber: Int)
case invalidNumberError(reason: String, lineNumber: Int, columnNumber: Int)
public var description: String {
switch self {
case unexpectedTokenError(let r, let l, let c):
return "UnexpectedTokenError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case insufficientTokenError(let r, let l, let c):
return "InsufficientTokenError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case extraTokenError(let r, let l, let c):
return "ExtraTokenError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case nonStringKeyError(let r, let l, let c):
return "NonStringKeyError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case invalidStringError(let r, let l, let c):
return "InvalidStringError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
case invalidNumberError(let r, let l, let c):
return "InvalidNumberError!\nLine: \(l)\nColumn: \(c)]\nReason: \(r)"
}
}
}
public struct JSONParser {
public init() {}
public func parse(data: Data) throws -> JSON {
return try GenericJSONParser(data).parse()
}
}
class GenericJSONParser<ByteSequence: Collection where ByteSequence.Iterator.Element == UInt8> {
typealias Source = ByteSequence
typealias Char = Source.Iterator.Element
let source: Source
var cur: Source.Index
let end: Source.Index
var lineNumber = 1
var columnNumber = 1
init(_ source: Source) {
self.source = source
self.cur = source.startIndex
self.end = source.endIndex
}
func parse() throws -> JSON {
let JSON = try parseValue()
skipWhitespaces()
if (cur == end) {
return JSON
} else {
throw JSONParseError.extraTokenError(
reason: "extra tokens found",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
}
// MARK: - Private
extension GenericJSONParser {
private func parseValue() throws -> JSON {
skipWhitespaces()
if cur == end {
throw JSONParseError.insufficientTokenError(
reason: "unexpected end of tokens",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
print("parsing char: line: \(lineNumber) col: \(columnNumber) char: \(currentChar)\n")
switch currentChar {
case Char(ascii: "n"): return try parseSymbol("null", JSON.nullValue)
case Char(ascii: "t"): return try parseSymbol("true", JSON.booleanValue(true))
case Char(ascii: "f"): return try parseSymbol("false", JSON.booleanValue(false))
case Char(ascii: "-"), Char(ascii: "0") ... Char(ascii: "9"): return try parseNumber()
case Char(ascii: "\""): return try parseString()
case Char(ascii: "{"): return try parseObject()
case Char(ascii: "["): return try parseArray()
case (let c): throw JSONParseError.unexpectedTokenError(
reason: "unexpected token: \(c)",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
private var currentChar: Char {
return source[cur]
}
private var nextChar: Char {
return source[cur.successor()]
}
private var currentSymbol: Character {
return Character(UnicodeScalar(currentChar))
}
private func parseSymbol(target: StaticString, @autoclosure _ iftrue: Void -> JSON) throws -> JSON {
if expect(target) {
return iftrue()
} else {
throw JSONParseError.unexpectedTokenError(
reason: "expected \"\(target)\" but \(currentSymbol)",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
private func parseString() throws -> JSON {
assert(currentChar == Char(ascii: "\""), "points a double quote")
advance()
var buffer: [CChar] = []
LOOP: while cur != end {
switch currentChar {
case Char(ascii: "\\"):
advance()
if (cur == end) {
throw JSONParseError.invalidStringError(
reason: "unexpected end of a string literal",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
if let c = parseEscapedChar() {
for u in String(c).utf8 {
buffer.append(CChar(bitPattern: u))
}
} else {
throw JSONParseError.invalidStringError(
reason: "invalid escape sequence",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
case Char(ascii: "\""): break LOOP
default: buffer.append(CChar(bitPattern: currentChar))
}
advance()
}
if !expect("\"") {
throw JSONParseError.invalidStringError(
reason: "missing double quote",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
buffer.append(0)
let s = String(validatingUTF8: buffer)!
return .stringValue(s)
}
private func parseEscapedChar() -> UnicodeScalar? {
let c = UnicodeScalar(currentChar)
if c == "u" {
var length = 0
var value: UInt32 = 0
while let d = hexToDigit(nextChar) {
advance()
length += 1
if length > 8 {
break
}
value = (value << 4) | d
}
if length < 2 {
return nil
}
return UnicodeScalar(value)
} else {
let c = UnicodeScalar(currentChar)
return unescapeMapping[c] ?? c
}
}
private func parseNumber() throws -> JSON {
print("parsing number")
let sign = expect("-") ? -1.0 : 1.0
var integer: Int64 = 0
switch currentChar {
case Char(ascii: "0"): advance()
case Char(ascii: "1") ... Char(ascii: "9"):
while cur != end {
if let value = digitToInt(currentChar) {
integer = (integer * 10) + Int64(value)
} else {
break
}
advance()
}
default:
throw JSONParseError.invalidStringError(
reason: "missing double quote",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
print("===============")
print("\(integer)\n")
print("\(Double(integer))\n")
print("\(Int64(Double(integer)))\n")
if integer != Int64(Double(integer)) {
throw JSONParseError.invalidNumberError(
reason: "too large number",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
var fraction: Double = 0.0
if expect(".") {
var factor = 0.1
var fractionLength = 0
while cur != end {
if let value = digitToInt(currentChar) {
fraction += (Double(value) * factor)
factor /= 10
fractionLength += 1
} else {
break
}
advance()
}
if fractionLength == 0 {
throw JSONParseError.invalidNumberError(
reason: "insufficient fraction part in number",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
var exponent: Int64 = 0
if expect("e") || expect("E") {
var expSign: Int64 = 1
if expect("-") {
expSign = -1
} else if expect("+") {}
exponent = 0
var exponentLength = 0
while cur != end {
if let value = digitToInt(currentChar) {
exponent = (exponent * 10) + Int64(value)
exponentLength += 1
} else {
break
}
advance()
}
if exponentLength == 0 {
throw JSONParseError.invalidNumberError(
reason: "insufficient exponent part in number",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
exponent *= expSign
}
return .numberValue(sign * (Double(integer) + fraction) * pow(10, Double(exponent)))
}
private func parseObject() throws -> JSON {
assert(currentChar == Char(ascii: "{"), "points \"{\"")
advance()
skipWhitespaces()
var object: [String: JSON] = [:]
LOOP: while cur != end && !expect("}") {
let keyValue = try parseValue()
switch keyValue {
case .stringValue(let key):
skipWhitespaces()
if !expect(":") {
throw JSONParseError.unexpectedTokenError(
reason: "missing colon (:)",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
skipWhitespaces()
let value = try parseValue()
object[key] = value
skipWhitespaces()
if expect(",") {
break
} else if expect("}") {
break LOOP
} else {
throw JSONParseError.unexpectedTokenError(
reason: "missing comma (,)",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
default:
throw JSONParseError.nonStringKeyError(
reason: "unexpected value for object key",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
return .objectValue(object)
}
private func parseArray() throws -> JSON {
assert(currentChar == Char(ascii: "["), "points \"[\"")
advance()
skipWhitespaces()
var array: [JSON] = []
LOOP: while cur != end && !expect("]") {
let JSON = try parseValue()
skipWhitespaces()
array.append(JSON)
if expect(",") {
continue
} else if expect("]") {
break LOOP
} else {
throw JSONParseError.unexpectedTokenError(
reason: "missing comma (,) (token: \(currentSymbol))",
lineNumber: lineNumber,
columnNumber: columnNumber
)
}
}
return .arrayValue(array)
}
private func expect(target: StaticString) -> Bool {
if cur == end {
return false
}
if !isIdentifier(target.utf8Start.pointee) {
if target.utf8Start.pointee == currentChar {
advance()
return true
} else {
return false
}
}
let start = cur
let l = lineNumber
let c = columnNumber
var p = target.utf8Start
let endp = p.advanced(by: Int(target.utf8CodeUnitCount))
while p != endp {
if p.pointee != currentChar {
cur = start
lineNumber = l
columnNumber = c
return false
}
p += 1
advance()
}
return true
}
// only "true", "false", "null" are identifiers
private func isIdentifier(char: Char) -> Bool {
switch char {
case Char(ascii: "a") ... Char(ascii: "z"):
return true
default:
return false
}
}
private func advance() {
assert(cur != end, "out of range")
cur = cur.successor()
if cur != end {
switch currentChar {
case Char(ascii: "\n"):
lineNumber += 1
columnNumber = 1
default:
columnNumber += 1
}
}
}
private func skipWhitespaces() {
while cur != end {
switch currentChar {
case Char(ascii: " "), Char(ascii: "\t"), Char(ascii: "\r"), Char(ascii: "\n"):
break
default:
return
}
advance()
}
}
}
let unescapeMapping: [UnicodeScalar: UnicodeScalar] = [
"t": "\t",
"r": "\r",
"n": "\n"
]
let escapeMapping: [Character: String] = [
"\r": "\\r",
"\n": "\\n",
"\t": "\\t",
"\\": "\\\\",
"\"": "\\\"",
"\u{2028}": "\\u2028",
"\u{2029}": "\\u2029",
"\r\n": "\\r\\n"
]
let hexMapping: [UnicodeScalar: UInt32] = [
"0": 0x0,
"1": 0x1,
"2": 0x2,
"3": 0x3,
"4": 0x4,
"5": 0x5,
"6": 0x6,
"7": 0x7,
"8": 0x8,
"9": 0x9,
"a": 0xA, "A": 0xA,
"b": 0xB, "B": 0xB,
"c": 0xC, "C": 0xC,
"d": 0xD, "D": 0xD,
"e": 0xE, "E": 0xE,
"f": 0xF, "F": 0xF
]
let digitMapping: [UnicodeScalar:Int] = [
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9
]
public func escapeAsJSONString(source : String) -> String {
var s = "\""
for c in source.characters {
if let escapedSymbol = escapeMapping[c] {
s.append(escapedSymbol)
} else {
s.append(c)
}
}
s.append("\"")
return s
}
func digitToInt(byte: UInt8) -> Int? {
return digitMapping[UnicodeScalar(byte)]
}
func hexToDigit(byte: UInt8) -> UInt32? {
return hexMapping[UnicodeScalar(byte)]
} | mit | 41065c3697bde57f2699e879142fad0c | 28.510018 | 104 | 0.498333 | 4.867788 | false | false | false | false |
CombineCommunity/CombineExt | Sources/Relays/Relay.swift | 1 | 1548 | //
// Relay.swift
// CombineExt
//
// Created by Shai Mishali on 15/03/2020.
// Copyright © 2020 Combine Community. All rights reserved.
//
#if canImport(Combine)
import Combine
/// A publisher that exposes a method for outside callers to publish values.
/// It is identical to a `Subject`, but it cannot publish a finish event (until it's deallocated).
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public protocol Relay: Publisher where Failure == Never {
associatedtype Output
/// Relays a value to the subscriber.
///
/// - Parameter value: The value to send.
func accept(_ value: Output)
/// Attaches the specified publisher to this relay.
///
/// - parameter publisher: An infallible publisher with the relay's Output type
///
/// - returns: `AnyCancellable`
func subscribe<P: Publisher>(_ publisher: P) -> AnyCancellable where P.Failure == Failure, P.Output == Output
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension Publisher where Failure == Never {
/// Attaches the specified relay to this publisher.
///
/// - parameter relay: Relay to attach to this publisher
///
/// - returns: `AnyCancellable`
func subscribe<R: Relay>(_ relay: R) -> AnyCancellable where R.Output == Output {
relay.subscribe(self)
}
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension Relay where Output == Void {
/// Relay a void to the subscriber.
func accept() {
accept(())
}
}
#endif
| mit | 922a5e45d410862cf9c779429962f6de | 29.94 | 113 | 0.657401 | 3.936387 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/Swift Note/LiveBroadcast/Client/LiveBroadcast/Classes/Home/WaterfallLayout.swift | 1 | 2237 | //
// WaterfallLayout.swift
// LiveBroadcast
//
// Created by 朱双泉 on 2018/12/10.
// Copyright © 2018 Castie!. All rights reserved.
//
import UIKit
protocol WaterfallLayoutDataSource: class {
func numberOfCols(_ waterfall: WaterfallLayout) -> Int
func waterfall(_ waterfall: WaterfallLayout, item: Int) -> CGFloat
}
class WaterfallLayout: UICollectionViewFlowLayout {
weak var dataSource: WaterfallLayoutDataSource?
fileprivate lazy var cellAttrs = [UICollectionViewLayoutAttributes]()
fileprivate lazy var cols: Int = {
return self.dataSource?.numberOfCols(self) ?? 3
}()
fileprivate lazy var totalHeights = Array(repeating: sectionInset.top, count: cols)
}
extension WaterfallLayout {
override func prepare() {
super.prepare()
let itemCount = collectionView!.numberOfItems(inSection: 0)
let cellW: CGFloat = (collectionView!.bounds.width - sectionInset.left - sectionInset.right - CGFloat(cols - 1) * minimumInteritemSpacing) / CGFloat(cols)
for i in cellAttrs.count..<itemCount {
let indexPath = IndexPath(item: i, section: 0)
let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
guard let cellH: CGFloat = dataSource?.waterfall(self, item: i) else {
fatalError("Error:\(#line) waterfall(_ waterfall: WaterfallLayout, item: Int)")
}
let minH = totalHeights.min()!
let minIndex = totalHeights.index(of: minH)!
let cellX: CGFloat = sectionInset.left + (minimumInteritemSpacing + cellW) * CGFloat(minIndex)
let cellY: CGFloat = minH
attr.frame = CGRect(x: cellX, y: cellY, width: cellW, height: cellH)
cellAttrs.append(attr)
totalHeights[minIndex] = minH + minimumLineSpacing + cellH
}
}
}
extension WaterfallLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return cellAttrs
}
}
extension WaterfallLayout {
override var collectionViewContentSize: CGSize {
return CGSize(width: 0, height: totalHeights.max()! + sectionInset.bottom - minimumLineSpacing)
}
}
| mit | b23a600fdb64057d8d8871c9dc9a913e | 34.396825 | 162 | 0.669507 | 4.724576 | false | false | false | false |
honishi/Hakumai | Hakumai/Managers/HandleNameManager/DatabaseValueCacher.swift | 1 | 1296 | //
// DatabaseValueCacher.swift
// Hakumai
//
// Created by Hiroyuki Onishi on 2021/12/28.
// Copyright © 2021 Hiroyuki Onishi. All rights reserved.
//
import Foundation
class DatabaseValueCacher<T: Equatable> {
enum CacheStatus: Equatable {
case cached(T?) // `.cached(nil)` means the value is cached as `nil`.
case notCached
}
private var cache: [String: CacheStatus] = [:]
func update(value: T?, for userId: String, in communityId: String) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
let key = cacheKey(userId, communityId)
let _value: CacheStatus = {
guard let value = value else { return .cached(nil) }
return .cached(value)
}()
cache[key] = _value
}
func updateValueAsNil(for userId: String, in communityId: String) {
update(value: nil, for: userId, in: communityId)
}
func cachedValue(for userId: String, in communityId: String) -> CacheStatus {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
let key = cacheKey(userId, communityId)
return cache[key] ?? .notCached
}
private func cacheKey(_ userId: String, _ communityId: String) -> String {
return "\(userId):\(communityId)"
}
}
| mit | b455da932b598d73702384eec0ac0a3e | 28.431818 | 81 | 0.615444 | 3.900602 | false | false | false | false |
dbaldwin/DronePan | DronePanTests/ControllerUtilsTests.swift | 1 | 2393 | /*
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 XCTest
import DJISDK
@testable import DronePan
class ControllerUtilsTests: XCTestCase {
override func setUp() {
super.setUp()
let appDomain = NSBundle.mainBundle().bundleIdentifier!
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain)
}
func testGimbalYawIsRelativeToAircraft() {
let results = [
DJIAircraftModelNameInspire1: true,
DJIAircraftModelNameInspire1Pro: true,
DJIAircraftModelNameInspire1RAW: true,
DJIAircraftModelNamePhantom3Professional: false,
DJIAircraftModelNamePhantom3Advanced: false,
DJIAircraftModelNamePhantom3Standard: false,
DJIAircraftModelNamePhantom34K: false,
DJIAircraftModelNameMatrice100: true,
DJIAircraftModelNamePhantom4: true,
DJIAircraftModelNameMatrice600: true,
DJIAircraftModelNameA3: false
]
for (aircraft, result) in results {
XCTAssertTrue(ControllerUtils.gimbalYawIsRelativeToAircraft(aircraft) == result, "\(aircraft) incorrect result for gimbal yaw")
}
}
func testDefaultDisplayIsInMeters() {
let value = ControllerUtils.displayDistance(10)
XCTAssertEqual(value, "10m", "Incorrect display \(value)")
}
func testDisplayIsInMeters() {
ControllerUtils.setMetricUnits(true)
let value = ControllerUtils.displayDistance(10)
XCTAssertEqual(value, "10m", "Incorrect display \(value)")
}
func testDisplayIsInFeet() {
ControllerUtils.setMetricUnits(false)
let value = ControllerUtils.displayDistance(10)
XCTAssertEqual(value, "33'", "Incorrect display \(value)")
}
}
| gpl-3.0 | 0e69235f189b7868845487ec22a4fc82 | 32.704225 | 139 | 0.700794 | 4.59309 | false | true | false | false |
benjaminsnorris/CloudKitReactor | Sources/SubscribeToCloudKit.swift | 1 | 3293 | /*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import Foundation
import CloudKit
import Reactor
public struct SubscribeToCloudKit<T: CloudKitSyncable, U: State>: Command {
public var predicate: NSPredicate
public var options: CKQuerySubscription.Options
public var notificationInfo: CKSubscription.NotificationInfo
public var subscriptionID: String?
public var databaseScope: CKDatabase.Scope
public var zoneID: CKRecordZone.ID
public init(predicate: NSPredicate = NSPredicate(value: true), options: CKQuerySubscription.Options = [.firesOnRecordCreation, .firesOnRecordUpdate, .firesOnRecordDeletion], notificationInfo: CKSubscription.NotificationInfo? = nil, subscriptionID: String? = nil, databaseScope: CKDatabase.Scope = .private, zoneID: CKRecordZone.ID = CloudKitReactorConstants.zoneID) {
self.predicate = predicate
self.options = options
if let notificationInfo = notificationInfo {
self.notificationInfo = notificationInfo
} else {
self.notificationInfo = CKSubscription.NotificationInfo()
notificationInfo?.shouldSendContentAvailable = true
}
self.subscriptionID = subscriptionID
self.databaseScope = databaseScope
self.zoneID = zoneID
}
public func execute(state: U, core: Core<U>) {
let subscription: CKQuerySubscription
if let subscriptionID = subscriptionID {
subscription = CKQuerySubscription(recordType: T.recordType, predicate: predicate, subscriptionID: subscriptionID, options: options)
} else {
subscription = CKQuerySubscription(recordType: T.recordType, predicate: predicate, options: options)
}
subscription.notificationInfo = notificationInfo
subscription.zoneID = zoneID
let container = CKContainer.default()
switch databaseScope {
case .private:
container.privateCloudDatabase.save(subscription) { subscription, error in
if let error = error {
core.fire(event: CloudKitSubscriptionError(error: error))
} else {
core.fire(event: CloudKitSubscriptionSuccessful(type: .privateQuery, subscriptionID: self.subscriptionID))
}
}
case .shared:
container.sharedCloudDatabase.save(subscription) { subscription, error in
if let error = error {
core.fire(event: CloudKitSubscriptionError(error: error))
} else {
core.fire(event: CloudKitSubscriptionSuccessful(type: .sharedQuery, subscriptionID: self.subscriptionID))
}
}
case .public:
container.publicCloudDatabase.save(subscription) { subscription, error in
if let error = error {
core.fire(event: CloudKitSubscriptionError(error: error))
} else {
core.fire(event: CloudKitSubscriptionSuccessful(type: .publicQuery, subscriptionID: self.subscriptionID))
}
}
@unknown default:
fatalError()
}
}
}
| mit | 5c0e2cc19d8508feb29799a5f569d82f | 41.934211 | 371 | 0.628256 | 5.34918 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/SES/SES_Paginator.swift | 1 | 6461 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension SES {
/// Lists the existing custom verification email templates for your account in the current AWS Region. For more information about custom verification email templates, see Using Custom Verification Email Templates in the Amazon SES Developer Guide. You can execute this operation no more than once per second.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listCustomVerificationEmailTemplatesPaginator<Result>(
_ input: ListCustomVerificationEmailTemplatesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListCustomVerificationEmailTemplatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listCustomVerificationEmailTemplates,
tokenKey: \ListCustomVerificationEmailTemplatesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listCustomVerificationEmailTemplatesPaginator(
_ input: ListCustomVerificationEmailTemplatesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListCustomVerificationEmailTemplatesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listCustomVerificationEmailTemplates,
tokenKey: \ListCustomVerificationEmailTemplatesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list containing all of the identities (email addresses and domains) for your AWS account in the current AWS Region, regardless of verification status. You can execute this operation no more than once per second.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listIdentitiesPaginator<Result>(
_ input: ListIdentitiesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListIdentitiesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listIdentities,
tokenKey: \ListIdentitiesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listIdentitiesPaginator(
_ input: ListIdentitiesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListIdentitiesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listIdentities,
tokenKey: \ListIdentitiesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension SES.ListCustomVerificationEmailTemplatesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SES.ListCustomVerificationEmailTemplatesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension SES.ListIdentitiesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SES.ListIdentitiesRequest {
return .init(
identityType: self.identityType,
maxItems: self.maxItems,
nextToken: token
)
}
}
| apache-2.0 | 6f38e9ee06dcd25b6d0fa6affe3d73a4 | 44.5 | 313 | 0.657793 | 5.197908 | false | false | false | false |
sivu22/AnyTracker | AnyTracker/Lists.swift | 1 | 11435 | //
// Lists.swift
// AnyTracker
//
// Created by Cristian Sava on 11/03/16.
// Copyright © 2016 Cristian Sava. All rights reserved.
//
import Foundation
class Lists {
struct ListInfo {
var name: String
var numItems: Int
}
struct ListsCache {
var numItemsAll: Int
var lists: [ListInfo]
}
// Used for reducing disk access (Lists ViewController)
fileprivate(set) var cache: ListsCache?
fileprivate(set) var listsData: [String]
init() {
listsData = []
cache = ListsCache(numItemsAll: 0, lists: [])
}
init(listsData: [String]) {
self.listsData = listsData
cache = ListsCache(numItemsAll: 0, lists: [])
if listsData.count > 0 {
if !buildCache() {
cache = nil
}
}
}
// MARK: - Lists operations
func getListIDs() -> [String] {
return listsData
}
func saveListsToFile() throws {
guard let JSONString = toJSONString() else {
Utils.debugLog("Failed to serialize JSON lists")
throw Status.errorJSONSerialize
}
if !Utils.createFile(withName: Constants.File.lists, withContent: JSONString, overwriteExisting: true) {
Utils.debugLog("Failed to save lists to file")
throw Status.errorListsFileSave
}
}
static func loadListsFromFile() throws -> Lists {
let content = Utils.readFile(withName: Constants.File.lists)
guard content != nil else {
Utils.debugLog("Failed to load lists from file")
throw Status.errorListsFileLoad
}
guard let lists = fromJSONString(content) else {
Utils.debugLog("Failed to deserialize JSON lists")
throw Status.errorJSONDeserialize
}
return lists
}
func insertList(withName name: String, atFront front: Bool) throws -> Int {
var newList: List
do {
newList = try List.createList(withName: name)
try newList.saveListToFile()
} catch let error as Status {
throw error
} catch {
throw Status.errorDefault
}
var index = 0
if front {
listsData.insert(newList.ID, at: 0)
} else {
listsData.append(newList.ID)
index = listsData.count - 1
}
// Keep cache in sync
if !insertCache(atIndex: index) {
Utils.debugLog("Failed to update cache, will remove the added list")
// Failure
if index == 0 {
listsData.removeFirst()
} else {
listsData.removeLast()
}
index = -1
}
return index
}
// Doesn't throw or fail because it's only a cosmetic change for the ALL list
func changedList(atIndex index: Int, withNumItems numItems: Int) {
Utils.debugLog("Will update cache at index \(index) with numItems \(numItems)")
if !updateCache(atIndex: index, withNumItems: numItems) {
Utils.debugLog("Failed to update cache at index \(index)")
}
}
fileprivate func clearList(withName listName: String) {
var list: List?
do {
list = try List.loadListFromFile(listName)
} catch {
Utils.debugLog("Failed to load list \(listName): \(error)")
}
for item in list!.items {
let filePath = Utils.documentsPath + "/" + item
if !Utils.deleteFile(atPath: filePath) {
Utils.debugLog("Failed to delete item \(item)")
} else {
Utils.debugLog("Deleted file \(item)")
}
}
}
func updateList(atIndex index: Int, withNewName newName: String) throws {
guard index >= 0 && index < listsData.count else {
Utils.debugLog("Bad list index \(index)")
return
}
var list: List?
do {
list = try List.loadListFromFile(listsData[index])
try list!.updateList(withName: newName)
} catch {
throw error
}
if !updateCache(atIndex: index, withName: newName) {
Utils.debugLog("Failed to update cache at index \(index)")
}
}
func deleteLists() throws {
if listsData.count == 0 {
Utils.debugLog("No lists to clear")
return
}
for list in listsData {
clearList(withName: list)
let filePath = Utils.documentsPath + "/" + list
if !Utils.deleteFile(atPath: filePath) {
Utils.debugLog("Failed to delete list \(list)")
} else {
Utils.debugLog("Deleted file \(list)")
}
}
listsData.removeAll();
clearCache();
do {
try saveListsToFile()
} catch let error as Status {
throw error
}
Utils.debugLog("Successfully cleared app data")
}
// Delete required lists and returns number of items the list had (-1 if error)
func deleteList(atIndex index: Int) -> Int {
guard index >= 0 && index < listsData.count else {
Utils.debugLog("Bad index")
return -1
}
let numItems = cache?.lists[index].numItems ?? -1
let listID = listsData[index]
clearList(withName: listID)
listsData.remove(at: index)
let _ = removeCache(atIndex: index)
let filePath = Utils.documentsPath + "/" + listID
if !Utils.deleteFile(atPath: filePath) {
Utils.debugLog("Failed to delete list at index \(index)")
return -1
} else {
Utils.debugLog("Deleted file \(listID)")
}
Utils.debugLog("Successfully deleted list at index \(index)")
return numItems
}
func exchangeList(fromIndex src: Int, toIndex dst: Int) {
if src < 0 || dst < 0 || src >= listsData.count || dst >= listsData.count {
return
}
listsData.swapAt(src, dst)
swapCache(atIndex: src, withIndex: dst)
}
func getListNumItems(atIndex index: Int) -> Int {
return getCacheNumItems(atIndex: index)
}
// MARK: -
}
extension Lists: JSON {
// MARK: JSON Protocol
func toJSONString() -> String? {
let jsonString = Utils.getJSONFromObject(listsData as JSONObject)
Utils.debugLog("Serialized lists to JSON string \(String(describing: jsonString))")
return jsonString
}
static func fromJSONString(_ input: String?) -> Lists? {
guard input != nil else {
return nil
}
let dict = Utils.getArrayFromJSON(input)
guard dict != nil else {
return nil
}
guard let listsData = dict! as? [String] else {
return nil
}
return Lists(listsData: listsData)
}
// MARK: -
}
// Cache is used only for displaying Lists ViewController and minimize disk access
private extension Lists {
// MARK: - Cache
func buildCache() -> Bool {
guard cache != nil else {
Utils.debugLog("Cache missing!")
return false
}
do {
for list in listsData {
let listData = try List.loadListFromFile(list)
let listInfo = ListInfo(name: listData.name, numItems: listData.numItems)
cache!.numItemsAll += listInfo.numItems
cache!.lists.append(listInfo)
}
} catch {
Utils.debugLog("Failed to load specific list")
return false
}
return true
}
func clearCache() {
guard cache != nil else {
Utils.debugLog("Cache missing!")
return
}
cache!.numItemsAll = 0
cache!.lists.removeAll()
Utils.debugLog("Cache cleared")
}
func insertCache(atIndex index: Int) -> Bool {
guard cache != nil else {
Utils.debugLog("Cache missing!")
return false
}
guard index < listsData.count && index >= 0 else {
Utils.debugLog("Index out of bounds")
return false
}
do {
let listData = try List.loadListFromFile(listsData[index])
let listInfo = ListInfo(name: listData.name, numItems: listData.numItems)
cache!.numItemsAll += listInfo.numItems
cache!.lists.insert(listInfo, at: index)
Utils.debugLog("Updated cache at index \(index): \(listInfo.name), \(listInfo.numItems)")
Utils.debugLog("Total items: \(cache!.numItemsAll)")
} catch {
Utils.debugLog("Failed to load specific list")
return false
}
return true
}
func updateCache(atIndex index: Int, withNumItems numItems: Int) -> Bool {
guard cache != nil else {
Utils.debugLog("Cache missing!")
return false
}
guard index < listsData.count && index >= 0 else {
Utils.debugLog("Index out of bounds")
return false
}
cache!.numItemsAll += numItems - cache!.lists[index].numItems
cache!.lists[index].numItems = numItems
return true
}
func updateCache(atIndex index: Int, withName name: String) -> Bool {
guard cache != nil else {
Utils.debugLog("Cache missing!")
return false
}
guard index < listsData.count && index >= 0 else {
Utils.debugLog("Index out of bounds")
return false
}
cache!.lists[index].name = name
return true
}
func removeCache(atIndex index: Int) -> Bool {
guard cache != nil else {
Utils.debugLog("Cache missing!")
return false
}
guard index < cache!.lists.count && index >= 0 else {
Utils.debugLog("Index out of bounds")
return false
}
let listInfo = cache!.lists.remove(at: index)
cache!.numItemsAll -= listInfo.numItems
Utils.debugLog("Removed from cache at index \(index): \(listInfo.name), \(listInfo.numItems)")
return true
}
func getCacheNumItems(atIndex index: Int) -> Int {
guard let cache = cache else {
Utils.debugLog("Cache missing!")
return -1
}
guard index < cache.lists.count && index >= 0 else {
Utils.debugLog("Index out of bounds")
return -1
}
return cache.lists[index].numItems;
}
func swapCache(atIndex src: Int, withIndex dst: Int) {
guard cache != nil else {
Utils.debugLog("Cache missing!")
return
}
if src < 0 || dst < 0 || src >= listsData.count || dst >= listsData.count {
return
}
cache!.lists.swapAt(src, dst)
}
}
| mit | 4ba5638470764b844e610d4dad943d31 | 28.242967 | 112 | 0.529299 | 4.903087 | false | false | false | false |
mvader/advent-of-code | 2020/07/01.swift | 1 | 1017 | import Foundation
typealias Rules = [String: [String]]
func parseRule(rule: String) -> (String, [String]) {
let parts = rule.components(separatedBy: " bags contain ")
let (type, contained) = (parts[0], parts[1])
if contained.hasPrefix("no other bags") {
return (type, [])
}
let containedBags: [String] = contained.components(separatedBy: ", ")
.map { x in
let parts = x.components(separatedBy: " ")
return parts[1] + " " + parts[2]
}
return (type, containedBags)
}
func canHoldBag(_ rules: Rules, _ target: String, _ type: String) -> Bool {
if target == type {
return true
}
for type in rules[type]! {
if canHoldBag(rules, target, type) {
return true
}
}
return false
}
let input = try String(contentsOfFile: "./input.txt", encoding: .utf8)
let rules = Rules(
uniqueKeysWithValues: input.components(separatedBy: "\n").map(parseRule)
)
let target = "shiny gold"
print(rules.keys.filter { $0 != target && canHoldBag(rules, target, $0) }.count)
| mit | ea750c160648befe25771071c73e7109 | 23.804878 | 80 | 0.641101 | 3.412752 | false | false | false | false |
vkedwardli/SignalR-Swift | SignalR-Swift/Client/Hubs/HubInvocation.swift | 2 | 1223 | //
// HubInvocation.swift
// SignalR-Swift
//
//
// Copyright © 2017 Jordan Camara. All rights reserved.
//
import Foundation
private let kCallbackId = "I"
private let kHub = "H"
private let kMethod = "M"
private let kArgs = "A"
private let kState = "S"
struct HubInvocation {
let callbackId: String
let hub: String
let method: String
let args: [Any]
let state: [String: Any]
init(callbackId: String, hub: String, method: String, args: [Any], state: [String: Any] = [:]) {
self.callbackId = callbackId
self.hub = hub
self.method = method
self.args = args
self.state = state
}
init(jsonObject dict: [String: Any]) {
callbackId = dict[kCallbackId] as? String ?? ""
hub = dict[kHub] as? String ?? ""
method = dict[kMethod] as? String ?? ""
args = dict[kArgs] as? [Any] ?? []
state = dict[kState] as? [String: Any] ?? [:]
}
func toJSONString() -> String? {
let json: [String: Any] = [
kCallbackId: callbackId,
kHub: hub,
kMethod: method,
kArgs: args,
kState: state
]
return json.toJSONString()
}
}
| mit | 827b8d723ab09f520d0613d7d98057d6 | 22.960784 | 100 | 0.552373 | 3.70303 | false | false | false | false |
notbenoit/tvOS-Twitch | Code/Common/ViewModels/TopGames/GameCellViewModel.swift | 1 | 1589 | // Copyright (c) 2015 Benoit Layer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import ReactiveSwift
struct GameCellViewModel: ReuseIdentifierProvider {
let reuseIdentifier: String = GameCell.identifier
let game: Game
let gameImageURL: String
let gameName: String
init(game: Game) {
self.game = game
self.gameImageURL = game.box.medium
self.gameName = game.name
}
}
// MARK: Equatable
extension GameCellViewModel: Equatable { }
func == (lhs: GameCellViewModel, rhs: GameCellViewModel) -> Bool {
return lhs.game == rhs.game
}
| bsd-3-clause | f5c4f6f7df2f2e50ac860fcb5bd27d69 | 35.953488 | 80 | 0.759597 | 4.283019 | false | false | false | false |
ptangen/equityStatus | EquityStatus/CompanyDetailView.swift | 1 | 12150 | //
// CompanyDetailView.swift
// EquityStatus
//
// Created by Paul Tangen on 12/29/16.
// Copyright © 2016 Paul Tangen. All rights reserved.
//
import UIKit
protocol CompanyDetailViewDelegate: class {
func openMeasureDetail(measure: String)
}
class CompanyDetailView: UIView {
weak var delegate: CompanyDetailViewDelegate?
var company: Company!
let scrollView = UIScrollView()
var heightOfScrolledContent = CGFloat()
var measure = String()
let lineSpacing:CGFloat = 18
let subTitle = UILabel()
let eps_i_ResultDesc = UILabel()
let eps_i_ResultDescTap = UITapGestureRecognizer()
let eps_i_StatusDesc = UILabel()
let eps_sd_ResultDesc = UILabel()
let eps_sd_ResultDescTap = UITapGestureRecognizer()
let eps_sd_StatusDesc = UILabel()
let roe_avg_ResultDesc = UILabel()
let roe_avg_ResultDescTap = UITapGestureRecognizer()
let roe_avg_StatusDesc = UILabel()
let bv_i_ResultDesc = UILabel()
let bv_i_ResultDescTap = UITapGestureRecognizer()
let bv_i_StatusDesc = UILabel()
let dr_avg_ResultDesc = UILabel()
let dr_avg_ResultDescTap = UITapGestureRecognizer()
let dr_avg_StatusDesc = UILabel()
let so_reduced_ResultDesc = UILabel()
let so_reduced_ResultDescTap = UITapGestureRecognizer()
let so_reduced_StatusDesc = UILabel()
let pe_change_ResultDesc = UILabel()
let pe_change_ResultDescTap = UITapGestureRecognizer()
let pe_change_StatusDesc = UILabel()
let previous_roi_ResultDesc = UILabel()
let previous_roi_ResultDescTap = UITapGestureRecognizer()
let previous_roi_StatusDesc = UILabel()
let expected_roi_ResultDesc = UILabel()
let expected_roi_ResultDescTap = UITapGestureRecognizer()
let expected_roi_StatusDesc = UILabel()
let q1_Desc = UILabel()
let q1_DescTap = UITapGestureRecognizer()
let q1_StatusDesc = UILabel()
let q2_Desc = UILabel()
let q2_DescTap = UITapGestureRecognizer()
let q2_StatusDesc = UILabel()
let q3_Desc = UILabel()
let q3_DescTap = UITapGestureRecognizer()
let q3_StatusDesc = UILabel()
let q4_Desc = UILabel()
let q4_DescTap = UITapGestureRecognizer()
let q4_StatusDesc = UILabel()
let q5_Desc = UILabel()
let q5_DescTap = UITapGestureRecognizer()
let q5_StatusDesc = UILabel()
let q6_Desc = UILabel()
let q6_DescTap = UITapGestureRecognizer()
let q6_StatusDesc = UILabel()
let own_Desc = UILabel()
let own_DescTap = UITapGestureRecognizer()
let own_StatusDesc = UILabel()
override init(frame:CGRect){
super.init(frame: frame)
// the 5 and SE devices (width=320) need more vertical space
UIScreen.main.bounds.width == 320 ? (self.heightOfScrolledContent = 840) : (self.heightOfScrolledContent = 800)
self.pageLayout()
self.accessibilityLabel = "equityDetailViewInst"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func pageLayout() {
self.addSubview(self.scrollView)
self.scrollView.backgroundColor = UIColor.black
self.scrollView.translatesAutoresizingMaskIntoConstraints = false
self.scrollView.backgroundColor = UIColor.white
self.scrollView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
self.scrollView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
self.scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
self.scrollView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
self.scrollView.autoresizingMask = [.flexibleRightMargin, .flexibleLeftMargin, .flexibleBottomMargin]
self.scrollView.contentSize = CGSize(width: self.bounds.width, height: self.heightOfScrolledContent)
// subtitle
self.scrollView.addSubview(self.subTitle)
self.subTitle.translatesAutoresizingMaskIntoConstraints = false
self.subTitle.topAnchor.constraint(equalTo: self.scrollView.topAnchor, constant: 36).isActive = true
self.subTitle.leftAnchor.constraint(equalTo: self.scrollView.leftAnchor, constant: 10).isActive = true
self.subTitle.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
self.subTitle.text = "Review the measures for this equity and provide values for measures with undefined values."
self.subTitle.font = UIFont(name: Constants.appFont.regular.rawValue, size: Constants.fontSize.small.rawValue)
self.subTitle.numberOfLines = 0
// EPSiResultsDesc
self.scrollView.addSubview(self.eps_i_ResultDesc)
self.eps_i_ResultDesc.translatesAutoresizingMaskIntoConstraints = false
self.eps_i_ResultDesc.topAnchor.constraint(equalTo: self.subTitle.bottomAnchor, constant: 36).isActive = true
self.eps_i_ResultDesc.leftAnchor.constraint(equalTo: self.subTitle.leftAnchor, constant: 30).isActive = true
self.eps_i_ResultDesc.rightAnchor.constraint(equalTo: self.subTitle.rightAnchor).isActive = true
self.eps_i_ResultDesc.numberOfLines = 0
self.eps_i_ResultDesc.font = UIFont(name: Constants.appFont.regular.rawValue, size: Constants.fontSize.small.rawValue)
self.eps_i_ResultDescTap.addTarget(self, action: #selector(self.onClickLineItem))
self.eps_i_ResultDesc.isUserInteractionEnabled = true
self.eps_i_ResultDesc.addGestureRecognizer(eps_i_ResultDescTap)
// EPSiStatusDesc
self.scrollView.addSubview(self.eps_i_StatusDesc)
self.eps_i_StatusDesc.translatesAutoresizingMaskIntoConstraints = false
self.eps_i_StatusDesc.topAnchor.constraint(equalTo: self.eps_i_ResultDesc.topAnchor, constant: 0).isActive = true
self.eps_i_StatusDesc.rightAnchor.constraint(equalTo: self.eps_i_ResultDesc.leftAnchor, constant: -10).isActive = true
self.eps_i_StatusDesc.font = UIFont(name: Constants.iconFont.fontAwesome.rawValue, size: Constants.iconSize.xsmall.rawValue)
// after the row for the first measure is in place, the other rows can be added through the function
// eps_sd
self.addRowForMeasure(
resultDesc: self.eps_sd_ResultDesc,
previousResultDesc: self.eps_i_ResultDesc,
resultDescTap: self.eps_sd_ResultDescTap,
statusDesc: self.eps_sd_StatusDesc
)
// roe_avg
self.addRowForMeasure(
resultDesc: self.roe_avg_ResultDesc,
previousResultDesc: self.eps_sd_ResultDesc,
resultDescTap: self.roe_avg_ResultDescTap,
statusDesc: self.roe_avg_StatusDesc
)
// bv_i
self.addRowForMeasure(
resultDesc: self.bv_i_ResultDesc,
previousResultDesc: self.roe_avg_ResultDesc,
resultDescTap: self.bv_i_ResultDescTap,
statusDesc: self.bv_i_StatusDesc
)
// dr_avg
self.addRowForMeasure(
resultDesc: self.dr_avg_ResultDesc,
previousResultDesc: self.bv_i_ResultDesc,
resultDescTap: self.dr_avg_ResultDescTap,
statusDesc: self.dr_avg_StatusDesc
)
// so_reduced
self.addRowForMeasure(
resultDesc: self.so_reduced_ResultDesc,
previousResultDesc: self.dr_avg_ResultDesc,
resultDescTap: self.so_reduced_ResultDescTap,
statusDesc: self.so_reduced_StatusDesc
)
// pe_change
self.addRowForMeasure(
resultDesc: self.pe_change_ResultDesc,
previousResultDesc: self.so_reduced_ResultDesc,
resultDescTap: self.pe_change_ResultDescTap,
statusDesc: self.pe_change_StatusDesc
)
// previous_roi
self.addRowForMeasure(
resultDesc: self.previous_roi_ResultDesc,
previousResultDesc: self.pe_change_ResultDesc,
resultDescTap: self.previous_roi_ResultDescTap,
statusDesc: self.previous_roi_StatusDesc
)
// expected_roi
self.addRowForMeasure(
resultDesc: self.expected_roi_ResultDesc,
previousResultDesc: self.previous_roi_ResultDesc,
resultDescTap: self.expected_roi_ResultDescTap,
statusDesc: self.expected_roi_StatusDesc
)
// q1
self.addRowForMeasure(
resultDesc: self.q1_Desc,
previousResultDesc: self.expected_roi_ResultDesc,
resultDescTap: self.q1_DescTap,
statusDesc: self.q1_StatusDesc
)
// q2
self.addRowForMeasure(
resultDesc: self.q2_Desc,
previousResultDesc: self.q1_Desc,
resultDescTap: self.q2_DescTap,
statusDesc: self.q2_StatusDesc
)
// q3
self.addRowForMeasure(
resultDesc: self.q3_Desc,
previousResultDesc: self.q2_Desc,
resultDescTap: self.q3_DescTap,
statusDesc: self.q3_StatusDesc
)
// q4
self.addRowForMeasure(
resultDesc: self.q4_Desc,
previousResultDesc: self.q3_Desc,
resultDescTap: self.q4_DescTap,
statusDesc: self.q4_StatusDesc
)
// q5
self.addRowForMeasure(
resultDesc: self.q5_Desc,
previousResultDesc: self.q4_Desc,
resultDescTap: self.q5_DescTap,
statusDesc: self.q5_StatusDesc
)
// q6
self.addRowForMeasure(
resultDesc: self.q6_Desc,
previousResultDesc: self.q5_Desc,
resultDescTap: self.q6_DescTap,
statusDesc: self.q6_StatusDesc
)
// own
self.addRowForMeasure(
resultDesc: self.own_Desc,
previousResultDesc: self.q6_Desc,
resultDescTap: self.own_DescTap,
statusDesc: self.own_StatusDesc
)
}
func addRowForMeasure(resultDesc: UILabel, previousResultDesc: UILabel, resultDescTap: UITapGestureRecognizer, statusDesc: UILabel){
// BViResultDesc
self.scrollView.addSubview(resultDesc)
resultDesc.translatesAutoresizingMaskIntoConstraints = false
resultDesc.topAnchor.constraint(equalTo: previousResultDesc.bottomAnchor, constant: self.lineSpacing).isActive = true
resultDesc.leftAnchor.constraint(equalTo: previousResultDesc.leftAnchor).isActive = true
resultDesc.rightAnchor.constraint(equalTo: previousResultDesc.rightAnchor).isActive = true
resultDesc.numberOfLines = 0
resultDesc.font = UIFont(name: Constants.appFont.regular.rawValue, size: Constants.fontSize.small.rawValue)
resultDescTap.addTarget(self, action: #selector(self.onClickLineItem))
resultDesc.isUserInteractionEnabled = true
resultDesc.addGestureRecognizer(resultDescTap)
// BViStatusDesc
self.scrollView.addSubview(statusDesc)
statusDesc.translatesAutoresizingMaskIntoConstraints = false
statusDesc.topAnchor.constraint(equalTo: resultDesc.topAnchor, constant: 0).isActive = true
statusDesc.rightAnchor.constraint(equalTo: resultDesc.leftAnchor, constant: -10).isActive = true
statusDesc.font = UIFont(name: Constants.iconFont.fontAwesome.rawValue, size: Constants.iconSize.xsmall.rawValue)
}
@objc func onClickLineItem(sender: UILabel){
if let measure = sender.accessibilityLabel {
self.delegate?.openMeasureDetail(measure: measure)
}
}
}
| apache-2.0 | 84403eeb224f96be1815415c2cc19ea1 | 40.323129 | 136 | 0.645321 | 4.300531 | false | false | false | false |
OneBestWay/EasyCode | Framework/Phonercise/Phonercise/ActionViewController.swift | 1 | 3298 | /*
* Copyright (c) 2016 Razeware 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 UIKit
import CoreMotion
import ThreeRingControl
private let oneCircleLength = 30.0 // 30s to fill a circle
private let scanInterval = 0.5 // check each 1/2 second
extension ThreeRingView {
var move: CGFloat {
get { return innerRingValue }
set { innerRingValue = newValue }
}
var exercise: CGFloat {
get { return middleRingValue }
set { middleRingValue = newValue }
}
var stand: CGFloat {
get { return outerRingValue }
set { outerRingValue = newValue }
}
}
class ActionViewController: UIViewController {
@IBOutlet weak var ringControl: ThreeRingView!
var shakeStart: Date?
var manager = CMMotionManager()
override var canBecomeFirstResponder : Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
Fanfare.sharedInstance.playSoundsWhenReady()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
becomeFirstResponder()
manager.deviceMotionUpdateInterval = scanInterval
manager.startDeviceMotionUpdates(to: OperationQueue.main) { motion, error in
if let upright = motion?.attitude.pitch , upright > M_PI_2 * 0.75 {
self.ringControl.stand += CGFloat(1.0 / (oneCircleLength / scanInterval))
}
if let rotationRate = motion?.rotationRate {
let x = abs(rotationRate.x), y = abs(rotationRate.y), z = abs(rotationRate.z)
if x > 0.5 || y > 0.5 || z > 0.5 {
self.ringControl.move += CGFloat(1.0 / (oneCircleLength / scanInterval))
}
}
}
}
override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
shakeStart = Date()
}
}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
let shakeEnd = Date()
#if (arch(i386) || arch(x86_64)) && os(iOS)
//Test on the simulator with a simple gesture action
let diff = 2.0
#else
let diff = shakeEnd.timeIntervalSince(shakeStart!)
#endif
shake(diff)
}
}
func shake(_ forNSeconds: TimeInterval) {
self.ringControl.exercise += CGFloat(forNSeconds / oneCircleLength)
}
}
| mit | 883b8f1294aca68d812b07c24a580424 | 30.113208 | 85 | 0.698908 | 4.228205 | false | false | false | false |
mnisn/zhangchu | zhangchu/zhangchu/classes/recipe/recommend/main/view/RecommendOtherFoodCell.swift | 1 | 4030 | //
// RecommendOtherFoodCell.swift
// zhangchu
//
// Created by 苏宁 on 2016/10/28.
// Copyright © 2016年 suning. All rights reserved.
//
import UIKit
class RecommendOtherFoodCell: UITableViewCell {
var clickClosure:RecipClickClosure?
var listModel:RecipeRecommendWidgetList?{
didSet{
showData()
}
}
func showData()
{
//左
//图
if listModel?.widget_data?.count > 0
{
let sceneData = listModel?.widget_data![0]
sceneBtn.kf_setBackgroundImageWithURL(NSURL(string: (sceneData?.content)!), forState: .Normal)
sceneBtn.contentMode = .ScaleAspectFill
}
//name
if listModel?.widget_data?.count > 1
{
let nameData = listModel?.widget_data![1]
nameLabel.text = nameData?.content
}
//num
if listModel?.widget_data?.count > 2
{
let naumData = listModel?.widget_data![2]
numLabel.text = naumData?.content
}
//右
for i in 0 ..< 4
{
//图
if listModel?.widget_data?.count > i * 2 + 3
{
let btnData = listModel?.widget_data![i * 2 + 3]
if btnData?.type == "image"
{
let tmpView = contentView.viewWithTag(100 + i)
if tmpView?.isKindOfClass(UIButton) == true
{
let btn = tmpView as! UIButton
btn.kf_setBackgroundImageWithURL(NSURL(string: (btnData?.content)!), forState: .Normal)
btn.contentMode = .ScaleAspectFill
}
}
}
//视频
}
//desc
descLabel.text = listModel?.desc
}
@IBOutlet weak var sceneBtn: UIButton!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var numLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
@IBAction func sceneBtnClick(sender: UIButton)
{
if listModel?.widget_data?.count > 0
{
let sceneData = listModel?.widget_data![0]
if sceneData?.link != nil && clickClosure != nil
{
clickClosure!((sceneData?.link)!)
}
}
}
@IBAction func imgBtnClick(sender: UIButton)
{
let index = sender.tag - 100
if listModel?.widget_data?.count > index * 2 + 3
{
let data = listModel?.widget_data![index * 2 + 3]
if data?.link != nil && clickClosure != nil
{
clickClosure!((data?.link)!)
}
}
}
@IBAction func playBtnClick(sender: UIButton)
{
let index = sender.tag - 200
if listModel?.widget_data?.count > index * 2 + 4
{
let data = listModel?.widget_data![index * 2 + 4]
if data?.content != nil && clickClosure != nil
{
clickClosure!((data?.content)!)
}
}
}
//创建cell
class func createOtherCell(tableView: UITableView, atIndexPath indexPath:NSIndexPath, listModel:RecipeRecommendWidgetList?) ->RecommendOtherFoodCell
{
let cellID = "recommendOtherFoodCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? RecommendOtherFoodCell
if cell == nil
{
cell = NSBundle.mainBundle().loadNibNamed("RecommendOtherFoodCell", owner: nil, options: nil).last as? RecommendOtherFoodCell
}
cell?.listModel = listModel!
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | cadf3ba8c193bd647f2c2a3fe2a7aef7 | 27.020979 | 152 | 0.524332 | 4.880633 | false | false | false | false |
moonrailgun/OpenCode | OpenCode/Classes/News/View/Trending/TrendingView.swift | 1 | 4810 | //
// TrendingView.swift
// OpenCode
//
// Created by 陈亮 on 16/5/30.
// Copyright © 2016年 moonrailgun. All rights reserved.
//
import UIKit
import SwiftyJSON
import MJRefresh
class TrendingView: UIView, UITableViewDataSource, UITableViewDelegate {
let TRENDING_CELL_ID = "trending"
lazy var tableView:UITableView = UITableView(frame: self.bounds, style: .Plain)
var data:JSON?
var controller:UIViewController?
var currentMaxPage = 1
init(frame: CGRect, controller:UIViewController?) {
super.init(frame:frame)
self.controller = controller
initView()
initData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initView(){
tableView.registerNib(UINib(nibName: "SearchRepoCell", bundle: nil), forCellReuseIdentifier: TRENDING_CELL_ID)
tableView.rowHeight = 130
tableView.dataSource = self
tableView.delegate = self
tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
self.currentMaxPage += 1
self.addonData(self.currentMaxPage)
})
self.addSubview(tableView)
}
func initData(){
Github.getGithubTrending(nil) { (data:AnyObject?) in
if let d = data{
let json = JSON(d)
print("共\(json["total_count"].int!)个近期热门项目")
let items = json["items"]
self.data = items
OperationQueueHelper.operateInMainQueue({
let header = UILabel(frame: CGRectMake(0,0,self.bounds.width,24))
header.text = "共\(json["total_count"].int!)个近期热门项目"
header.textColor = UIColor.whiteColor()
header.backgroundColor = UIColor.turquoiseFlatColor()
header.textAlignment = .Center
header.font = UIFont.systemFontOfSize(14)
self.tableView.tableHeaderView = header
self.tableView.reloadData()
})
}
}
}
func addonData(page:Int){
Github.getGithubTrending(page) { (data:AnyObject?) in
if let d = data{
let json = JSON(d)
print("加载新数据完毕,加载页码\(page)")
let items = json["items"]
if(self.data != nil) {
var tmp = self.data?.array
for i in 0 ... items.count - 1{
tmp!.append(items[i])
}
self.data = JSON(tmp!)
}
OperationQueueHelper.operateInMainQueue({
self.tableView.reloadData()
self.tableView.mj_footer.endRefreshing()
})
}
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(TRENDING_CELL_ID)
if(cell == nil){
cell = SearchRepoCell(style: .Default, reuseIdentifier: TRENDING_CELL_ID)
cell?.accessoryType = .DisclosureIndicator
}
if(data != nil){
let item = data![indexPath.row]
(cell as! SearchRepoCell).setData(item)
}
return cell!
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let _ = data{
return self.data!.count
}else{
return 0
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print(indexPath)
let item = self.data![indexPath.row]
if let repoFullName = item["full_name"].string{
ProgressHUD.show()
Github.getRepoInfo(repoFullName, completionHandler: { (data:AnyObject?) in
OperationQueueHelper.operateInMainQueue({
ProgressHUD.dismiss()
let controller = RepoDetailController()
controller.repoDetailData = data
self.controller?.navigationController?.pushViewController(controller, animated: true)
})
})
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| gpl-2.0 | be4cd8d1b14aa8139b85f9e041c9e951 | 31.979167 | 118 | 0.551274 | 5.122977 | false | false | false | false |
thinkaboutiter/SimpleLogger | Sources/SimpleLoggerCLITest/main.swift | 1 | 4056 | // The MIT License (MIT)
//
// Copyright (c) 2020 thinkaboutiter ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import SimpleLogger
let messge_start: String = "Starting Simple logger excercise!"
debugPrint("🔧 \(#file) » \(#function) » \(#line)", messge_start, separator: "\n")
private func log_message() {
// info
Logger.general.message("Logging `genereal` message")
Logger.debug.message("Logging `debug` message")
// status
Logger.success.message("Logging `success` message")
Logger.warning.message("Logging `warning` message")
Logger.error.message("Logging `error` message")
Logger.fatal.message("Logging `fatal` message")
// data
Logger.network.message("Logging `network` message")
Logger.cache.message("Logging `cache` message")
}
private func log_objects() {
// array
let sampleArray: [Int] = [
0,
1,
2,
3
]
Logger.debug.message("Array:").object(sampleArray)
// dictionary
let sampleDictionary: [String: String] = [
"key_0": "value_0",
"key_1": "value_1",
"key_2": "value_2",
"key_3": "value_3"
]
Logger.debug.message("Dictionary:").object(sampleDictionary)
}
private struct Constants {
static let scope_1_name: String = "scope_1"
}
private func log_scopeObjects() {
// array
let sampleArray: [Int] = [
0,
1,
2,
3
]
Logger.debug
.message("Array:",
scopeName: Constants.scope_1_name)
.object(sampleArray,
scopeName: Constants.scope_1_name)
// dictionary
let sampleDictionary: [String: String] = [
"key_0": "value_0",
"key_1": "value_1",
"key_2": "value_2",
"key_3": "value_3"
]
Logger.debug
.message("Dictionary:",
scopeName: Constants.scope_1_name)
.object(sampleDictionary,
scopeName: Constants.scope_1_name)
}
private func log_nil() {
Logger.debug.message("Logging nil:").object(nil)
}
private func exerciseSimpleLogger() {
log_message()
log_objects()
log_scopeObjects()
log_nil()
}
private func test_writing_to_file() {
guard let valid_directoryPath: String = Logger.currentDirectoryPath() else {
let message: String = "Unable to obtain valid directory path!"
Logger.error.message(message)
return
}
let logsDirectoryPath: String = "\(valid_directoryPath)/logs"
Logger.setLogsDirectoryPath(logsDirectoryPath)
// Logger.setSingleLogFileName("application.log")
// Logger.setSingleLogFileMaxSizeInBytes(1024*1024*1)
Logger.setFileLogging(.multipleFiles)
Logger.setPrefix(.ascii)
}
test_writing_to_file()
for _ in 0..<10 {
exerciseSimpleLogger()
}
let messge_finish: String = "Finished Simple logger excercise!"
debugPrint("🔧 \(#file) » \(#function) » \(#line)", messge_finish, separator: "\n")
| mit | ed97da167f4cee7dee6f5a9993aa8b95 | 29.885496 | 82 | 0.653238 | 3.886647 | false | false | false | false |
googlemaps/maps-sdk-for-ios-samples | GooglePlaces-Swift/GooglePlacesSwiftDemos/Swift/Samples/Autocomplete/AutocompleteBaseViewController.swift | 1 | 5309 | // Copyright 2020 Google LLC. 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 GooglePlaces
import UIKit
/// All other autocomplete demo classes inherit from this class. This class optionally adds a button
/// to present the autocomplete widget, and displays the results when these are selected.
class AutocompleteBaseViewController: UIViewController {
private lazy var textView: UITextView = {
let textView = UITextView()
textView.isEditable = false
textView.textContainerInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
return textView
}()
private lazy var photoButton: UIBarButtonItem = {
return UIBarButtonItem(
title: "Photos", style: .plain, target: self, action: #selector(showPhotos))
}()
private lazy var pagingPhotoView: PagingPhotoView = {
let photoView = PagingPhotoView()
photoView.isHidden = true
return photoView
}()
var autocompleteConfiguration: AutocompleteConfiguration?
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 13.0, *) {
view.backgroundColor = .systemBackground
} else {
view.backgroundColor = .white
}
view.addSubview(textView)
textView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pagingPhotoView)
pagingPhotoView.translatesAutoresizingMaskIntoConstraints = false
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
textView.topAnchor.constraint(equalTo: guide.topAnchor),
textView.bottomAnchor.constraint(equalTo: guide.bottomAnchor),
textView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
textView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
])
NSLayoutConstraint.activate([
pagingPhotoView.topAnchor.constraint(equalTo: guide.topAnchor),
pagingPhotoView.bottomAnchor.constraint(equalTo: guide.bottomAnchor),
pagingPhotoView.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
pagingPhotoView.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
])
}
@objc func showPhotos() {
pagingPhotoView.isHidden = false
navigationItem.rightBarButtonItem = nil
textView.isHidden = true
}
func autocompleteDidSelectPlace(_ place: GMSPlace) {
let text = NSMutableAttributedString(string: place.description)
text.append(NSAttributedString(string: "\nPlace status: "))
text.append(NSAttributedString(string: place.isOpen().description))
if let attributions = place.attributions {
text.append(NSAttributedString(string: "\n\n"))
text.append(attributions)
}
if #available(iOS 13.0, *) {
text.addAttribute(.foregroundColor, value: UIColor.label, range: NSMakeRange(0, text.length))
}
textView.attributedText = text
textView.isHidden = false
pagingPhotoView.isHidden = true
if let photos = place.photos, photos.count > 0 {
preloadPhotoList(photos: photos)
}
}
func autocompleteDidFail(_ error: Error) {
textView.text = String(
format: NSLocalizedString(
"Demo.Content.Autocomplete.FailedErrorMessage",
comment: "Format string for 'autocomplete failed with error' message"), error as NSError)
}
func autocompleteDidCancel() {
textView.text = NSLocalizedString(
"Demo.Content.Autocomplete.WasCanceledMessage",
comment: "String for 'autocomplete canceled message'")
}
override func viewWillTransition(
to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator
) {
super.viewWillTransition(to: size, with: coordinator)
pagingPhotoView.shouldRedraw = true
}
}
extension AutocompleteBaseViewController {
// Preload the photos to be displayed.
func preloadPhotoList(photos: [GMSPlacePhotoMetadata]) {
var attributedPhotos: [AttributedPhoto] = []
let placeClient = GMSPlacesClient.shared()
DispatchQueue.global().async {
let downloadGroup = DispatchGroup()
photos.forEach { photo in
downloadGroup.enter()
placeClient.loadPlacePhoto(photo) { imageData, error in
if let image = imageData, let attributions = photo.attributions {
attributedPhotos.append(AttributedPhoto(image: image, attributions: attributions))
}
downloadGroup.leave()
}
}
downloadGroup.notify(queue: DispatchQueue.main) {
self.navigationItem.rightBarButtonItem = self.photoButton
self.pagingPhotoView.updatePhotos(attributedPhotos)
}
}
}
}
extension GMSPlaceOpenStatus: CustomStringConvertible {
public var description: String {
switch self {
case .open:
return "Open"
case .closed:
return "Closed"
case .unknown:
return "Unknown"
default:
return ""
}
}
}
| apache-2.0 | 936934fbf9f39c9f713cb0dbcd432a32 | 33.927632 | 100 | 0.719533 | 4.848402 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPress/Classes/ViewRelated/People/PersonViewController.swift | 2 | 18399 | import Foundation
import UIKit
import CocoaLumberjack
import WordPressShared
/// Displays a Blog's User Details
///
final class PersonViewController: UITableViewController {
/// PersonViewController operation modes
///
enum ScreenMode: String {
case User = "user"
case Follower = "follower"
case Viewer = "viewer"
var title: String {
switch self {
case .User:
return NSLocalizedString("Blog's User", comment: "Blog's User Profile. Displayed when the name is empty!")
case .Follower:
return NSLocalizedString("Blog's Follower", comment: "Blog's Follower Profile. Displayed when the name is empty!")
case .Viewer:
return NSLocalizedString("Blog's Viewer", comment: "Blog's Viewer Profile. Displayed when the name is empty!")
}
}
var name: String {
switch self {
case .User:
return NSLocalizedString("user", comment: "Noun. Describes a site's user.")
case .Follower:
return NSLocalizedString("follower", comment: "Noun. Describes a site's follower.")
case .Viewer:
return NSLocalizedString("viewer", comment: "Noun. Describes a site's viewer.")
}
}
}
// MARK: - Public Properties
/// Blog to which the Person belongs
///
var blog: Blog!
/// Core Data Context that should be used
///
var context: NSManagedObjectContext!
/// Person to be displayed
///
var person: Person! {
didSet {
refreshInterfaceIfNeeded()
}
}
/// Mode: User / Follower / Viewer
///
var screenMode: ScreenMode = .User
/// Gravatar Image
///
@IBOutlet var gravatarImageView: UIImageView! {
didSet {
refreshGravatarImage()
}
}
/// Person's Full Name
///
@IBOutlet var fullNameLabel: UILabel! {
didSet {
setupFullNameLabel()
refreshFullNameLabel()
}
}
/// Person's User Name
///
@IBOutlet var usernameLabel: UILabel! {
didSet {
setupUsernameLabel()
refreshUsernameLabel()
}
}
/// Person's Role
///
@IBOutlet var roleCell: UITableViewCell! {
didSet {
setupRoleCell()
refreshRoleCell()
}
}
/// Person's First Name
///
@IBOutlet var firstNameCell: UITableViewCell! {
didSet {
setupFirstNameCell()
refreshFirstNameCell()
}
}
/// Person's Last Name
///
@IBOutlet var lastNameCell: UITableViewCell! {
didSet {
setupLastNameCell()
refreshLastNameCell()
}
}
/// Person's Display Name
///
@IBOutlet var displayNameCell: UITableViewCell! {
didSet {
setupDisplayNameCell()
refreshDisplayNameCell()
}
}
/// Nuking the User
///
@IBOutlet var removeCell: UITableViewCell! {
didSet {
setupRemoveCell()
refreshRemoveCell()
}
}
// MARK: - View Lifecyle Methods
override func viewDidLoad() {
assert(person != nil)
assert(blog != nil)
super.viewDidLoad()
title = person.fullName.nonEmptyString() ?? screenMode.title
WPStyleGuide.configureColors(for: view, andTableView: tableView)
WPStyleGuide.configureAutomaticHeightRows(for: tableView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
WPAnalytics.track(.openedPerson)
}
// MARK: - UITableView Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectSelectedRowWithAnimation(true)
guard let cell = tableView.cellForRow(at: indexPath) else {
return
}
switch cell {
case roleCell:
roleWasPressed()
case removeCell:
removeWasPressed()
default:
break
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Forgive Me:
// ===========
// Why do we check the indexPath's values, instead of grabbing the cellForRowAtIndexPath, and check if
// it's hidden or not?
//
// Because:
// UITableView is crashing if we do so, in this method. Probably due to an internal structure
// not being timely initialized.
//
//
if isFullnamePrivate == true && fullnameSection == indexPath.section && fullnameRows.contains(indexPath.row) {
return CGFloat.leastNormalMagnitude
}
return super.tableView(tableView, heightForRowAt: indexPath)
}
// MARK: - Storyboard Methods
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let roleViewController = segue.destination as? RoleViewController else {
return
}
roleViewController.roles = blog.sortedRoles?.map({ $0.toUnmanaged() }) ?? []
roleViewController.selectedRole = person.role
roleViewController.onChange = { [weak self] newRole in
self?.updateUserRole(newRole)
}
}
// MARK: - Constants
fileprivate let roleSegueIdentifier = "editRole"
fileprivate let gravatarPlaceholderImage = UIImage(named: "gravatar.png")
fileprivate let fullnameSection = 1
fileprivate let fullnameRows = [1, 2]
}
// MARK: - Private Helpers: Actions
//
private extension PersonViewController {
func roleWasPressed() {
performSegue(withIdentifier: roleSegueIdentifier, sender: nil)
}
func removeWasPressed() {
let titleFormat = NSLocalizedString("Remove @%@", comment: "Remove Person Alert Title")
let titleText = String(format: titleFormat, person.username)
let name = person.firstName?.nonEmptyString() ?? person.username
var messageFirstLine: String
switch screenMode {
case .User:
messageFirstLine = NSLocalizedString( "If you remove " + name + ", that user will no longer be able to access this site, " +
"but any content that was created by " + name + " will remain on the site.",
comment: "First line of remove user warning")
case .Follower:
messageFirstLine = NSLocalizedString( "If removed, this follower will stop receiving notifications about this site, unless they re-follow.",
comment: "First line of remove follower warning")
case .Viewer:
messageFirstLine = NSLocalizedString( "If you remove this viewer, he or she will not be able to visit this site.",
comment: "First line of remove viewer warning")
}
let messageSecondLineFormat = NSLocalizedString("Would you still like to remove this %@?", comment: "Second line of Remove user/follower/viewer confirmation. ")
let messageSecondLineText = String(format: messageSecondLineFormat, screenMode.name)
let message = messageFirstLine + "\n\n" + messageSecondLineText
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel Action")
let removeTitle = NSLocalizedString("Remove", comment: "Remove Action")
let alert = UIAlertController(title: titleText, message: message, preferredStyle: .alert)
alert.addCancelActionWithTitle(cancelTitle)
alert.addDestructiveActionWithTitle(removeTitle) { [weak self] action in
guard let strongSelf = self else {
return
}
switch strongSelf.screenMode {
case .User:
strongSelf.deleteUser()
case .Follower:
strongSelf.deleteFollower()
case .Viewer:
strongSelf.deleteViewer()
return
}
}
alert.presentFromRootViewController()
}
func deleteUser() {
guard let user = user else {
DDLogError("Error: Only Users can be deleted here")
assertionFailure()
return
}
let service = PeopleService(blog: blog, context: context)
service?.deleteUser(user, success: {
WPAnalytics.track(.personRemoved)
}, failure: {[weak self] (error: Error?) -> () in
guard let strongSelf = self, let error = error as NSError? else {
return
}
guard let personWithError = strongSelf.person else {
return
}
strongSelf.handleRemoveUserError(error, userName: "@" + personWithError.username)
})
_ = navigationController?.popViewController(animated: true)
}
func deleteFollower() {
guard let follower = follower, isFollower else {
DDLogError("Error: Only Followers can be deleted here")
assertionFailure()
return
}
let service = PeopleService(blog: blog, context: context)
service?.deleteFollower(follower, failure: {[weak self] (error: Error?) -> () in
guard let strongSelf = self, let error = error as NSError? else {
return
}
strongSelf.handleRemoveViewerOrFollowerError(error)
})
_ = navigationController?.popViewController(animated: true)
}
func deleteViewer() {
guard let viewer = viewer, isViewer else {
DDLogError("Error: Only Viewers can be deleted here")
assertionFailure()
return
}
let service = PeopleService(blog: blog, context: context)
service?.deleteViewer(viewer, success: {
WPAnalytics.track(.personRemoved)
}, failure: {[weak self] (error: Error?) -> () in
guard let strongSelf = self, let error = error as NSError? else {
return
}
strongSelf.handleRemoveViewerOrFollowerError(error)
})
_ = navigationController?.popViewController(animated: true)
}
func handleRemoveUserError(_ error: NSError, userName: String) {
// The error code will be "forbidden" per:
// https://developer.wordpress.com/docs/api/1.1/post/sites/%24site/users/%24user_ID/delete/
guard let errorCode = error.userInfo[WordPressComRestApi.ErrorKeyErrorCode] as? String,
errorCode.localizedCaseInsensitiveContains("forbidden") else {
let errorWithSource = NSError(domain: error.domain, code: error.code, userInfo: error.userInfo)
WPError.showNetworkingAlertWithError(errorWithSource)
return
}
let errorTitleFormat = NSLocalizedString("Error removing %@", comment: "Title of error dialog when removing a site owner fails.")
let errorTitleText = String(format: errorTitleFormat, userName)
let errorMessage = NSLocalizedString("The user you are trying to remove is the owner of this site. " +
"Please contact support for assistance.",
comment: "Error message shown when user attempts to remove the site owner.")
WPError.showAlert(withTitle: errorTitleText, message: errorMessage, withSupportButton: true)
}
func handleRemoveViewerOrFollowerError(_ error: NSError) {
let errorWithSource = NSError(domain: error.domain, code: error.code, userInfo: error.userInfo)
WPError.showNetworkingAlertWithError(errorWithSource)
}
func updateUserRole(_ newRole: String) {
guard let user = user else {
DDLogError("Error: Only Users have Roles!")
assertionFailure()
return
}
guard let service = PeopleService(blog: blog, context: context) else {
DDLogError("Couldn't instantiate People Service")
return
}
let updated = service.updateUser(user, role: newRole) { (error, reloadedPerson) in
self.person = reloadedPerson
self.retryUpdatingRole(newRole)
}
// Optimistically refresh the UI
self.person = updated
WPAnalytics.track(.personUpdated)
}
func retryUpdatingRole(_ newRole: String) {
let retryTitle = NSLocalizedString("Retry", comment: "Retry updating User's Role")
let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel updating User's Role")
let title = NSLocalizedString("Sorry!", comment: "Update User Failed Title")
let localizedError = NSLocalizedString("There was an error updating @%@", comment: "Updating Role failed error message")
let messageText = String(format: localizedError, person.username)
let alertController = UIAlertController(title: title, message: messageText, preferredStyle: .alert)
alertController.addCancelActionWithTitle(cancelTitle, handler: nil)
alertController.addDefaultActionWithTitle(retryTitle) { action in
self.updateUserRole(newRole)
}
alertController.presentFromRootViewController()
}
}
// MARK: - Private Helpers: Initializing Interface
//
private extension PersonViewController {
func setupFullNameLabel() {
fullNameLabel.font = WPStyleGuide.tableviewTextFont()
fullNameLabel.textColor = WPStyleGuide.darkGrey()
}
func setupUsernameLabel() {
usernameLabel.font = WPStyleGuide.tableviewSectionHeaderFont()
usernameLabel.textColor = WPStyleGuide.wordPressBlue()
}
func setupFirstNameCell() {
firstNameCell.textLabel?.text = NSLocalizedString("First Name", comment: "User's First Name")
WPStyleGuide.configureTableViewCell(firstNameCell)
}
func setupLastNameCell() {
lastNameCell.textLabel?.text = NSLocalizedString("Last Name", comment: "User's Last Name")
WPStyleGuide.configureTableViewCell(lastNameCell)
}
func setupDisplayNameCell() {
displayNameCell.textLabel?.text = NSLocalizedString("Display Name", comment: "User's Display Name")
WPStyleGuide.configureTableViewCell(displayNameCell)
}
func setupRoleCell() {
roleCell.textLabel?.text = NSLocalizedString("Role", comment: "User's Role")
WPStyleGuide.configureTableViewCell(roleCell)
}
func setupRemoveCell() {
let removeFormat = NSLocalizedString("Remove @%@", comment: "Remove User. Verb")
let removeText = String(format: removeFormat, person.username)
removeCell.textLabel?.text = removeText as String
WPStyleGuide.configureTableViewDestructiveActionCell(removeCell)
}
}
// MARK: - Private Helpers: Refreshing Interface
//
private extension PersonViewController {
func refreshInterfaceIfNeeded() {
guard isViewLoaded else {
return
}
refreshGravatarImage()
refreshFullNameLabel()
refreshUsernameLabel()
refreshRoleCell()
refreshFirstNameCell()
refreshLastNameCell()
refreshDisplayNameCell()
refreshRemoveCell()
}
func refreshGravatarImage() {
let gravatar = person.avatarURL.flatMap { Gravatar($0) }
let placeholder = UIImage(named: "gravatar")!
gravatarImageView.downloadGravatar(gravatar, placeholder: placeholder, animate: false)
}
func refreshFullNameLabel() {
fullNameLabel.text = person.fullName
}
func refreshUsernameLabel() {
usernameLabel.text = "@" + person.username
}
func refreshFirstNameCell() {
firstNameCell.detailTextLabel?.text = person.firstName
firstNameCell.isHidden = isFullnamePrivate
}
func refreshLastNameCell() {
lastNameCell.detailTextLabel?.text = person.lastName
lastNameCell.isHidden = isFullnamePrivate
}
func refreshDisplayNameCell() {
displayNameCell.detailTextLabel?.text = person.displayName
}
func refreshRoleCell() {
let enabled = isPromoteEnabled
roleCell.accessoryType = enabled ? .disclosureIndicator : .none
roleCell.selectionStyle = enabled ? .gray : .none
roleCell.isUserInteractionEnabled = enabled
roleCell.detailTextLabel?.text = role?.name
}
func refreshRemoveCell() {
removeCell.isHidden = !isRemoveEnabled
}
}
// MARK: - Private Computed Properties
//
private extension PersonViewController {
var isMyself: Bool {
return blog.account!.userID.intValue == person.ID || blog.account!.userID.intValue == person.linkedUserID
}
var isFullnamePrivate: Bool {
// Followers + Viewers shouldn't display First / Last name
return isUser == false
}
var isPromoteEnabled: Bool {
// Note: *Only* users can be promoted.
//
return blog.isUserCapableOf(.PromoteUsers) && isMyself == false && isUser == true
}
var isRemoveEnabled: Bool {
switch screenMode {
case .User:
// YES, ListUsers. Brought from Calypso's code
return blog.isUserCapableOf(.ListUsers) && isMyself == false && isUser == true
case .Follower:
return isFollower == true
case .Viewer:
return isViewer == true
}
}
var isUser: Bool {
return user != nil
}
var user: User? {
return person as? User
}
var isFollower: Bool {
return follower != nil
}
var follower: Follower? {
return person as? Follower
}
var isViewer: Bool {
return viewer != nil
}
var viewer: Viewer? {
return person as? Viewer
}
var role: RemoteRole? {
switch screenMode {
case .Follower:
return .follower
case .Viewer:
return .viewer
case .User:
guard let service = RoleService(blog: blog, context: context) else {
return nil
}
return service.getRole(slug: person.role)?.toUnmanaged()
}
}
}
| gpl-2.0 | 31002ecdc7e2436c36c4acb069d0c755 | 30.998261 | 168 | 0.612262 | 5.22402 | false | false | false | false |
hrscy/TodayNews | News/News/Classes/Mine/View/RelationRecommendView.swift | 1 | 1708 | //
// RelationRecommendView.swift
// News
//
// Created by 杨蒙 on 2017/12/5.
// Copyright © 2017年 hrscy. All rights reserved.
//
import UIKit
class RelationRecommendView: UIView, NibLoadable {
var userCards = [UserCard]()
@IBOutlet weak var labelHeight: NSLayoutConstraint!
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
theme_backgroundColor = "colors.cellBackgroundColor"
collectionView.collectionViewLayout = RelationRecommendFlowLayout()
collectionView.ym_registerCell(cell: RelationRecommendCell.self)
collectionView.delegate = self
collectionView.dataSource = self
}
}
extension RelationRecommendView: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return userCards.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.ym_dequeueReusableCell(indexPath: indexPath) as RelationRecommendCell
cell.userCard = userCards[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
class RelationRecommendFlowLayout: UICollectionViewFlowLayout {
override func prepare() {
super.prepare()
scrollDirection = .horizontal
itemSize = CGSize(width: 142, height: 190)
minimumLineSpacing = 10
sectionInset = UIEdgeInsetsMake(0, 10, 0, 10)
}
}
| mit | 0ed712763949a753f4e7cf8c6ece19ba | 29.375 | 121 | 0.703116 | 5.451923 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Network/Sources/NetworkKit/General/NetworkCommunicator.swift | 1 | 8690 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import Combine
import DIKit
import Errors
import Foundation
import ToolKit
public protocol NetworkCommunicatorAPI {
/// Performs network requests
/// - Parameter request: the request object describes the network request to be performed
func dataTaskPublisher(
for request: NetworkRequest
) -> AnyPublisher<ServerResponse, NetworkError>
func dataTaskWebSocketPublisher(
for request: NetworkRequest
) -> AnyPublisher<ServerResponse, NetworkError>
}
public protocol NetworkDebugLogger {
func storeRequest(
_ request: URLRequest,
response: URLResponse?,
error: Error?,
data: Data?,
metrics: URLSessionTaskMetrics?,
session: URLSession?
)
}
final class NetworkCommunicator: NetworkCommunicatorAPI {
// MARK: - Private properties
private let session: NetworkSession
private let authenticator: AuthenticatorAPI?
private let eventRecorder: AnalyticsEventRecorderAPI?
private let networkDebugLogger: NetworkDebugLogger
// MARK: - Setup
init(
session: NetworkSession = resolve(),
sessionDelegate: SessionDelegateAPI = resolve(),
sessionHandler: NetworkSessionDelegateAPI = resolve(),
authenticator: AuthenticatorAPI? = nil,
eventRecorder: AnalyticsEventRecorderAPI? = nil,
networkDebugLogger: NetworkDebugLogger = resolve()
) {
self.session = session
self.authenticator = authenticator
self.eventRecorder = eventRecorder
self.networkDebugLogger = networkDebugLogger
sessionDelegate.delegate = sessionHandler
}
// MARK: - Internal methods
func dataTaskPublisher(
for request: NetworkRequest
) -> AnyPublisher<ServerResponse, NetworkError> {
guard request.authenticated else {
return execute(request: request)
}
guard let authenticator = authenticator else {
fatalError("Authenticator missing")
}
let _execute = execute
return authenticator
.authenticate { [execute = _execute] token in
execute(request.adding(authenticationToken: token))
}
}
func dataTaskWebSocketPublisher(
for request: NetworkRequest
) -> AnyPublisher<ServerResponse, NetworkError> {
guard request.authenticated else {
return openWebSocket(request: request)
}
guard let authenticator = authenticator else {
fatalError("Authenticator missing")
}
let _executeWebsocketRequest = executeWebsocketRequest
return authenticator
.authenticate { [executeWebsocketRequest = _executeWebsocketRequest] token in
executeWebsocketRequest(request.adding(authenticationToken: token))
}
}
private func openWebSocket(
request: NetworkRequest
) -> AnyPublisher<ServerResponse, NetworkError> {
session.erasedWebSocketTaskPublisher(
for: request.peek("🌎", \.urlRequest.cURLCommand, if: \.isDebugging.request).urlRequest
)
.mapError { error in
NetworkError(request: request.urlRequest, type: .urlError(error))
}
.flatMap { elements in
request.responseHandler.handle(message: elements, for: request)
}
.eraseToAnyPublisher()
}
// MARK: - Private methods
private func execute(
request: NetworkRequest
) -> AnyPublisher<ServerResponse, NetworkError> {
session.erasedDataTaskPublisher(
for: request.peek("🌎", \.urlRequest.cURLCommand, if: \.isDebugging.request).urlRequest
)
.handleEvents(
receiveOutput: { [networkDebugLogger, session] data, response in
networkDebugLogger.storeRequest(
request.urlRequest,
response: response,
error: nil,
data: data,
metrics: nil,
session: session as? URLSession
)
},
receiveCompletion: { [networkDebugLogger, session] completion in
guard case .failure(let error) = completion else {
return
}
networkDebugLogger.storeRequest(
request.urlRequest,
response: nil,
error: error,
data: nil,
metrics: nil,
session: session as? URLSession
)
}
)
.mapError { error in
NetworkError(request: request.urlRequest, type: .urlError(error))
}
.flatMap { elements -> AnyPublisher<ServerResponse, NetworkError> in
request.responseHandler.handle(elements: elements, for: request)
}
.eraseToAnyPublisher()
.recordErrors(on: eventRecorder, request: request) { request, error -> AnalyticsEvent? in
error.analyticsEvent(for: request) { serverErrorResponse in
request.decoder.decodeFailureToString(errorResponse: serverErrorResponse)
}
}
.eraseToAnyPublisher()
}
private func executeWebsocketRequest(
request: NetworkRequest
) -> AnyPublisher<ServerResponse, NetworkError> {
session.erasedWebSocketTaskPublisher(
for: request.peek("🌎", \.urlRequest.cURLCommand, if: \.isDebugging.request).urlRequest
)
.handleEvents(
receiveOutput: { [networkDebugLogger, session] _ in
networkDebugLogger.storeRequest(
request.urlRequest,
response: nil,
error: nil,
data: nil,
metrics: nil,
session: session as? URLSession
)
},
receiveCompletion: { [networkDebugLogger, session] completion in
guard case .failure(let error) = completion else {
return
}
networkDebugLogger.storeRequest(
request.urlRequest,
response: nil,
error: error,
data: nil,
metrics: nil,
session: session as? URLSession
)
}
)
.mapError { error in
NetworkError(request: request.urlRequest, type: .urlError(error))
}
.flatMap { messages -> AnyPublisher<ServerResponse, NetworkError> in
request.responseHandler.handle(message: messages, for: request)
}
.eraseToAnyPublisher()
.recordErrors(on: eventRecorder, request: request) { request, error -> AnalyticsEvent? in
error.analyticsEvent(for: request) { serverErrorResponse in
request.decoder.decodeFailureToString(errorResponse: serverErrorResponse)
}
}
.eraseToAnyPublisher()
}
}
protocol NetworkSession {
func erasedDataTaskPublisher(
for request: URLRequest
) -> AnyPublisher<(data: Data, response: URLResponse), URLError>
func erasedWebSocketTaskPublisher(
for request: URLRequest)
-> AnyPublisher<URLSessionWebSocketTask.Message, URLError>
}
extension URLSession: NetworkSession {
func erasedDataTaskPublisher(
for request: URLRequest
) -> AnyPublisher<(data: Data, response: URLResponse), URLError> {
dataTaskPublisher(for: request)
.eraseToAnyPublisher()
}
func erasedWebSocketTaskPublisher(
for request: URLRequest
) -> AnyPublisher<URLSessionWebSocketTask.Message, URLError> {
WebSocketTaskPublisher(with: request)
.eraseToAnyPublisher()
}
}
extension AnyPublisher where Output == ServerResponse,
Failure == NetworkError
{
fileprivate func recordErrors(
on recorder: AnalyticsEventRecorderAPI?,
request: NetworkRequest,
errorMapper: @escaping (NetworkRequest, NetworkError) -> AnalyticsEvent?
) -> AnyPublisher<ServerResponse, NetworkError> {
handleEvents(
receiveCompletion: { completion in
guard case .failure(let communicatorError) = completion else {
return
}
guard let event = errorMapper(request, communicatorError) else {
return
}
recorder?.record(event: event)
}
)
.eraseToAnyPublisher()
}
}
| lgpl-3.0 | 47cc47e33b6d8a0daf576f5270800b9b | 33.3083 | 98 | 0.603802 | 5.725594 | false | false | false | false |
huonw/swift | stdlib/public/core/Collection.swift | 1 | 71958 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that provides subscript access to its elements, with forward
/// index traversal.
///
/// In most cases, it's best to ignore this protocol and use the `Collection`
/// protocol instead, because it has a more complete interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'Collection' instead")
public typealias IndexableBase = Collection
/// A type that provides subscript access to its elements, with forward index
/// traversal.
///
/// In most cases, it's best to ignore this protocol and use the `Collection`
/// protocol instead, because it has a more complete interface.
@available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'Collection' instead")
public typealias Indexable = Collection
/// A type that iterates over a collection using its indices.
///
/// The `IndexingIterator` type is the default iterator for any collection that
/// doesn't declare its own. It acts as an iterator by using a collection's
/// indices to step over each value in the collection. Most collections in the
/// standard library use `IndexingIterator` as their iterator.
///
/// By default, any custom collection type you create will inherit a
/// `makeIterator()` method that returns an `IndexingIterator` instance,
/// making it unnecessary to declare your own. When creating a custom
/// collection type, add the minimal requirements of the `Collection`
/// protocol: starting and ending indices and a subscript for accessing
/// elements. With those elements defined, the inherited `makeIterator()`
/// method satisfies the requirements of the `Sequence` protocol.
///
/// Here's an example of a type that declares the minimal requirements for a
/// collection. The `CollectionOfTwo` structure is a fixed-size collection
/// that always holds two elements of a specific type.
///
/// struct CollectionOfTwo<Element>: Collection {
/// let elements: (Element, Element)
///
/// init(_ first: Element, _ second: Element) {
/// self.elements = (first, second)
/// }
///
/// var startIndex: Int { return 0 }
/// var endIndex: Int { return 2 }
///
/// subscript(index: Int) -> Element {
/// switch index {
/// case 0: return elements.0
/// case 1: return elements.1
/// default: fatalError("Index out of bounds.")
/// }
/// }
///
/// func index(after i: Int) -> Int {
/// precondition(i < endIndex, "Can't advance beyond endIndex")
/// return i + 1
/// }
/// }
///
/// Because `CollectionOfTwo` doesn't define its own `makeIterator()`
/// method or `Iterator` associated type, it uses the default iterator type,
/// `IndexingIterator`. This example shows how a `CollectionOfTwo` instance
/// can be created holding the values of a point, and then iterated over
/// using a `for`-`in` loop.
///
/// let point = CollectionOfTwo(15.0, 20.0)
/// for element in point {
/// print(element)
/// }
/// // Prints "15.0"
/// // Prints "20.0"
@_fixed_layout
public struct IndexingIterator<Elements : Collection> {
@usableFromInline
internal let _elements: Elements
@usableFromInline
internal var _position: Elements.Index
@inlinable
@inline(__always)
/// Creates an iterator over the given collection.
public /// @testable
init(_elements: Elements) {
self._elements = _elements
self._position = _elements.startIndex
}
@inlinable
@inline(__always)
/// Creates an iterator over the given collection.
public /// @testable
init(_elements: Elements, _position: Elements.Index) {
self._elements = _elements
self._position = _position
}
}
extension IndexingIterator: IteratorProtocol, Sequence {
public typealias Element = Elements.Element
public typealias Iterator = IndexingIterator<Elements>
public typealias SubSequence = AnySequence<Element>
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Repeatedly calling this method returns all the elements of the underlying
/// sequence in order. As soon as the sequence has run out of elements, all
/// subsequent calls return `nil`.
///
/// This example shows how an iterator can be used explicitly to emulate a
/// `for`-`in` loop. First, retrieve a sequence's iterator, and then call
/// the iterator's `next()` method until it returns `nil`.
///
/// let numbers = [2, 3, 5, 7]
/// var numbersIterator = numbers.makeIterator()
///
/// while let num = numbersIterator.next() {
/// print(num)
/// }
/// // Prints "2"
/// // Prints "3"
/// // Prints "5"
/// // Prints "7"
///
/// - Returns: The next element in the underlying sequence if a next element
/// exists; otherwise, `nil`.
@inlinable
@inline(__always)
public mutating func next() -> Elements.Element? {
if _position == _elements.endIndex { return nil }
let element = _elements[_position]
_elements.formIndex(after: &_position)
return element
}
}
/// A sequence whose elements can be traversed multiple times,
/// nondestructively, and accessed by an indexed subscript.
///
/// Collections are used extensively throughout the standard library. When you
/// use arrays, dictionaries, and other collections, you benefit from the
/// operations that the `Collection` protocol declares and implements. In
/// addition to the operations that collections inherit from the `Sequence`
/// protocol, you gain access to methods that depend on accessing an element
/// at a specific position in a collection.
///
/// For example, if you want to print only the first word in a string, you can
/// search for the index of the first space, and then create a substring up to
/// that position.
///
/// let text = "Buffalo buffalo buffalo buffalo."
/// if let firstSpace = text.firstIndex(of: " ") {
/// print(text[..<firstSpace])
/// }
/// // Prints "Buffalo"
///
/// The `firstSpace` constant is an index into the `text` string---the position
/// of the first space in the string. You can store indices in variables, and
/// pass them to collection algorithms or use them later to access the
/// corresponding element. In the example above, `firstSpace` is used to
/// extract the prefix that contains elements up to that index.
///
/// Accessing Individual Elements
/// =============================
///
/// You can access an element of a collection through its subscript by using
/// any valid index except the collection's `endIndex` property. This property
/// is a "past the end" index that does not correspond with any element of the
/// collection.
///
/// Here's an example of accessing the first character in a string through its
/// subscript:
///
/// let firstChar = text[text.startIndex]
/// print(firstChar)
/// // Prints "B"
///
/// The `Collection` protocol declares and provides default implementations for
/// many operations that depend on elements being accessible by their
/// subscript. For example, you can also access the first character of `text`
/// using the `first` property, which has the value of the first element of
/// the collection, or `nil` if the collection is empty.
///
/// print(text.first)
/// // Prints "Optional("B")"
///
/// You can pass only valid indices to collection operations. You can find a
/// complete set of a collection's valid indices by starting with the
/// collection's `startIndex` property and finding every successor up to, and
/// including, the `endIndex` property. All other values of the `Index` type,
/// such as the `startIndex` property of a different collection, are invalid
/// indices for this collection.
///
/// Saved indices may become invalid as a result of mutating operations. For
/// more information about index invalidation in mutable collections, see the
/// reference for the `MutableCollection` and `RangeReplaceableCollection`
/// protocols, as well as for the specific type you're using.
///
/// Accessing Slices of a Collection
/// ================================
///
/// You can access a slice of a collection through its ranged subscript or by
/// calling methods like `prefix(while:)` or `suffix(_:)`. A slice of a
/// collection can contain zero or more of the original collection's elements
/// and shares the original collection's semantics.
///
/// The following example creates a `firstWord` constant by using the
/// `prefix(while:)` method to get a slice of the `text` string.
///
/// let firstWord = text.prefix(while: { $0 != " " })
/// print(firstWord)
/// // Prints "Buffalo"
///
/// You can retrieve the same slice using the string's ranged subscript, which
/// takes a range expression.
///
/// if let firstSpace = text.firstIndex(of: " ") {
/// print(text[..<firstSpace]
/// // Prints "Buffalo"
/// }
///
/// The retrieved slice of `text` is equivalent in each of these cases.
///
/// Slices Share Indices
/// --------------------
///
/// A collection and its slices share the same indices. An element of a
/// collection is located under the same index in a slice as in the base
/// collection, as long as neither the collection nor the slice has been
/// mutated since the slice was created.
///
/// For example, suppose you have an array holding the number of absences from
/// each class during a session.
///
/// var absences = [0, 2, 0, 4, 0, 3, 1, 0]
///
/// You're tasked with finding the day with the most absences in the second
/// half of the session. To find the index of the day in question, follow
/// these steps:
///
/// 1) Create a slice of the `absences` array that holds the second half of the
/// days.
/// 2) Use the `max(by:)` method to determine the index of the day with the
/// most absences.
/// 3) Print the result using the index found in step 2 on the original
/// `absences` array.
///
/// Here's an implementation of those steps:
///
/// let secondHalf = absences.suffix(absences.count / 2)
/// if let i = secondHalf.indices.max(by: { secondHalf[$0] < secondHalf[$1] }) {
/// print("Highest second-half absences: \(absences[i])")
/// }
/// // Prints "Highest second-half absences: 3"
///
/// Slices Inherit Collection Semantics
/// -----------------------------------
///
/// A slice inherits the value or reference semantics of its base collection.
/// That is, when working with a slice of a mutable collection that has value
/// semantics, such as an array, mutating the original collection triggers a
/// copy of that collection and does not affect the contents of the slice.
///
/// For example, if you update the last element of the `absences` array from
/// `0` to `2`, the `secondHalf` slice is unchanged.
///
/// absences[7] = 2
/// print(absences)
/// // Prints "[0, 2, 0, 4, 0, 3, 1, 2]"
/// print(secondHalf)
/// // Prints "[0, 3, 1, 0]"
///
/// Traversing a Collection
/// =======================
///
/// Although a sequence can be consumed as it is traversed, a collection is
/// guaranteed to be *multipass*: Any element can be repeatedly accessed by
/// saving its index. Moreover, a collection's indices form a finite range of
/// the positions of the collection's elements. The fact that all collections
/// are finite guarantees the safety of many sequence operations, such as
/// using the `contains(_:)` method to test whether a collection includes an
/// element.
///
/// Iterating over the elements of a collection by their positions yields the
/// same elements in the same order as iterating over that collection using
/// its iterator. This example demonstrates that the `characters` view of a
/// string returns the same characters in the same order whether the view's
/// indices or the view itself is being iterated.
///
/// let word = "Swift"
/// for character in word {
/// print(character)
/// }
/// // Prints "S"
/// // Prints "w"
/// // Prints "i"
/// // Prints "f"
/// // Prints "t"
///
/// for i in word.indices {
/// print(word[i])
/// }
/// // Prints "S"
/// // Prints "w"
/// // Prints "i"
/// // Prints "f"
/// // Prints "t"
///
/// Conforming to the Collection Protocol
/// =====================================
///
/// If you create a custom sequence that can provide repeated access to its
/// elements, make sure that its type conforms to the `Collection` protocol in
/// order to give a more useful and more efficient interface for sequence and
/// collection operations. To add `Collection` conformance to your type, you
/// must declare at least the following requirements:
///
/// - The `startIndex` and `endIndex` properties
/// - A subscript that provides at least read-only access to your type's
/// elements
/// - The `index(after:)` method for advancing an index into your collection
///
/// Expected Performance
/// ====================
///
/// Types that conform to `Collection` are expected to provide the `startIndex`
/// and `endIndex` properties and subscript access to elements as O(1)
/// operations. Types that are not able to guarantee this performance must
/// document the departure, because many collection operations depend on O(1)
/// subscripting performance for their own performance guarantees.
///
/// The performance of some collection operations depends on the type of index
/// that the collection provides. For example, a random-access collection,
/// which can measure the distance between two indices in O(1) time, can
/// calculate its `count` property in O(1) time. Conversely, because a forward
/// or bidirectional collection must traverse the entire collection to count
/// the number of contained elements, accessing its `count` property is an
/// O(*n*) operation.
public protocol Collection: Sequence where SubSequence: Collection {
// FIXME(ABI): Associated type inference requires this.
associatedtype Element
/// A type that represents a position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript
/// argument.
associatedtype Index : Comparable
/// The position of the first element in a nonempty collection.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
var startIndex: Index { get }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// When you need a range that includes the last element of a collection, use
/// the half-open range operator (`..<`) with `endIndex`. The `..<` operator
/// creates a range that doesn't include the upper bound, so it's always
/// safe to use with `endIndex`. For example:
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let index = numbers.firstIndex(of: 30) {
/// print(numbers[index ..< numbers.endIndex])
/// }
/// // Prints "[30, 40, 50]"
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
var endIndex: Index { get }
/// A type that provides the collection's iteration interface and
/// encapsulates its iteration state.
///
/// By default, a collection conforms to the `Sequence` protocol by
/// supplying `IndexingIterator` as its associated `Iterator`
/// type.
associatedtype Iterator = IndexingIterator<Self>
// FIXME(ABI)#179 (Type checker): Needed here so that the `Iterator` is properly deduced from
// a custom `makeIterator()` function. Otherwise we get an
// `IndexingIterator`. <rdar://problem/21539115>
/// Returns an iterator over the elements of the collection.
func makeIterator() -> Iterator
/// A sequence that represents a contiguous subrange of the collection's
/// elements.
///
/// This associated type appears as a requirement in the `Sequence`
/// protocol, but it is restated here with stricter constraints. In a
/// collection, the subsequence should also conform to `Collection`.
associatedtype SubSequence = Slice<Self> where SubSequence.Index == Index
/// Accesses the element at the specified position.
///
/// The following example accesses an element of an array through its
/// subscript to print its value:
///
/// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// print(streets[1])
/// // Prints "Bryant"
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
///
/// - Complexity: O(1)
subscript(position: Index) -> Element { get }
/// Accesses a contiguous subrange of the collection's elements.
///
/// For example, using a `PartialRangeFrom` range expression with an array
/// accesses the subrange from the start of the range expression until the
/// end of the array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2..<5]
/// print(streetsSlice)
/// // ["Channing", "Douglas", "Evarts"]
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection. This example searches `streetsSlice` for one of the
/// strings in the slice, and then uses that index in the original array.
///
/// let index = streetsSlice.firstIndex(of: "Evarts")! // 4
/// print(streets[index])
/// // "Evarts"
///
/// Always use the slice's `startIndex` property instead of assuming that its
/// indices start at a particular value. Attempting to access an element by
/// using an index outside the bounds of the slice may result in a runtime
/// error, even if that index is valid for the original collection.
///
/// print(streetsSlice.startIndex)
/// // 2
/// print(streetsSlice[2])
/// // "Channing"
///
/// print(streetsSlice[0])
/// // error: Index out of bounds
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
///
/// - Complexity: O(1)
subscript(bounds: Range<Index>) -> SubSequence { get }
/// A type that represents the indices that are valid for subscripting the
/// collection, in ascending order.
associatedtype Indices : Collection = DefaultIndices<Self>
where Indices.Element == Index,
Indices.Index == Index,
Indices.SubSequence == Indices
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be nonuniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can result in an unexpected copy of the collection. To avoid
/// the unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
var indices: Indices { get }
/// Returns a subsequence from the start of the collection up to, but not
/// including, the specified position.
///
/// The resulting subsequence *does not include* the element at the position
/// `end`. The following example searches for the index of the number `40`
/// in an array of integers, and then prints the prefix of the array up to,
/// but not including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers.prefix(upTo: i))
/// }
/// // Prints "[10, 20, 30]"
///
/// Passing the collection's starting index as the `end` parameter results in
/// an empty subsequence.
///
/// print(numbers.prefix(upTo: numbers.startIndex))
/// // Prints "[]"
///
/// Using the `prefix(upTo:)` method is equivalent to using a partial
/// half-open range as the collection's subscript. The subscript notation is
/// preferred over `prefix(upTo:)`.
///
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers[..<i])
/// }
/// // Prints "[10, 20, 30]"
///
/// - Parameter end: The "past the end" index of the resulting subsequence.
/// `end` must be a valid index of the collection.
/// - Returns: A subsequence up to, but not including, the `end` position.
///
/// - Complexity: O(1)
func prefix(upTo end: Index) -> SubSequence
/// Returns a subsequence from the specified position to the end of the
/// collection.
///
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the suffix of the array starting at
/// that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers.suffix(from: i))
/// }
/// // Prints "[40, 50, 60]"
///
/// Passing the collection's `endIndex` as the `start` parameter results in
/// an empty subsequence.
///
/// print(numbers.suffix(from: numbers.endIndex))
/// // Prints "[]"
///
/// Using the `suffix(from:)` method is equivalent to using a partial range
/// from the index as the collection's subscript. The subscript notation is
/// preferred over `suffix(from:)`.
///
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers[i...])
/// }
/// // Prints "[40, 50, 60]"
///
/// - Parameter start: The index at which to start the resulting subsequence.
/// `start` must be a valid index of the collection.
/// - Returns: A subsequence starting at the `start` position.
///
/// - Complexity: O(1)
func suffix(from start: Index) -> SubSequence
/// Returns a subsequence from the start of the collection through the
/// specified position.
///
/// The resulting subsequence *includes* the element at the position `end`.
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the prefix of the array up to, and
/// including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers.prefix(through: i))
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// Using the `prefix(through:)` method is equivalent to using a partial
/// closed range as the collection's subscript. The subscript notation is
/// preferred over `prefix(through:)`.
///
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers[...i])
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter end: The index of the last element to include in the
/// resulting subsequence. `end` must be a valid index of the collection
/// that is not equal to the `endIndex` property.
/// - Returns: A subsequence up to, and including, the `end` position.
///
/// - Complexity: O(1)
func prefix(through position: Index) -> SubSequence
/// A Boolean value indicating whether the collection is empty.
///
/// When you need to check whether your collection is empty, use the
/// `isEmpty` property instead of checking that the `count` property is
/// equal to zero. For collections that don't conform to
/// `RandomAccessCollection`, accessing the `count` property iterates
/// through the elements of the collection.
///
/// let horseName = "Silver"
/// if horseName.isEmpty {
/// print("I've been through the desert on a horse with no name.")
/// } else {
/// print("Hi ho, \(horseName)!")
/// }
/// // Prints "Hi ho, Silver!"
///
/// - Complexity: O(1)
var isEmpty: Bool { get }
/// The number of elements in the collection.
///
/// To check whether a collection is empty, use its `isEmpty` property
/// instead of comparing `count` to zero. Unless the collection guarantees
/// random-access performance, calculating `count` can be an O(*n*)
/// operation.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
var count: Int { get }
// The following requirements enable dispatching for firstIndex(of:) and
// lastIndex(of:) when the element type is Equatable.
/// Returns `Optional(Optional(index))` if an element was found
/// or `Optional(nil)` if an element was determined to be missing;
/// otherwise, `nil`.
///
/// - Complexity: O(*n*)
func _customIndexOfEquatableElement(_ element: Element) -> Index??
/// Customization point for `Collection.lastIndex(of:)`.
///
/// Define this method if the collection can find an element in less than
/// O(*n*) by exploiting collection-specific knowledge.
///
/// - Returns: `nil` if a linear search should be attempted instead,
/// `Optional(nil)` if the element was not found, or
/// `Optional(Optional(index))` if an element was found.
///
/// - Complexity: Hopefully less than O(`count`).
func _customLastIndexOfEquatableElement(_ element: Element) -> Index??
/// The first element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let firstNumber = numbers.first {
/// print(firstNumber)
/// }
/// // Prints "10"
var first: Element? { get }
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(_ i: Index, offsetBy n: Int) -> Index
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index?
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
func distance(from start: Index, to end: Index) -> Int
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(bounds.contains(index))
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>)
func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>)
/// Performs a range check in O(1), or a no-op when a range check is not
/// implementable in O(1).
///
/// The range check, if performed, is equivalent to:
///
/// precondition(
/// bounds.contains(range.lowerBound) ||
/// range.lowerBound == bounds.upperBound)
/// precondition(
/// bounds.contains(range.upperBound) ||
/// range.upperBound == bounds.upperBound)
///
/// Use this function to perform a cheap range check for QoI purposes when
/// memory safety is not a concern. Do not rely on this range check for
/// memory safety.
///
/// The default implementation for forward and bidirectional indices is a
/// no-op. The default implementation for random access indices performs a
/// range check.
///
/// - Complexity: O(1).
func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>)
/// Returns the position immediately after the given index.
///
/// The successor of an index must be well defined. For an index `i` into a
/// collection `c`, calling `c.index(after: i)` returns the same index every
/// time.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
func index(after i: Index) -> Index
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
func formIndex(after i: inout Index)
/// Returns a random element of the collection, using the given generator as
/// a source for randomness.
///
/// You use this method to select a random element from a collection when you
/// are using a custom random number generator. For example, call
/// `randomElement(using:)` to select a random element from an array of names.
///
/// let names = ["Zoey", "Chloe", "Amani", "Amaia"]
/// let randomName = names.randomElement(using: &myGenerator)!
/// // randomName == "Amani"
///
/// - Parameter generator: The random number generator to use when choosing
/// a random element.
/// - Returns: A random element from the collection. If the collection is
/// empty, the method returns `nil`.
func randomElement<T: RandomNumberGenerator>(
using generator: inout T
) -> Element?
@available(*, deprecated, message: "all index distances are now of type Int")
typealias IndexDistance = Int
}
/// Default implementation for forward collections.
extension Collection {
/// Replaces the given index with its successor.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func formIndex(after i: inout Index) {
i = index(after: i)
}
@inlinable
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= index,
"Out of bounds: index < startIndex")
_precondition(
index < bounds.upperBound,
"Out of bounds: index >= endIndex")
}
@inlinable
public func _failEarlyRangeCheck(_ index: Index, bounds: ClosedRange<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= index,
"Out of bounds: index < startIndex")
_precondition(
index <= bounds.upperBound,
"Out of bounds: index > endIndex")
}
@inlinable
public func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) {
// FIXME: swift-3-indexing-model: tests.
_precondition(
bounds.lowerBound <= range.lowerBound,
"Out of bounds: range begins before startIndex")
_precondition(
range.lowerBound <= bounds.upperBound,
"Out of bounds: range ends after endIndex")
_precondition(
bounds.lowerBound <= range.upperBound,
"Out of bounds: range ends before bounds.lowerBound")
_precondition(
range.upperBound <= bounds.upperBound,
"Out of bounds: range begins after bounds.upperBound")
}
/// Returns an index that is the specified distance from the given index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
///
/// let s = "Swift"
/// let i = s.index(s.startIndex, offsetBy: 4)
/// print(s[i])
/// // Prints "t"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - Returns: An index offset by `n` from the index `i`. If `n` is positive,
/// this is the same value as the result of `n` calls to `index(after:)`.
/// If `n` is negative, this is the same value as the result of `-n` calls
/// to `index(before:)`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
return self._advanceForward(i, by: n)
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// The following example obtains an index advanced four positions from a
/// string's starting index and then prints the character at that position.
/// The operation doesn't require going beyond the limiting `s.endIndex`
/// value, so it succeeds.
///
/// let s = "Swift"
/// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
/// print(s[i])
/// }
/// // Prints "t"
///
/// The next example attempts to retrieve an index six positions from
/// `s.startIndex` but fails, because that distance is beyond the index
/// passed as `limit`.
///
/// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
/// print(j)
/// // Prints "nil"
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: An index offset by `n` from the index `i`, unless that index
/// would be beyond `limit` in the direction of movement. In that case,
/// the method returns `nil`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
return self._advanceForward(i, by: n, limitedBy: limit)
}
/// Offsets the given index by the specified distance.
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@inlinable
public func formIndex(_ i: inout Index, offsetBy n: Int) {
i = index(i, offsetBy: n)
}
/// Offsets the given index by the specified distance, or so that it equals
/// the given limiting index.
///
/// The value passed as `n` must not offset `i` beyond the bounds of the
/// collection, unless the index passed as `limit` prevents offsetting
/// beyond those bounds.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - n: The distance to offset `i`. `n` must not be negative unless the
/// collection conforms to the `BidirectionalCollection` protocol.
/// - limit: A valid index of the collection to use as a limit. If `n > 0`,
/// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a
/// limit that is greater than `i` has no effect.
/// - Returns: `true` if `i` has been offset by exactly `n` steps without
/// going beyond `limit`; otherwise, `false`. When the return value is
/// `false`, the value of `i` is equal to `limit`.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the absolute
/// value of `n`.
@inlinable
public func formIndex(
_ i: inout Index, offsetBy n: Int, limitedBy limit: Index
) -> Bool {
if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) {
i = advancedIndex
return true
}
i = limit
return false
}
/// Returns the distance between two indices.
///
/// Unless the collection conforms to the `BidirectionalCollection` protocol,
/// `start` must be less than or equal to `end`.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection. If `end` is equal to
/// `start`, the result is zero.
/// - Returns: The distance between `start` and `end`. The result can be
/// negative only if the collection conforms to the
/// `BidirectionalCollection` protocol.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the
/// resulting distance.
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
_precondition(start <= end,
"Only BidirectionalCollections can have end come before start")
var start = start
var count = 0
while start != end {
count = count + 1
formIndex(after: &start)
}
return count
}
/// Returns a random element of the collection, using the given generator as
/// a source for randomness.
///
/// Call `randomElement(using:)` to select a random element from an array or
/// another collection when you are using a custom random number generator.
/// This example picks a name at random from an array:
///
/// let names = ["Zoey", "Chloe", "Amani", "Amaia"]
/// let randomName = names.randomElement(using: &myGenerator)!
/// // randomName == "Amani"
///
/// - Parameter generator: The random number generator to use when choosing
/// a random element.
/// - Returns: A random element from the collection. If the collection is
/// empty, the method returns `nil`.
@inlinable
public func randomElement<T: RandomNumberGenerator>(
using generator: inout T
) -> Element? {
guard !isEmpty else { return nil }
let random = generator.next(upperBound: UInt(count))
let index = self.index(
startIndex,
offsetBy: numericCast(random)
)
return self[index]
}
/// Returns a random element of the collection.
///
/// Call `randomElement()` to select a random element from an array or
/// another collection. This example picks a name at random from an array:
///
/// let names = ["Zoey", "Chloe", "Amani", "Amaia"]
/// let randomName = names.randomElement()!
/// // randomName == "Amani"
///
/// This method uses the default random generator, `Random.default`. The call
/// to `names.randomElement()` above is equivalent to calling
/// `names.randomElement(using: &Random.default)`.
///
/// - Returns: A random element from the collection. If the collection is
/// empty, the method returns `nil`.
@inlinable
public func randomElement() -> Element? {
return randomElement(using: &Random.default)
}
/// Do not use this method directly; call advanced(by: n) instead.
@inlinable
@inline(__always)
internal func _advanceForward(_ i: Index, by n: Int) -> Index {
_precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
var i = i
for _ in stride(from: 0, to: n, by: 1) {
formIndex(after: &i)
}
return i
}
/// Do not use this method directly; call advanced(by: n, limit) instead.
@inlinable
@inline(__always)
internal func _advanceForward(
_ i: Index, by n: Int, limitedBy limit: Index
) -> Index? {
_precondition(n >= 0,
"Only BidirectionalCollections can be advanced by a negative amount")
var i = i
for _ in stride(from: 0, to: n, by: 1) {
if i == limit {
return nil
}
formIndex(after: &i)
}
return i
}
}
/// Supply the default `makeIterator()` method for `Collection` models
/// that accept the default associated `Iterator`,
/// `IndexingIterator<Self>`.
extension Collection where Iterator == IndexingIterator<Self> {
/// Returns an iterator over the elements of the collection.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func makeIterator() -> IndexingIterator<Self> {
return IndexingIterator(_elements: self)
}
}
/// Supply the default "slicing" `subscript` for `Collection` models
/// that accept the default associated `SubSequence`, `Slice<Self>`.
extension Collection where SubSequence == Slice<Self> {
/// Accesses a contiguous subrange of the collection's elements.
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection. Always use the slice's `startIndex` property
/// instead of assuming that its indices start at a particular value.
///
/// This example demonstrates getting a slice of an array of strings, finding
/// the index of one of the strings in the slice, and then using that index
/// in the original array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2 ..< streets.endIndex]
/// print(streetsSlice)
/// // Prints "["Channing", "Douglas", "Evarts"]"
///
/// let index = streetsSlice.firstIndex(of: "Evarts") // 4
/// print(streets[index!])
/// // Prints "Evarts"
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
///
/// - Complexity: O(1)
@inlinable
public subscript(bounds: Range<Index>) -> Slice<Self> {
_failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex)
return Slice(base: self, bounds: bounds)
}
}
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// - Returns: The first element of the collection if the collection is
/// not empty; otherwise, `nil`.
///
/// - Complexity: O(1)
@inlinable
public mutating func popFirst() -> Element? {
// TODO: swift-3-indexing-model - review the following
guard !isEmpty else { return nil }
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
}
/// Default implementations of core requirements
extension Collection {
/// A Boolean value indicating whether the collection is empty.
///
/// When you need to check whether your collection is empty, use the
/// `isEmpty` property instead of checking that the `count` property is
/// equal to zero. For collections that don't conform to
/// `RandomAccessCollection`, accessing the `count` property iterates
/// through the elements of the collection.
///
/// let horseName = "Silver"
/// if horseName.isEmpty {
/// print("I've been through the desert on a horse with no name.")
/// } else {
/// print("Hi ho, \(horseName)!")
/// }
/// // Prints "Hi ho, Silver!")
///
/// - Complexity: O(1)
@inlinable
public var isEmpty: Bool {
return startIndex == endIndex
}
/// The first element of the collection.
///
/// If the collection is empty, the value of this property is `nil`.
///
/// let numbers = [10, 20, 30, 40, 50]
/// if let firstNumber = numbers.first {
/// print(firstNumber)
/// }
/// // Prints "10"
@inlinable
public var first: Element? {
@inline(__always)
get {
// NB: Accessing `startIndex` may not be O(1) for some lazy collections,
// so instead of testing `isEmpty` and then returning the first element,
// we'll just rely on the fact that the iterator always yields the
// first element first.
var i = makeIterator()
return i.next()
}
}
// TODO: swift-3-indexing-model - uncomment and replace above ready (or should we still use the iterator one?)
/// Returns the first element of `self`, or `nil` if `self` is empty.
///
/// - Complexity: O(1)
// public var first: Element? {
// return isEmpty ? nil : self[startIndex]
// }
/// A value less than or equal to the number of elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
@inlinable
public var underestimatedCount: Int {
// TODO: swift-3-indexing-model - review the following
return count
}
/// The number of elements in the collection.
///
/// To check whether a collection is empty, use its `isEmpty` property
/// instead of comparing `count` to zero. Unless the collection guarantees
/// random-access performance, calculating `count` can be an O(*n*)
/// operation.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length
/// of the collection.
@inlinable
public var count: Int {
return distance(from: startIndex, to: endIndex)
}
// TODO: swift-3-indexing-model - rename the following to _customIndexOfEquatable(element)?
/// Customization point for `Collection.firstIndex(of:)`.
///
/// Define this method if the collection can find an element in less than
/// O(*n*) by exploiting collection-specific knowledge.
///
/// - Returns: `nil` if a linear search should be attempted instead,
/// `Optional(nil)` if the element was not found, or
/// `Optional(Optional(index))` if an element was found.
///
/// - Complexity: Hopefully less than O(`count`).
@inlinable
public // dispatching
func _customIndexOfEquatableElement(_: Iterator.Element) -> Index?? {
return nil
}
/// Customization point for `Collection.lastIndex(of:)`.
///
/// Define this method if the collection can find an element in less than
/// O(*n*) by exploiting collection-specific knowledge.
///
/// - Returns: `nil` if a linear search should be attempted instead,
/// `Optional(nil)` if the element was not found, or
/// `Optional(Optional(index))` if an element was found.
///
/// - Complexity: Hopefully less than O(`count`).
@inlinable
public // dispatching
func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? {
return nil
}
}
//===----------------------------------------------------------------------===//
// Default implementations for Collection
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns an array containing the results of mapping the given closure
/// over the sequence's elements.
///
/// In this example, `map` is used first to convert the names in the array
/// to lowercase strings and then to count their characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let lowercaseNames = cast.map { $0.lowercased() }
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
/// let letterCounts = cast.map { $0.count }
/// // 'letterCounts' == [6, 6, 3, 4]
///
/// - Parameter transform: A mapping closure. `transform` accepts an
/// element of this sequence as its parameter and returns a transformed
/// value of the same or of a different type.
/// - Returns: An array containing the transformed elements of this
/// sequence.
@inlinable
public func map<T>(
_ transform: (Element) throws -> T
) rethrows -> [T] {
// TODO: swift-3-indexing-model - review the following
let n = self.count
if n == 0 {
return []
}
var result = ContiguousArray<T>()
result.reserveCapacity(n)
var i = self.startIndex
for _ in 0..<n {
result.append(try transform(self[i]))
formIndex(after: &i)
}
_expectEnd(of: self, is: i)
return Array(result)
}
/// Returns a subsequence containing all but the given number of initial
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence starting after the specified number of
/// elements.
///
/// - Complexity: O(*n*), where *n* is the number of elements to drop from
/// the beginning of the collection.
@inlinable
public func dropFirst(_ n: Int) -> SubSequence {
_precondition(n >= 0, "Can't drop a negative number of elements from a collection")
let start = index(startIndex,
offsetBy: n, limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
/// Returns a subsequence containing all but the specified number of final
/// elements.
///
/// If the number of elements to drop exceeds the number of elements in the
/// collection, the result is an empty subsequence.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// collection. `n` must be greater than or equal to zero.
/// - Returns: A subsequence that leaves off the specified number of elements
/// at the end.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func dropLast(_ n: Int) -> SubSequence {
_precondition(
n >= 0, "Can't drop a negative number of elements from a collection")
let amount = Swift.max(0, count - n)
let end = index(startIndex,
offsetBy: amount, limitedBy: endIndex) ?? endIndex
return self[startIndex..<end]
}
/// Returns a subsequence by skipping elements while `predicate` returns
/// `true` and returning the remaining elements.
///
/// - Parameter predicate: A closure that takes an element of the
/// sequence as its argument and returns `true` if the element should
/// be skipped or `false` if it should be included. Once the predicate
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func drop(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
var start = startIndex
while try start != endIndex && predicate(self[start]) {
formIndex(after: &start)
}
return self[start..<endIndex]
}
/// Returns a subsequence, up to the specified maximum length, containing
/// the initial elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains all the elements in the collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence starting at the beginning of this collection
/// with at most `maxLength` elements.
@inlinable
public func prefix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a prefix of negative length from a collection")
let end = index(startIndex,
offsetBy: maxLength, limitedBy: endIndex) ?? endIndex
return self[startIndex..<end]
}
/// Returns a subsequence containing the initial elements until `predicate`
/// returns `false` and skipping the remaining elements.
///
/// - Parameter predicate: A closure that takes an element of the
/// sequence as its argument and returns `true` if the element should
/// be included or `false` if it should be excluded. Once the predicate
/// returns `false` it will not be called again.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func prefix(
while predicate: (Element) throws -> Bool
) rethrows -> SubSequence {
var end = startIndex
while try end != endIndex && predicate(self[end]) {
formIndex(after: &end)
}
return self[startIndex..<end]
}
/// Returns a subsequence, up to the given maximum length, containing the
/// final elements of the collection.
///
/// If the maximum length exceeds the number of elements in the collection,
/// the result contains all the elements in the collection.
///
/// let numbers = [1, 2, 3, 4, 5]
/// print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
/// - Returns: A subsequence terminating at the end of the collection with at
/// most `maxLength` elements.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func suffix(_ maxLength: Int) -> SubSequence {
_precondition(
maxLength >= 0,
"Can't take a suffix of negative length from a collection")
let amount = Swift.max(0, count - maxLength)
let start = index(startIndex,
offsetBy: amount, limitedBy: endIndex) ?? endIndex
return self[start..<endIndex]
}
/// Returns a subsequence from the start of the collection up to, but not
/// including, the specified position.
///
/// The resulting subsequence *does not include* the element at the position
/// `end`. The following example searches for the index of the number `40`
/// in an array of integers, and then prints the prefix of the array up to,
/// but not including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers.prefix(upTo: i))
/// }
/// // Prints "[10, 20, 30]"
///
/// Passing the collection's starting index as the `end` parameter results in
/// an empty subsequence.
///
/// print(numbers.prefix(upTo: numbers.startIndex))
/// // Prints "[]"
///
/// Using the `prefix(upTo:)` method is equivalent to using a partial
/// half-open range as the collection's subscript. The subscript notation is
/// preferred over `prefix(upTo:)`.
///
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers[..<i])
/// }
/// // Prints "[10, 20, 30]"
///
/// - Parameter end: The "past the end" index of the resulting subsequence.
/// `end` must be a valid index of the collection.
/// - Returns: A subsequence up to, but not including, the `end` position.
///
/// - Complexity: O(1)
@inlinable
public func prefix(upTo end: Index) -> SubSequence {
return self[startIndex..<end]
}
/// Returns a subsequence from the specified position to the end of the
/// collection.
///
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the suffix of the array starting at
/// that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers.suffix(from: i))
/// }
/// // Prints "[40, 50, 60]"
///
/// Passing the collection's `endIndex` as the `start` parameter results in
/// an empty subsequence.
///
/// print(numbers.suffix(from: numbers.endIndex))
/// // Prints "[]"
///
/// Using the `suffix(from:)` method is equivalent to using a partial range
/// from the index as the collection's subscript. The subscript notation is
/// preferred over `suffix(from:)`.
///
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers[i...])
/// }
/// // Prints "[40, 50, 60]"
///
/// - Parameter start: The index at which to start the resulting subsequence.
/// `start` must be a valid index of the collection.
/// - Returns: A subsequence starting at the `start` position.
///
/// - Complexity: O(1)
@inlinable
public func suffix(from start: Index) -> SubSequence {
return self[start..<endIndex]
}
/// Returns a subsequence from the start of the collection through the
/// specified position.
///
/// The resulting subsequence *includes* the element at the position `end`.
/// The following example searches for the index of the number `40` in an
/// array of integers, and then prints the prefix of the array up to, and
/// including, that index:
///
/// let numbers = [10, 20, 30, 40, 50, 60]
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers.prefix(through: i))
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// Using the `prefix(through:)` method is equivalent to using a partial
/// closed range as the collection's subscript. The subscript notation is
/// preferred over `prefix(through:)`.
///
/// if let i = numbers.firstIndex(of: 40) {
/// print(numbers[...i])
/// }
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter end: The index of the last element to include in the
/// resulting subsequence. `end` must be a valid index of the collection
/// that is not equal to the `endIndex` property.
/// - Returns: A subsequence up to, and including, the `end` position.
///
/// - Complexity: O(1)
@inlinable
public func prefix(through position: Index) -> SubSequence {
return prefix(upTo: index(after: position))
}
/// Returns the longest possible subsequences of the collection, in order,
/// that don't contain elements satisfying the given predicate.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the sequence are not returned as part of
/// any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string using a
/// closure that matches spaces. The first use of `split` returns each word
/// that was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(whereSeparator: { $0 == " " }))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.split(maxSplits: 1, whereSeparator: { $0 == " " }))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each pair of consecutive elements
/// satisfying the `isSeparator` predicate and for each element at the
/// start or end of the collection satisfying the `isSeparator`
/// predicate. The default value is `true`.
/// - isSeparator: A closure that takes an element as an argument and
/// returns a Boolean value indicating whether the collection should be
/// split at that element.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
@inlinable
public func split(
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true,
whereSeparator isSeparator: (Element) throws -> Bool
) rethrows -> [SubSequence] {
// TODO: swift-3-indexing-model - review the following
_precondition(maxSplits >= 0, "Must take zero or more splits")
var result: [SubSequence] = []
var subSequenceStart: Index = startIndex
func appendSubsequence(end: Index) -> Bool {
if subSequenceStart == end && omittingEmptySubsequences {
return false
}
result.append(self[subSequenceStart..<end])
return true
}
if maxSplits == 0 || isEmpty {
_ = appendSubsequence(end: endIndex)
return result
}
var subSequenceEnd = subSequenceStart
let cachedEndIndex = endIndex
while subSequenceEnd != cachedEndIndex {
if try isSeparator(self[subSequenceEnd]) {
let didAppend = appendSubsequence(end: subSequenceEnd)
formIndex(after: &subSequenceEnd)
subSequenceStart = subSequenceEnd
if didAppend && result.count == maxSplits {
break
}
continue
}
formIndex(after: &subSequenceEnd)
}
if subSequenceStart != cachedEndIndex || !omittingEmptySubsequences {
result.append(self[subSequenceStart..<cachedEndIndex])
}
return result
}
}
extension Collection where Element : Equatable {
/// Returns the longest possible subsequences of the collection, in order,
/// around elements equal to the given element.
///
/// The resulting array consists of at most `maxSplits + 1` subsequences.
/// Elements that are used to split the collection are not returned as part
/// of any subsequence.
///
/// The following examples show the effects of the `maxSplits` and
/// `omittingEmptySubsequences` parameters when splitting a string at each
/// space character (" "). The first use of `split` returns each word that
/// was originally separated by one or more spaces.
///
/// let line = "BLANCHE: I don't want realism. I want magic!"
/// print(line.split(separator: " "))
/// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// The second example passes `1` for the `maxSplits` parameter, so the
/// original string is split just once, into two new strings.
///
/// print(line.split(separator: " ", maxSplits: 1))
/// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]"
///
/// The final example passes `false` for the `omittingEmptySubsequences`
/// parameter, so the returned array contains empty strings where spaces
/// were repeated.
///
/// print(line.split(separator: " ", omittingEmptySubsequences: false))
/// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"
///
/// - Parameters:
/// - separator: The element that should be split upon.
/// - maxSplits: The maximum number of times to split the collection, or
/// one less than the number of subsequences to return. If
/// `maxSplits + 1` subsequences are returned, the last one is a suffix
/// of the original collection containing the remaining elements.
/// `maxSplits` must be greater than or equal to zero. The default value
/// is `Int.max`.
/// - omittingEmptySubsequences: If `false`, an empty subsequence is
/// returned in the result for each consecutive pair of `separator`
/// elements in the collection and for each instance of `separator` at
/// the start or end of the collection. If `true`, only nonempty
/// subsequences are returned. The default value is `true`.
/// - Returns: An array of subsequences, split from this collection's
/// elements.
@inlinable
public func split(
separator: Element,
maxSplits: Int = Int.max,
omittingEmptySubsequences: Bool = true
) -> [SubSequence] {
// TODO: swift-3-indexing-model - review the following
return split(
maxSplits: maxSplits,
omittingEmptySubsequences: omittingEmptySubsequences,
whereSeparator: { $0 == separator })
}
}
extension Collection where SubSequence == Self {
/// Removes and returns the first element of the collection.
///
/// The collection must not be empty.
///
/// - Returns: The first element of the collection.
///
/// - Complexity: O(1)
@inlinable
@discardableResult
public mutating func removeFirst() -> Element {
// TODO: swift-3-indexing-model - review the following
_precondition(!isEmpty, "Can't remove items from an empty collection")
let element = first!
self = self[index(after: startIndex)..<endIndex]
return element
}
/// Removes the specified number of elements from the beginning of the
/// collection.
///
/// - Parameter n: The number of elements to remove. `n` must be greater than
/// or equal to zero, and must be less than or equal to the number of
/// elements in the collection.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`; otherwise, O(*n*).
@inlinable
public mutating func removeFirst(_ n: Int) {
if n == 0 { return }
_precondition(n >= 0, "Number of elements to remove should be non-negative")
_precondition(count >= n,
"Can't remove more items from a collection than it contains")
self = self[index(startIndex, offsetBy: n)..<endIndex]
}
}
extension Collection {
@inlinable
public func _preprocessingPass<R>(
_ preprocess: () throws -> R
) rethrows -> R? {
return try preprocess()
}
}
extension Collection {
// FIXME: <rdar://problem/34142121>
// This typealias should be removed as it predates the source compatibility
// guarantees of Swift 3, but it cannot due to a bug.
@available(*, unavailable, renamed: "Iterator")
public typealias Generator = Iterator
@available(swift, deprecated: 3.2, renamed: "Element")
public typealias _Element = Element
@available(*, deprecated, message: "all index distances are now of type Int")
public func index<T: BinaryInteger>(_ i: Index, offsetBy n: T) -> Index {
return index(i, offsetBy: Int(n))
}
@available(*, deprecated, message: "all index distances are now of type Int")
public func formIndex<T: BinaryInteger>(_ i: inout Index, offsetBy n: T) {
return formIndex(&i, offsetBy: Int(n))
}
@available(*, deprecated, message: "all index distances are now of type Int")
public func index<T: BinaryInteger>(_ i: Index, offsetBy n: T, limitedBy limit: Index) -> Index? {
return index(i, offsetBy: Int(n), limitedBy: limit)
}
@available(*, deprecated, message: "all index distances are now of type Int")
public func formIndex<T: BinaryInteger>(_ i: inout Index, offsetBy n: T, limitedBy limit: Index) -> Bool {
return formIndex(&i, offsetBy: Int(n), limitedBy: limit)
}
@available(*, deprecated, message: "all index distances are now of type Int")
public func distance<T: BinaryInteger>(from start: Index, to end: Index) -> T {
return numericCast(distance(from: start, to: end) as Int)
}
}
| apache-2.0 | 9418a4464df96a2e620298698db8e589 | 38.278384 | 112 | 0.642083 | 4.180931 | false | false | false | false |
rb-de0/RBSegmentedControl | Pod/Classes/RBSegmentedControl.swift | 1 | 7603 | //
// RBSegmentedControl.swift
// RBSegmentedControl
//
// Created by rb_de0 on 2016/04/09.
// Copyright © 2016年 rb_de0. All rights reserved.
//
import UIKit
public class RBSegmentedControl: UIView{
private var segmentMap = [String: RBSegment]()
private var segmentConstrains = [NSLayoutConstraint]()
private var borderMap = [String: UIView]()
private(set) var selectedSegmentIndex = 0
public weak var delegate: RBSegmentedControlDelegate?
public var selectedSegmentTextColor = RBSegmentControlConst.DefaultSelectedTextColor{
didSet{
updateColors()
}
}
public var segmentTextColor = RBSegmentControlConst.DefaultTextColor{
didSet{
updateColors()
}
}
public var selectedSegmentBackgroundColor = RBSegmentControlConst.DefaultSelectedBackgroundColor{
didSet{
updateColors()
}
}
public var segmentBackgroundColor = RBSegmentControlConst.DefaultBackgroundColor{
didSet{
updateColors()
}
}
public var borderColor = RBSegmentControlConst.DefaultBorderColor{
didSet{
self.layer.borderColor = borderColor.CGColor
borderMap.forEach{$0.1.backgroundColor = borderColor}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initView()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initView()
}
private func initView(){
self.layer.masksToBounds = true
self.layer.cornerRadius = 4
self.layer.borderWidth = 1
self.layer.borderColor = borderColor.CGColor
}
}
// MARK: - add/remove
extension RBSegmentedControl{
public func addSegments(titles: String...){
for (index, title) in titles.enumerate(){
let newSegment = RBSegment(title: title)
newSegment.translatesAutoresizingMaskIntoConstraints = false
newSegment.addTarget(self, action: #selector(RBSegmentedControl.onTapped(_:)), forControlEvents: .TouchUpInside)
segmentMap.updateValue(newSegment, forKey: "segment_\(viewMap.count)")
addSubview(newSegment)
if index != titles.count - 1{
let newBorder = UIView()
newBorder.translatesAutoresizingMaskIntoConstraints = false
newBorder.backgroundColor = borderColor
borderMap.updateValue(newBorder, forKey: "border_\(viewMap.count)")
addSubview(newBorder)
}
}
updateSegments()
updateColors()
}
public func removeSegments(count: Int){
let targetSegments = segmentMap.sort({RBSegmentHelper.compare($0.0, value2: $1.0)}).suffix(count)
targetSegments.forEach{
segmentMap.removeValueForKey($0.0)
$0.1.removeFromSuperview()
}
let targetBorders = borderMap.sort({RBSegmentHelper.compare($0.0, value2: $1.0)}).suffix(count)
targetBorders.forEach{
borderMap.removeValueForKey($0.0)
$0.1.removeFromSuperview()
}
selectedSegmentIndex = 0
updateSegments()
updateColors()
}
func onTapped(sender: RBSegment){
for (index, segment) in segmentMap.sort({RBSegmentHelper.compare($0.0, value2: $1.0)}).map({$0.1}).enumerate(){
if segment == sender && selectedSegmentIndex != index{
delegate?.rb_segmentedControl(didChangedSelectedIndex: index)
selectedSegmentIndex = index
break
}
}
updateColors()
}
}
// MARK: - update
extension RBSegmentedControl{
private var viewMap: [String: UIView]{
var viewMap = [String: UIView]()
segmentMap.forEach{viewMap.updateValue($0.1, forKey: $0.0)}
borderMap.forEach{viewMap.updateValue($0.1, forKey: $0.0)}
return viewMap
}
private func updateSegments(){
if segmentMap.count <= 1{
return
}
removeSegmentConstrains()
updateHorizontalMarigin()
updateVerticalMargin()
updateSegmentWidth()
updateBorderWidth()
layoutIfNeeded()
}
private func updateBorderWidth(){
let keys = borderMap.keys.sort(RBSegmentHelper.compare)
for key in keys{
let width = NSLayoutConstraint.constraintsWithVisualFormat("[\(key)(1)]", options: NSLayoutFormatOptions(), metrics: nil, views: borderMap)
addSegmentConstrains(width)
}
}
private func updateSegmentWidth(){
let keys = segmentMap.keys.sort(RBSegmentHelper.compare)
let first = keys.first!
for key in keys where key != first{
let equalWidth = NSLayoutConstraint.constraintsWithVisualFormat("[\(first)(==\(key))]", options: NSLayoutFormatOptions(), metrics: nil, views: segmentMap)
addSegmentConstrains(equalWidth)
}
}
private func updateVerticalMargin(){
for key in segmentMap.keys{
let verticalMargin = NSLayoutConstraint.constraintsWithVisualFormat("V:|[\(key)]|", options: NSLayoutFormatOptions(), metrics: nil, views: segmentMap)
addSegmentConstrains(verticalMargin)
}
for key in borderMap.keys{
let verticalMargin = NSLayoutConstraint.constraintsWithVisualFormat("V:|[\(key)]|", options: NSLayoutFormatOptions(), metrics: nil, views: borderMap)
addSegmentConstrains(verticalMargin)
}
}
private func updateHorizontalMarigin(){
let keys = viewMap.keys.sort(RBSegmentHelper.compare)
let visualFormat = keys.reduce(""){$0 + "[\($1)]"}
let horizontalMargin = NSLayoutConstraint.constraintsWithVisualFormat("H:|\(visualFormat)|", options: NSLayoutFormatOptions(), metrics: nil, views: viewMap)
addSegmentConstrains(horizontalMargin)
}
private func addSegmentConstrains(segmentConstraints: [NSLayoutConstraint]){
segmentConstrains.appendContentsOf(segmentConstraints)
addConstraints(segmentConstraints)
}
private func removeSegmentConstrains(){
segmentConstrains.forEach(removeConstraint)
segmentConstrains.removeAll()
}
private func updateColors(){
for (index, segment) in segmentMap.sort({RBSegmentHelper.compare($0.0, value2: $1.0)}).map({$0.1}).enumerate(){
if selectedSegmentIndex != index{
segment.setBackgroundColor(selectedSegmentBackgroundColor.colorWithAlphaComponent(0.2), forUIControlState: .Highlighted)
segment.setBackgroundColor(segmentBackgroundColor, forUIControlState: .Normal)
segment.setTitleColor(segmentTextColor.colorWithAlphaComponent(0.8), forState: .Highlighted)
segment.setTitleColor(segmentTextColor, forState: .Normal)
}else{
segment.setBackgroundColor(selectedSegmentBackgroundColor.colorWithAlphaComponent(0.8), forUIControlState: .Highlighted)
segment.setBackgroundColor(selectedSegmentBackgroundColor, forUIControlState: .Normal)
segment.setTitleColor(selectedSegmentTextColor.colorWithAlphaComponent(0.8), forState: .Highlighted)
segment.setTitleColor(selectedSegmentTextColor, forState: .Normal)
}
}
}
}
| mit | 5fab96acd400c2afd317614f3d774d93 | 34.185185 | 166 | 0.632105 | 5.292479 | false | false | false | false |
huonw/swift | test/SILOptimizer/definite_init_value_types.swift | 2 | 3307 | // RUN: %target-swift-frontend -emit-sil -enable-sil-ownership %s | %FileCheck %s
enum ValueEnum {
case a(String)
case b
case c
init() { self = .b }
init(a: Double) {
self.init()
_ = self // okay: self has been initialized by the delegation above
self = .c
}
init(a: Float) {
self.init()
self.init() // this is now OK
}
init(e: Bool) {
if e {
self = ValueEnum()
} else {
self.init()
}
}
// CHECK-LABEL: sil hidden @$S25definite_init_value_types9ValueEnumO1xACSb_tcfC : $@convention(method) (Bool, @thin ValueEnum.Type) -> @owned ValueEnum
// CHECK: bb0(%0 : $Bool, %1 : $@thin ValueEnum.Type):
// CHECK-NEXT: [[STATE:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ValueEnum
// CHECK-NEXT: [[INIT_STATE:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[INIT_STATE]] to [[STATE]]
// CHECK: [[BOOL:%.*]] = struct_extract %0 : $Bool, #Bool._value
// CHECK-NEXT: cond_br [[BOOL]], bb1, bb2
// CHECK: bb1:
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin ValueEnum.Type
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $ValueEnum, #ValueEnum.b!enumelt
// CHECK-NEXT: [[SELF_ACCESS:%.*]] = begin_access [modify] [static] [[SELF_BOX]]
// CHECK-NEXT: [[NEW_STATE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[NEW_STATE]] to [[STATE]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_ACCESS]]
// CHECK-NEXT: end_access [[SELF_ACCESS]]
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin ValueEnum.Type
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $ValueEnum, #ValueEnum.c!enumelt
// CHECK-NEXT: [[SELF_ACCESS:%.*]] = begin_access [modify] [static] [[SELF_BOX]]
// CHECK-NEXT: [[STATE_VALUE:%.*]] = load [[STATE]]
// CHECK-NEXT: cond_br [[STATE_VALUE]], bb3, bb4
// CHECK: bb3:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb4
// CHECK: bb4:
// CHECK-NEXT: [[NEW_STATE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[NEW_STATE]] to [[STATE]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_ACCESS]]
// CHECK-NEXT: end_access [[SELF_ACCESS]]
// CHECK-NEXT: retain_value [[NEW_SELF]]
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[STATE]]
// CHECK-NEXT: return [[NEW_SELF]]
init(x: Bool) {
if x {
self = .b
}
self = .c
}
}
enum AddressEnum {
case a(Any)
case b
case c
init() { self = .b }
init(e: Bool) {
if e {
self = AddressEnum()
} else {
self.init()
}
}
init(x: Bool) {
if x {
self = .b
}
self = .c
}
}
struct EmptyStruct {}
struct ValueStruct {
var ivar: EmptyStruct
init() { ivar = EmptyStruct() }
init(a: Float) {
self.init()
self.init()
}
init(e: Bool) {
if e {
self.init()
} else {
self = ValueStruct()
}
}
}
struct AddressStruct {
var ivar: EmptyStruct // expected-note {{'self.ivar' not initialized}}
var any: Any?
init() { ivar = EmptyStruct(); any = nil }
init(e: Bool) {
if e {
self = AddressStruct()
} else {
self.init()
}
}
}
| apache-2.0 | 9e533eebabc1a7121b8d6959cf61fcd8 | 24.438462 | 153 | 0.551557 | 3.108083 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/Hero/Sources/Transition/HeroTransition+Animate.swift | 4 | 3012 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension HeroTransition {
open func animate() {
guard state == .starting else { return }
state = .animating
if let toView = toView {
context.unhide(view: toView)
}
// auto hide all animated views
for view in animatingFromViews {
context.hide(view: view)
}
for view in animatingToViews {
context.hide(view: view)
}
var totalDuration: TimeInterval = 0
var animatorWantsInteractive = false
if context.insertToViewFirst {
for v in animatingToViews { _ = context.snapshotView(for: v) }
for v in animatingFromViews { _ = context.snapshotView(for: v) }
} else {
for v in animatingFromViews { _ = context.snapshotView(for: v) }
for v in animatingToViews { _ = context.snapshotView(for: v) }
}
// UIKit appears to set fromView setNeedLayout to be true.
// We don't want fromView to layout after our animation starts.
// Therefore we kick off the layout beforehand
fromView?.layoutIfNeeded()
for animator in animators {
let duration = animator.animate(fromViews: animatingFromViews.filter({ animator.canAnimate(view: $0, appearing: false) }),
toViews: animatingToViews.filter({ animator.canAnimate(view: $0, appearing: true) }))
if duration == .infinity {
animatorWantsInteractive = true
} else {
totalDuration = max(totalDuration, duration)
}
}
self.totalDuration = totalDuration
if let forceFinishing = forceFinishing {
complete(finished: forceFinishing)
} else if let startingProgress = startingProgress {
update(startingProgress)
} else if animatorWantsInteractive {
update(0)
} else {
complete(after: totalDuration, finishing: true)
}
fullScreenSnapshot?.removeFromSuperview()
}
}
| mit | 05fc1c8fdae259eab26d0692ac4c28a7 | 36.185185 | 128 | 0.696215 | 4.529323 | false | false | false | false |
andrehenrique92/SQLQueryCreator | Example/Tests/Tests.swift | 1 | 1182 | // https://github.com/Quick/Quick
import Quick
import Nimble
import SQLQueryCreator
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
dispatch_async(dispatch_get_main_queue()) {
time = "done"
}
waitUntil { done in
NSThread.sleepForTimeInterval(0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | 77f1b6152de4f93c3ccddc6ec51ebfd3 | 22.52 | 63 | 0.366497 | 5.469767 | false | false | false | false |
LearningSwift2/LearningApps | IntermediateTableView/SimpleTableView/MovieService.swift | 1 | 1095 | //
// ViewController.swift
// MovieTV
//
// Created by Phil Wright on 12/3/15.
// Copyright © 2015 Touchopia, LLC. All rights reserved.
//
import Foundation
struct MovieService {
let movieAPIKey: String
init(APIKey: String) {
self.movieAPIKey = APIKey
}
func getPopularMovies(completion: ([Movie]? -> Void)) {
guard let movieURL = NSURL(string: "http://api.themoviedb.org/3/movie/popular?api_key=\(movieAPIKey)")
else {
print("Could not construct a valid URL")
return
}
let manager = APIManager(url: movieURL)
manager.GET { (let jsonDictionary) in
var movies = [Movie]()
let results = jsonDictionary?["results"] as! [AnyObject]
for result in results {
let r = result as! [String:AnyObject]
let movie = Movie(jsonDictionary: r)
movies.append(movie)
}
// Call Completion Block
completion(movies)
}
}
}
| apache-2.0 | 8c58d641fa9b1392690ee27544a618a4 | 22.276596 | 110 | 0.532907 | 4.655319 | false | false | false | false |
ZakariyyaSv/LYNetwork | LYNetwork/LYNetworkDemo/Accessory/LYAnimatingRequestAccessory.swift | 1 | 1138 | //
// LYAnimatingRequestAccessory.swift
// LYNetwork
//
// Created by XuHaonan on 2017/7/9.
// Copyright © 2017年 yangqianguan.com. All rights reserved.
//
import Foundation
import UIKit
class LYAnimatingRequestAccessoty: LYRequestAccessory {
public weak var animatingView: UIView?
public var animatingText: String?
public init(_ animatingView: UIView? = nil, _ animatingText: String? = nil) {
self.animatingView = animatingView
self.animatingText = animatingText
}
public class func accessoryAnimating(_ animatingView: UIView? = nil, _ animatingText: String? = nil) -> LYAnimatingRequestAccessoty {
return LYAnimatingRequestAccessoty.init(animatingView, animatingText)
}
// MARK: - LYRequestAccessory
func requestWillStart(_ request: AnyObject) {
if self.animatingView != nil {
DispatchQueue.main.async {
// TODO: show loading
}
}
}
func requestWillStop(_ request: AnyObject) {
if self.animatingView != nil {
DispatchQueue.main.async {
// TODO: hide loading
}
}
}
func requestDidStop(_ request: AnyObject) {
}
}
| mit | 922a479e2a7ce25f04a3e4c2564eb876 | 23.673913 | 135 | 0.682819 | 4.235075 | false | false | false | false |
joncottonskyuk/SwiftValidation | SwiftValidation/StringValidator.swift | 1 | 2610 | //
// StringValidator.swift
// SwiftValidation
//
// Created by Jon on 01/06/2016.
// Copyright © 2016 joncotton. All rights reserved.
//
import Foundation
public enum StringValidator: Validator {
case nonEmpty
case regex(RegexPattern)
case match(String)
case minimumLength(Int)
case maximumLength(Int)
case lengthWithinRange(Int, Int)
case oneOf([String])
public func isValid(value: String) throws -> Bool {
let string = value
var minLength: Int?
var maxLength: Int?
switch self {
case .nonEmpty:
guard string != "" else {
throw StringValidationError.stringIsEmpty
}
case .regex(let pattern):
try pattern.match(string)
case .match(let toMatch):
guard string == toMatch else {
throw StringValidationError.stringsDoNotMatch
}
case .minimumLength(let min):
minLength = min
case .maximumLength(let max):
maxLength = max
case .lengthWithinRange(let min, let max):
minLength = Swift.min(min, max)
maxLength = Swift.max(min, max)
case .oneOf(let allowedValues):
guard allowedValues.contains(string) else {
throw StringValidationError.stringIsNotOneOfAllowedValues(allowedValues)
}
}
if let minLength = minLength {
guard string.characters.count >= minLength else {
throw StringValidationError.stringIsShorterThanAllowedMinimumLength(minLength)
}
}
if let maxLength = maxLength {
guard string.characters.count <= maxLength else {
throw StringValidationError.stringIsLongerThanAllowedMaximumLength(maxLength)
}
}
return true
}
}
extension String: Validateable {
public typealias ValidatorType = StringValidator
}
extension UITextField: Validateable {
public typealias ValidatorType = StringValidator
public func validValue(validators: [StringValidator]) throws -> String {
do {
return try text.validValue(validators)
} catch let errors as AggregateError {
let UIError = ValidationUserInputError(UIElement: self, errors: errors)
throw UIError
}
}
public func validValue(validators: StringValidator...) throws -> String {
return try validValue(validators)
}
} | apache-2.0 | dd778b48f650cf80e506e157124eef84 | 28 | 94 | 0.590648 | 5.260081 | false | false | false | false |
blueXstar597/GA-AI-Simluation-in-Swift | Sprint 3 Final/GG 2/GG/GameScene.swift | 1 | 35114 | //
// GameScene.swift
// 2DSimatulorAI
//
// Created by Student on 2017-06-03.
// Copyright © 2017 Danny. All rights reserved.
//
import SpriteKit
import GameplayKit
//Setting a previous update time to compare the delta
var lastUpdateTime: TimeInterval = 0
let MaxHealth: CGFloat = 100
let HealthBarWidth: CGFloat = 40
let HealthBarHeight: CGFloat = 4
let Population = 20
var Generation = 1
var Fitness: CGFloat = 0
var PopulationDNA = [[Int]] ()
var largest : CGFloat = 0
var GreatestDNA = [Int] ()
//Genetics Evolution
var GroupFitness: [CGFloat] = Array (repeating: 0, count: Population)
var SplitNeuralWeights = [[CGFloat]] ()
var NeuralWeights = [[CGFloat]] ()
struct game {
static var IsOver : Bool = false
}
enum ColliderType: UInt32 {
case player = 1
case obstacles = 2
case food = 4
case wall = 8
case Sensor = 16
}
//#MARK : MATH GROUP
//Enable Vector Properties
func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
func / (point: CGPoint, scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x / scalar, y: point.y / scalar)
}
#if !(arch(x86_64) || arch(arm64))
func sqrt(a: CGFloat) -> CGFloat {
return CGFloat(sqrtf(Float(a)))
}
#endif
//Develop to 2D vectors maths and techiques
extension CGPoint {
func length() -> CGFloat {
return sqrt(x*x + y*y)
}
func normalized() -> CGPoint {
return self / length()
}
func angleForVector () -> CGFloat{
var alfa: CGFloat = atan2 (self.y,self.x)
return alfa
}
}
//Creating a random min and max function
func random (min: Float, max: Float) -> Float
{
let random = Float (Double (arc4random()%1000) / (1000.0))
return random * (max-min) + min
}
//------------------------------
//Develop the class scene
class GameScene: SKScene, SKPhysicsContactDelegate {
//Create SKSpirtNode and Picture
//Set Parameter for the Wander Algthorim
let radius: CGFloat = 5
let distance: CGFloat = 50
let angleNosise: Float = 0.3
let speedD: CGFloat = 10 //20
var angle : [CGFloat] = Array (repeating: 0, count: Population)
var Circle = [SKSpriteNode] ()
var Target = [SKSpriteNode] ()
var counter = 0
//Save every location - (Rather than saving every point, the points are updated every 5 seconds)
var locationObstacle = [CGPoint] ()
var locationFood = [CGPoint] ()
//Fitness Score and Generation #
var scoreLabel: SKLabelNode!
var genLabel : SKLabelNode!
var largestLabel : SKLabelNode!
var bestLabel: SKLabelNode!
var possibleChar = ["player1","player2","player3"]
var possibleObs = ["obstacles0", "obstacles1"]
//Generate a gameTimer to recrod and update everytime
var ObsTimer: Timer!
var FoodTimer: Timer!
//Player's Properties and Behavior
var HealthBar = [SKSpriteNode] ()
var playerHP : [CGFloat] = Array (repeating: MaxHealth, count: Population)
var foodeaten = Array (repeating: 0, count: Population)
//Setuping AI System and Connect to Neural Network
var AIradius: CGFloat = 40
var playerRef: [CGFloat] = Array (repeating: 0, count: Population)
var locationObjPos = ([Int](), [SKSpriteNode] (), [SKSpriteNode] ())
var FieldView: CGFloat = 180
var ReponseSystem = Array (repeating: 0, count: Population)
var NewWeights = [[CGFloat]] ()
//Set-up Function and the new World
override func didMove(to view: SKView) {
//Set BackGround and Wall to white
backgroundColor = SKColor.white
self.physicsWorld.contactDelegate = self
//Develop Edge detection
var edge = SKSpriteNode()
edge.color = UIColor.black
let edgeRect = CGRect (x: 0, y:0 , width:frame.size.width, height:frame.size.height)
edge.physicsBody = SKPhysicsBody (edgeLoopFrom: edgeRect)
//Allow Wall to have collision and set-up physics
edge.physicsBody!.categoryBitMask = ColliderType.wall.rawValue
//edge.physicsBody!.collisionBitMask = ColliderType.player.rawValue
edge.physicsBody!.contactTestBitMask = ColliderType.player.rawValue
edge.physicsBody!.isDynamic = false
edge.name = "wall"
addChild(edge)
//Develop the Players
for _ in 0...Population - 1
{
self.addPlayer()
counter += 1
}
//If 1st Generation, the genes are randomly generated
if Generation == 1
{
PopulationDNA = PopulationMod()
for Individuals in 0...Population - 1
{
SplitNeuralWeights.append ((ConvertBinToNum(Binary: PopulationDNA [Individuals])))
NeuralWeights.append ((FromGreyToWeights(Binary: SplitNeuralWeights [Individuals])))
}
}
else
{
//Else the gene is carried through its parent
for Individuals in 0...Population - 1
{
NewWeights.append ((ConvertBinToNum(Binary: PopulationDNA [Individuals])))
//A Evalution Method to detect the presence of mutation
if areEqual(NewWeight: NewWeights [Individuals], OldWeight: SplitNeuralWeights [Individuals])
{
print ("No Mutation \(Individuals)")
}
else
{
print ("Yes Mutation \(Individuals)")
SplitNeuralWeights [Individuals] = NewWeights [Individuals]
}
//Save into the neural network
NeuralWeights.append ((FromGreyToWeights(Binary: SplitNeuralWeights [Individuals])))
}
}
//Set a counter
counter = 0
// Score Label //
scoreLabel = SKLabelNode(text: "Fitness: \(Int(Fitness))")
scoreLabel.position = CGPoint (x: 115, y:self.frame.size.height - 60)
scoreLabel.fontSize = 36
scoreLabel.fontColor = UIColor.black
self.addChild (scoreLabel)
//Generation Label
genLabel = SKLabelNode (text: "Generation \(Generation)")
genLabel.position = CGPoint (x: 110, y: self.frame.size.height - 100)
genLabel.fontSize = 36
genLabel.fontColor = UIColor.blue
self.addChild (genLabel)
//Greatest Label
largestLabel = SKLabelNode (text: "Greatest: \(Int(largest))")
largestLabel.position = CGPoint (x: 110, y: self.frame.size.height - 140)
largestLabel.fontSize = 36
largestLabel.fontColor = UIColor.black
self.addChild (largestLabel)
//Update every second for the addObstacle
ObsTimer = Timer.scheduledTimer(timeInterval: 1.00, target: self, selector: #selector(addObstacle), userInfo: nil, repeats: true)
//AddFood
FoodTimer = Timer.scheduledTimer(timeInterval: 1.00, target: self, selector: #selector(addFood), userInfo: nil, repeats: true)
}
//Method to develop player
func addPlayer()
{
//Set a SpriteImage
let ri = Int(arc4random_uniform(UInt32(possibleChar.count)))
//Declare Players and Physics
let player = SKSpriteNode(imageNamed: "player\(ri)")
let playerHealthBar = SKSpriteNode ()
player.position = CGPoint (x:self.frame.size.width/2 , y:self.frame.size.height/2)
self.physicsWorld.gravity = CGVector (dx: 0, dy: 0)
//Physics and Collision for Player
player.physicsBody = SKPhysicsBody (rectangleOf: player.size)
player.physicsBody?.categoryBitMask = ColliderType.player.rawValue
player.physicsBody?.collisionBitMask = ColliderType.obstacles.rawValue //|ColliderType.wall.rawValue
player.physicsBody?.contactTestBitMask = ColliderType.obstacles.rawValue | ColliderType.wall.rawValue
player.physicsBody?.usesPreciseCollisionDetection = true
player.physicsBody?.isDynamic = true
player.physicsBody?.restitution = 1.0;
player.physicsBody?.friction = 0.0;
player.physicsBody?.linearDamping = 0.0;
player.physicsBody?.angularDamping = 0.0;
player.name = "player"
player.userData = NSMutableDictionary ()
player.userData?.setValue(counter, forKey: "Key")
self.addChild(player)
//Set the health bar to the player
playerHealthBar.position = CGPoint (
x: player.position.x,
y: player.position.y - player.size.height/2 - 15
)
self.addChild(playerHealthBar)
//Save the health num
HealthBar.append (playerHealthBar)
//Develop and Setup the Wander Algthroim - Detector/ Position
let circle = SKSpriteNode (imageNamed: "circle")
circle.position = CGPoint (x: 0 + player.position.x,y: distance + player.position.y)
circle.xScale = radius/50
circle.yScale = radius/50
circle.physicsBody = SKPhysicsBody (circleOfRadius: circle.size.width + 15)
circle.physicsBody!.categoryBitMask = ColliderType.Sensor.rawValue
circle.physicsBody?.collisionBitMask = 0
//Need for a FOV detection
circle.physicsBody?.contactTestBitMask = ColliderType.food.rawValue | ColliderType.obstacles.rawValue | ColliderType.player.rawValue
circle.userData = NSMutableDictionary ()
circle.userData?.setValue(counter, forKey: "Key")
self.addChild(circle)
Circle.append(circle)
//Wander Algortim - Sliding Transition
let target = SKSpriteNode (imageNamed: "")
target.position = CGPoint (x:0 + circle.position.x, y: radius + circle.position.y )
target.xScale = radius / 2000
target.yScale = radius / 2000
self.addChild(target)
Target.append(target)
}
//Adding Obstacle and entitles
func addObstacle()
{
let ri = Int(arc4random_uniform(UInt32(possibleObs.count)))
//Declare Obsctacles for Local Variables
let localobstacle = SKSpriteNode (imageNamed: "obstacles\(ri)")
//Contain a physics body on the local variables
localobstacle.physicsBody = SKPhysicsBody (rectangleOf: localobstacle.size)
//Allow Collision to take place with certain Item ID
localobstacle.physicsBody?.categoryBitMask = ColliderType.obstacles.rawValue
localobstacle.physicsBody?.contactTestBitMask = ColliderType.player.rawValue
localobstacle.physicsBody?.collisionBitMask = ColliderType.player.rawValue
localobstacle.physicsBody?.isDynamic = false
localobstacle.physicsBody?.usesPreciseCollisionDetection = true
//Name the local obstacles
localobstacle.name = "obstacle"
//Selecting a random x and y position
while (true)
{
//Use a bool to exit the random poistion searching
var gate = true
let randomX : CGFloat = CGFloat (arc4random_uniform(UInt32(self.frame.size.width - 100))+55)
let randomY : CGFloat = CGFloat (arc4random_uniform(UInt32(self.frame.size.height - 150))+50)
//Set poisition based on random Point
localobstacle.position = CGPoint(x: randomX,y: randomY)
//If there is no obstacles within the area
if locationObstacle.count == 0
{
//Add obstacles into the ground
locationObstacle.append (localobstacle.position)
self.addChild(localobstacle)
break
}
//However, if != 0
for sprite in 0 ... locationObstacle.count - 1
{
//Set a range of position that is not inbetween the obstacle's range (The obstacle will range about 20 units long from each other)
if (localobstacle.position.x > locationObstacle [sprite].x - 30 && localobstacle.position.x < locationObstacle [sprite].x + 30 ) && (localobstacle.position.y > locationObstacle [sprite].y - 30 &&
localobstacle.position.y < locationObstacle [sprite].y + 30)
{
//But, if it lies witin another obstacle range
//Re-determine the random function
gate = false
break
}
}
//If the random Point is safe
if gate == true
{
//Store and break out of the random loop
locationObstacle.append (localobstacle.position)
self.addChild(localobstacle)
break
}
}
}
//Develop Food and Image
func addFood ()
{
//Set up SpriteNode and Image
let localFood = SKSpriteNode (imageNamed: "food")
localFood.physicsBody = SKPhysicsBody (rectangleOf: localFood.size)
localFood.physicsBody?.categoryBitMask = ColliderType.food.rawValue
localFood.physicsBody?.contactTestBitMask = ColliderType.player.rawValue
localFood.physicsBody?.collisionBitMask = ColliderType.player.rawValue
localFood.physicsBody?.isDynamic = false
localFood.physicsBody?.usesPreciseCollisionDetection = true
localFood.name = "food"
while true
{
//Find Random Position and see if it is safe, if it is, allow to place
var gate = true
let randomX : CGFloat = CGFloat (arc4random_uniform(UInt32(self.frame.size.width - 100))+55)
let randomY : CGFloat = CGFloat (arc4random_uniform(UInt32(self.frame.size.height - 150))+50)
//Set poisition based on random Point
localFood.position = CGPoint(x: randomX,y: randomY)
//If there is no obstacles within the area
if locationFood.count == 0
{
//Add obstacles into the ground
locationFood.append (localFood.position)
self.addChild(localFood)
break
}
//However, if != 0
for sprite in 0 ... locationFood.count - 1
{
//Set a range of position that is not inbetween the obstacle's range (The obstacle will range about 20 units long from each other)
if (localFood.position.x > locationFood [sprite].x - 30 && localFood.position.x < locationFood [sprite].x + 30 ) && (localFood.position.y > locationFood [sprite].y - 30 &&
localFood.position.y < locationFood [sprite].y + 30)
{
//But, if it lies witin another obstacle range
//Re-determine the random function
gate = false
break
}
}
//If the random Point is safe
if gate == true
{
//Store and break out of the random loop
locationFood.append (localFood.position)
self.addChild(localFood)
break
}
}
}
//Function for updating the player's speed and direction
func updatePlayer (player: SKSpriteNode,health: SKSpriteNode, target: SKSpriteNode, circle: SKSpriteNode, counter: Int )
{
//Design a desireable location
var targetLoc = target.position
//Find the distance in between the target and the player
var desiredDirection = CGPoint (x: targetLoc.x - player.position.x ,y: targetLoc.y - player.position.y )
//Normalized the distance to a unit of 1
desiredDirection = desiredDirection.normalized()
//Find the speed and its movement
let velocity = CGPoint (x: desiredDirection.x*speedD, y:desiredDirection.y*speedD)
//Re-position the player
player.position = CGPoint (x: player.position.x + velocity.x, y: player.position.y + velocity.y)
player.zRotation = velocity.angleForVector() - 90 * CGFloat (M_PI/180)
playerRef.append (player.zRotation)
//See if the player exit out of the screen, reposition themselves
if (player.position.x >= frame.size.width)
{
player.position = CGPoint (x:player.position.x - size.width,y:player.position.y)
}
if (player.position.x <= 0)
{
player.position = CGPoint (x:player.position.x + size.width,y:player.position.y)
}
if (player.position.y >= frame.size.height)
{
player.position = CGPoint (x:player.position.x,y:player.position.y - size.height)
}
if (player.position.y <= 0)
{
player.position = CGPoint (x:player.position.x,y:player.position.y + size.height)
}
//Reposition the Health bar to match up the player
health.position = CGPoint (
x: player.position.x,
y: player.position.y - player.size.height/2 - 15
)
//Decrease its health according to movement
playerHP [counter] -= 1
//Declare a circle location, which takes in the unit 1
var circleLoc = velocity.normalized()
//Re-define the circleLoc to maintain its distance and take in the travelled distance
circleLoc = CGPoint (x: circleLoc.x*distance, y: circleLoc.y*distance)
//Reset the position of the circle's location to continue the player's circular movement
circleLoc = CGPoint (x: player.position.x + circleLoc.x, y: player.position.y + circleLoc.y)
//Develop an angle for the player to move within
if ReponseSystem [counter] == 2
{
angle [counter] = angle [counter] + CGFloat (-angleNosise) //Left
//print ("left")
}
else if ReponseSystem [counter] == 1
{
angle [counter] = angle [counter] + CGFloat (angleNosise) //Right
//print ("right")
}
else
{
angle [counter] = angle [counter] + CGFloat (random(min: -angleNosise, max: angleNosise))
}
//Empty out the response system after response
ReponseSystem [counter] = 0
//Use direction vectors to calculate the x and y component of the point
var perimitterPoint = CGPoint (x: CGFloat (cosf(Float(angle [counter]))),y: CGFloat(sinf(Float(angle [counter]))))
//The "sliding" effect within the target poistion
perimitterPoint = CGPoint (x: perimitterPoint.x * radius, y: perimitterPoint.y * radius)
//Relocate the target loc to mimic the steering effect within the circle
targetLoc = CGPoint (x: circleLoc.x + perimitterPoint.x, y: circleLoc.y + perimitterPoint.y)
//Re-define the location of the circle and the target to allow for continous movement
circle.position = circleLoc
target.position = targetLoc
}
//Deleting Nodes
func deleteNodes (Onebody: SKSpriteNode)
{
Onebody.removeFromParent()
Onebody.physicsBody = nil
}
//Collision and Contact Dectection
func didBegin(_ contact: SKPhysicsContact)
{
var firstBody : SKPhysicsBody
var secondBody: SKPhysicsBody
if contact.bodyA.categoryBitMask == ColliderType.player.rawValue && contact.bodyB.categoryBitMask == ColliderType.obstacles.rawValue
{
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else if contact.bodyB.categoryBitMask == ColliderType.player.rawValue && contact.bodyA.categoryBitMask == ColliderType.obstacles.rawValue
{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
else if contact.bodyA.categoryBitMask == ColliderType.player.rawValue && contact.bodyB.categoryBitMask == ColliderType.food.rawValue
{
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else if contact.bodyB.categoryBitMask == ColliderType.player.rawValue && contact.bodyA.categoryBitMask == ColliderType.food.rawValue
{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
else if contact.bodyB.categoryBitMask == ColliderType.Sensor.rawValue
{
firstBody = contact.bodyB
secondBody = contact.bodyA
}
else if contact.bodyA.categoryBitMask == ColliderType.Sensor.rawValue
{
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else
{
return
}
//Object Collision
if let firstNode = firstBody.node as? SKSpriteNode,
let secondNode = secondBody.node as? SKSpriteNode
{
if firstBody.categoryBitMask == ColliderType.player.rawValue &&
secondBody.categoryBitMask == ColliderType.obstacles.rawValue
{
deleteNodes(Onebody: secondNode)
if let playerNode = firstBody.node
{
if let num = playerNode.userData?.value(forKey: "Key") as? Int
{
playerHP [num] -= 100
foodeaten [num] += 1
}
}
}
if firstBody.categoryBitMask == ColliderType.player.rawValue &&
secondBody.categoryBitMask == ColliderType.food.rawValue
{
deleteNodes(Onebody: secondNode)
if let playerNode = firstBody.node
{
if let num = playerNode.userData?.value(forKey:"Key") as? Int
{
playerHP [num] += 50
if playerHP [num] > 500
{
playerHP [num] = MaxHealth
}
}
}
}
if firstBody.categoryBitMask == ColliderType.Sensor.rawValue && (secondBody.categoryBitMask == ColliderType.food.rawValue || secondBody.categoryBitMask == ColliderType.obstacles.rawValue || secondBody.categoryBitMask == ColliderType.player.rawValue)
{
if let playerPos = firstBody.node
{
if let num = playerPos.userData?.value(forKey: "Key") as? Int
{
locationObjPos.0.append (num)
locationObjPos.1.append (firstBody.node as! SKSpriteNode)
locationObjPos.2.append (secondBody.node as! SKSpriteNode)
}
}
}
else if secondBody.categoryBitMask == ColliderType.Sensor.rawValue && firstBody.categoryBitMask == ColliderType.food.rawValue | ColliderType.obstacles.rawValue | ColliderType.player.rawValue
{
if let playerPos = secondBody.node
{
if let num = playerPos.userData?.value(forKey: "Key") as? Int
{
locationObjPos.0.append(num)
locationObjPos.1.append (firstBody.node as! SKSpriteNode)
locationObjPos.2.append(secondBody.node as! SKSpriteNode)
}
}
}
}
}
//Develop the FOV AI for the player
func AISensor(numValue: [Int], playPos: [SKSpriteNode], objPos: [SKSpriteNode])
{
var input = Array (repeating: CGFloat (0.0), count: 36)
var Allow = false
if numValue.count == 0
{
return
}
for individual in 0...numValue.count - 1
{
for tracking in 0...objPos.count - 1
{
var Setfactor = 1
if objPos [tracking].physicsBody?.categoryBitMask == ColliderType.food.rawValue
{
//Food Section - Neuron
Setfactor = 1
}
else if objPos [tracking].physicsBody?.categoryBitMask == ColliderType.obstacles.rawValue
{
//Obstacles Section - Neuron
Setfactor = 2
}
else if objPos [tracking].physicsBody?.categoryBitMask == ColliderType.player.rawValue
{
//Player Section - Neuron
Setfactor = 3
}
//1
let gapLength = CGPoint (x: playPos [individual].position.x - objPos [tracking].position.x, y: playPos [individual].position.y - objPos [tracking].position.y)
let gapDistance = gapLength.length()
let AngluarPos: CGFloat = atan2 (CGFloat(gapLength.y), CGFloat(gapLength.x))
if AIradius > gapDistance
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/2) && AngluarPos < (playerRef [numValue [individual]] + FieldView/2)
{
Allow = true
//Left Side of the 90 deg
if AngluarPos > (playerRef [numValue [individual]] - FieldView/2)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/6)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/12)
{
//1
input [Setfactor - 1] = gapDistance
}
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/12)
{
//2
input [Setfactor + 2] = gapDistance
}
}
else if AngluarPos < (playerRef [numValue [individual]] - FieldView/6) && AngluarPos > (playerRef [numValue [individual]] - FieldView/6)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/12)
{
//3
input [Setfactor + 5] = gapDistance
}
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/12)
{
//4
input [Setfactor + 8] = gapDistance
}
}
else if AngluarPos < (playerRef [numValue [individual]] - FieldView/6)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/12)
{
//5
input [Setfactor + 11] = gapDistance
}
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/12)
{
//6
input [Setfactor + 14] = gapDistance
}
}
}
//Right Side of the 90 deg
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/2)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/6)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/12)
{
//7
input [Setfactor + 17] = gapDistance
}
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/12)
{
//8
input [Setfactor + 20] = gapDistance
}
}
else if AngluarPos < (playerRef [numValue [individual]] - FieldView/6) && AngluarPos > (playerRef [numValue [individual]] - FieldView/6)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/12)
{
//9
input [Setfactor + 23] = gapDistance
}
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/12)
{
//10
input [Setfactor + 26] = gapDistance
}
}
else if AngluarPos < (playerRef [numValue [individual]] - FieldView/6)
{
if AngluarPos > (playerRef [numValue [individual]] - FieldView/12)
{
//11
input [Setfactor + 29] = gapDistance
}
else if AngluarPos < (playerRef [numValue [individual]] + FieldView/12)
{
//12
input [Setfactor + 32] = gapDistance
}
}
}
}
}
}
if Allow == true
{
//If accesses the FOV, it activates the neural network
ReponseSystem [numValue [individual]] = NeuralNetwork(Parent: PopulationDNA [numValue [individual]], Weights: NeuralWeights [numValue[individual]], Sensory: input)
input = Array (repeating: CGFloat (0.0), count: 36)
}
}
}
func updateHealthBar(node: SKSpriteNode, withHealthPoints hp: CGFloat) {
let barSize = CGSize(width: HealthBarWidth, height: HealthBarHeight);
let fillColor = UIColor(red: 113.0/255, green: 202.0/255, blue: 53.0/255, alpha:1)
let borderColor = UIColor(red: 35.0/255, green: 28.0/255, blue: 40.0/255, alpha:1)
// create drawing context
UIGraphicsBeginImageContextWithOptions(barSize, false, 0)
let context = UIGraphicsGetCurrentContext()
// draw the outline for the health bar
borderColor.setStroke()
let borderRect = CGRect(origin: CGPoint.zero, size: barSize)
context!.stroke(borderRect, width: 1)
// draw the health bar with a colored rectangle
fillColor.setFill()
let barWidth = (barSize.width - 1) * CGFloat(hp) / CGFloat(MaxHealth)
let barRect = CGRect(x: 0.5, y: 0.5, width: barWidth, height: barSize.height - 1)
context!.fill(barRect)
// extract image
let spriteImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// set sprite texture and size
node.texture = SKTexture(image: spriteImage!)
node.size = barSize
}
func goToGameScene ()
{
let gameScene: GameScene = GameScene(size: self.view!.bounds.size) // create your new scene
let transition = SKTransition.fade(withDuration: 1.0) // create type of transition (you can check in documentation for more transtions)
gameScene.scaleMode = SKSceneScaleMode.fill
self.view!.presentScene(gameScene, transition: transition)
}
//Update within frames
override func update(_ currentTime: TimeInterval) {
//Update players
self.enumerateChildNodes(withName: "player")
{
node, stop in
if let num = node.userData?.value(forKey: "Key") as? Int
{
self.updatePlayer(player:node as! SKSpriteNode, health:self.HealthBar [num], target: self.Target [num], circle: self.Circle [num], counter: num)
if self.playerHP [num] <= 0
{
self.deleteNodes(Onebody: node as! SKSpriteNode)
GroupFitness [num] = EvalutionMod(Time: currentTime, Food: self.foodeaten [num])
}
self.updateHealthBar(node: self.HealthBar [num], withHealthPoints: self.playerHP [num])
self.counter += 1
}
}
if counter == 0
{
game.IsOver = true
Generation += 1
let Picker = RouletteSel(Generation: PopulationDNA ,GenFitness: GroupFitness)
var breeding = [[Int]] ()
var breedingWeights = [[CGFloat]] ()
for x in 0...Picker.count - 1
{
breeding.append (PopulationDNA [Picker [x]])
breedingWeights.append (SplitNeuralWeights [Picker [x]])
}
(PopulationDNA,SplitNeuralWeights) = CrossingOver(Population: breeding, inDividualWeight: breedingWeights)
PopulationDNA = Mutation(Population: PopulationDNA)
NeuralWeights = [[CGFloat]] ()
lastUpdateTime = currentTime
removeAllChildren()
goToGameScene()
}
counter = 0
//If the node of the obstacle exceed 6, the obstacle will relocate themselves
if locationObstacle.count >= 10
{
//In the child node, where the node are called "obstacles"
self.enumerateChildNodes(withName: "obstacle")
{
node, stop in
//Remove nodes within the parent node
node.removeFromParent();
node.physicsBody = nil
}
//Clear the location of the stored nodes (obstacles)
locationObstacle = []
}
if locationFood.count >= 10
{
self.enumerateChildNodes(withName: "food")
{
node, stop in
node.removeFromParent();
node.physicsBody = nil
}
locationFood = []
}
AISensor(numValue: locationObjPos.0, playPos: locationObjPos.1, objPos: locationObjPos.2)
playerRef = Array (repeating: 0, count: Population)
}
}
| apache-2.0 | 428081c80039af8c6048877deeebadd6 | 41.820732 | 261 | 0.549768 | 4.851872 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/Extension/Array+ZSExtension.swift | 1 | 1566 | //
// Array+ZSExtension.swift
// zhuishushenqi
//
// Created by yung on 2018/7/4.
// Copyright © 2018年 QS. All rights reserved.
//
import Foundation
import HandyJSON
extension Array {
func find <T: Equatable> (array: [T], item : T) ->Int? {
var index = 0
while(index < array.count) {
if(item == array[index]) {
return index
}
index = index + 1
}
return nil
}
// 去重
func filterDuplicates<E: Equatable>(_ filter: (Element) -> E) -> [Element] {
var result = [Element]()
for value in self {
let key = filter(value)
if !result.map({filter($0)}).contains(key) {
result.append(value)
}
}
return result
}
subscript (safe index:Int) -> Element? {
return (0..<count).contains(index) ? self[index]:nil
}
}
extension Collection where Index:Comparable {
subscript (safe index:Index) ->Element? {
guard startIndex <= index && index < endIndex else {
return nil
}
return self[index]
}
}
extension Array where Element:NSCopying {
var copy:[Element] {
return self.map { $0.copy(with: nil) as! Element };
}
}
extension Array where Element:HandyJSON {
func toJson() ->[[String:Any]] {
var array:[[String:Any]] = []
for item in self {
if let json = item.toJSON() {
array.append(json)
}
}
return array
}
}
| mit | d7fafb5506d72548ea97a9912e387620 | 21.594203 | 80 | 0.516998 | 4.049351 | false | false | false | false |
imex94/KCLTech-iOS-2015 | Hackalendar/Hackalendar/HackalendarTests/HCHackathonProviderTest.swift | 1 | 1710 | //
// HCHackathonProviderTest.swift
// Hackalendar
//
// Created by Clarence Ji on 11/17/15.
// Copyright © 2015 Alex Telek. All rights reserved.
//
import XCTest
@testable import Hackalendar
class HCHackathonProviderTest: XCTestCase {
let validURL = "http://www.hackalist.org/api/1.0/2015/12.json"
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 testProviderReturnsHackathonObject() {
let expectation = expectationWithDescription("Provider parse Hackathon objects")
let hackkings = HCHackathon(title: "HackKings")
hackkings.startDate = "December 12"
hackkings.city = "London, United Kingdom"
HCHackathonProvider.provideHackathonsFor(12) { (hackathons) -> Void in
expectation.fulfill()
XCTAssertEqual(hackathons.count, 2)
XCTAssertEqual(hackathons.first!.title, hackkings.title)
XCTAssertEqual(hackathons.first!.startDate, hackkings.startDate)
XCTAssertEqual(hackathons.first!.city, hackkings.city)
}
waitForExpectationsWithTimeout(10.0) { (error) -> Void in
print(error)
}
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit | 90eb426e49697ed02be486ccb1beee51 | 29.517857 | 111 | 0.629608 | 4.348601 | false | true | false | false |
AllenConquest/emonIOS | emonIOS/FeedView.swift | 1 | 4268 | //
// FeedView.swift
// emonIOS
//
// Created by Allen Conquest on 26/07/2015.
// Copyright (c) 2015 Allen Conquest. All rights reserved.
//
import UIKit
class FeedView: UIView, UIGestureRecognizerDelegate {
var label = UILabel()
var value = UILabel()
var viewFeed: Feed?
var imageView: UIImageView!
var tapGestureRecognizer: UITapGestureRecognizer!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func handleCloseTap(sender: UIPanGestureRecognizer) {
print("handleCloseTap")
if sender.state == .Ended {
self.removeFromSuperview()
if let name = viewFeed?.name {
Persist.delete(name)
}
}
}
func handleLongPressGesture(sender: UILongPressGestureRecognizer) {
switch sender.state {
case .Began:
print("Long Press Began")
if let feedView = sender.view as? FeedView {
feedView.smoothJiggle()
}
default:
print("default")
}
}
func handlePanGesture(sender: UIPanGestureRecognizer) {
switch sender.state {
case .Changed:
sender.view?.center = sender.locationInView(sender.view?.superview)
case .Ended:
if let feedView = sender.view as? FeedView {
if let feed = feedView.viewFeed {
feed.position = sender.view?.center
let success = Persist.save(feed.name, object: feed)
print(success)
}
}
default:
print("default")
}
}
func addCustomView(feed: Feed) {
imageView = UIImageView(image: UIImage(named: "delete32"))
imageView.userInteractionEnabled = true
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleCloseTap:")
tapGestureRecognizer.delegate = self
imageView.addGestureRecognizer(tapGestureRecognizer)
viewFeed = feed
label.frame = CGRectMake(10, 15, 180, 50)
label.textAlignment = NSTextAlignment.Center
label.text = feed.name
addSubview(label)
value.frame = CGRectMake(200, 15, 180, 50)
value.textAlignment = NSTextAlignment.Center
value.text = "\(feed.value)"
imageView.hidden = true
userInteractionEnabled = true
let long = UILongPressGestureRecognizer(target: self, action: "handleLongPressGesture:")
long.minimumPressDuration = 0.5
long.enabled = true
addGestureRecognizer(long)
addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "handlePanGesture:"))
addSubview(imageView)
addSubview(value)
}
/* Degrees to radians conversion */
func degreesToRadians (degrees: CGFloat) -> CGFloat {
return CGFloat(Double(degrees) / 180.0 * M_PI)
}
func smoothJiggle() {
imageView.hidden = false
let degrees: CGFloat = 5.0
let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
animation.duration = 0.6
animation.cumulative = true
animation.repeatCount = Float.infinity
animation.values = [0.0,
degreesToRadians(-degrees) * 0.25,
0.0,
degreesToRadians(degrees) * 0.5,
0.0,
degreesToRadians(-degrees),
0.0,
degreesToRadians(degrees),
0.0,
degreesToRadians(-degrees) * 0.5,
0.0,
degreesToRadians(degrees) * 0.25,
0.0]
animation.fillMode = kCAFillModeForwards;
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.removedOnCompletion = true
layer.addAnimation(animation, forKey: "wobble")
}
func stopJiggling() {
imageView.hidden = true
layer.removeAllAnimations()
transform = CGAffineTransformIdentity
layer.anchorPoint = CGPointMake(0.5, 0.5)
}
} | gpl-2.0 | 85923e9f9965488dbcd83c5e6b1a9524 | 29.71223 | 96 | 0.589035 | 5.056872 | false | false | false | false |
Noders/NodersCL-App | StrongLoopForiOS/MenuTableViewController.swift | 1 | 4076 | //
// MenuTableViewController.swift
// StrongLoopForiOS
//
// Created by Jose Vildosola on 13-05-15.
// Copyright (c) 2015 DevIn. All rights reserved.
//
import UIKit
class MenuTableViewController: UITableViewController {
var menuArray = NSMutableArray()
@IBOutlet var menuTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
menuArray.addObject("Home");
menuArray.addObject("Clase 1");
menuArray.addObject("Clase 2");
menuArray.addObject("Clase 3");
self.revealViewController().rearViewController = self;
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
/*
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = menuArray.objectAtIndex(indexPath.row) as? String
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row{
case 0:
self.performSegueWithIdentifier("homeSegue", sender: nil)
break;
default:
break;
}
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| gpl-2.0 | 3df7686f6574bf15346e0f2d94f21131 | 34.137931 | 157 | 0.670756 | 5.508108 | false | false | false | false |
EstefaniaGilVaquero/ciceIOS | iwach2/AppTest1WatchOSX2 WatchKit Extension/InterfaceController.swift | 2 | 2681 | //
// InterfaceController.swift
// AppTest1WatchOSX2 WatchKit Extension
//
// Created by CICE on 24/10/16.
// Copyright © 2016 CICE. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
//MARK: - VARIABLES LOCALES
var myNombre = "Andres"
let colorNaranja = UIColor.orangeColor()
let colorAzul = UIColor.blueColor()
var valorSlider = 0
//MARK - IBOUTLET
@IBOutlet var myButton: WKInterfaceButton!
@IBOutlet var mySwitch: WKInterfaceSwitch!
@IBOutlet var mySlider: WKInterfaceSlider!
@IBOutlet var myLabel: WKInterfaceLabel!
@IBAction func myBotonAction() {
actionUno()
}
@IBAction func mySwitchAction(value: Bool) {
if value{
actionDos()
}else{
}
}
@IBAction func mySliderAction(value: Float) {
valorSlider = Int(value)
actionTres()
}
//MARK: - UTILS ACTIONS
func actionUno(){
myButton.setTitle("CICE")
myButton.setBackgroundColor(colorNaranja)
myLabel.setText("HOLA MUNDO")
myLabel.setTextColor(colorNaranja)
mySwitch.setColor(colorNaranja)
mySwitch.setOn(false)
mySlider.setColor(colorNaranja)
}
func actionDos(){
myButton.setTitle("ICOLOGIC")
myButton.setBackgroundColor(colorAzul)
myLabel.setTextColor(colorAzul)
myLabel.setText("HOLA ESTEFI")
mySlider.setColor(colorAzul)
}
func actionTres(){
switch valorSlider {
case 1:
mySlider.setColor(colorAzul)
myLabel.setText(String(valorSlider))
case 2:
mySlider.setColor(UIColor.magentaColor())
case 3:
mySlider.setColor(UIColor.yellowColor())
case 4:
mySlider.setColor(UIColor.whiteColor())
case 5:
mySlider.setColor(UIColor.orangeColor())
case 6:
mySlider.setColor(UIColor.greenColor())
default:
mySlider.setColor(UIColor.brownColor())
}
}
//MARK: - LIFE VC
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
| apache-2.0 | fd6ded87abf9a59b8ea4086b51b9dee5 | 24.046729 | 90 | 0.603358 | 4.596913 | false | false | false | false |
apple/swift | test/SILOptimizer/moveonly_objectchecker_diagnostics.swift | 1 | 85146 | // RUN: %target-swift-emit-sil -verify -enable-experimental-move-only %s
//////////////////
// Declarations //
//////////////////
@_moveOnly
public class Klass {
var intField: Int
var k: Klass?
init() {
k = Klass()
intField = 5
}
}
var boolValue: Bool { return true }
public func classUseMoveOnlyWithoutEscaping(_ x: Klass) {
}
public func classConsume(_ x: __owned Klass) {
}
@_moveOnly
public struct NonTrivialStruct {
var k = Klass()
}
public func nonConsumingUseNonTrivialStruct(_ s: NonTrivialStruct) {}
@_moveOnly
public enum NonTrivialEnum {
case first
case second(Klass)
case third(NonTrivialStruct)
}
public func nonConsumingUseNonTrivialEnum(_ e : NonTrivialEnum) {}
@_moveOnly
public final class FinalKlass {
var k: Klass? = nil
}
///////////
// Tests //
///////////
/////////////////
// Class Tests //
/////////////////
public func classSimpleChainTest(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
// expected-error @-1 {{'x2' consumed more than once}}
let y2 = x2 // expected-note {{consuming use}}
let k2 = y2
let k3 = x2 // expected-note {{consuming use}}
let _ = k3
classUseMoveOnlyWithoutEscaping(k2)
}
public func classSimpleChainArgTest(_ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
let y2 = x2 // expected-note {{consuming use}}
let k2 = y2
classUseMoveOnlyWithoutEscaping(k2)
}
public func classSimpleChainOwnedArgTest(_ x2: __owned Klass) {
let y2 = x2
let k2 = y2
classUseMoveOnlyWithoutEscaping(k2)
}
public func classSimpleNonConsumingUseTest(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2)
}
public func classSimpleNonConsumingUseArgTest(_ x2: Klass) {
classUseMoveOnlyWithoutEscaping(x2)
}
public func classSimpleNonConsumingUseOwnedArgTest(_ x2: __owned Klass) {
classUseMoveOnlyWithoutEscaping(x2)
}
public func classMultipleNonConsumingUseTest(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2)
classUseMoveOnlyWithoutEscaping(x2)
print(x2)
}
public func classMultipleNonConsumingUseArgTest(_ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
classUseMoveOnlyWithoutEscaping(x2)
classUseMoveOnlyWithoutEscaping(x2)
print(x2) // expected-note {{consuming use}}
}
public func classMultipleNonConsumingUseOwnedArgTest(_ x2: __owned Klass) {
classUseMoveOnlyWithoutEscaping(x2)
classUseMoveOnlyWithoutEscaping(x2)
print(x2)
}
public func classUseAfterConsume(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func classUseAfterConsumeArg(_ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func classUseAfterConsumeOwnedArg(_ x2: __owned Klass) { // expected-error {{'x2' consumed more than once}}
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func classDoubleConsume(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
classConsume(x2) // expected-note {{consuming use}}
classConsume(x2) // expected-note {{consuming use}}
}
public func classDoubleConsumeArg(_ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
classConsume(x2) // expected-note {{consuming use}}
classConsume(x2) // expected-note {{consuming use}}
}
public func classDoubleConsumeOwnedArg(_ x2: __owned Klass) { // expected-error {{'x2' consumed more than once}}
classConsume(x2) // expected-note {{consuming use}}
classConsume(x2) // expected-note {{consuming use}}
}
public func classLoopConsume(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
classConsume(x2) // expected-note {{consuming use}}
}
}
public func classLoopConsumeArg(_ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
classConsume(x2) // expected-note {{consuming use}}
}
}
public func classLoopConsumeOwnedArg(_ x2: __owned Klass) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
classConsume(x2) // expected-note {{consuming use}}
}
}
public func classDiamond(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
if boolValue {
classConsume(x2)
} else {
classConsume(x2)
}
}
public func classDiamondArg(_ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
if boolValue {
classConsume(x2) // expected-note {{consuming use}}
} else {
classConsume(x2) // expected-note {{consuming use}}
}
}
public func classDiamondOwnedArg(_ x2: __owned Klass) {
if boolValue {
classConsume(x2)
} else {
classConsume(x2)
}
}
public func classDiamondInLoop(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
if boolValue {
classConsume(x2) // expected-note {{consuming use}}
} else {
classConsume(x2) // expected-note {{consuming use}}
}
}
}
public func classDiamondInLoopArg(_ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
if boolValue {
classConsume(x2) // expected-note {{consuming use}}
} else {
classConsume(x2) // expected-note {{consuming use}}
}
}
}
public func classDiamondInLoopOwnedArg(_ x2: __owned Klass) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
if boolValue {
classConsume(x2) // expected-note {{consuming use}}
} else {
classConsume(x2) // expected-note {{consuming use}}
}
}
}
// TODO: We shouldn't be erroring on x3.
public func classAssignToVar1(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
x3 = x // expected-note {{consuming use}}
print(x3)
}
// TODO: We shouldn't see a consuming use on x3.
public func classAssignToVar1Arg(_ x: Klass, _ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
x3 = x // expected-note {{consuming use}}
print(x3)
}
// NOTE: print(x3) shouldn't be marked! This is most likely due to some form of
// load forwarding. We may need to make predictable mem opts more conservative
// with move only var.
public func classAssignToVar1OwnedArg(_ x: Klass, _ x2: __owned Klass) { // expected-error {{'x2' consumed more than once}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func classAssignToVar2(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x3)
}
public func classAssignToVar2Arg(_ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x3)
}
public func classAssignToVar2OwnedArg(_ x2: __owned Klass) { // expected-error {{'x2' consumed more than once}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x3)
}
// NOTE: print(x3) should not be marked.
public func classAssignToVar3(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
var x3 = x2
x3 = x // expected-note {{consuming use}}
print(x3)
}
// NOTE: print(x3) is a bug.
public func classAssignToVar3Arg(_ x: Klass, _ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x // expected-note {{consuming use}}
print(x3)
}
// This is a bug around print(x3)
public func classAssignToVar3OwnedArg(_ x: Klass, _ x2: __owned Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
var x3 = x2
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func classAssignToVar4(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
let x3 = x2 // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
print(x3)
}
public func classAssignToVar4Arg(_ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
let x3 = x2 // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
print(x3)
}
public func classAssignToVar4OwnedArg(_ x2: __owned Klass) { // expected-error {{'x2' consumed more than once}}
let x3 = x2 // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
print(x3)
}
public func classAssignToVar5(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
var x3 = x2 // expected-note {{consuming use}}
// TODO: Need to mark this as the lifetime extending use. We fail
// appropriately though.
classUseMoveOnlyWithoutEscaping(x2)
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func classAssignToVar5Arg(_ x: Klass, _ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
// TODO: Need to mark this as the lifetime extending use. We fail
// appropriately though.
classUseMoveOnlyWithoutEscaping(x2)
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func classAssignToVar5OwnedArg(_ x: Klass, _ x2: __owned Klass) { // expected-error {{'x2' consumed more than once}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
// TODO: Need to mark this as the lifetime extending use. We fail
// appropriately though.
classUseMoveOnlyWithoutEscaping(x2)
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func classAccessAccessField(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2.k!)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.k!)
}
}
public func classAccessAccessFieldArg(_ x2: Klass) {
classUseMoveOnlyWithoutEscaping(x2.k!)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.k!)
}
}
public func classAccessAccessFieldOwnedArg(_ x2: __owned Klass) {
classUseMoveOnlyWithoutEscaping(x2.k!)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.k!)
}
}
public func classAccessConsumeField(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
// Since a class is a reference type, we do not emit an error here.
classConsume(x2.k!)
for _ in 0..<1024 {
classConsume(x2.k!)
}
}
public func classAccessConsumeFieldArg(_ x2: Klass) {
// Since a class is a reference type, we do not emit an error here.
classConsume(x2.k!)
for _ in 0..<1024 {
classConsume(x2.k!)
}
}
public func classAccessConsumeFieldOwnedArg(_ x2: __owned Klass) {
// Since a class is a reference type, we do not emit an error here.
classConsume(x2.k!)
for _ in 0..<1024 {
classConsume(x2.k!)
}
}
extension Klass {
func testNoUseSelf() { // expected-error {{'self' has guaranteed ownership but was consumed}}
let x = self // expected-note {{consuming use}}
let _ = x
}
}
/////////////////
// Final Class //
/////////////////
public func finalClassUseMoveOnlyWithoutEscaping(_ x: FinalKlass) {
}
public func finalClassConsume(_ x: __owned FinalKlass) {
}
public func finalClassSimpleChainTest(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
let y2 = x2
let k2 = y2
finalClassUseMoveOnlyWithoutEscaping(k2)
}
public func finalClassSimpleChainTestArg(_ x2: FinalKlass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
let y2 = x2 // expected-note {{consuming use}}
let k2 = y2
finalClassUseMoveOnlyWithoutEscaping(k2)
}
public func finalClassSimpleChainTestOwnedArg(_ x2: __owned FinalKlass) {
let y2 = x2
let k2 = y2
finalClassUseMoveOnlyWithoutEscaping(k2)
}
public func finalClassSimpleNonConsumingUseTest(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
finalClassUseMoveOnlyWithoutEscaping(x2)
}
public func finalClassSimpleNonConsumingUseTestArg(_ x2: FinalKlass) {
finalClassUseMoveOnlyWithoutEscaping(x2)
}
public func finalClassSimpleNonConsumingUseTestOwnedArg(_ x2: __owned FinalKlass) {
finalClassUseMoveOnlyWithoutEscaping(x2)
}
public func finalClassMultipleNonConsumingUseTest(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
finalClassUseMoveOnlyWithoutEscaping(x2)
finalClassUseMoveOnlyWithoutEscaping(x2)
print(x2)
}
public func finalClassMultipleNonConsumingUseTestArg(_ x2: FinalKlass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
finalClassUseMoveOnlyWithoutEscaping(x2)
finalClassUseMoveOnlyWithoutEscaping(x2)
print(x2) // expected-note {{consuming use}}
}
public func finalClassMultipleNonConsumingUseTestownedArg(_ x2: __owned FinalKlass) {
finalClassUseMoveOnlyWithoutEscaping(x2)
finalClassUseMoveOnlyWithoutEscaping(x2)
print(x2)
}
public func finalClassUseAfterConsume(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
finalClassUseMoveOnlyWithoutEscaping(x2)
finalClassConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func finalClassUseAfterConsumeArg(_ x2: FinalKlass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
finalClassUseMoveOnlyWithoutEscaping(x2)
finalClassConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func finalClassUseAfterConsumeOwnedArg(_ x2: __owned FinalKlass) { // expected-error {{'x2' consumed more than once}}
finalClassUseMoveOnlyWithoutEscaping(x2)
finalClassConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func finalClassDoubleConsume(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
finalClassConsume(x2) // expected-note {{consuming use}}
finalClassConsume(x2) // expected-note {{consuming use}}
}
public func finalClassDoubleConsumeArg(_ x2: FinalKlass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
finalClassConsume(x2) // expected-note {{consuming use}}
finalClassConsume(x2) // expected-note {{consuming use}}
}
public func finalClassDoubleConsumeownedArg(_ x2: __owned FinalKlass) { // expected-error {{'x2' consumed more than once}}
finalClassConsume(x2) // expected-note {{consuming use}}
finalClassConsume(x2) // expected-note {{consuming use}}
}
public func finalClassLoopConsume(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
finalClassConsume(x2) // expected-note {{consuming use}}
}
}
public func finalClassLoopConsumeArg(_ x2: FinalKlass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
finalClassConsume(x2) // expected-note {{consuming use}}
}
}
public func finalClassLoopConsumeOwnedArg(_ x2: __owned FinalKlass) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
finalClassConsume(x2) // expected-note {{consuming use}}
}
}
public func finalClassDiamond(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
if boolValue {
finalClassConsume(x2)
} else {
finalClassConsume(x2)
}
}
public func finalClassDiamondArg(_ x2: FinalKlass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
if boolValue {
finalClassConsume(x2) // expected-note {{consuming use}}
} else {
finalClassConsume(x2) // expected-note {{consuming use}}
}
}
public func finalClassDiamondOwnedArg(_ x2: __owned FinalKlass) {
if boolValue {
finalClassConsume(x2)
} else {
finalClassConsume(x2)
}
}
public func finalClassDiamondInLoop(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
if boolValue {
finalClassConsume(x2) // expected-note {{consuming use}}
} else {
finalClassConsume(x2) // expected-note {{consuming use}}
}
}
}
public func finalClassDiamondInLoopArg(_ x2: FinalKlass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
if boolValue {
finalClassConsume(x2) // expected-note {{consuming use}}
} else {
finalClassConsume(x2) // expected-note {{consuming use}}
}
}
}
public func finalClassDiamondInLoopOwnedArg(_ x2: __owned FinalKlass) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
if boolValue {
finalClassConsume(x2) // expected-note {{consuming use}}
} else {
finalClassConsume(x2) // expected-note {{consuming use}}
}
}
}
public func finalClassAssignToVar1(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func finalClassAssignToVar1Arg(_ x: FinalKlass, _ x2: FinalKlass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func finalClassAssignToVar1OwnedArg(_ x: FinalKlass, _ x2: __owned FinalKlass) { // expected-error {{'x2' consumed more than once}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func finalClassAssignToVar2(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
finalClassUseMoveOnlyWithoutEscaping(x3)
}
public func finalClassAssignToVar2Arg(_ x2: FinalKlass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
finalClassUseMoveOnlyWithoutEscaping(x3)
}
public func finalClassAssignToVar2OwnedArg(_ x2: __owned FinalKlass) { // expected-error {{'x2' consumed more than once}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
finalClassUseMoveOnlyWithoutEscaping(x3)
}
public func finalClassAssignToVar3(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
var x3 = x2
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func finalClassAssignToVar3Arg(_ x: FinalKlass, _ x2: FinalKlass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func finalClassAssignToVar3OwnedArg(_ x: FinalKlass, _ x2: __owned FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
var x3 = x2
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func finalClassAssignToVar4(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
let x3 = x2 // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
print(x3)
}
public func finalClassAssignToVar4Arg(_ x2: FinalKlass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
let x3 = x2 // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
print(x3)
}
public func finalClassAssignToVar4OwnedArg(_ x2: __owned FinalKlass) { // expected-error {{'x2' consumed more than once}}
let x3 = x2 // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
print(x3)
}
public func finalClassAssignToVar5(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
var x3 = x2 // expected-note {{consuming use}}
// TODO: Need to mark this as the lifetime extending use. We fail
// appropriately though.
finalClassUseMoveOnlyWithoutEscaping(x2)
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func finalClassAssignToVar5Arg(_ x: FinalKlass, _ x2: FinalKlass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
// TODO: Need to mark this as the lifetime extending use. We fail
// appropriately though.
finalClassUseMoveOnlyWithoutEscaping(x2)
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func finalClassAssignToVar5OwnedArg(_ x: FinalKlass, _ x2: __owned FinalKlass) { // expected-error {{'x2' consumed more than once}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
// TODO: Need to mark this as the lifetime extending use. We fail
// appropriately though.
finalClassUseMoveOnlyWithoutEscaping(x2)
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func finalClassAccessField(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2.k!)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.k!)
}
}
public func finalClassAccessFieldArg(_ x2: FinalKlass) {
classUseMoveOnlyWithoutEscaping(x2.k!)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.k!)
}
}
public func finalClassAccessFieldOwnedArg(_ x2: __owned FinalKlass) {
classUseMoveOnlyWithoutEscaping(x2.k!)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.k!)
}
}
public func finalClassConsumeField(_ x: FinalKlass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
// No diagnostic here since class is a reference type and we are not copying
// the class, we are copying its field.
classConsume(x2.k!)
for _ in 0..<1024 {
classConsume(x2.k!)
}
}
public func finalClassConsumeFieldArg(_ x2: FinalKlass) {
// No diagnostic here since class is a reference type and we are not copying
// the class, we are copying its field.
classConsume(x2.k!)
for _ in 0..<1024 {
classConsume(x2.k!)
}
}
public func finalClassConsumeFieldArg(_ x2: __owned FinalKlass) {
// No diagnostic here since class is a reference type and we are not copying
// the class, we are copying its field.
classConsume(x2.k!)
for _ in 0..<1024 {
classConsume(x2.k!)
}
}
//////////////////////
// Aggregate Struct //
//////////////////////
@_moveOnly
public struct KlassPair {
var lhs: Klass
var rhs: Klass
}
@_moveOnly
public struct AggStruct {
var lhs: Klass
var center: Int32
var rhs: Klass
var pair: KlassPair
}
public func aggStructUseMoveOnlyWithoutEscaping(_ x: AggStruct) {
}
public func aggStructConsume(_ x: __owned AggStruct) {
}
public func aggStructSimpleChainTest(_ x: AggStruct) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
let y2 = x2
let k2 = y2
aggStructUseMoveOnlyWithoutEscaping(k2)
}
public func aggStructSimpleChainTestArg(_ x2: AggStruct) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
let y2 = x2 // expected-note {{consuming use}}
let k2 = y2
aggStructUseMoveOnlyWithoutEscaping(k2)
}
public func aggStructSimpleChainTestOwnedArg(_ x2: __owned AggStruct) {
let y2 = x2
let k2 = y2
aggStructUseMoveOnlyWithoutEscaping(k2)
}
public func aggStructSimpleNonConsumingUseTest(_ x: AggStruct) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
aggStructUseMoveOnlyWithoutEscaping(x2)
}
public func aggStructSimpleNonConsumingUseTestArg(_ x2: AggStruct) {
aggStructUseMoveOnlyWithoutEscaping(x2)
}
public func aggStructSimpleNonConsumingUseTestOwnedArg(_ x2: __owned AggStruct) {
aggStructUseMoveOnlyWithoutEscaping(x2)
}
public func aggStructMultipleNonConsumingUseTest(_ x: AggStruct) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
aggStructUseMoveOnlyWithoutEscaping(x2)
aggStructUseMoveOnlyWithoutEscaping(x2)
print(x2)
}
public func aggStructMultipleNonConsumingUseTestArg(_ x2: AggStruct) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
aggStructUseMoveOnlyWithoutEscaping(x2)
aggStructUseMoveOnlyWithoutEscaping(x2)
print(x2) // expected-note {{consuming use}}
}
public func aggStructMultipleNonConsumingUseTestOwnedArg(_ x2: __owned AggStruct) {
aggStructUseMoveOnlyWithoutEscaping(x2)
aggStructUseMoveOnlyWithoutEscaping(x2)
print(x2)
}
public func aggStructUseAfterConsume(_ x: AggStruct) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
aggStructUseMoveOnlyWithoutEscaping(x2)
aggStructConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func aggStructUseAfterConsumeArg(_ x2: AggStruct) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
aggStructUseMoveOnlyWithoutEscaping(x2)
aggStructConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func aggStructUseAfterConsumeOwnedArg(_ x2: __owned AggStruct) { // expected-error {{'x2' consumed more than once}}
aggStructUseMoveOnlyWithoutEscaping(x2)
aggStructConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func aggStructDoubleConsume(_ x: AggStruct) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
aggStructConsume(x2) // expected-note {{consuming use}}
aggStructConsume(x2) // expected-note {{consuming use}}
}
public func aggStructDoubleConsumeArg(_ x2: AggStruct) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
aggStructConsume(x2) // expected-note {{consuming use}}
aggStructConsume(x2) // expected-note {{consuming use}}
}
public func aggStructDoubleConsumeOwnedArg(_ x2: __owned AggStruct) { // expected-error {{'x2' consumed more than once}}
aggStructConsume(x2) // expected-note {{consuming use}}
aggStructConsume(x2) // expected-note {{consuming use}}
}
public func aggStructLoopConsume(_ x: AggStruct) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
aggStructConsume(x2) // expected-note {{consuming use}}
}
}
public func aggStructLoopConsumeArg(_ x2: AggStruct) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
aggStructConsume(x2) // expected-note {{consuming use}}
}
}
public func aggStructLoopConsumeOwnedArg(_ x2: __owned AggStruct) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
aggStructConsume(x2) // expected-note {{consuming use}}
}
}
public func aggStructDiamond(_ x: AggStruct) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
if boolValue {
aggStructConsume(x2)
} else {
aggStructConsume(x2)
}
}
public func aggStructDiamondArg(_ x2: AggStruct) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
if boolValue {
aggStructConsume(x2) // expected-note {{consuming use}}
} else {
aggStructConsume(x2) // expected-note {{consuming use}}
}
}
public func aggStructDiamondOwnedArg(_ x2: __owned AggStruct) {
if boolValue {
aggStructConsume(x2)
} else {
aggStructConsume(x2)
}
}
public func aggStructDiamondInLoop(_ x: AggStruct) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
if boolValue {
aggStructConsume(x2) // expected-note {{consuming use}}
} else {
aggStructConsume(x2) // expected-note {{consuming use}}
}
}
}
public func aggStructDiamondInLoopArg(_ x2: AggStruct) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
if boolValue {
aggStructConsume(x2) // expected-note {{consuming use}}
} else {
aggStructConsume(x2) // expected-note {{consuming use}}
}
}
}
public func aggStructDiamondInLoopOwnedArg(_ x2: __owned AggStruct) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
if boolValue {
aggStructConsume(x2) // expected-note {{consuming use}}
} else {
aggStructConsume(x2) // expected-note {{consuming use}}
}
}
}
public func aggStructAccessField(_ x: AggStruct) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.lhs)
}
}
public func aggStructAccessFieldArg(_ x2: AggStruct) {
classUseMoveOnlyWithoutEscaping(x2.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.lhs)
}
}
public func aggStructAccessFieldOwnedArg(_ x2: __owned AggStruct) {
classUseMoveOnlyWithoutEscaping(x2.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.lhs)
}
}
public func aggStructConsumeField(_ x: AggStruct) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classConsume(x2.lhs)
for _ in 0..<1024 {
classConsume(x2.lhs)
}
}
// TODO: We should error here!
public func aggStructConsumeFieldArg(_ x2: AggStruct) {
classConsume(x2.lhs)
for _ in 0..<1024 {
classConsume(x2.lhs)
}
}
public func aggStructConsumeFieldOwnedArg(_ x2: __owned AggStruct) {
classConsume(x2.lhs)
for _ in 0..<1024 {
classConsume(x2.lhs)
}
}
public func aggStructAccessGrandField(_ x: AggStruct) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
}
}
public func aggStructAccessGrandFieldArg(_ x2: AggStruct) {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
}
}
public func aggStructAccessGrandFieldOwnedArg(_ x2: __owned AggStruct) {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
}
}
public func aggStructConsumeGrandField(_ x: AggStruct) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classConsume(x2.pair.lhs)
for _ in 0..<1024 {
classConsume(x2.pair.lhs)
}
}
// TODO: This needs to error.
public func aggStructConsumeGrandFieldArg(_ x2: AggStruct) {
classConsume(x2.pair.lhs)
for _ in 0..<1024 {
classConsume(x2.pair.lhs)
}
}
public func aggStructConsumeGrandFieldOwnedArg(_ x2: __owned AggStruct) {
classConsume(x2.pair.lhs)
for _ in 0..<1024 {
classConsume(x2.pair.lhs)
}
}
//////////////////////////////
// Aggregate Generic Struct //
//////////////////////////////
@_moveOnly
public struct AggGenericStruct<T> {
var lhs: Klass
var rhs: UnsafeRawPointer
var pair: KlassPair
}
public func aggGenericStructUseMoveOnlyWithoutEscaping(_ x: AggGenericStruct<Klass>) {
}
public func aggGenericStructConsume(_ x: __owned AggGenericStruct<Klass>) {
}
public func aggGenericStructSimpleChainTest(_ x: AggGenericStruct<Klass>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
let y2 = x2
let k2 = y2
aggGenericStructUseMoveOnlyWithoutEscaping(k2)
}
public func aggGenericStructSimpleChainTestArg(_ x2: AggGenericStruct<Klass>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
let y2 = x2 // expected-note {{consuming use}}
let k2 = y2
aggGenericStructUseMoveOnlyWithoutEscaping(k2)
}
public func aggGenericStructSimpleChainTestOwnedArg(_ x2: __owned AggGenericStruct<Klass>) {
let y2 = x2
let k2 = y2
aggGenericStructUseMoveOnlyWithoutEscaping(k2)
}
public func aggGenericStructSimpleNonConsumingUseTest(_ x: AggGenericStruct<Klass>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
}
public func aggGenericStructSimpleNonConsumingUseTestArg(_ x2: AggGenericStruct<Klass>) {
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
}
public func aggGenericStructSimpleNonConsumingUseTestOwnedArg(_ x2: __owned AggGenericStruct<Klass>) {
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
}
public func aggGenericStructMultipleNonConsumingUseTest(_ x: AggGenericStruct<Klass>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
print(x2)
}
public func aggGenericStructMultipleNonConsumingUseTestArg(_ x2: AggGenericStruct<Klass>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
print(x2) // expected-note {{consuming use}}
}
public func aggGenericStructMultipleNonConsumingUseTestOwnedArg(_ x2: __owned AggGenericStruct<Klass>) {
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
print(x2)
}
public func aggGenericStructUseAfterConsume(_ x: AggGenericStruct<Klass>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
aggGenericStructConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func aggGenericStructUseAfterConsumeArg(_ x2: AggGenericStruct<Klass>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
aggGenericStructConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func aggGenericStructUseAfterConsumeOwnedArg(_ x2: __owned AggGenericStruct<Klass>) { // expected-error {{'x2' consumed more than once}}
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
aggGenericStructConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func aggGenericStructDoubleConsume(_ x: AggGenericStruct<Klass>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
aggGenericStructConsume(x2) // expected-note {{consuming use}}
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
public func aggGenericStructDoubleConsumeArg(_ x2: AggGenericStruct<Klass>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
aggGenericStructConsume(x2) // expected-note {{consuming use}}
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
public func aggGenericStructDoubleConsumeOwnedArg(_ x2: __owned AggGenericStruct<Klass>) { // expected-error {{'x2' consumed more than once}}
aggGenericStructConsume(x2) // expected-note {{consuming use}}
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
public func aggGenericStructLoopConsume(_ x: AggGenericStruct<Klass>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
public func aggGenericStructLoopConsumeArg(_ x2: AggGenericStruct<Klass>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
public func aggGenericStructLoopConsumeOwnedArg(_ x2: __owned AggGenericStruct<Klass>) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
public func aggGenericStructDiamond(_ x: AggGenericStruct<Klass>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
if boolValue {
aggGenericStructConsume(x2)
} else {
aggGenericStructConsume(x2)
}
}
public func aggGenericStructDiamondArg(_ x2: AggGenericStruct<Klass>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
if boolValue {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
} else {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
public func aggGenericStructDiamondOwnedArg(_ x2: __owned AggGenericStruct<Klass>) {
if boolValue {
aggGenericStructConsume(x2)
} else {
aggGenericStructConsume(x2)
}
}
public func aggGenericStructDiamondInLoop(_ x: AggGenericStruct<Klass>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
if boolValue {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
} else {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
}
public func aggGenericStructDiamondInLoopArg(_ x2: AggGenericStruct<Klass>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
if boolValue {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
} else {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
}
public func aggGenericStructDiamondInLoopOwnedArg(_ x2: __owned AggGenericStruct<Klass>) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
if boolValue {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
} else {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
}
public func aggGenericStructAccessField(_ x: AggGenericStruct<Klass>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.lhs)
}
}
public func aggGenericStructAccessFieldArg(_ x2: AggGenericStruct<Klass>) {
classUseMoveOnlyWithoutEscaping(x2.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.lhs)
}
}
public func aggGenericStructAccessFieldOwnedArg(_ x2: __owned AggGenericStruct<Klass>) {
classUseMoveOnlyWithoutEscaping(x2.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.lhs)
}
}
public func aggGenericStructConsumeField(_ x: AggGenericStruct<Klass>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classConsume(x2.lhs)
for _ in 0..<1024 {
classConsume(x2.lhs)
}
}
public func aggGenericStructConsumeFieldArg(_ x2: AggGenericStruct<Klass>) {
classConsume(x2.lhs)
for _ in 0..<1024 {
classConsume(x2.lhs)
}
}
public func aggGenericStructConsumeFieldOwnedArg(_ x2: __owned AggGenericStruct<Klass>) {
classConsume(x2.lhs)
for _ in 0..<1024 {
classConsume(x2.lhs)
}
}
public func aggGenericStructAccessGrandField(_ x: AggGenericStruct<Klass>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
}
}
public func aggGenericStructAccessGrandFieldArg(_ x2: AggGenericStruct<Klass>) {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
}
}
public func aggGenericStructAccessGrandFieldOwnedArg(_ x2: __owned AggGenericStruct<Klass>) {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
}
}
public func aggGenericStructConsumeGrandField(_ x: AggGenericStruct<Klass>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classConsume(x2.pair.lhs)
for _ in 0..<1024 {
classConsume(x2.pair.lhs)
}
}
public func aggGenericStructConsumeGrandFieldArg(_ x2: AggGenericStruct<Klass>) {
classConsume(x2.pair.lhs)
for _ in 0..<1024 {
classConsume(x2.pair.lhs)
}
}
public func aggGenericStructConsumeGrandFieldOwnedArg(_ x2: __owned AggGenericStruct<Klass>) {
classConsume(x2.pair.lhs)
for _ in 0..<1024 {
classConsume(x2.pair.lhs)
}
}
////////////////////////////////////////////////////////////
// Aggregate Generic Struct + Generic But Body is Trivial //
////////////////////////////////////////////////////////////
public func aggGenericStructUseMoveOnlyWithoutEscaping<T>(_ x: AggGenericStruct<T>) {
}
public func aggGenericStructConsume<T>(_ x: __owned AggGenericStruct<T>) {
}
public func aggGenericStructSimpleChainTest<T>(_ x: AggGenericStruct<T>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
let y2 = x2
let k2 = y2
aggGenericStructUseMoveOnlyWithoutEscaping(k2)
}
public func aggGenericStructSimpleChainTestArg<T>(_ x2: AggGenericStruct<T>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
let y2 = x2 // expected-note {{consuming use}}
let k2 = y2
aggGenericStructUseMoveOnlyWithoutEscaping(k2)
}
public func aggGenericStructSimpleChainTestOwnedArg<T>(_ x2: __owned AggGenericStruct<T>) {
let y2 = x2
let k2 = y2
aggGenericStructUseMoveOnlyWithoutEscaping(k2)
}
public func aggGenericStructSimpleNonConsumingUseTest<T>(_ x: AggGenericStruct<T>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
}
public func aggGenericStructSimpleNonConsumingUseTestArg<T>(_ x2: AggGenericStruct<T>) {
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
}
public func aggGenericStructSimpleNonConsumingUseTestOwnedArg<T>(_ x2: __owned AggGenericStruct<T>) {
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
}
public func aggGenericStructMultipleNonConsumingUseTest<T>(_ x: AggGenericStruct<T>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
print(x2)
}
public func aggGenericStructMultipleNonConsumingUseTestArg<T>(_ x2: AggGenericStruct<T>) { //expected-error {{'x2' has guaranteed ownership but was consumed}}
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
print(x2) // expected-note {{consuming use}}
}
public func aggGenericStructMultipleNonConsumingUseTestOwnedArg<T>(_ x2: __owned AggGenericStruct<T>) {
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
print(x2)
}
public func aggGenericStructUseAfterConsume<T>(_ x: AggGenericStruct<T>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
aggGenericStructConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func aggGenericStructUseAfterConsumeArg<T>(_ x2: AggGenericStruct<T>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
aggGenericStructConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func aggGenericStructUseAfterConsumeOwnedArg<T>(_ x2: __owned AggGenericStruct<T>) { // expected-error {{'x2' consumed more than once}}
aggGenericStructUseMoveOnlyWithoutEscaping(x2)
aggGenericStructConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func aggGenericStructDoubleConsume<T>(_ x: AggGenericStruct<T>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
aggGenericStructConsume(x2) // expected-note {{consuming use}}
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
public func aggGenericStructDoubleConsumeArg<T>(_ x2: AggGenericStruct<T>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
aggGenericStructConsume(x2) // expected-note {{consuming use}}
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
public func aggGenericStructDoubleConsumeOwnedArg<T>(_ x2: __owned AggGenericStruct<T>) { // expected-error {{'x2' consumed more than once}}
aggGenericStructConsume(x2) // expected-note {{consuming use}}
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
public func aggGenericStructLoopConsume<T>(_ x: AggGenericStruct<T>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
public func aggGenericStructLoopConsumeArg<T>(_ x2: AggGenericStruct<T>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
public func aggGenericStructLoopConsumeOwnedArg<T>(_ x2: __owned AggGenericStruct<T>) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
public func aggGenericStructDiamond<T>(_ x: AggGenericStruct<T>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
if boolValue {
aggGenericStructConsume(x2)
} else {
aggGenericStructConsume(x2)
}
}
public func aggGenericStructDiamondArg<T>(_ x2: AggGenericStruct<T>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
if boolValue {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
} else {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
public func aggGenericStructDiamondOwnedArg<T>(_ x2: __owned AggGenericStruct<T>) {
if boolValue {
aggGenericStructConsume(x2)
} else {
aggGenericStructConsume(x2)
}
}
public func aggGenericStructDiamondInLoop<T>(_ x: AggGenericStruct<T>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
if boolValue {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
} else {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
}
public func aggGenericStructDiamondInLoopArg<T>(_ x2: AggGenericStruct<T>) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
if boolValue {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
} else {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
}
public func aggGenericStructDiamondInLoopOwnedArg<T>(_ x2: __owned AggGenericStruct<T>) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
if boolValue {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
} else {
aggGenericStructConsume(x2) // expected-note {{consuming use}}
}
}
}
public func aggGenericStructAccessField<T>(_ x: AggGenericStruct<T>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.lhs)
}
}
public func aggGenericStructAccessFieldArg<T>(_ x2: AggGenericStruct<T>) {
classUseMoveOnlyWithoutEscaping(x2.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.lhs)
}
}
public func aggGenericStructAccessFieldOwnedArg<T>(_ x2: __owned AggGenericStruct<T>) {
classUseMoveOnlyWithoutEscaping(x2.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.lhs)
}
}
public func aggGenericStructConsumeField<T>(_ x: AggGenericStruct<T>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classConsume(x2.lhs)
for _ in 0..<1024 {
classConsume(x2.lhs)
}
}
public func aggGenericStructConsumeFieldArg<T>(_ x2: AggGenericStruct<T>) {
classConsume(x2.lhs)
for _ in 0..<1024 {
classConsume(x2.lhs)
}
}
public func aggGenericStructConsumeFieldOwnedArg<T>(_ x2: __owned AggGenericStruct<T>) {
classConsume(x2.lhs)
for _ in 0..<1024 {
classConsume(x2.lhs)
}
}
public func aggGenericStructAccessGrandField<T>(_ x: AggGenericStruct<T>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
}
}
public func aggGenericStructAccessGrandFieldArg<T>(_ x2: AggGenericStruct<T>) {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
}
}
public func aggGenericStructAccessGrandFieldOwnedArg<T>(_ x2: __owned AggGenericStruct<T>) {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
for _ in 0..<1024 {
classUseMoveOnlyWithoutEscaping(x2.pair.lhs)
}
}
public func aggGenericStructConsumeGrandField<T>(_ x: AggGenericStruct<T>) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
classConsume(x2.pair.lhs)
for _ in 0..<1024 {
classConsume(x2.pair.lhs)
}
}
public func aggGenericStructConsumeGrandFieldArg<T>(_ x2: AggGenericStruct<T>) {
classConsume(x2.pair.lhs)
for _ in 0..<1024 {
classConsume(x2.pair.lhs)
}
}
public func aggGenericStructConsumeGrandFieldOwnedArg<T>(_ x2: __owned AggGenericStruct<T>) {
classConsume(x2.pair.lhs)
for _ in 0..<1024 {
classConsume(x2.pair.lhs)
}
}
/////////////////////
// Enum Test Cases //
/////////////////////
@_moveOnly
public enum EnumTy {
case klass(Klass)
case int(Int)
func doSomething() -> Bool { true }
}
public func enumUseMoveOnlyWithoutEscaping(_ x: EnumTy) {
}
public func enumConsume(_ x: __owned EnumTy) {
}
public func enumSimpleChainTest(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
let y2 = x2
let k2 = y2
enumUseMoveOnlyWithoutEscaping(k2)
}
public func enumSimpleChainTestArg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
let y2 = x2 // expected-note {{consuming use}}
let k2 = y2
enumUseMoveOnlyWithoutEscaping(k2)
}
public func enumSimpleChainTestOwnedArg(_ x2: __owned EnumTy) {
let y2 = x2
let k2 = y2
enumUseMoveOnlyWithoutEscaping(k2)
}
public func enumSimpleNonConsumingUseTest(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
enumUseMoveOnlyWithoutEscaping(x2)
}
public func enumSimpleNonConsumingUseTestArg(_ x2: EnumTy) {
enumUseMoveOnlyWithoutEscaping(x2)
}
public func enumSimpleNonConsumingUseTestOwnedArg(_ x2: __owned EnumTy) {
enumUseMoveOnlyWithoutEscaping(x2)
}
public func enumMultipleNonConsumingUseTest(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
enumUseMoveOnlyWithoutEscaping(x2)
enumUseMoveOnlyWithoutEscaping(x2)
print(x2)
}
public func enumMultipleNonConsumingUseTestArg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
enumUseMoveOnlyWithoutEscaping(x2)
enumUseMoveOnlyWithoutEscaping(x2)
print(x2) // expected-note {{consuming use}}
}
public func enumMultipleNonConsumingUseTestOwnedArg(_ x2: __owned EnumTy) {
enumUseMoveOnlyWithoutEscaping(x2)
enumUseMoveOnlyWithoutEscaping(x2)
print(x2)
}
public func enumUseAfterConsume(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
enumUseMoveOnlyWithoutEscaping(x2)
enumConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func enumUseAfterConsumeArg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
enumUseMoveOnlyWithoutEscaping(x2)
enumConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func enumUseAfterConsumeOwnedArg(_ x2: __owned EnumTy) { // expected-error {{'x2' consumed more than once}}
enumUseMoveOnlyWithoutEscaping(x2)
enumConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
public func enumDoubleConsume(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
enumConsume(x2) // expected-note {{consuming use}}
enumConsume(x2) // expected-note {{consuming use}}
}
public func enumDoubleConsumeArg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
enumConsume(x2) // expected-note {{consuming use}}
enumConsume(x2) // expected-note {{consuming use}}
}
public func enumDoubleConsumeOwnedArg(_ x2: __owned EnumTy) { // expected-error {{'x2' consumed more than once}}
enumConsume(x2) // expected-note {{consuming use}}
enumConsume(x2) // expected-note {{consuming use}}
}
public func enumLoopConsume(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
enumConsume(x2) // expected-note {{consuming use}}
}
}
public func enumLoopConsumeArg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
enumConsume(x2) // expected-note {{consuming use}}
}
}
public func enumLoopConsumeOwnedArg(_ x2: __owned EnumTy) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
enumConsume(x2) // expected-note {{consuming use}}
}
}
public func enumDiamond(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
if boolValue {
enumConsume(x2)
} else {
enumConsume(x2)
}
}
public func enumDiamondArg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
if boolValue {
enumConsume(x2) // expected-note {{consuming use}}
} else {
enumConsume(x2) // expected-note {{consuming use}}
}
}
public func enumDiamondOwnedArg(_ x2: __owned EnumTy) {
if boolValue {
enumConsume(x2)
} else {
enumConsume(x2)
}
}
public func enumDiamondInLoop(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
if boolValue {
enumConsume(x2) // expected-note {{consuming use}}
} else {
enumConsume(x2) // expected-note {{consuming use}}
}
}
}
public func enumDiamondInLoopArg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
if boolValue {
enumConsume(x2) // expected-note {{consuming use}}
} else {
enumConsume(x2) // expected-note {{consuming use}}
}
}
}
public func enumDiamondInLoopOwnedArg(_ x2: __owned EnumTy) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
if boolValue {
enumConsume(x2) // expected-note {{consuming use}}
} else {
enumConsume(x2) // expected-note {{consuming use}}
}
}
}
public func enumAssignToVar1(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func enumAssignToVar1Arg(_ x: EnumTy, _ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func enumAssignToVar1OwnedArg(_ x: EnumTy, _ x2: __owned EnumTy) { // expected-error {{'x2' consumed more than once}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func enumAssignToVar2(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
enumUseMoveOnlyWithoutEscaping(x3)
}
public func enumAssignToVar2Arg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
enumUseMoveOnlyWithoutEscaping(x3)
}
public func enumAssignToVar2OwnedArg(_ x2: __owned EnumTy) { // expected-error {{'x2' consumed more than once}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x2 // expected-note {{consuming use}}
enumUseMoveOnlyWithoutEscaping(x3)
}
public func enumAssignToVar3(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
var x3 = x2
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func enumAssignToVar3Arg(_ x: EnumTy, _ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func enumAssignToVar3OwnedArg(_ x: EnumTy, _ x2: __owned EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
var x3 = x2
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func enumAssignToVar4(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
let x3 = x2 // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
print(x3)
}
public func enumAssignToVar4Arg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
let x3 = x2 // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
print(x3)
}
public func enumAssignToVar4OwnedArg(_ x2: __owned EnumTy) { // expected-error {{'x2' consumed more than once}}
let x3 = x2 // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
print(x3)
}
public func enumAssignToVar5(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
var x3 = x2 // expected-note {{consuming use}}
// TODO: Need to mark this as the lifetime extending use. We fail
// appropriately though.
enumUseMoveOnlyWithoutEscaping(x2)
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func enumAssignToVar5Arg(_ x: EnumTy, _ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
// TODO: Need to mark this as the lifetime extending use. We fail
// appropriately though.
enumUseMoveOnlyWithoutEscaping(x2)
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func enumAssignToVar5OwnedArg(_ x: EnumTy, _ x2: __owned EnumTy) { // expected-error {{'x2' consumed more than once}}
// expected-error @-1 {{'x' has guaranteed ownership but was consumed}}
var x3 = x2 // expected-note {{consuming use}}
// TODO: Need to mark this as the lifetime extending use. We fail
// appropriately though.
enumUseMoveOnlyWithoutEscaping(x2)
x3 = x // expected-note {{consuming use}}
print(x3)
}
public func enumPatternMatchIfLet1(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
if case let .klass(x) = x2 { // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x)
}
if case let .klass(x) = x2 { // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x)
}
}
public func enumPatternMatchIfLet1Arg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
if case let .klass(x) = x2 { // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x)
}
if case let .klass(x) = x2 { // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x)
}
}
public func enumPatternMatchIfLet1OwnedArg(_ x2: __owned EnumTy) { // expected-error {{'x2' consumed more than once}}
if case let .klass(x) = x2 { // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x)
}
if case let .klass(x) = x2 { // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x)
}
}
public func enumPatternMatchIfLet2(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
for _ in 0..<1024 {
if case let .klass(x) = x2 { // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x)
}
}
}
public func enumPatternMatchIfLet2Arg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
for _ in 0..<1024 {
if case let .klass(x) = x2 { // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x)
}
}
}
public func enumPatternMatchIfLet2OwnedArg(_ x2: __owned EnumTy) { // expected-error {{'x2' consumed more than once}}
for _ in 0..<1024 {
if case let .klass(x) = x2 { // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x)
}
}
}
// This is wrong.
public func enumPatternMatchSwitch1(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
switch x2 { // expected-note {{consuming use}}
case let .klass(k):
classUseMoveOnlyWithoutEscaping(k)
// This should be flagged as the use after free use. We are atleast
// erroring though.
enumUseMoveOnlyWithoutEscaping(x2)
case .int:
break
}
}
public func enumPatternMatchSwitch1Arg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
switch x2 { // expected-note {{consuming use}}
case let .klass(k):
classUseMoveOnlyWithoutEscaping(k)
// This should be flagged as the use after free use. We are atleast
// erroring though.
enumUseMoveOnlyWithoutEscaping(x2)
case .int:
break
}
}
public func enumPatternMatchSwitch1OwnedArg(_ x2: __owned EnumTy) { // expected-error {{'x2' consumed more than once}}
switch x2 { // expected-note {{consuming use}}
case let .klass(k):
classUseMoveOnlyWithoutEscaping(k)
// This should be flagged as the use after free use. We are atleast
// erroring though.
enumUseMoveOnlyWithoutEscaping(x2)
case .int:
break
}
}
public func enumPatternMatchSwitch2(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
switch x2 {
case let .klass(k):
classUseMoveOnlyWithoutEscaping(k)
case .int:
break
}
}
public func enumPatternMatchSwitch2Arg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
switch x2 { // expected-note {{consuming use}}
case let .klass(k):
classUseMoveOnlyWithoutEscaping(k)
case .int:
break
}
}
public func enumPatternMatchSwitch2OwnedArg(_ x2: __owned EnumTy) {
switch x2 {
case let .klass(k):
classUseMoveOnlyWithoutEscaping(k)
case .int:
break
}
}
// QOI: We can do better here. We should also flag x2
public func enumPatternMatchSwitch2WhereClause(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
switch x2 { // expected-note {{consuming use}}
case let .klass(k)
where x2.doSomething():
classUseMoveOnlyWithoutEscaping(k)
case .int:
break
case .klass:
break
}
}
public func enumPatternMatchSwitch2WhereClauseArg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
switch x2 { // expected-note {{consuming use}}
case let .klass(k)
where x2.doSomething():
classUseMoveOnlyWithoutEscaping(k)
case .int:
break
case .klass:
break
}
}
public func enumPatternMatchSwitch2WhereClauseOwnedArg(_ x2: __owned EnumTy) { // expected-error {{'x2' consumed more than once}}
switch x2 { // expected-note {{consuming use}}
case let .klass(k)
where x2.doSomething():
classUseMoveOnlyWithoutEscaping(k)
case .int:
break
case .klass:
break
}
}
public func enumPatternMatchSwitch2WhereClause2(_ x: EnumTy) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
switch x2 {
case let .klass(k)
where boolValue:
classUseMoveOnlyWithoutEscaping(k)
case .int:
break
case .klass:
break
}
}
public func enumPatternMatchSwitch2WhereClause2Arg(_ x2: EnumTy) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
switch x2 { // expected-note {{consuming use}}
case let .klass(k)
where boolValue:
classUseMoveOnlyWithoutEscaping(k)
case .int:
break
case .klass:
break
}
}
public func enumPatternMatchSwitch2WhereClause2OwnedArg(_ x2: __owned EnumTy) {
switch x2 {
case let .klass(k)
where boolValue:
classUseMoveOnlyWithoutEscaping(k)
case .int:
break
case .klass:
break
}
}
/////////////////////////////
// Closure and Defer Tests //
/////////////////////////////
public func closureClassUseAfterConsume1(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let f = { // expected-note {{consuming use}}
let x2 = x // expected-error {{'x2' consumed more than once}}
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
f()
}
public func closureClassUseAfterConsume2(_ argX: Klass) {
let f = { (_ x: Klass) in // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
f(argX)
}
public func closureClassUseAfterConsumeArg(_ argX: Klass) {
// TODO: Fix this
let f = { (_ x2: Klass) in // expected-error {{'x2' has guaranteed ownership but was consumed}}
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2) // expected-note {{consuming use}}
print(x2) // expected-note {{consuming use}}
}
f(argX)
}
public func closureCaptureClassUseAfterConsume(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
let f = {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
f()
}
public func closureCaptureClassUseAfterConsumeError(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
let f = { // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
f()
let x3 = x2 // expected-note {{consuming use}}
let _ = x3
}
public func closureCaptureClassArgUseAfterConsume(_ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
let f = { // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
f()
}
public func closureCaptureClassOwnedArgUseAfterConsume(_ x2: __owned Klass) {
let f = {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
f()
}
public func closureCaptureClassOwnedArgUseAfterConsume2(_ x2: __owned Klass) { // expected-error {{'x2' consumed more than once}}
let f = { // expected-note {{consuming use}}
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
f()
let x3 = x2 // expected-note {{consuming use}}
let _ = x3
}
public func deferCaptureClassUseAfterConsume(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
defer {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
print(x) // expected-note {{consuming use}}
}
public func deferCaptureClassUseAfterConsume2(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
// TODO: Defer error is b/c we have to lifetime extend x2 for the defer. The
// use is a guaranteed use, so we don't emit an error on that use.
defer {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
let x3 = x2 // expected-note {{consuming use}}
let _ = x3
}
public func deferCaptureClassArgUseAfterConsume(_ x2: Klass) {
classUseMoveOnlyWithoutEscaping(x2)
defer {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
print("foo")
}
public func deferCaptureClassOwnedArgUseAfterConsume(_ x2: __owned Klass) {
defer {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
print("foo")
}
public func deferCaptureClassOwnedArgUseAfterConsume2(_ x2: __owned Klass) { // expected-error {{'x2' consumed more than once}}
defer {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
print(x2) // expected-note {{consuming use}}
}
public func closureAndDeferCaptureClassUseAfterConsume(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
let f = {
defer {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
print("foo")
}
f()
}
public func closureAndDeferCaptureClassUseAfterConsume2(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
let f = {
classConsume(x2)
defer {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
print("foo")
}
f()
}
public func closureAndDeferCaptureClassUseAfterConsume3(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
let f = { // expected-note {{consuming use}}
classConsume(x2)
defer {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
print("foo")
}
f()
classConsume(x2) // expected-note {{consuming use}}
}
public func closureAndDeferCaptureClassArgUseAfterConsume(_ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
let f = { // expected-note {{consuming use}}
defer {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
print("foo")
}
f()
}
public func closureAndDeferCaptureClassOwnedArgUseAfterConsume(_ x2: __owned Klass) {
let f = {
defer {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
print("foo")
}
f()
}
public func closureAndDeferCaptureClassOwnedArgUseAfterConsume2(_ x2: __owned Klass) { // expected-error {{'x2' consumed more than once}}
let f = { // expected-note {{consuming use}}
defer {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
print("foo")
}
f()
print(x2) // expected-note {{consuming use}}
}
public func closureAndClosureCaptureClassUseAfterConsume(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-note {{consuming use}}
let f = {
let g = {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
g()
}
f()
}
public func closureAndClosureCaptureClassUseAfterConsume2(_ x: Klass) { // expected-error {{'x' has guaranteed ownership but was consumed}}
let x2 = x // expected-error {{'x2' consumed more than once}}
// expected-note @-1 {{consuming use}}
let f = { // expected-note {{consuming use}}
let g = {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
g()
}
f()
print(x2) // expected-note {{consuming use}}
}
public func closureAndClosureCaptureClassArgUseAfterConsume(_ x2: Klass) { // expected-error {{'x2' has guaranteed ownership but was consumed}}
let f = { // expected-note {{consuming use}}
let g = {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
g()
}
f()
}
public func closureAndClosureCaptureClassOwnedArgUseAfterConsume(_ x2: __owned Klass) {
let f = {
let g = {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
g()
}
f()
}
public func closureAndClosureCaptureClassOwnedArgUseAfterConsume2(_ x2: __owned Klass) { // expected-error {{'x2' consumed more than once}}
let f = { // expected-note {{consuming use}}
let g = {
classUseMoveOnlyWithoutEscaping(x2)
classConsume(x2)
print(x2)
}
g()
}
f()
print(x2) // expected-note {{consuming use}}
}
/////////////////////////////
// Tests For Move Operator //
/////////////////////////////
func moveOperatorTest(_ k: __owned Klass) {
let k2 = k // expected-error {{'k2' consumed more than once}}
let k3 = _move k2 // expected-note {{consuming use}}
let _ = _move k2 // expected-note {{consuming use}}
let _ = k3
}
/////////////////////////////////////////
// Black hole initialization test case//
/////////////////////////////////////////
func blackHoleTestCase(_ k: __owned Klass) {
let k2 = k // expected-error {{'k2' consumed more than once}}
let _ = k2 // expected-note {{consuming use}}
let _ = k2 // expected-note {{consuming use}}
}
| apache-2.0 | 6341f0264e9492b72919fc0f13906cb8 | 35.247765 | 160 | 0.657271 | 3.722718 | false | false | false | false |
little2s/NoChat | Sources/NoChat/ItemCell.swift | 1 | 922 | //
// ItemCell.swift
//
//
// Created by yinglun on 2020/8/9.
//
import UIKit
public protocol ItemCellDelegate: AnyObject { }
open class ItemCell: UICollectionViewCell {
open class var reuseIdentifier: String { NSStringFromClass(Self.self) }
open weak var delegate: ItemCellDelegate?
open var layout: AnyItemLayout? {
didSet {
if let size = layout?.size, size != itemView.frame.size {
itemView.frame = CGRect(origin: .zero, size: size)
}
}
}
public let itemView = UIView()
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
itemView.frame = contentView.bounds
contentView.addSubview(itemView)
}
}
| mit | 574d2c96267bd3c91034b94bcb5e6e6e | 20.952381 | 75 | 0.592191 | 4.432692 | false | false | false | false |
vchuo/Photoasis | Photoasis/Classes/Views/Views/TableViewCells/POTableViewCell.swift | 1 | 1951 | //
// POTableViewCell.swift
// アプリすべてのテーブルビューセルはこのクラスを継承する。
//
// Created by Vernon Chuo Chian Khye on 2017/02/25.
// Copyright © 2017 Vernon Chuo Chian Khye. All rights reserved.
//
import UIKit
class POTableViewCell: UITableViewCell {
// MARK: - Public Properties
let queue = POSerialOperationQueue()
// MARK: - Init
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK: - Public Functions
/**
テーブルビューセルとセルのサブビューのセットアップを設定する。
*/
func configureSetupForViewAndSubviews() {
self.translatesAutoresizingMaskIntoConstraints = true
self.selectionStyle = .None
self.opaque = true
self.clipsToBounds = true
self.subviews.forEach { subview in
subview.translatesAutoresizingMaskIntoConstraints = true
subview.opaque = true
subview.clipsToBounds = true
}
}
/**
テーブルセルのシリアルオパレーションキューの実行ブロックを更新。
- parameter block: 実行ブロック
*/
func updateSerialOperationQueueWith(block: () -> Void) {
self.queue.cancelAllOperations()
let operation = NSBlockOperation()
operation.addExecutionBlock(block)
self.queue.addOperation(operation)
}
// MARK: - Private Functions
/**
セットアップ。
*/
private func setup() {
self.backgroundColor = UIColor.whiteColor()
self.exclusiveTouch = true
self.contentView.exclusiveTouch = true
}
}
| mit | fb2946f0a2b13318729676a0b1bf8aac | 23.535211 | 74 | 0.611366 | 4.512953 | false | false | false | false |
nsdictionary/CFCityPickerVC | CFCityPickerVC/CFCityPickerVC/View/HeaderItemView.swift | 4 | 3792 | //
// HeaderItemView.swift
// CFCityPickerVC
//
// Created by 冯成林 on 15/7/30.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
class HeaderItemView: UIView {
@IBOutlet weak var itemLabel: UILabel!
@IBOutlet weak var lineView: UIView!
@IBOutlet weak var lineViewHC: NSLayoutConstraint!
@IBOutlet weak var msgLabel: UILabel!
@IBOutlet weak var contentView: CFCPContentView!
var cityModles: [CFCityPickerVC.CityModel]!{didSet{dataCome()}}
}
extension HeaderItemView{
override func awakeFromNib() {
super.awakeFromNib()
lineViewHC.constant = 0.5
}
func dataCome(){
self.msgLabel.hidden = cityModles.count != 0
self.contentView.cityModles = cityModles
}
class func getHeaderItemView(title: String) -> HeaderItemView{
let itemView = NSBundle.mainBundle().loadNibNamed("HeaderItemView", owner: nil, options: nil).first as! HeaderItemView
itemView.itemLabel.text = title
return itemView
}
}
extension CFCPContentView{
class ItemBtn: UIButton {
var cityModel: CFCityPickerVC.CityModel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
/** 视图准备 */
self.viewPrepare()
}
override init(frame: CGRect) {
super.init(frame: frame)
/** 视图准备 */
self.viewPrepare()
}
/** 视图准备 */
func viewPrepare(){
self.setTitleColor(CFCityPickerVC.rgba(31, g: 31, b: 31, a: 1), forState: UIControlState.Normal)
self.setTitleColor(CFCityPickerVC.rgba(141, g: 141, b: 141, a: 1), forState: UIControlState.Highlighted)
self.titleLabel?.font = UIFont.systemFontOfSize(15)
self.layer.cornerRadius = 4
self.layer.masksToBounds = true
self.backgroundColor = CFCityPickerVC.rgba(241, g: 241, b: 241, a: 1)
}
}
}
class CFCPContentView: UIView{
var cityModles: [CFCityPickerVC.CityModel]!{didSet{btnsPrepare()}}
let maxRowCount = 4
var btns: [ItemBtn] = []
/** 添加按钮 */
func btnsPrepare(){
if cityModles == nil {return}
for cityModel in cityModles{
let itemBtn = ItemBtn()
itemBtn.setTitle(cityModel.name, forState: UIControlState.Normal)
itemBtn.addTarget(self, action: "btnClick:", forControlEvents: UIControlEvents.TouchUpInside)
btns.append(itemBtn)
itemBtn.cityModel = cityModel
self.addSubview(itemBtn)
}
}
/** 按钮点击事件 */
func btnClick(btn: ItemBtn){
NSNotificationCenter.defaultCenter().postNotificationName(CityChoosedNoti, object: nil, userInfo: ["citiModel":btn.cityModel])
}
override func layoutSubviews() {
super.layoutSubviews()
if btns.count == 0 {return}
let marginForRow: CGFloat = 16.0
let marginForCol: CGFloat = 13
let width: CGFloat = (self.bounds.size.width - (CGFloat(maxRowCount - 1)) * marginForRow) / CGFloat(maxRowCount)
let height: CGFloat = 30
for (index,btn) in btns.enumerate() {
let row = index % maxRowCount
let col = index / maxRowCount
let x = (width + marginForRow) * CGFloat(row)
let y = (height + marginForCol) * CGFloat(col)
btn.frame = CGRectMake(x, y, width, height)
}
}
}
| mit | f39d687d12a7a55e7074d98fa1fadf85 | 24.751724 | 134 | 0.567756 | 4.515115 | false | false | false | false |
WestlakeAPC/game-off-2016 | external/Fiber2D/Fiber2D/Setup.swift | 1 | 1197 | //
// Setup.swift
// Fiber2D
//
// Created by Andrey Volodin on 02.11.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
public class Setup {
public static let shared = Setup()
/**
Global content scale for the app.
This is the number of pixels on the screen that are equivalent to a point in Fiber2D.
*/
public var contentScale: Float = 1.0
/**
Minimum content scale of assets such as textures, TTF labels or render textures.
Normally you want this value to be the same as the contentScale, but on Mac you may want a higher value since the user could resize the window.
*/
public var assetScale: Float = 1.0
/**
UI scaling factor. Positions and content sizes are scale by this factor if the position type is set to UIScale.
This is useful for creating UIs that have the same physical size (ex: centimeters) on different devices.
This also affects the loading of assets marked as having a UIScale.
*/
public var UIScale: Float = 1.0
/**
Default fixed update interval that will be used when initializing schedulers.
*/
public var fixedUpdateInterval: Float = 1.0 / 60.0
}
| apache-2.0 | 3f76ee2edb55d22ed3c1517e67f29dbe | 33.171429 | 148 | 0.677258 | 4.196491 | false | false | false | false |
brentdax/swift | stdlib/public/SDK/Network/NWProtocolTLS.swift | 6 | 1879 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 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
//
//===----------------------------------------------------------------------===//
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
public class NWProtocolTLS : NWProtocol {
public static let definition: NWProtocolDefinition = {
NWProtocolDefinition(nw_protocol_copy_tls_definition(), "tls")
}()
public class Options : NWProtocolOptions {
/// Access the sec_protocol_options_t for a given network protocol
/// options instance. See <Security/SecProtocolOptions.h> for functions
/// to further configure security options.
public var securityProtocolOptions: sec_protocol_options_t {
return nw_tls_copy_sec_protocol_options(self.nw)
}
/// Create TLS options to set in an NWParameters.ProtocolStack
public init() {
super.init(nw_tls_create_options())
}
override internal init(_ nw: nw_protocol_options_t) {
super.init(nw)
}
}
/// Access TLS metadata using NWConnection.metadata(protocolDefinition: NWProtocolTLS.definition)
/// or in received ContentContext
public class Metadata: NWProtocolMetadata {
/// Access the sec_protocol_metadata_t for a given network protocol
/// metadata instance. See <Security/SecProtocolMetadata.h> for functions
/// to further access security metadata.
public var securityProtocolMetadata: sec_protocol_metadata_t {
return nw_tls_copy_sec_protocol_metadata(self.nw)
}
override internal init(_ nw: nw_protocol_metadata_t) {
super.init(nw)
}
}
}
| apache-2.0 | 55ffcef688005026e1af13fe1756ffe8 | 35.843137 | 98 | 0.675891 | 3.955789 | false | false | false | false |
bsorrentino/slidesOnTV | slides/slides/SlideshareItem.swift | 1 | 2749 | //
// SlideshareItem.swift
// slides
//
// Created by softphone on 04/07/21.
// Copyright © 2021 bsorrentino. All rights reserved.
//
import Foundation
import UIKit
struct SlidehareItem : SlideItem {
static let Title = "title"
static let DownloadUrl = "downloadurl"
static let ITEMID = "id"
static let Url = "url" // permalink
static let Created = "created"
static let Updated = "updated"
static let Format = "format"
static let Language = "language"
static let Thumbnail = "thumbnailxlargeurl" // thumbnail, thumbnailsmallurl, thumbnailxlargeurl, thumbnailxxlargeurl
static let ThumbnailSize = "thumbnailsize"
static let Query = "query"
static let ResultOffset = "resultoffset"
static let NumResults = "numresults"
static let TotalResults = "totalresults"
static let Message = "message"
static let names = [
Title,
DownloadUrl,
ITEMID,
Url,
Updated,
Format,
Thumbnail,
ThumbnailSize,
Created,
Language,
// META
Query,
ResultOffset,
NumResults,
TotalResults,
// Error
Message
]
let data:Slideshow
let thumbnailSize: CGSize
init( data:Slideshow ) {
self.data = data
if let result = data[SlidehareItem.ThumbnailSize],
let value = result.data( using: .utf8),
let points = try? JSONDecoder().decode([Int].self, from: value ) {
thumbnailSize = CGSize( width: points[0], height: points[1] )
}
else {
thumbnailSize = CGSize(width:170, height: 130)
}
print( "thumbnailSize: \(thumbnailSize)" )
}
// Equatable
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.id == rhs.id
}
// Identifiable
var id: String {
self.data[SlidehareItem.ITEMID]!
}
var title: String {
guard let result = self.data[SlidehareItem.Title] else {
return ""
}
return result
}
var downloadUrl: URL? {
guard let result = self.data[SlidehareItem.DownloadUrl] else {
return nil
}
return URL(string:result)
}
var thumbnail: String? {
guard let result = self.data[SlidehareItem.Thumbnail] else {
return nil
}
return result.starts(with: "http") ? result : "https:\(result)"
}
var created: String? {
self.data[SlidehareItem.Created]
}
var updated: String? {
self.data[SlidehareItem.Updated]
}
}
| mit | 28c79c759f173aee5f69648d018cb731 | 23.105263 | 127 | 0.553857 | 4.280374 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Controller/BaseFilterSortController.swift | 1 | 3401 | //
// BaseFilterSortController.swift
// DereGuide
//
// Created by zzk on 2017/1/12.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import SnapKit
class BaseFilterSortController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
var toolbar: UIToolbar!
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView()
tableView.register(FilterTableViewCell.self, forCellReuseIdentifier: "FilterCell")
tableView.register(SortTableViewCell.self, forCellReuseIdentifier: "SortCell")
tableView.delegate = self
tableView.dataSource = self
tableView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 44, right: 0)
tableView.tableFooterView = UIView.init(frame: CGRect.zero)
tableView.estimatedRowHeight = 50
tableView.cellLayoutMarginsFollowReadableWidth = false
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.left.right.bottom.equalToSuperview()
make.top.equalTo(topLayoutGuide.snp.bottom)
}
toolbar = UIToolbar()
toolbar.tintColor = Color.parade
view.addSubview(toolbar)
toolbar.snp.makeConstraints { (make) in
if #available(iOS 11.0, *) {
make.left.right.equalToSuperview()
make.bottom.equalTo(view.safeAreaLayoutGuide)
} else {
make.bottom.left.right.equalToSuperview()
}
make.height.equalTo(44)
}
let leftSpaceItem = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
leftSpaceItem.width = 0
let doneItem = UIBarButtonItem.init(title: NSLocalizedString("完成", comment: "导航栏按钮"), style: .done, target: self, action: #selector(doneAction))
let middleSpaceItem = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let resetItem = UIBarButtonItem.init(title: NSLocalizedString("重置", comment: "导航栏按钮"), style: .plain, target: self, action: #selector(resetAction))
let rightSpaceItem = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
rightSpaceItem.width = 0
toolbar.setItems([leftSpaceItem, resetItem, middleSpaceItem, doneItem, rightSpaceItem], animated: false)
}
@objc func doneAction() {
}
@objc func resetAction() {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return NSLocalizedString("筛选", comment: "")
} else {
return NSLocalizedString("排序", comment: "")
}
}
}
| mit | 5547bec210af3c8f26c7407790983068 | 33.306122 | 155 | 0.641582 | 5.093939 | false | false | false | false |
Workday/DrawAction | DrawAction/DrawBorder.swift | 1 | 2349 | /*
* Copyright 2016 Workday, Inc.
*
* This software is available under the MIT license.
* Please see the LICENSE.txt file in this project.
*/
import Foundation
/**
Action that strokes a border on the current rect or path
*/
final public class DrawBorder : DrawAction {
fileprivate let color: UIColor
fileprivate let lineWidth: CGFloat
fileprivate let dashedLineLengths: [CGFloat]?
/**
Initializes a DrawBorder
- parameter color: The color of the border
- parameter lineWidth: The width of the border
- parameter dashedLineLengths: If non-nil, specifies the lengths of painted and unpainted segments as the border is
drawn. For example, passing [2,3] would cause the border to draw 2 points of border followed by 3 points of space in a repeating pattern.
*/
public init(color: UIColor, lineWidth: CGFloat, dashedLineLengths: [CGFloat]?) {
self.color = color
self.lineWidth = lineWidth
self.dashedLineLengths = dashedLineLengths
super.init()
}
/**
Initializes a DrawBorder with a lineWidth of 1
- parameter color: The color of the border
*/
convenience public init(color: UIColor) {
self.init(color: color, lineWidth: 1)
}
/**
Initializes a DrawBorder with the specified lineWidth and color
- parameter color: The color of the border
- parameter lineWidth: The width of the border
*/
convenience public init(color: UIColor, lineWidth: CGFloat) {
self.init(color: color, lineWidth: lineWidth, dashedLineLengths: nil)
}
override func performActionInContext(_ context: DrawContext) {
context.performGraphicsActions { gContext in
gContext.setLineWidth(lineWidth)
gContext.setStrokeColor(color.cgColor)
let strokeClosure = {
if context.addPathToGraphicsContext() {
gContext.strokePath()
} else {
gContext.stroke(context.rect)
}
}
if let lineLengths = dashedLineLengths {
gContext.setLineDash(phase: 0, lengths: lineLengths)
strokeClosure()
} else {
strokeClosure()
}
}
next?.performActionInContext(context)
}
}
| mit | 9bd93a00a274387c37c13d0aa4b12f58 | 30.743243 | 142 | 0.63261 | 4.89375 | false | false | false | false |
shyamalschandra/swix | swix_ios_app/swix_ios_app/swix/matrix/m-complex-math.swift | 6 | 3302 | //
// twoD-complex-math.swift
// swix
//
// Created by Scott Sievert on 7/15/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Swift
import Accelerate
func rank(x:matrix)->Double{
let (_, S, _) = svd(x, compute_uv:false)
let m:Double = (x.shape.0 < x.shape.1 ? x.shape.1 : x.shape.0).double
let tol = S.max() * m * DOUBLE_EPSILON
return sum(S > tol)
}
func dot(x: matrix, y: matrix) -> matrix{
return x.dot(y)
}
func dot(A: matrix, x: ndarray) -> ndarray{
return A.dot(x)
}
func svd(x: matrix, compute_uv:Bool=true) -> (matrix, ndarray, matrix){
let (m, n) = x.shape
let nS = m < n ? m : n // number singular values
let sigma = zeros(nS)
let vt = zeros((n,n))
var u = zeros((m,m))
var xx = zeros_like(x)
xx.flat = x.flat
xx = xx.T
let c_uv:CInt = compute_uv==true ? 1 : 0
svd_objc(!xx, m.cint, n.cint, !sigma, !vt, !u, c_uv)
// to get the svd result to match Python
let v = transpose(vt)
u = transpose(u)
return (u, sigma, v)
}
func pinv(x:matrix)->matrix{
var (u, s, v) = svd(x)
let m = u.shape.0
let n = v.shape.1
let ma = m < n ? n : m
let cutoff = DOUBLE_EPSILON * ma.double * max(s)
let i = s > cutoff
let ipos = argwhere(i)
s[ipos] = 1 / s[ipos]
let ineg = argwhere(1-i)
s[ineg] = zeros_like(ineg)
var z = zeros((n, m))
z["diag"] = s
let res = v.T.dot(z).dot(u.T)
return res
}
func inv(x: matrix) -> matrix{
assert(x.shape.0 == x.shape.1, "To take an inverse of a matrix, the matrix must be square. If you want the inverse of a rectangular matrix, use psuedoinverse.")
let y = x.copy()
let (M, N) = x.shape
var ipiv:Array<__CLPK_integer> = Array(count:M*M, repeatedValue:0)
var lwork:__CLPK_integer = __CLPK_integer(N*N)
// var work:[CDouble] = [CDouble](count:lwork, repeatedValue:0)
var work = [CDouble](count: Int(lwork), repeatedValue: 0.0)
var info:__CLPK_integer=0
var nc = __CLPK_integer(N)
dgetrf_(&nc, &nc, !y, &nc, &ipiv, &info)
dgetri_(&nc, !y, &nc, &ipiv, &work, &lwork, &info)
return y
}
func solve(A: matrix, b: ndarray) -> ndarray{
let (m, n) = A.shape
assert(b.n == m, "Ax = b, A.rows == b.n. Sizes must match which makes sense mathematically")
assert(n == m, "Matrix must be square -- dictated by OpenCV")
let x = zeros(n)
CVWrapper.solve(!A, b:!b, x:!x, m:m.cint, n:n.cint)
return x
}
func eig(x: matrix)->ndarray{
// matrix, value, vectors
let (m, n) = x.shape
assert(m == n, "Input must be square")
let value_real = zeros(m)
let value_imag = zeros(n)
var vector = zeros((n,n))
var work:[Double] = Array(count:n*n, repeatedValue:0.0)
var lwork = __CLPK_integer(4 * n)
var info = __CLPK_integer(1)
// don't compute right or left eigenvectors
let job = "N"
var jobvl = (job.cStringUsingEncoding(NSUTF8StringEncoding)?[0])!
var jobvr = (job.cStringUsingEncoding(NSUTF8StringEncoding)?[0])!
work[0] = Double(lwork)
var nc = __CLPK_integer(n)
dgeev_(&jobvl, &jobvr, &nc, !x, &nc,
!value_real, !value_imag, !vector, &nc, !vector, &nc,
&work, &lwork, &info)
vector = vector.T
return value_real
}
| mit | f559fb02b3bb66a83cebdb8494d71c26 | 26.747899 | 164 | 0.58298 | 2.871304 | false | false | false | false |
wireapp/wire-ios | Wire-iOS Tests/Views/RoundedSegmentedViewTests.swift | 1 | 1917 | //
// Wire
// Copyright (C) 2021 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
import SnapshotTesting
@testable import Wire
class RoundedSegmentedViewTests: XCTestCase {
var sut: RoundedSegmentedView!
override func setUp() {
super.setUp()
}
override func tearDown() {
sut = nil
super.tearDown()
}
private func createView(with items: [String]) -> RoundedSegmentedView {
let view = RoundedSegmentedView()
items.forEach {
view.addButton(withTitle: $0, actionHandler: {})
}
view.frame = CGRect(x: 0, y: 0, width: 95, height: 25)
return view
}
func testTwoItems_Unselected() {
// GIVEN / WHEN
sut = createView(with: ["one", "two"])
// THEN
verify(matching: sut)
}
func testTwoItems_FirstSelected() {
// GIVEN / WHEN
sut = createView(with: ["one", "two"])
sut.setSelected(true, forItemAt: 0)
// THEN
verify(matching: sut)
}
func testTwoItems_SecondSelected_AfterFirst() {
// GIVEN / WHEN
sut = createView(with: ["one", "two"])
sut.setSelected(true, forItemAt: 0)
sut.setSelected(true, forItemAt: 1)
// THEN
verify(matching: sut)
}
}
| gpl-3.0 | f0230472fc7ae53b783fd8cf28fa2226 | 26.782609 | 75 | 0.63276 | 4.298206 | false | true | false | false |
firebase/firebase-ios-sdk | Firestore/Swift/Source/Codable/ExplicitNull.swift | 2 | 1872 | /*
* Copyright 2019 Google
*
* 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 FirebaseFirestore
/// Wraps an `Optional` field in a `Codable` object such that when the field
/// has a `nil` value it will encode to a null value in Firestore. Normally,
/// optional fields are omitted from the encoded document.
///
/// This is useful for ensuring a field is present in a Firestore document,
/// even when there is no associated value.
@propertyWrapper
public struct ExplicitNull<Value> {
var value: Value?
public init(wrappedValue value: Value?) {
self.value = value
}
public var wrappedValue: Value? {
get { value }
set { value = newValue }
}
}
extension ExplicitNull: Equatable where Value: Equatable {}
extension ExplicitNull: Hashable where Value: Hashable {}
extension ExplicitNull: Encodable where Value: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if let value = value {
try container.encode(value)
} else {
try container.encodeNil()
}
}
}
extension ExplicitNull: Decodable where Value: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
value = nil
} else {
value = try container.decode(Value.self)
}
}
}
| apache-2.0 | 7414a14d4548f0a10008606f15cc5c08 | 28.714286 | 76 | 0.711538 | 4.293578 | false | false | false | false |
benlangmuir/swift | test/Distributed/distributed_actor_var_implicitly_async_throws.swift | 5 | 2516 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift
// RUN: %target-swift-frontend -typecheck -verify -disable-availability-checking -I %t 2>&1 %s
// REQUIRES: concurrency
// REQUIRES: distributed
import Distributed
import FakeDistributedActorSystems
@available(SwiftStdlib 5.5, *)
typealias DefaultDistributedActorSystem = FakeActorSystem
struct NotCodable {}
distributed actor D {
// expected-note@+1{{access to property 'normal' is only permitted within distributed actor 'D'}}
var normal: String = "normal"
// expected-note@+1{{access to property 'computed' is only permitted within distributed actor 'D'}}
var computed: String {
"normal"
}
// expected-error@+1{{property 'dlet' cannot be 'distributed', only computed properties can}}
distributed let dlet: String = "illegal"
// expected-error@+1{{distributed property 'dletvar' cannot be 'distributed', only computed properties can}}
distributed var dletvar: String = "illegal"
// OK:
distributed var dist: String {
"dist"
}
// FIXME: The following should be accepted.
/*
distributed var distGet: String {
get distributed {
"okey"
}
}
*/
distributed var distSetGet: String { // expected-error {{'distributed' computed property 'distSetGet' cannot have setter}}
set distributed { // expected-error {{expected '{' to start setter definition}}
_ = newValue
}
get distributed {
"okey"
}
}
// expected-error@+1{{'distributed' property 'hello' cannot be 'static'}}
static distributed var hello: String {
"nope!"
}
// expected-error@+1{{result type 'NotCodable' of distributed property 'notCodable' does not conform to serialization requirement 'Codable'}}
distributed var notCodable: NotCodable {
.init()
}
//expected-error@+1{{'distributed' computed property 'dist_nope' cannot have setter}}
distributed var dist_nope: String {
get {
"dist"
}
set {
// ignore
}
}
}
func test_outside(distributed: D) async throws {
_ = distributed.normal
// expected-error@-1{{distributed actor-isolated property 'normal' can not be accessed from a non-isolated context}}
_ = distributed.computed
// expected-error@-1{{distributed actor-isolated property 'computed' can not be accessed from a non-isolated context}}
}
| apache-2.0 | 7336e3fe6d2e558079a5cf9f04aed2b1 | 29.313253 | 219 | 0.705087 | 4.214405 | false | false | false | false |
benlangmuir/swift | stdlib/public/core/Stride.swift | 3 | 26338 | //===--- Stride.swift - Components for stride(...) iteration --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type representing continuous, one-dimensional values that can be offset
/// and measured.
///
/// You can use a type that conforms to the `Strideable` protocol with the
/// `stride(from:to:by:)` and `stride(from:through:by:)` functions. For
/// example, you can use `stride(from:to:by:)` to iterate over an
/// interval of floating-point values:
///
/// for radians in stride(from: 0.0, to: .pi * 2, by: .pi / 2) {
/// let degrees = Int(radians * 180 / .pi)
/// print("Degrees: \(degrees), radians: \(radians)")
/// }
/// // Degrees: 0, radians: 0.0
/// // Degrees: 90, radians: 1.5707963267949
/// // Degrees: 180, radians: 3.14159265358979
/// // Degrees: 270, radians: 4.71238898038469
///
/// The last parameter of these functions is of the associated `Stride`
/// type---the type that represents the distance between any two instances of
/// the `Strideable` type.
///
/// Types that have an integer `Stride` can be used as the boundaries of a
/// countable range or as the lower bound of an iterable one-sided range. For
/// example, you can iterate over a range of `Int` and use sequence and
/// collection methods.
///
/// var sum = 0
/// for x in 1...100 {
/// sum += x
/// }
/// // sum == 5050
///
/// let digits = (0..<10).map(String.init)
/// // ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
///
/// Conforming to the Strideable Protocol
/// =====================================
///
/// To add `Strideable` conformance to a custom type, choose a `Stride` type
/// that can represent the distance between two instances and implement the
/// `advanced(by:)` and `distance(to:)` methods. For example, this
/// hypothetical `Date` type stores its value as the number of days before or
/// after January 1, 2000:
///
/// struct Date: Equatable, CustomStringConvertible {
/// var daysAfterY2K: Int
///
/// var description: String {
/// // ...
/// }
/// }
///
/// The `Stride` type for `Date` is `Int`, inferred from the parameter and
/// return types of `advanced(by:)` and `distance(to:)`:
///
/// extension Date: Strideable {
/// func advanced(by n: Int) -> Date {
/// var result = self
/// result.daysAfterY2K += n
/// return result
/// }
///
/// func distance(to other: Date) -> Int {
/// return other.daysAfterY2K - self.daysAfterY2K
/// }
/// }
///
/// The `Date` type can now be used with the `stride(from:to:by:)` and
/// `stride(from:through:by:)` functions and as the bounds of an iterable
/// range.
///
/// let startDate = Date(daysAfterY2K: 0) // January 1, 2000
/// let endDate = Date(daysAfterY2K: 15) // January 16, 2000
///
/// for date in stride(from: startDate, to: endDate, by: 7) {
/// print(date)
/// }
/// // January 1, 2000
/// // January 8, 2000
/// // January 15, 2000
///
/// - Important: The `Strideable` protocol provides default implementations for
/// the equal-to (`==`) and less-than (`<`) operators that depend on the
/// `Stride` type's implementations. If a type conforming to `Strideable` is
/// its own `Stride` type, it must provide concrete implementations of the
/// two operators to avoid infinite recursion.
public protocol Strideable<Stride>: Comparable {
/// A type that represents the distance between two values.
associatedtype Stride: SignedNumeric, Comparable
/// Returns the distance from this value to the given value, expressed as a
/// stride.
///
/// If this type's `Stride` type conforms to `BinaryInteger`, then for two
/// values `x` and `y`, and a distance `n = x.distance(to: y)`,
/// `x.advanced(by: n) == y`. Using this method with types that have a
/// noninteger `Stride` may result in an approximation.
///
/// - Parameter other: The value to calculate the distance to.
/// - Returns: The distance from this value to `other`.
///
/// - Complexity: O(1)
func distance(to other: Self) -> Stride
/// Returns a value that is offset the specified distance from this value.
///
/// Use the `advanced(by:)` method in generic code to offset a value by a
/// specified distance. If you're working directly with numeric values, use
/// the addition operator (`+`) instead of this method.
///
/// func addOne<T: Strideable>(to x: T) -> T
/// where T.Stride: ExpressibleByIntegerLiteral
/// {
/// return x.advanced(by: 1)
/// }
///
/// let x = addOne(to: 5)
/// // x == 6
/// let y = addOne(to: 3.5)
/// // y = 4.5
///
/// If this type's `Stride` type conforms to `BinaryInteger`, then for a
/// value `x`, a distance `n`, and a value `y = x.advanced(by: n)`,
/// `x.distance(to: y) == n`. Using this method with types that have a
/// noninteger `Stride` may result in an approximation. If the result of
/// advancing by `n` is not representable as a value of this type, then a
/// runtime error may occur.
///
/// - Parameter n: The distance to advance this value.
/// - Returns: A value that is offset from this value by `n`.
///
/// - Complexity: O(1)
func advanced(by n: Stride) -> Self
/// Returns the next result of striding by a specified distance.
///
/// This method is an implementation detail of `Strideable`; do not call it
/// directly.
///
/// While striding, `_step(after:from:by:)` is called at each step to
/// determine the next result. At the first step, the value of `current` is
/// `(index: 0, value: start)`. At each subsequent step, the value of
/// `current` is the result returned by this method in the immediately
/// preceding step.
///
/// If the result of advancing by a given `distance` is not representable as a
/// value of this type, then a runtime error may occur.
///
/// Implementing `_step(after:from:by:)` to Customize Striding Behavior
/// ===================================================================
///
/// The default implementation of this method calls `advanced(by:)` to offset
/// `current.value` by a specified `distance`. No attempt is made to count the
/// number of prior steps, and the result's `index` is always `nil`.
///
/// To avoid incurring runtime errors that arise from advancing past
/// representable bounds, a conforming type can signal that the result of
/// advancing by a given `distance` is not representable by using `Int.min` as
/// a sentinel value for the result's `index`. In that case, the result's
/// `value` must be either the minimum representable value of this type if
/// `distance` is less than zero or the maximum representable value of this
/// type otherwise. Fixed-width integer types make use of arithmetic
/// operations reporting overflow to implement this customization.
///
/// A conforming type may use any positive value for the result's `index` as
/// an opaque state that is private to that type. For example, floating-point
/// types increment `index` with each step so that the corresponding `value`
/// can be computed by multiplying the number of steps by the specified
/// `distance`. Serially calling `advanced(by:)` would accumulate
/// floating-point rounding error at each step, which is avoided by this
/// customization.
///
/// - Parameters:
/// - current: The result returned by this method in the immediately
/// preceding step while striding, or `(index: 0, value: start)` if there
/// have been no preceding steps.
/// - start: The starting value used for the striding sequence.
/// - distance: The amount to step by with each iteration of the striding
/// sequence.
/// - Returns: A tuple of `index` and `value`; `index` may be `nil`, any
/// positive value as an opaque state private to the conforming type, or
/// `Int.min` to signal that the notional result of advancing by `distance`
/// is unrepresentable, and `value` is the next result after `current.value`
/// while striding from `start` by `distance`.
///
/// - Complexity: O(1)
static func _step(
after current: (index: Int?, value: Self),
from start: Self, by distance: Self.Stride
) -> (index: Int?, value: Self)
}
extension Strideable {
@inlinable
public static func < (x: Self, y: Self) -> Bool {
return x.distance(to: y) > 0
}
@inlinable
public static func == (x: Self, y: Self) -> Bool {
return x.distance(to: y) == 0
}
}
extension Strideable {
@inlinable // protocol-only
public static func _step(
after current: (index: Int?, value: Self),
from start: Self, by distance: Self.Stride
) -> (index: Int?, value: Self) {
return (nil, current.value.advanced(by: distance))
}
}
extension Strideable where Self: FixedWidthInteger & SignedInteger {
@_alwaysEmitIntoClient
public static func _step(
after current: (index: Int?, value: Self),
from start: Self, by distance: Self.Stride
) -> (index: Int?, value: Self) {
let value = current.value
let (partialValue, overflow) =
Self.bitWidth >= Self.Stride.bitWidth ||
(value < (0 as Self)) == (distance < (0 as Self.Stride))
? value.addingReportingOverflow(Self(distance))
: (Self(Self.Stride(value) + distance), false)
return overflow
? (.min, distance < (0 as Self.Stride) ? .min : .max)
: (nil, partialValue)
}
}
extension Strideable where Self: FixedWidthInteger & UnsignedInteger {
@_alwaysEmitIntoClient
public static func _step(
after current: (index: Int?, value: Self),
from start: Self, by distance: Self.Stride
) -> (index: Int?, value: Self) {
let (partialValue, overflow) = distance < (0 as Self.Stride)
? current.value.subtractingReportingOverflow(Self(-distance))
: current.value.addingReportingOverflow(Self(distance))
return overflow
? (.min, distance < (0 as Self.Stride) ? .min : .max)
: (nil, partialValue)
}
}
extension Strideable where Stride: FloatingPoint {
@inlinable // protocol-only
public static func _step(
after current: (index: Int?, value: Self),
from start: Self, by distance: Self.Stride
) -> (index: Int?, value: Self) {
if let i = current.index {
// When Stride is a floating-point type, we should avoid accumulating
// rounding error from repeated addition.
return (i + 1, start.advanced(by: Stride(i + 1) * distance))
}
return (nil, current.value.advanced(by: distance))
}
}
extension Strideable where Self: FloatingPoint, Self == Stride {
@inlinable // protocol-only
public static func _step(
after current: (index: Int?, value: Self),
from start: Self, by distance: Self.Stride
) -> (index: Int?, value: Self) {
if let i = current.index {
// When both Self and Stride are the same floating-point type, we should
// take advantage of fused multiply-add (where supported) to eliminate
// intermediate rounding error.
return (i + 1, start.addingProduct(Stride(i + 1), distance))
}
return (nil, current.value.advanced(by: distance))
}
}
/// An iterator for a `StrideTo` instance.
@frozen
public struct StrideToIterator<Element: Strideable> {
@usableFromInline
internal let _start: Element
@usableFromInline
internal let _end: Element
@usableFromInline
internal let _stride: Element.Stride
@usableFromInline
internal var _current: (index: Int?, value: Element)
@inlinable
internal init(_start: Element, end: Element, stride: Element.Stride) {
self._start = _start
_end = end
_stride = stride
_current = (0, _start)
}
}
extension StrideToIterator: IteratorProtocol {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable
public mutating func next() -> Element? {
let result = _current.value
if _stride > 0 ? result >= _end : result <= _end {
return nil
}
_current = Element._step(after: _current, from: _start, by: _stride)
return result
}
}
// FIXME: should really be a Collection, as it is multipass
/// A sequence of values formed by striding over a half-open interval.
///
/// Use the `stride(from:to:by:)` function to create `StrideTo` instances.
@frozen
public struct StrideTo<Element: Strideable> {
@usableFromInline
internal let _start: Element
@usableFromInline
internal let _end: Element
@usableFromInline
internal let _stride: Element.Stride
@inlinable
internal init(_start: Element, end: Element, stride: Element.Stride) {
_precondition(stride != 0, "Stride size must not be zero")
// At start, striding away from end is allowed; it just makes for an
// already-empty Sequence.
self._start = _start
self._end = end
self._stride = stride
}
}
extension StrideTo: Sequence {
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@inlinable
public __consuming func makeIterator() -> StrideToIterator<Element> {
return StrideToIterator(_start: _start, end: _end, stride: _stride)
}
// FIXME(conditional-conformances): this is O(N) instead of O(1), leaving it
// here until a proper Collection conformance is possible
@inlinable
public var underestimatedCount: Int {
var it = self.makeIterator()
var count = 0
while it.next() != nil {
count += 1
}
return count
}
@inlinable
public func _customContainsEquatableElement(
_ element: Element
) -> Bool? {
if _stride < 0 {
if element <= _end || _start < element { return false }
} else {
if element < _start || _end <= element { return false }
}
// TODO: Additional implementation work will avoid always falling back to the
// predicate version of `contains` when the sequence *does* contain `element`.
return nil
}
}
#if SWIFT_ENABLE_REFLECTION
extension StrideTo: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: ["from": _start, "to": _end, "by": _stride])
}
}
#endif
// FIXME(conditional-conformances): This does not yet compile (SR-6474).
#if false
extension StrideTo: RandomAccessCollection
where Element.Stride: BinaryInteger {
public typealias Index = Int
public typealias SubSequence = Slice<StrideTo<Element>>
public typealias Indices = Range<Int>
@inlinable
public var startIndex: Index { return 0 }
@inlinable
public var endIndex: Index { return count }
@inlinable
public var count: Int {
let distance = _start.distance(to: _end)
guard distance != 0 && (distance < 0) == (_stride < 0) else { return 0 }
return Int((distance - 1) / _stride) + 1
}
public subscript(position: Index) -> Element {
_failEarlyRangeCheck(position, bounds: startIndex..<endIndex)
return _start.advanced(by: Element.Stride(position) * _stride)
}
public subscript(bounds: Range<Index>) -> Slice<StrideTo<Element>> {
_failEarlyRangeCheck(bounds, bounds: startIndex ..< endIndex)
return Slice(base: self, bounds: bounds)
}
@inlinable
public func index(before i: Index) -> Index {
_failEarlyRangeCheck(i, bounds: startIndex + 1...endIndex)
return i - 1
}
@inlinable
public func index(after i: Index) -> Index {
_failEarlyRangeCheck(i, bounds: startIndex - 1..<endIndex)
return i + 1
}
}
#endif
/// Returns a sequence from a starting value to, but not including, an end
/// value, stepping by the specified amount.
///
/// You can use this function to stride over values of any type that conforms
/// to the `Strideable` protocol, such as integers or floating-point types.
/// Starting with `start`, each successive value of the sequence adds `stride`
/// until the next value would be equal to or beyond `end`.
///
/// for radians in stride(from: 0.0, to: .pi * 2, by: .pi / 2) {
/// let degrees = Int(radians * 180 / .pi)
/// print("Degrees: \(degrees), radians: \(radians)")
/// }
/// // Degrees: 0, radians: 0.0
/// // Degrees: 90, radians: 1.5707963267949
/// // Degrees: 180, radians: 3.14159265358979
/// // Degrees: 270, radians: 4.71238898038469
///
/// You can use `stride(from:to:by:)` to create a sequence that strides upward
/// or downward. Pass a negative value as `stride` to create a sequence from a
/// higher start to a lower end:
///
/// for countdown in stride(from: 3, to: 0, by: -1) {
/// print("\(countdown)...")
/// }
/// // 3...
/// // 2...
/// // 1...
///
/// If you pass a value as `stride` that moves away from `end`, the sequence
/// contains no values.
///
/// for x in stride(from: 0, to: 10, by: -1) {
/// print(x)
/// }
/// // Nothing is printed.
///
/// - Parameters:
/// - start: The starting value to use for the sequence. If the sequence
/// contains any values, the first one is `start`.
/// - end: An end value to limit the sequence. `end` is never an element of
/// the resulting sequence.
/// - stride: The amount to step by with each iteration. A positive `stride`
/// iterates upward; a negative `stride` iterates downward.
/// - Returns: A sequence from `start` toward, but not including, `end`. Each
/// value in the sequence steps by `stride`.
@inlinable
public func stride<T>(
from start: T, to end: T, by stride: T.Stride
) -> StrideTo<T> {
return StrideTo(_start: start, end: end, stride: stride)
}
/// An iterator for a `StrideThrough` instance.
@frozen
public struct StrideThroughIterator<Element: Strideable> {
@usableFromInline
internal let _start: Element
@usableFromInline
internal let _end: Element
@usableFromInline
internal let _stride: Element.Stride
@usableFromInline
internal var _current: (index: Int?, value: Element)
@usableFromInline
internal var _didReturnEnd: Bool = false
@inlinable
internal init(_start: Element, end: Element, stride: Element.Stride) {
self._start = _start
_end = end
_stride = stride
_current = (0, _start)
}
}
extension StrideThroughIterator: IteratorProtocol {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable
public mutating func next() -> Element? {
let result = _current.value
if _stride > 0 ? result >= _end : result <= _end {
// Note the `>=` and `<=` operators above. When `result == _end`, the
// following check is needed to prevent advancing `_current` past the
// representable bounds of the `Strideable` type unnecessarily.
//
// If the `Strideable` type is a fixed-width integer, overflowed results
// are represented using a sentinel value for `_current.index`, `Int.min`.
if result == _end && !_didReturnEnd && _current.index != .min {
_didReturnEnd = true
return result
}
return nil
}
_current = Element._step(after: _current, from: _start, by: _stride)
return result
}
}
// FIXME: should really be a Collection, as it is multipass
/// A sequence of values formed by striding over a closed interval.
///
/// Use the `stride(from:through:by:)` function to create `StrideThrough`
/// instances.
@frozen
public struct StrideThrough<Element: Strideable> {
@usableFromInline
internal let _start: Element
@usableFromInline
internal let _end: Element
@usableFromInline
internal let _stride: Element.Stride
@inlinable
internal init(_start: Element, end: Element, stride: Element.Stride) {
_precondition(stride != 0, "Stride size must not be zero")
self._start = _start
self._end = end
self._stride = stride
}
}
extension StrideThrough: Sequence {
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@inlinable
public __consuming func makeIterator() -> StrideThroughIterator<Element> {
return StrideThroughIterator(_start: _start, end: _end, stride: _stride)
}
// FIXME(conditional-conformances): this is O(N) instead of O(1), leaving it
// here until a proper Collection conformance is possible
@inlinable
public var underestimatedCount: Int {
var it = self.makeIterator()
var count = 0
while it.next() != nil {
count += 1
}
return count
}
@inlinable
public func _customContainsEquatableElement(
_ element: Element
) -> Bool? {
if _stride < 0 {
if element < _end || _start < element { return false }
} else {
if element < _start || _end < element { return false }
}
// TODO: Additional implementation work will avoid always falling back to the
// predicate version of `contains` when the sequence *does* contain `element`.
return nil
}
}
#if SWIFT_ENABLE_REFLECTION
extension StrideThrough: CustomReflectable {
public var customMirror: Mirror {
return Mirror(self,
children: ["from": _start, "through": _end, "by": _stride])
}
}
#endif
// FIXME(conditional-conformances): This does not yet compile (SR-6474).
#if false
extension StrideThrough: RandomAccessCollection
where Element.Stride: BinaryInteger {
public typealias Index = ClosedRangeIndex<Int>
public typealias SubSequence = Slice<StrideThrough<Element>>
@inlinable
public var startIndex: Index {
let distance = _start.distance(to: _end)
return distance == 0 || (distance < 0) == (_stride < 0)
? ClosedRangeIndex(0)
: ClosedRangeIndex()
}
@inlinable
public var endIndex: Index { return ClosedRangeIndex() }
@inlinable
public var count: Int {
let distance = _start.distance(to: _end)
guard distance != 0 else { return 1 }
guard (distance < 0) == (_stride < 0) else { return 0 }
return Int(distance / _stride) + 1
}
public subscript(position: Index) -> Element {
let offset = Element.Stride(position._dereferenced) * _stride
return _start.advanced(by: offset)
}
public subscript(bounds: Range<Index>) -> Slice<StrideThrough<Element>> {
return Slice(base: self, bounds: bounds)
}
@inlinable
public func index(before i: Index) -> Index {
switch i._value {
case .inRange(let n):
_precondition(n > 0, "Incrementing past start index")
return ClosedRangeIndex(n - 1)
case .pastEnd:
_precondition(_end >= _start, "Incrementing past start index")
return ClosedRangeIndex(count - 1)
}
}
@inlinable
public func index(after i: Index) -> Index {
switch i._value {
case .inRange(let n):
return n == (count - 1)
? ClosedRangeIndex()
: ClosedRangeIndex(n + 1)
case .pastEnd:
_preconditionFailure("Incrementing past end index")
}
}
}
#endif
/// Returns a sequence from a starting value toward, and possibly including, an end
/// value, stepping by the specified amount.
///
/// You can use this function to stride over values of any type that conforms
/// to the `Strideable` protocol, such as integers or floating-point types.
/// Starting with `start`, each successive value of the sequence adds `stride`
/// until the next value would be beyond `end`.
///
/// for radians in stride(from: 0.0, through: .pi * 2, by: .pi / 2) {
/// let degrees = Int(radians * 180 / .pi)
/// print("Degrees: \(degrees), radians: \(radians)")
/// }
/// // Degrees: 0, radians: 0.0
/// // Degrees: 90, radians: 1.5707963267949
/// // Degrees: 180, radians: 3.14159265358979
/// // Degrees: 270, radians: 4.71238898038469
/// // Degrees: 360, radians: 6.28318530717959
///
/// You can use `stride(from:through:by:)` to create a sequence that strides
/// upward or downward. Pass a negative value as `stride` to create a sequence
/// from a higher start to a lower end:
///
/// for countdown in stride(from: 3, through: 1, by: -1) {
/// print("\(countdown)...")
/// }
/// // 3...
/// // 2...
/// // 1...
///
/// The value you pass as `end` is not guaranteed to be included in the
/// sequence. If stepping from `start` by `stride` does not produce `end`,
/// the last value in the sequence will be one step before going beyond `end`.
///
/// for multipleOfThree in stride(from: 3, through: 10, by: 3) {
/// print(multipleOfThree)
/// }
/// // 3
/// // 6
/// // 9
///
/// If you pass a value as `stride` that moves away from `end`, the sequence
/// contains no values.
///
/// for x in stride(from: 0, through: 10, by: -1) {
/// print(x)
/// }
/// // Nothing is printed.
///
/// - Parameters:
/// - start: The starting value to use for the sequence. If the sequence
/// contains any values, the first one is `start`.
/// - end: An end value to limit the sequence. `end` is an element of
/// the resulting sequence if and only if it can be produced from `start`
/// using steps of `stride`.
/// - stride: The amount to step by with each iteration. A positive `stride`
/// iterates upward; a negative `stride` iterates downward.
/// - Returns: A sequence from `start` toward, and possibly including, `end`.
/// Each value in the sequence is separated by `stride`.
@inlinable
public func stride<T>(
from start: T, through end: T, by stride: T.Stride
) -> StrideThrough<T> {
return StrideThrough(_start: start, end: end, stride: stride)
}
extension StrideToIterator: Sendable
where Element: Sendable, Element.Stride: Sendable { }
extension StrideTo: Sendable
where Element: Sendable, Element.Stride: Sendable { }
extension StrideThroughIterator: Sendable
where Element: Sendable, Element.Stride: Sendable { }
extension StrideThrough: Sendable
where Element: Sendable, Element.Stride: Sendable { }
| apache-2.0 | 3373fccf82ce3e04a010413efe087739 | 34.023936 | 83 | 0.643823 | 3.912359 | false | false | false | false |
onmyway133/Github.swift | Carthage/Checkouts/Tailor/Sources/Shared/Extensions/Dictionary+Tailor.swift | 1 | 7632 | import Sugar
// MARK: - Basic
public extension Dictionary {
/**
- Parameter name: The name of the property that you want to map
- Returns: A generic type if casting succeeds, otherwise it returns nil
*/
func property<T>(name: String) -> T? {
guard let key = name as? Key,
value = self[key] as? T
else { return nil }
return value
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A generic type if casting succeeds, otherwise it throws
*/
func propertyOrThrow<T>(name: String) throws -> T {
guard let result: T = property(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") }
return result
}
/**
- Parameter name: The name of the property that you want to map
- Parameter transformer: A transformation closure
- Returns: A generic type if casting succeeds, otherwise it returns nil
*/
func transform<T, U>(name: String, transformer: ((value: U) -> T?)) -> T? {
guard let key = name as? Key,
value = self[key] as? U
else { return nil }
return transformer(value: value)
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object directory, otherwise it returns nil
*/
func directory<T : Mappable>(name: String) -> [String : T]? {
guard let key = name as? Key,
dictionary = self[key] as? JSONDictionary
else { return nil }
var directory = [String : T]()
for (key, value) in dictionary {
guard let value = value as? JSONDictionary else { continue }
directory[key] = T(value)
}
return directory
}
/**
- Parameter name: The name of the key
- Returns: A child dictionary for that key, otherwise it returns nil
*/
func dictionary(name: String) -> JSONDictionary? {
guard let key = name as? Key,
value = self[key] as? JSONDictionary
else { return nil }
return value
}
/**
- Parameter name: The name of the key
- Returns: A child dictionary for that key, otherwise it throws
*/
func dictionaryOrThrow(name: String) throws -> JSONDictionary {
guard let result = dictionary(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as JSONDictionary") }
return result
}
/**
- Parameter name: The name of the key
- Returns: A child array for that key, otherwise it returns nil
*/
func array(name: String) -> JSONArray? {
guard let key = name as? Key,
value = self[key] as? JSONArray
else { return nil }
return value
}
/**
- Parameter name: The name of the key
- Returns: A child array for that key, otherwise it throws
*/
func arrayOrThrow(name: String) throws -> JSONArray {
guard let result = array(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as JSONArray") }
return result
}
/**
- Parameter name: The name of the key
- Returns: An enum if casting succeeds, otherwise it returns nil
*/
func `enum`<T: RawRepresentable>(name: String) -> T? {
guard let key = name as? Key,
value = self[key] as? T.RawValue
else { return nil }
return T(rawValue: value)
}
/**
- Parameter name: The name of the key
- Returns: An enum if casting succeeds, otherwise it throws
*/
func enumOrThrow<T: RawRepresentable>(name: String) throws -> T {
guard let result: T = `enum`(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as enum") }
return result
}
}
// MARK: - Relation
public extension Dictionary {
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object, otherwise it returns nil
*/
func relation<T : Mappable>(name: String) -> T? {
guard let key = name as? Key,
dictionary = self[key] as? JSONDictionary
else { return nil }
return T(dictionary)
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A generic type if casting succeeds, otherwise it throws
*/
func relationOrThrow<T : Mappable>(name: String) throws -> T {
guard let result: T = relation(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") }
return result
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object, otherwise it returns nil
*/
func relation<T : SafeMappable>(name: String) -> T? {
guard let key = name as? Key,
dictionary = self[key] as? JSONDictionary
else { return nil }
let result: T?
do {
result = try T(dictionary)
} catch {
result = nil
}
return result
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A generic type if casting succeeds, otherwise it throws
*/
func relationOrThrow<T : SafeMappable>(name: String) throws -> T {
guard let result: T = relation(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") }
return result
}
}
// MARK: - Relations
public extension Dictionary {
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object array, otherwise it returns nil
*/
func relations<T : Mappable>(name: String) -> [T]? {
guard let key = name as? Key,
array = self[key] as? JSONArray
else { return nil }
return array.map { T($0) }
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object array, otherwise it throws
*/
func relationsOrThrow<T : Mappable>(name: String) throws -> [T] {
guard let result: [T] = relations(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") }
return result
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object array, otherwise it returns nil
*/
func relations<T : SafeMappable>(name: String) -> [T]? {
guard let key = name as? Key,
array = self[key] as? JSONArray
else { return nil }
var result = [T]()
do {
result = try array.map { try T($0) }
} catch {}
return result
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object array, otherwise it throws
*/
func relationsOrThrow<T : SafeMappable>(name: String) throws -> [T] {
guard let result: [T] = relations(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") }
return result
}
}
// MARK: - Relation Hierarchically
public extension Dictionary {
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object, considering hierarchy, otherwise it returns nil
*/
func relationHierarchically<T where T: Mappable, T: HierarchyType>(name: String) -> T? {
guard let key = name as? Key,
dictionary = self[key] as? JSONDictionary
else { return nil }
return T.cluster(dictionary) as? T
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object array, considering hierarchy, otherwise it returns nil
*/
func relationsHierarchically<T where T: Mappable, T: HierarchyType>(name: String) -> [T]? {
guard let key = name as? Key,
array = self[key] as? JSONArray
else { return nil }
return array.flatMap { T.cluster($0) as? T }
}
}
| mit | 2a1504e46c430725a7e6e1a891934284 | 26.752727 | 105 | 0.641116 | 4.004197 | false | false | false | false |
saurabhj80/EarlGrey | Tests/FunctionalTests/Sources/FTRSwiftTests.swift | 2 | 10462 | //
// Copyright 2016 Google 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 EarlGrey
import XCTest
class TextFieldEventsRecorder {
var textDidBeginEditing = false
var textDidChange = false
var textDidEndEditing = false
var editingDidBegin = false
var editingChanged = false
var editingDidEndOnExit = false
var editingDidEnd = false
func registerActionBlock() -> GREYActionBlock {
NotificationCenter.default.addObserver(self,
selector: #selector(textDidBeginEditingHandler),
name: NSNotification.Name.UITextFieldTextDidBeginEditing,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(textDidChangeHandler),
name: NSNotification.Name.UITextFieldTextDidChange,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(textDidEndEditingHandler),
name: NSNotification.Name.UITextFieldTextDidEndEditing,
object: nil)
return GREYActionBlock.action(withName: "Register to editing events") {
(element: Any?, errorOrNil: UnsafeMutablePointer<NSError?>?) -> Bool in
let element:UIControl = element as! UIControl
element.addTarget(self,
action: #selector(self.editingDidBeginHandler), for: .editingDidBegin)
element.addTarget(self,
action: #selector(self.editingChangedHandler), for: .editingChanged)
element.addTarget(self,
action: #selector(self.editingDidEndOnExitHandler),
for: .editingDidEndOnExit)
element.addTarget(self,
action: #selector(self.editingDidEndHandler), for: .editingDidEnd)
return true
}
}
func verify() -> Bool {
return textDidBeginEditing && textDidChange && textDidEndEditing &&
editingDidBegin && editingChanged && editingDidEndOnExit && editingDidEnd
}
@objc func textDidBeginEditingHandler() { textDidBeginEditing = true }
@objc func textDidChangeHandler() { textDidChange = true }
@objc func textDidEndEditingHandler() { textDidEndEditing = true }
@objc func editingDidBeginHandler() { editingDidBegin = true }
@objc func editingChangedHandler() { editingChanged = true }
@objc func editingDidEndOnExitHandler() { editingDidEndOnExit = true }
@objc func editingDidEndHandler() { editingDidEnd = true }
}
class FTRSwiftTests: XCTestCase {
override func tearDown() {
super.tearDown()
let delegateWindow:UIWindow! = UIApplication.shared.delegate!.window!
var navController:UINavigationController?
if ((delegateWindow.rootViewController?.isKind(of: UINavigationController.self)) != nil) {
navController = delegateWindow.rootViewController as? UINavigationController
} else {
navController = delegateWindow.rootViewController!.navigationController
}
_ = navController?.popToRootViewController(animated: true)
}
func testOpeningView() {
self.openTestView("Typing Views")
}
func testRotation() {
EarlGrey.rotateDeviceTo(orientation: UIDeviceOrientation.landscapeLeft, errorOrNil: nil)
EarlGrey.rotateDeviceTo(orientation: UIDeviceOrientation.portrait, errorOrNil: nil)
}
func testTyping() {
self.openTestView("Typing Views")
let matcher = grey_accessibilityID("TypingTextField")
let action = grey_typeText("Sample Swift Test")
let assertionMatcher = grey_text("Sample Swift Test")
EarlGrey.select(elementWithMatcher: matcher)
.perform(action)
.assert(assertionMatcher)
}
func testTypingWithError() {
self.openTestView("Typing Views")
EarlGrey.select(elementWithMatcher: grey_accessibilityID("TypingTextField"))
.perform(grey_typeText("Sample Swift Test"))
.assert(grey_text("Sample Swift Test"))
var error: NSError?
EarlGrey.select(elementWithMatcher: grey_accessibilityID("TypingTextField"))
.perform(grey_typeText(""), error: &error)
.assert(grey_text("Sample Swift Test"), error: nil)
GREYAssert(error != nil, reason: "Performance should have errored")
error = nil
EarlGrey.select(elementWithMatcher: grey_accessibilityID("TypingTextField"))
.perform(grey_clearText())
.perform(grey_typeText("Sample Swift Test"), error: nil)
.assert(grey_text("Garbage Value"), error: &error)
GREYAssert(error != nil, reason: "Performance should have errored")
}
func testFastTyping() {
self.openTestView("Typing Views")
let textFieldEventsRecorder = TextFieldEventsRecorder()
EarlGrey.select(elementWithMatcher: grey_accessibilityID("TypingTextField"))
.perform(textFieldEventsRecorder.registerActionBlock())
.perform(grey_replaceText("Sample Swift Test"))
.assert(grey_text("Sample Swift Test"))
GREYAssert(textFieldEventsRecorder.verify(), reason: "Text field events were not all received")
}
func testTypingWithDeletion() {
self.openTestView("Typing Views")
EarlGrey.select(elementWithMatcher: grey_accessibilityID("TypingTextField"))
.perform(grey_typeText("Fooo\u{8}B\u{8}Bar"))
.assert(grey_text("FooBar"))
}
func testButtonPressWithGREYAllOf() {
self.openTestView("Basic Views")
EarlGrey.select(elementWithMatcher: grey_text("Tab 2")).perform(grey_tap())
let matcher = grey_allOf([grey_text("Long Press"), grey_sufficientlyVisible()])
EarlGrey.select(elementWithMatcher: matcher).perform(grey_longPressWithDuration(1.1))
.assert(grey_notVisible())
}
func testPossibleOpeningViews() {
self.openTestView("Alert Views")
let matcher = grey_anyOf([grey_text("FooText"),
grey_text("Simple Alert"),
grey_buttonTitle("BarTitle")])
EarlGrey.select(elementWithMatcher: matcher).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_text("Flee"))
.assert(grey_sufficientlyVisible())
.perform(grey_tap())
}
func testSwiftCustomMatcher() {
// Verify description in custom matcher isn't nil.
// unexpectedly found nil while unwrapping an Optional value
EarlGrey.select(elementWithMatcher: grey_allOf([grey_firstElement(),
grey_text("FooText")]))
.assert(grey_nil())
}
func testInteractionWithALabelWithParentHidden() {
let checkHiddenBlock:GREYActionBlock =
GREYActionBlock.action(withName: "checkHiddenBlock", perform: { element, errorOrNil in
// Check if the found element is hidden or not.
let superView:UIView! = element as! UIView
return !superView.isHidden
})
self.openTestView("Basic Views")
EarlGrey.select(elementWithMatcher: grey_text("Tab 2")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("tab2Container"))
.perform(checkHiddenBlock).assert(grey_sufficientlyVisible())
var error: NSError?
EarlGrey.select(elementWithMatcher: grey_text("Non Existent Element"))
.perform(grey_tap(), error:&error)
if let errorVal = error {
GREYAssertEqual(errorVal.domain as AnyObject?, kGREYInteractionErrorDomain as AnyObject?,
reason: "Element Not Found Error")
}
}
func testChangingDatePickerToAFutureDate() {
self.openTestView("Picker Views")
// Have an arbitrary date created
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
let date = Date(timeIntervalSinceReferenceDate: 118800)
dateFormatter.locale = Locale(identifier: "en_US")
EarlGrey.select(elementWithMatcher: grey_text("Date")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityID("DatePickerId"))
.perform(grey_setDate(date))
EarlGrey.select(elementWithMatcher: grey_accessibilityID("DatePickerId"))
.assert(grey_datePickerValue(date))
}
func testStepperActionWithCondition() {
self.openTestView("Basic Views")
var stepperValue = 51.0
// Without the parameter using the value of the wait action, a warning should be seen.
_ = GREYCondition.init(name: "conditionWithAction", block: {
stepperValue += 1
EarlGrey.select(elementWithMatcher: grey_kindOfClass(UIStepper.self))
.perform(grey_setStepperValue(stepperValue))
return stepperValue == 55
}).waitWithTimeout(seconds: 10.0)
EarlGrey.select(elementWithMatcher: grey_kindOfClass(UIStepper.self))
.assert(with: grey_stepperValue(55))
}
func openTestView(_ name: String) {
var errorOrNil : NSError?
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel(name))
.perform(grey_tap(), error: &errorOrNil)
if ((errorOrNil == nil)) {
return
}
EarlGrey.select(elementWithMatcher: grey_kindOfClass(UITableView.self))
.perform(grey_scrollToContentEdge(GREYContentEdge.top))
EarlGrey.select(elementWithMatcher: grey_allOf([grey_accessibilityLabel(name),
grey_interactable()]))
.using(searchAction: grey_scrollInDirection(GREYDirection.down, 200),
onElementWithMatcher: grey_kindOfClass(UITableView.self))
.perform(grey_tap())
}
func grey_firstElement() -> GREYMatcher {
var firstMatch = true
let matches: MatchesBlock = { (element: Any) -> Bool in
if firstMatch {
firstMatch = false
return true
}
return false
}
let describe: DescribeToBlock = { (description: GREYDescription?) -> Void in
description!.appendText("first match")
}
return GREYElementMatcherBlock.init(matchesBlock: matches, descriptionBlock: describe)
}
}
| apache-2.0 | 7e89b449c6c623285061f9b3ac16fc30 | 40.848 | 100 | 0.681132 | 4.932579 | false | true | false | false |
Zewo/System | Tests/POSIXTests/LockTests.swift | 6 | 1336 | import XCTest
import Foundation
@testable import POSIX
public class LockTests: XCTestCase {
func testWaitsForCondition() throws {
let start = NSDate().timeIntervalSince1970
let condition = try Condition()
let lock = try Lock()
_ = try PThread {
sleep(1)
condition.resolve()
}
try lock.withLock {
lock.wait(for: condition)
}
let duration = NSDate().timeIntervalSince1970 - start
XCTAssertGreaterThan(duration, 1)
}
func testLockEnsuresThreadSafety() throws {
// if it doesnt crash, it succeeds
let lock = try Lock()
var results = [Int]()
_ = try PThread {
for i in 1...10000 {
try lock.withLock {
results.append(i)
}
}
}
_ = try PThread {
for i in 1...10000 {
try lock.withLock {
results.append(i)
}
}
}
sleep(1)
}
}
extension LockTests {
public static var allTests : [(String, (LockTests) -> () throws -> Void)] {
return [
("testWaitsForCondition", testWaitsForCondition),
("testLockEnsuresThreadSafety", testLockEnsuresThreadSafety)
]
}
}
| mit | 1094ce934b736ad37cae0b777b88e3c4 | 22.438596 | 79 | 0.512725 | 4.771429 | false | true | false | false |
TwoRingSoft/shared-utils | Sources/PippinLibrary/Foundation/NSBundle/Build.swift | 1 | 1053 | //
// Build.swift
// Pippin
//
// Created by Andrew McKnight on 2/26/17.
// Copyright © 2017 Two Ring Software. All rights reserved.
//
import Foundation
typealias BuildNumber = UInt
public struct Build {
var number: BuildNumber
public static var zero = Build(number: 0)
}
extension Build: CustomStringConvertible {
public var description: String {
return String(format: "%llu", number)
}
}
extension Build: LosslessStringConvertible {
public init?(_ description: String) {
number = description.unsignedIntegerValue
}
}
extension Build: Equatable {}
public func ==(lhs: Build, rhs: Build) -> Bool {
return lhs.number == rhs.number
}
extension Build: Comparable {}
public func <(lhs: Build, rhs: Build) -> Bool {
return lhs.number < rhs.number
}
public func <=(lhs: Build, rhs: Build) -> Bool {
return lhs == rhs || lhs < rhs
}
public func >(lhs: Build, rhs: Build) -> Bool {
return !(lhs <= rhs)
}
public func >=(lhs: Build, rhs: Build) -> Bool {
return !(lhs < rhs)
}
| mit | 690c4fae16aa00d0d7b8a6179bf01b0b | 16.830508 | 60 | 0.645437 | 3.678322 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/01165-swift-parser-parsetoken.swift | 11 | 721 | // 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
func p<p>() -> (p, p -> p) -> p {
l c l.l = {
}
{
p) {
})
}
protocol p {
}
class h: p {
}
(h() as p).dynamicType.g()
protocol p {
}
protocol h : p {
}
protocol g : p {
}
protocol n {
}
struct h : n {
t : n q m.t == m> (h: m) {
}
func q<t : n q t.t == g> (h: t) {
}
func b<d-> d { class d:b class b
protocol A {
}
func f() {
({})
| apache-2.0 | 47bd9c0c6bda7d80b8822540df8d4958 | 17.973684 | 78 | 0.614424 | 2.751908 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/AutoLayout/AutoLayoutCookbook/ImageViewsAndAspectFitMode.swift | 1 | 2914 | //
// ImageViewsAndAspectFitMode.swift
// UIScrollViewDemo
//
// Created by 黄伯驹 on 2017/10/24.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
class ImageViewsAndAspectFitMode: AutoLayoutBaseController {
override func initSubviews() {
let topContentView = generatContentView()
view.addSubview(topContentView)
let imageView = UIImageView(image: UIImage(named: "flowers"))
imageView.contentMode = .scaleAspectFit
imageView.setContentHuggingPriority(UILayoutPriority(rawValue: 251), for: .vertical)
imageView.setContentHuggingPriority(UILayoutPriority(rawValue: 251), for: .horizontal)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.backgroundColor = UIColor(white: 0.8, alpha: 1)
view.addSubview(imageView)
let bottomContentView = generatContentView()
view.addSubview(bottomContentView)
do {
topContentView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true
if #available(iOS 11, *) {
topContentView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
} else {
topContentView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 20).isActive = true
}
topContentView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true
topContentView.heightAnchor.constraint(equalTo: bottomContentView.heightAnchor).isActive = true
}
do {
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: topContentView.bottomAnchor, constant: 8).isActive = true
imageView.heightAnchor.constraint(equalTo: bottomContentView.heightAnchor, multiplier: 2).isActive = true
}
do {
bottomContentView.trailingAnchor.constraint(equalTo: topContentView.trailingAnchor).isActive = true
bottomContentView.leadingAnchor.constraint(equalTo: topContentView.leadingAnchor).isActive = true
bottomContentView.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 8).isActive = true
if #available(iOS 11, *) {
view.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: bottomContentView.bottomAnchor, constant: 20).isActive = true
} else {
bottomLayoutGuide.topAnchor.constraint(equalTo: bottomContentView.bottomAnchor, constant: 20).isActive = true
}
}
}
private func generatContentView() -> UIView {
let contentView = UIView()
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.backgroundColor = .lightGray
return contentView
}
}
| mit | 4bab723d92040734f9e6c2761d97471e | 45.758065 | 135 | 0.694722 | 5.408582 | false | false | false | false |
ConfusedVorlon/HSGoogleDrivePicker | HSGoogleDrivePicker/HSGoogleDrivePicker/HSDrivePicker.swift | 1 | 3424 | import GoogleSignIn
import GoogleAPIClientForREST
import UIKit
/// Navigation controller to present the File Viewer and signin controller
@objcMembers open class HSDrivePicker: UINavigationController {
/** Provide your API secret
Note that the client ID is read from your GoogleService-Info.plist
**/
/** Present the picker from your view controller. It will present as a modal form.
The completion returns both the file, and the authorised manager which can be used to download the file **/
/*
Appearance can mostly be managed through the appearance proxy.
e.g. [[UINavigationBar appearance] setBackgroundImage: <your image> ];
or to style the segmented control (which is addmittedly wierd)
//selected text
[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} forState:UIControlStateSelected];
//not selected text
[[UISegmentedControl appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor greenColor]} forState:UIControlStateNormal];
//background
[[UIImageView appearanceWhenContainedIn:[UISegmentedControl class],nil] setTintColor:[UIColor blueColor]];
*/
//*specify status bar style. Default is UIStatusBarStyleDefault *
/**
Handle the url callback from google authentication
@param url the callback url
*/
private var viewer: HSDriveFileViewer?
public class func handle(_ url: URL?) -> Bool {
_ = HSGIDSignInHandler.sharedInstance
if let url, GIDSignIn.sharedInstance.handle(url) {
return true
}
return false
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public init() {
let viewer = HSDriveFileViewer()
super.init(rootViewController: viewer)
modalPresentationStyle = UIModalPresentationStyle.pageSheet
self.viewer = viewer
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func pick(from vc: UIViewController?, withCompletion completion: @escaping (_ manager: HSDriveManager?, _ file: GTLRDrive_File?) -> Void) {
viewer?.completion = completion
viewer?.shouldSignInOnAppear = true
vc?.present(self, animated: true)
}
func downloadFileContent(withService service: GTLRDriveService?, file: GTLRDrive_File?, completionBlock: @escaping (Data?, Error?) -> Void) {
guard let downloadURL = file?.downloadURL else {
completionBlock(nil, NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: nil))
return
}
let fetcher = service?.fetcherService.fetcher(with: downloadURL)
fetcher?.beginFetch(completionHandler: { data, error in
if error == nil {
// Success.
completionBlock(data, nil)
} else {
if let error = error {
print("An error occurred: \(error)")
}
completionBlock(nil, error!)
}
})
}
}
| mit | 69f9d03caf81e541c3480622d4dc7e17 | 33.24 | 150 | 0.63347 | 5.549433 | false | false | false | false |
Aishwarya-Ramakrishnan/sparkios | Source/Phone/WebSocketService.swift | 1 | 8319 | // Copyright 2016 Cisco Systems Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Starscream
import SwiftyJSON
class WebSocketService: WebSocketDelegate {
static let sharedInstance = WebSocketService()
private var socket: WebSocket?
private let MessageBatchingIntervalInSec = 0.5
private let ConnectionTimeoutIntervalInSec = 60.0
private var connectionTimeoutTimer: Timer?
private var messageBatchingTimer: Timer?
private var connectionRetryCounter: ExponentialBackOffCounter
private var pendingMessages: [JSON]
init() {
connectionRetryCounter = ExponentialBackOffCounter(minimum: 0.5, maximum: 32, multiplier: 2)
pendingMessages = [JSON]()
}
deinit {
cancelConnectionTimeOutTimer()
cancelMessageBatchingTimer()
}
func connect(_ webSocketUrl: URL) {
if socket == nil {
socket = createWebSocket(webSocketUrl)
guard socket != nil else {
Logger.error("Skip connection due to failure of creating socket")
return
}
}
if socket!.isConnected {
Logger.warn("Web socket is already connected")
return
}
Logger.info("Web socket is being connected")
socket?.connect()
scheduleConnectionTimeoutTimer()
}
func disconnect() {
guard socket != nil else {
Logger.warn("Web socket has not been connected")
return
}
guard socket!.isConnected else {
Logger.warn("Web socket is already disconnected")
return
}
Logger.info("Web socket is being disconnected")
socket?.disconnect()
socket = nil
}
private func reconnect() {
guard socket != nil else {
Logger.warn("Web socket has not been connected")
return
}
guard !socket!.isConnected else {
Logger.warn("Web socket has already connected")
return
}
Logger.info("Web socket is being reconnected")
socket?.connect()
}
private func createWebSocket(_ webSocketUrl: URL) -> WebSocket? {
// Need to check authorization, avoid crash when logout as soon as login
guard let authorization = AuthManager.sharedInstance.getAuthorization() else {
Logger.error("Failed to create web socket due to no authorization")
return nil
}
socket = WebSocket(url: webSocketUrl)
if socket == nil {
Logger.error("Failed to create web socket")
return nil
}
socket?.headers.unionInPlace(authorization)
socket?.voipEnabled = true
socket?.disableSSLCertValidation = true
socket?.delegate = self
return socket
}
private func despatch_main_after(_ delay: Double, closure: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC),
execute: closure
)
}
// MARK: - Websocket Delegate Methods.
func websocketDidConnect(socket: WebSocket) {
Logger.info("Websocket is connected")
connectionRetryCounter.reset()
scheduleMessageBatchingTimer()
cancelConnectionTimeOutTimer()
ReachabilityService.sharedInstance.fetch()
}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
cancelMessageBatchingTimer()
cancelConnectionTimeOutTimer()
guard let code = error?.code, let discription = error?.localizedDescription else {
return
}
Logger.info("Websocket is disconnected: \(code), \(discription)")
guard self.socket != nil else {
Logger.info("Websocket is disconnected on purpose")
return
}
let backoffTime = connectionRetryCounter.next()
if code > Int(WebSocket.CloseCode.normal.rawValue) {
// Abnormal disconnection, re-register device.
self.socket = nil
Logger.error("Abnormal disconnection, re-register device in \(backoffTime) seconds")
despatch_main_after(backoffTime) {
Spark.phone.register(nil)
}
} else {
// Unexpected disconnection, reconnect socket.
Logger.warn("Unexpected disconnection, websocket will reconnect in \(backoffTime) seconds")
despatch_main_after(backoffTime) {
self.reconnect()
}
}
}
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
Logger.info("Websocket got some text: \(text)")
}
func websocketDidReceiveData(socket: WebSocket, data: Data) {
let json = JSON(data: data)
ackMessage(socket, messageId: json["id"].string!)
pendingMessages.append(json)
}
// MARK: - Websocket Event Handler
private func ackMessage(_ socket: WebSocket, messageId: String) {
let ack = JSON(["type": "ack", "messageId": messageId])
do {
let ackData: Data = try ack.rawData(options: .prettyPrinted)
socket.write(data: ackData)
} catch {
Logger.error("Failed to acknowledge message")
}
}
private func processMessages() {
for message in pendingMessages {
let eventData = message["data"]
if let eventType = eventData["eventType"].string {
if eventType.hasPrefix("locus") {
Logger.info("locus event: \(eventData.object)")
CallManager.sharedInstance.handle(callEventJson: eventData.object)
}
}
}
pendingMessages.removeAll()
}
// MARK: - Web Socket Timers
private func scheduledTimerWithTimeInterval(_ timeInterval: TimeInterval, selector: Selector, repeats: Bool) -> Timer {
return Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: selector, userInfo: nil, repeats: repeats)
}
private func scheduleMessageBatchingTimer() {
messageBatchingTimer = scheduledTimerWithTimeInterval(MessageBatchingIntervalInSec, selector: #selector(onMessagesBatchingTimerFired), repeats: true)
}
private func cancelMessageBatchingTimer() {
messageBatchingTimer?.invalidate()
messageBatchingTimer = nil
}
private func scheduleConnectionTimeoutTimer() {
connectionTimeoutTimer = scheduledTimerWithTimeInterval(ConnectionTimeoutIntervalInSec, selector: #selector(onConnectionTimeOutTimerFired), repeats: false)
}
private func cancelConnectionTimeOutTimer() {
connectionTimeoutTimer?.invalidate()
connectionTimeoutTimer = nil
}
@objc private func onMessagesBatchingTimerFired() {
processMessages()
}
@objc private func onConnectionTimeOutTimerFired() {
Logger.info("Connect timed out, try to reconnect")
reconnect()
}
}
| mit | 49235964cfb0f722c653a121a5d87e12 | 33.6625 | 163 | 0.629883 | 5.271863 | false | false | false | false |
mightydeveloper/swift | test/expr/delayed-ident/static_var.swift | 10 | 945 | // RUN: %target-parse-verify-swift
// Simple struct types
struct X1 {
static var AnX1 = X1()
static var NotAnX1 = 42
}
func acceptInOutX1(inout x1: X1) { }
var x1: X1 = .AnX1
x1 = .AnX1
x1 = .NotAnX1 // expected-error{{type of expression is ambiguous without more context}}
// Delayed identifier expressions as lvalues
(.AnX1 = x1)
acceptInOutX1(&(.AnX1))
// Generic struct types
struct X2<T> {
static var AnX2 = X2() // expected-error{{generic parameter 'T' could not be inferred}}
static var NotAnX2 = 0 // expected-error {{static stored properties not yet supported in generic types}}
}
var x2: X2<Int> = .AnX2
x2 = .AnX2 // reference to isInvalid() decl.
x2 = .NotAnX2 // expected-error{{type of expression is ambiguous without more context}}
// Static variables through operators.
struct Foo {
static var Bar = Foo()
static var Wibble = Foo()
}
func & (x: Foo, y: Foo) -> Foo { }
var fooValue: Foo = .Bar & .Wibble
| apache-2.0 | 872f2e8d411cf34854e487b717b29622 | 24.540541 | 106 | 0.683598 | 3.129139 | false | false | false | false |
novi/proconapp | ProconApp/ProconBase/OnMemoryCache.swift | 1 | 1479 | //
// OnMemoryCache.swift
// ProconApp
//
// Created by ito on 2015/08/09.
// Copyright (c) 2015年 Procon. All rights reserved.
//
import Foundation
public class OnMemoryCache {
public static let sharedInstance = OnMemoryCache()
let expires: NSTimeInterval = 600
let size: Int = 30
class Value {
let createdAt: NSDate
let obj: AnyObject
init(_ obj: AnyObject) {
self.obj = obj
self.createdAt = NSDate()
}
}
var bucket:NSMutableDictionary = [:]
public func setObject(object: AnyObject, forKey key: NSCopying) {
bucket.setObject(Value(object), forKey: key)
cleanIfNeeded()
}
public func objectForKey(key: NSCopying) -> AnyObject? {
if let val = bucket.objectForKey(key) as? Value {
return val.obj
}
return nil
}
func cleanIfNeeded() {
let s: Int = Int(Double(self.size) * 1.4)
if bucket.count > s {
var keysToRemove: [AnyObject] = []
let now = NSDate().timeIntervalSince1970
for (k, v) in bucket {
if let vv = v as? Value {
if now - vv.createdAt.timeIntervalSince1970 > self.expires {
keysToRemove.append(k)
}
}
}
Logger.debug("deleted \(keysToRemove)")
bucket.removeObjectsForKeys(keysToRemove)
}
}
} | bsd-3-clause | c31dc4355fc7cb66fa27c147fa8466bd | 25.872727 | 80 | 0.542316 | 4.530675 | false | false | false | false |
ReactiveKit/ReactiveUIKit | Sources/UIRefreshControl.swift | 1 | 2423 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if os(iOS)
import ReactiveKit
import UIKit
extension UIRefreshControl {
private struct AssociatedKeys {
static var RefreshingKey = "r_RefreshingKey"
}
public var rRefreshing: Property<Bool> {
if let rRefreshing: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.RefreshingKey) {
return rRefreshing as! Property<Bool>
} else {
let rRefreshing = Property<Bool>(self.refreshing)
objc_setAssociatedObject(self, &AssociatedKeys.RefreshingKey, rRefreshing, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
var updatingFromSelf: Bool = false
rRefreshing.observeNext { [weak self] (value: Bool) in
if !updatingFromSelf {
if value {
self?.beginRefreshing()
} else {
self?.endRefreshing()
}
}
}.disposeIn(rBag)
self.rControlEvent
.filter { $0 == UIControlEvents.ValueChanged }
.observeNext { [weak rRefreshing] event in
guard let rRefreshing = rRefreshing else { return }
updatingFromSelf = true
rRefreshing.value = true
updatingFromSelf = false
}.disposeIn(rBag)
return rRefreshing
}
}
}
#endif
| mit | 7d969810903f318ca8eb2be69ce0c0ea | 34.115942 | 138 | 0.688403 | 4.520522 | false | false | false | false |
toadzky/SLF4Swift | SLF4Swift/LogLevelType.swift | 1 | 2860 | //
// Protocole.swift
// SLF4Swift
/*
The MIT License (MIT)
Copyright (c) 2015 Eric Marchand (phimage)
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
/* level to filter message */
internal protocol LogLevelType {
/* integer to compare log level */
var level: Int {get}
/* name of level, used to print level if necessarry */
var name: String {get}
}
public enum SLFLogLevel: Int, LogLevelType, Equatable, Comparable, CustomStringConvertible {
case Off, Severe, Error, Warn, Info, Debug, Verbose, All
public static var levels: [SLFLogLevel] {return [Off, Severe, Error, Warn, Info, Debug, Verbose, All]}
public static var config: [SLFLogLevel] {return [Off, All]}
public static var issues: [SLFLogLevel] {return [Severe, Error, Warn]}
public var level: Int {
return rawValue
}
public var name: String {
switch(self) {
case Off: return "Off"
case Severe: return "Severe" // Critical, Fatal
case Error: return "Error"
case Warn: return "Warn"
case Info: return "Info"
case Debug: return "Debug"
case Verbose: return "Verbose" // Trace
case All: return "All"
}
}
public var description : String { return self.name }
public var shortDescription : String {
let d = self.description
return String(d[d.startIndex])
}
public func isIssues() -> Bool {
return SLFLogLevel.issues.contains(self)
}
public func isConfig() -> Bool {
return SLFLogLevel.config.contains(self)
}
public func isFlag() -> Bool {
return !isConfig()
}
}
public func ==(lhs: SLFLogLevel, rhs: SLFLogLevel) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public func <(lhs: SLFLogLevel, rhs: SLFLogLevel) -> Bool {
return lhs.rawValue < rhs.rawValue
}
| mit | 4fa36c379930fb5118b4b596644f92bf | 33.047619 | 106 | 0.692308 | 4.199706 | false | false | false | false |
atrick/swift | test/AutoDiff/compiler_crashers_fixed/sr12650-noderivative-parameter-type-mangling.swift | 11 | 2413 | // RUN: %target-build-swift -g %s
// SR-12650: IRGenDebugInfo type reconstruction crash because `@noDerivative`
// parameters are not mangled.
// FIXME(SR-13021): Disabled due to flakiness on Linux, likely related to TF-1197.
// REQUIRES: SR13021
import _Differentiation
func id(_ x: Float, _ y: Float) -> Float { x }
let transformed: @differentiable(reverse) (Float, @noDerivative Float) -> Float = id
// Incorrect reconstructed type for $sS3fIedgyyd_D
// Original type:
// (sil_function_type type=@differentiable(reverse) @callee_guaranteed (Float, @noDerivative Float) -> Float
// (input=struct_type decl=Swift.(file).Float)
// (input=struct_type decl=Swift.(file).Float)
// (result=struct_type decl=Swift.(file).Float)
// (substitution_map generic_signature=<nullptr>)
// (substitution_map generic_signature=<nullptr>))
// Reconstructed type:
// (sil_function_type type=@differentiable(reverse) @callee_guaranteed (Float, Float) -> Float
// (input=struct_type decl=Swift.(file).Float)
// (input=struct_type decl=Swift.(file).Float)
// (result=struct_type decl=Swift.(file).Float)
// (substitution_map generic_signature=<nullptr>)
// (substitution_map generic_signature=<nullptr>))
// Stack dump:
// ...
// 1. Swift version 5.3-dev (LLVM 803d1b184d, Swift 477af9f90d)
// 2. While evaluating request IRGenSourceFileRequest(IR Generation for file "noderiv.swift")
// 0 swift 0x00000001104c7ae8 llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 40
// 1 swift 0x00000001104c6a68 llvm::sys::RunSignalHandlers() + 248
// 2 swift 0x00000001104c80dd SignalHandler(int) + 285
// 3 libsystem_platform.dylib 0x00007fff718335fd _sigtramp + 29
// 4 libsystem_platform.dylib 000000000000000000 _sigtramp + 18446603338611739168
// 5 libsystem_c.dylib 0x00007fff71709808 abort + 120
// 6 swift 0x0000000110604152 (anonymous namespace)::IRGenDebugInfoImpl::getOrCreateType(swift::irgen::DebugTypeInfo) (.cold.20) + 146
// 7 swift 0x000000010c24ab1e (anonymous namespace)::IRGenDebugInfoImpl::getOrCreateType(swift::irgen::DebugTypeInfo) + 3614
// 8 swift 0x000000010c245437 swift::irgen::IRGenDebugInfo::emitGlobalVariableDeclaration(llvm::GlobalVariable*, llvm::StringRef, llvm::StringRef, swift::irgen::DebugTypeInfo, bool, bool, llvm::Optional<swift::SILLocation>) + 167
| apache-2.0 | 5ee97c04854a8c1f9c4b12f32f998b27 | 59.325 | 249 | 0.709076 | 3.442225 | false | false | false | false |
snailjj/iOSDemos | SnailSwiftDemos/SnailSwiftDemos/Tools/CustomTool/RequestManager.swift | 2 | 3863 | //
// RequestManager.swift
// SnailSwiftDemos
//
// Created by Jian Wu on 2016/12/26.
// Copyright © 2016年 Snail. All rights reserved.
//
import UIKit
import AFNetworking
enum RequsetMethod: String {
case GET = "GET"
case POST = "POST"
}
class RequestManager: AFHTTPSessionManager {
//请求完成失败、成功回调
typealias FailureHandler = (_ errorMessage : String) -> ()
typealias SuccessHandler = (_ data : Any) -> ()
//单例
static let shared: RequestManager = {
let instance = RequestManager()
instance.responseSerializer.acceptableContentTypes?.insert("text/html")
instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
let userAgent = "APP,,iPhone,\(Device().model),\(Device().os),\(Device().appVersion)"
instance.requestSerializer.setValue(userAgent, forHTTPHeaderField: "USER-AGENT")
return instance
}()
/**
请求数据
- parameter method: 请求方式(GET、POST)
- parameter urlString: 地址字符串
- parameter parameters: 参数
- parameter successHandler: 成功处理
- parameter failureHandler: 失败处理
*/
func request(method: RequsetMethod = .GET, urlString: String = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json", parameters: [String: AnyObject]?,successHandler : @escaping SuccessHandler,failureHandler: @escaping FailureHandler) {
let success = { (dataTask : URLSessionTask,responseObject : Any) -> Void in
//if code == 0
successHandler(responseObject)
log.debug("success")
}
//失败处理
let failure = { (dataTask: URLSessionTask?, error: Error) -> Void in
failureHandler("网络请求错误,请稍后再试")
log.debug(error.localizedDescription)
}
if method == .GET {
get(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
}
if method == .POST {
post(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
}
}
/**
上传文件
- parameter method: 请求方式(GET、POST)
- parameter urlString: 地址字符串
- parameter parameters: 参数
- parameter successHandler: 成功处理
- parameter failureHandler: 失败处理
*/
func uploadHeadImage(data : Data, name : String,urlString : String, parameters : Any,successHandler : @escaping SuccessHandler,failureHandler: @escaping FailureHandler) {
let success = { (dataTask : URLSessionTask,responseObject : Any) -> Void in
if (responseObject as! [String: Any])["code"] as! Int == 0 {
var decodingString: String = ""
let data = (responseObject as! [String: Any])["data"] as? String
if (data != nil) {
}
successHandler(decodingString)
} else {
let errorMessage = (responseObject as! [String: Any])["desc"] as! String
failureHandler(errorMessage)
}
}
//失败处理
let failure = { (dataTask: URLSessionTask?, error: Error) -> Void in
failureHandler("网络请求错误,请稍后再试")
}
post(urlString, parameters: parameters, constructingBodyWith: { (formData) in
formData.appendPart(withFileData: data, name: name, fileName: "headImage.png", mimeType: "image/png")
}, progress: nil, success: success, failure: failure)
}
}
| apache-2.0 | 1729843f55e43dabd1cc97138e796f0e | 35.336634 | 314 | 0.59346 | 4.854497 | false | false | false | false |
camelCaseD/swift-http | http/HTTP.swift | 1 | 1891 | #if os(Linux)
import Glibc
#else
import Darwin
#endif
public class HTTP {
public var serverSocket : Int32 = 0
public var serverAddress : sockaddr_in?
var bufferSize : Int = 1024
func sockaddr_cast(p: UnsafeMutablePointer<Void>) -> UnsafeMutablePointer<sockaddr> {
return UnsafeMutablePointer<sockaddr>(p)
}
public func echo(socket: Int32, _ output: String) {
output.withCString { (bytes) in
#if os(Linux)
let flags = Int32(MSG_NOSIGNAL)
#else
let flags = Int32(0)
#endif
send(socket, bytes, Int(strlen(bytes)), flags)
}
}
public init(port: UInt16) {
#if os(Linux)
serverSocket = socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0)
#else
serverSocket = socket(AF_INET, Int32(SOCK_STREAM), 0)
#endif
if (serverSocket > 0) {
print("Socket init: OK")
}
#if os(Linux)
serverAddress = sockaddr_in(
sin_family: sa_family_t(AF_INET),
sin_port: port.htons(),
sin_addr: in_addr(s_addr: in_addr_t(0)),
sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)
)
#else
serverAddress = sockaddr_in(
sin_len: __uint8_t(sizeof(sockaddr_in)),
sin_family: sa_family_t(AF_INET),
sin_port: port.htons(),
sin_addr: in_addr(s_addr: in_addr_t(0)),
sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)
)
#endif
setsockopt(serverSocket, SOL_SOCKET, SO_RCVBUF, &bufferSize, socklen_t(sizeof(Int)))
#if !os(Linux)
var noSigPipe : Int32 = 1
setsockopt(serverSocket, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, socklen_t(sizeofValue(noSigPipe)))
#endif
let serverBind = bind(serverSocket, sockaddr_cast(&serverAddress), socklen_t(UInt8(sizeof(sockaddr_in))))
if (serverBind >= 0) {
print("Server started at port \(port)")
}
}
}
extension CUnsignedShort {
func htons() -> CUnsignedShort { return (self << 8) + (self >> 8); }
}
| mit | f174038488c96a76cb1b4a10f1205e13 | 26.014286 | 109 | 0.616076 | 3.232479 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/WalletPayload/Tests/WalletPayloadKitTests/General/WalletUpgradeJSServiceTests.swift | 1 | 2973 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import JavaScriptCore
import TestKit
import ToolKit
import ToolKitMock
@testable import WalletPayloadKit
import XCTest
class WalletUpgradeJSServiceTests: XCTestCase {
var contextProvider: MockContextProvider!
var sut: WalletUpgradeJSServicing!
override func setUp() {
super.setUp()
contextProvider = MockContextProvider()
sut = WalletUpgradeJSService(contextProvider: contextProvider, queue: .main)
}
override func tearDown() {
sut = nil
contextProvider = nil
super.tearDown()
}
private func newContext(script: String) -> JSContext {
let context = JSContext()
context?.evaluateScript(script)
return context!
}
private var successScript: String {
"""
var MyWalletPhone = {};
MyWalletPhone.upgradeToV3 = function(firstAccountName) {
objc_upgrade_V3_success();
};
"""
}
private var multipleSuccessScript: String {
"""
var MyWalletPhone = {};
MyWalletPhone.upgradeToV3 = function(firstAccountName) {
objc_upgrade_V3_success();
objc_upgrade_V3_success();
};
"""
}
private var successErrorScript: String {
"""
var MyWalletPhone = {};
MyWalletPhone.upgradeToV3 = function(firstAccountName) {
objc_upgrade_V3_success();
objc_upgrade_V3_error();
};
"""
}
private var failureScript: String {
"""
var MyWalletPhone = {};
MyWalletPhone.upgradeToV3 = function(firstAccountName) {
objc_upgrade_V3_error();
};
"""
}
func testSuccess() {
// Arrange
contextProvider.underlyingContext = newContext(script: successScript)
let expectedString = "V3"
let publisher = sut.upgradeToV3()
// Act + Assert
XCTAssertPublisherValues(publisher, [expectedString])
}
func testSuccessIsInvokedOnlyOnce() {
// Arrange
contextProvider.underlyingContext = newContext(script: multipleSuccessScript)
let expectedString = "V3"
let publisher = sut.upgradeToV3()
// Act + Assert
XCTAssertPublisherValues(publisher, [expectedString])
}
func testCompletesAfterFirstSuccess() {
// Arrange
contextProvider.underlyingContext = newContext(script: successErrorScript)
let expectedString = "V3"
let upgradePublisher = sut.upgradeToV3()
// Act + Assert
XCTAssertPublisherValues(upgradePublisher, [expectedString])
}
func testError() {
// Arrange
contextProvider.underlyingContext = newContext(script: failureScript)
let upgradePublisher = sut.upgradeToV3()
// Act + Assert
XCTAssertPublisherError(upgradePublisher, WalletUpgradeJSError.failedV3Upgrade)
}
}
| lgpl-3.0 | 540f9a891f52e5ba0f142ea95992bf18 | 26.266055 | 87 | 0.625168 | 4.840391 | false | true | false | false |
qiuncheng/study-for-swift | YLQRCodeHelper/YLQRCodeHelper/YLGenerateQRCode.swift | 1 | 3073 | //
// GenerateQRCode.swift
// YLQRCode
//
// Created by yolo on 2017/1/20.
// Copyright © 2017年 Qiuncheng. All rights reserved.
//
import UIKit
import CoreImage
struct YLGenerateQRCode {
static func beginGenerate(text: String, withLogo: Bool, completion: CompletionHandler<UIImage?>?) {
let strData = text.data(using: .utf8)
let qrFilter = CIFilter(name: "CIQRCodeGenerator")
qrFilter?.setValue(strData, forKey: "inputMessage")
qrFilter?.setValue("H", forKey: "inputCorrectionLevel")
if let ciImage = qrFilter?.outputImage {
let size = CGSize(width: 260, height: 260)
let context = CIContext(options: nil)
var cgImage = context.createCGImage(ciImage, from: ciImage.extent)
UIGraphicsBeginImageContext(size)
let cgContext = UIGraphicsGetCurrentContext()
cgContext?.interpolationQuality = .none
cgContext?.scaleBy(x: 1.0, y: -1.0)
cgContext?.draw(cgImage!, in: cgContext!.boundingBoxOfClipPath)
if withLogo, let image = UIImage(named: "29", in: Bundle.currentBundle, compatibleWith: nil) {
let image = YLGenerateQRCode.getBorderImage(image: image)
if let podfileCGImage = image?.cgImage {
cgContext?.draw(podfileCGImage, in: cgContext!.boundingBoxOfClipPath.insetBy(dx: (size.width - 34.0) * 0.5, dy: (size.height - 34.0) * 0.5))
}
}
let codeImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
completion?(codeImage)
cgImage = nil
return
}
completion?(nil)
}
fileprivate static func getBorderImage(image: UIImage) -> UIImage? {
let imageView = UIImageView()
imageView.frame = CGRect(x: 0, y: 0, width: 34, height: 34)
imageView.layer.borderColor = UIColor.white.cgColor
imageView.layer.borderWidth = 2.0
imageView.image = image
var currentImage: UIImage? = nil
UIGraphicsBeginImageContext(CGSize(width: 34.0, height: 34.0))
if let context = UIGraphicsGetCurrentContext() {
imageView.layer.render(in: context)
currentImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
return currentImage
// var currentImage: UIImage?
// UIGraphicsBeginImageContext(CGSize(width: 40, height: 40))
// let context = UIGraphicsGetCurrentContext()
// context?.scaleBy(x: 1.0, y: -1.0)
// let image = UIImage(named: "podfile")
// context?.setFillColor(UIColor.white.cgColor)
// if let cgImage = image?.cgImage {
// context?.draw(cgImage, in: context!.boundingBoxOfClipPath.insetBy(dx: 5, dy: 5))
// currentImage = UIGraphicsGetImageFromCurrentImageContext()
// }
// UIGraphicsEndImageContext()
// return currentImage
}
}
| mit | 5ce7773226b98d6e4a24c4d8acf661a7 | 38.87013 | 160 | 0.612378 | 4.781931 | false | false | false | false |
powerytg/PearlCam | PearlCam/PearlFX/Components/Processor.swift | 2 | 1858 | //
// Processor.swift
// Accented
//
// Created by Tiangong You on 6/9/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
import GPUImage
class Node : NSObject {
var enabled : Bool = true
func addNode(node : Node) {
}
func removeAllTargets() {
}
}
class FilterNode : Node {
var filter : BasicOperation
init(filter : BasicOperation) {
self.filter = filter
super.init()
}
override func addNode(node: Node) {
if node is FilterNode {
let filterNode = node as! FilterNode
filter.addTarget(filterNode.filter)
} else if node is OutputNode {
let outputNode = node as! OutputNode
filter.addTarget(outputNode.output)
}
}
override func removeAllTargets() {
filter.removeAllTargets()
}
func cloneFilter() -> FilterNode? {
// Base class has no implementation
return nil
}
}
class InputNode : Node {
var input : PictureInput
init(input : PictureInput) {
self.input = input
super.init()
}
override func addNode(node: Node) {
if node is FilterNode {
let filterNode = node as! FilterNode
input.addTarget(filterNode.filter)
} else if node is OutputNode {
let outputNode = node as! OutputNode
input.addTarget(outputNode.output)
}
}
override func removeAllTargets() {
input.removeAllTargets()
}
}
class OutputNode : Node {
var output : ImageConsumer
init(output : ImageConsumer) {
self.output = output
super.init()
}
override func addNode(node: Node) {
// Do nothing
}
override func removeAllTargets() {
// Do nothing
}
}
| bsd-3-clause | a4ca452797b8d747a1ef08d97c4aabf2 | 19.633333 | 55 | 0.568659 | 4.507282 | false | false | false | false |
steryokhin/AsciiArtPlayer | src/AsciiArtPlayer/Pods/Swinject/Sources/ResolutionPool.swift | 5 | 1379 | //
// ResolutionPool.swift
// Swinject
//
// Created by Yoichi Tagaya on 7/28/15.
// Copyright (c) 2015 Swinject Contributors. All rights reserved.
//
import Foundation
internal struct ResolutionPool {
private static let maxDepth = 200
private var pool = [ServiceKey: Any]()
private var depth: Int = 0
private var pendingCompletions: [()->()] = []
internal subscript(key: ServiceKey) -> Any? {
get { return pool[key] }
set { pool[key] = newValue }
}
internal mutating func incrementDepth() {
guard depth < ResolutionPool.maxDepth else {
fatalError("Infinite recursive call for circular dependency has been detected. " +
"To avoid the infinite call, 'initCompleted' handler should be used to inject circular dependency.")
}
depth += 1
}
internal mutating func decrementDepth() {
assert(depth > 0, "The depth cannot be negative.")
if depth == 1 {
while let pendingCompletion = pendingCompletions.popLast() {
pendingCompletion() // Must be invoked decrementing depth counter.
}
pool = [:]
}
depth -= 1
}
internal mutating func appendPendingCompletion(_ completion: @escaping ()->()) {
pendingCompletions.append(completion)
}
}
| mit | 94fdf4eab04f2ec1bb6acf0d14975cd9 | 28.978261 | 123 | 0.600435 | 4.907473 | false | false | false | false |
digal/DFImageManager | DFImageManager.playground/Contents.swift | 3 | 1375 | // Playground - noun: a place where people can play
import UIKit
import DFImageManagerKit
import XCPlayground
//: ## DFImageManager
let manager = DFImageManager.sharedManager()
//: Zero config image fetching. Use shared manager to request an image for the given URL. The completion block is called with a decompressed, fullsize image.
let imageURL = NSURL(string: "http://farm8.staticflickr.com/7315/16455839655_7d6deb1ebf_z_d.jpg")!
manager.imageTaskForResource(imageURL) { (image, _, _, _) -> Void in
var fetchedImage = image
}?.resume()
//: Use DFImageRequest class to set specific request parameters like output image size (in pixels).
let request = DFImageRequest(resource: imageURL, targetSize: CGSize(width: 100, height: 100), contentMode: .AspectFill, options: nil)
manager.imageTaskForRequest(request) { (image, _, _, _) -> Void in
var fetchedImage = image
}?.resume()
//: Image manager returns instance of DFImageTask class for each image request. Image task can be used to cancel request or change its priority and more.
let task = manager.imageTaskForResource(NSURL(string: "http://farm6.staticflickr.com/5311/14244377986_c3c660ef30_k_d.jpg")!, completion: { (image, error, _, _) -> Void in
var fetchedImage = image
let responseError = error
})
task?.resume()
task?.priority = .High
task?.cancel()
XCPSetExecutionShouldContinueIndefinitely()
| mit | 78e60c1253f23d5750cf43f5aab6b36f | 44.833333 | 170 | 0.751273 | 3.951149 | false | false | false | false |
nlampi/SwiftGridView | Examples/Universal/SwiftGridExample/Cells/BasicTextReusableView.swift | 1 | 2755 | // BasicTextSectionView.swift
// Copyright (c) 2016 Nathan Lampi (http://nathanlampi.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
import SwiftGridView
open class BasicTextReusableView : SwiftGridReusableView {
open var textLabel : UILabel!
open var padding : CGFloat!
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initView()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initView()
}
fileprivate func initView() {
self.backgroundView = UIView()
self.selectedBackgroundView = UIView()
self.selectedBackgroundView?.backgroundColor = UIColor.orange
self.padding = 8.0
self.textLabel = UILabel.init(frame: self.frame)
self.textLabel.textColor = UIColor.black
self.textLabel.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(self.textLabel)
let views : [String : Any] = ["tL": self.textLabel!]
let metrics : [String : Any] = ["p": self.padding!]
self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-p-[tL]-p-|",
options: NSLayoutConstraint.FormatOptions.directionLeftToRight, metrics: metrics, views: views))
self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[tL]|",
options: NSLayoutConstraint.FormatOptions.directionLeftToRight, metrics: metrics, views: views))
}
override open class func reuseIdentifier() -> String {
return "BasicTextReusableViewReuseId"
}
}
| mit | 0400e0046ebe8cbc8e5256902fd29d75 | 40.119403 | 108 | 0.702359 | 4.919643 | false | false | false | false |
apple/swift | test/SILGen/synthesized_conformance_enum.swift | 4 | 8052 | // RUN: %target-swift-frontend -emit-silgen %s -swift-version 4 | %FileCheck -check-prefix CHECK -check-prefix CHECK-FRAGILE %s
// RUN: %target-swift-frontend -emit-silgen %s -swift-version 4 -enable-library-evolution | %FileCheck -check-prefix CHECK -check-prefix CHECK-RESILIENT %s
enum Enum<T> {
case a(T), b(T)
}
// CHECK-LABEL: enum Enum<T> {
// CHECK: case a(T), b(T)
// CHECK: }
enum NoValues {
case a, b
}
// CHECK-LABEL: enum NoValues {
// CHECK: case a, b
// CHECK-FRAGILE: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: NoValues, _ b: NoValues) -> Bool
// CHECK-RESILIENT: static func == (a: NoValues, b: NoValues) -> Bool
// CHECK: func hash(into hasher: inout Hasher)
// CHECK: var hashValue: Int { get }
// CHECK: }
// CHECK-LABEL: extension Enum : Equatable where T : Equatable {
// CHECK-FRAGILE: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: Enum<T>, _ b: Enum<T>) -> Bool
// CHECK-RESILIENT: static func == (a: Enum<T>, b: Enum<T>) -> Bool
// CHECK: }
// CHECK-LABEL: extension Enum : Hashable where T : Hashable {
// CHECK: func hash(into hasher: inout Hasher)
// CHECK: var hashValue: Int { get }
// CHECK: }
// CHECK-LABEL: extension NoValues : CaseIterable {
// CHECK: typealias AllCases = [NoValues]
// CHECK: static var allCases: [NoValues] { get }
// CHECK: }
extension Enum: Equatable where T: Equatable {}
// CHECK-FRAGILE-LABEL: // static Enum<A>.__derived_enum_equals(_:_:)
// CHECK-FRAGILE-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASQRzlE010__derived_C7_equalsySbACyxG_AEtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Enum<T>, @in_guaranteed Enum<T>, @thin Enum<T>.Type) -> Bool {
// CHECK-RESILIENT-LABEL: // static Enum<A>.== infix(_:_:)
// CHECK-RESILIENT-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASQRzlE2eeoiySbACyxG_AEtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Enum<T>, @in_guaranteed Enum<T>, @thin Enum<T>.Type) -> Bool {
extension Enum: Hashable where T: Hashable {}
// CHECK-LABEL: // Enum<A>.hash(into:)
// CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASHRzlE4hash4intoys6HasherVz_tF : $@convention(method) <T where T : Hashable> (@inout Hasher, @in_guaranteed Enum<T>) -> () {
// CHECK-LABEL: // Enum<A>.hashValue.getter
// CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASHRzlE9hashValueSivg : $@convention(method) <T where T : Hashable> (@in_guaranteed Enum<T>) -> Int {
extension Enum: Codable where T: Codable {}
// CHECK-LABEL: // Enum<A>.encode(to:)
// CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASeRzSERzlE6encode2toys7Encoder_p_tKF : $@convention(method) <T where T : Decodable, T : Encodable> (@in_guaranteed any Encoder, @in_guaranteed Enum<T>) -> @error any Error {
// CHECK-LABEL: // Enum<A>.init(from:)
// CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum4EnumOAASeRzSERzlE4fromACyxGs7Decoder_p_tKcfC : $@convention(method) <T where T : Decodable, T : Encodable> (@in any Decoder, @thin Enum<T>.Type) -> (@out Enum<T>, @error any Error)
extension NoValues: CaseIterable {}
// CHECK-LABEL: // static NoValues.allCases.getter
// CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum8NoValuesO8allCasesSayACGvgZ : $@convention(method) (@thin NoValues.Type) -> @owned Array<NoValues> {
extension NoValues: Codable {}
// CHECK-LABEL: // NoValues.encode(to:)
// CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum8NoValuesO6encode2toys7Encoder_p_tKF : $@convention(method) (@in_guaranteed any Encoder, NoValues) -> @error any Error {
// CHECK-LABEL: // NoValues.init(from:)
// CHECK-NEXT: sil hidden [ossa] @$s28synthesized_conformance_enum8NoValuesO4fromACs7Decoder_p_tKcfC : $@convention(method) (@in any Decoder, @thin NoValues.Type) -> (NoValues, @error any Error)
// Witness tables for Enum
// CHECK-LABEL: sil_witness_table hidden <T where T : Equatable> Enum<T>: Equatable module synthesized_conformance_enum {
// CHECK-NEXT: method #Equatable."==": <Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool : @$s28synthesized_conformance_enum4EnumOyxGSQAASQRzlSQ2eeoiySbx_xtFZTW // protocol witness for static Equatable.== infix(_:_:) in conformance <A> Enum<A>
// CHECK-NEXT: conditional_conformance (T: Equatable): dependent
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden <T where T : Hashable> Enum<T>: Hashable module synthesized_conformance_enum {
// CHECK-DAG: base_protocol Equatable: <T where T : Equatable> Enum<T>: Equatable module synthesized_conformance_enum
// CHECK-DAG: method #Hashable.hashValue!getter: <Self where Self : Hashable> (Self) -> () -> Int : @$s28synthesized_conformance_enum4EnumOyxGSHAASHRzlSH9hashValueSivgTW // protocol witness for Hashable.hashValue.getter in conformance <A> Enum<A>
// CHECK-DAG: method #Hashable.hash: <Self where Self : Hashable> (Self) -> (inout Hasher) -> () : @$s28synthesized_conformance_enum4EnumOyxGSHAASHRzlSH4hash4intoys6HasherVz_tFTW // protocol witness for Hashable.hash(into:) in conformance <A> Enum<A>
// CHECK-DAG: method #Hashable._rawHashValue: <Self where Self : Hashable> (Self) -> (Int) -> Int : @$s28synthesized_conformance_enum4EnumOyxGSHAASHRzlSH13_rawHashValue4seedS2i_tFTW // protocol witness for Hashable._rawHashValue(seed:) in conformance <A> Enum<A>
// CHECK-DAG: conditional_conformance (T: Hashable): dependent
// CHECK: }
// CHECK-LABEL: sil_witness_table hidden <T where T : Decodable, T : Encodable> Enum<T>: Decodable module synthesized_conformance_enum {
// CHECK-NEXT: method #Decodable.init!allocator: <Self where Self : Decodable> (Self.Type) -> (any Decoder) throws -> Self : @$s28synthesized_conformance_enum4EnumOyxGSeAASeRzSERzlSe4fromxs7Decoder_p_tKcfCTW // protocol witness for Decodable.init(from:) in conformance <A> Enum<A>
// CHECK-NEXT: conditional_conformance (T: Decodable): dependent
// CHECK-NEXT: conditional_conformance (T: Encodable): dependent
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden <T where T : Decodable, T : Encodable> Enum<T>: Encodable module synthesized_conformance_enum {
// CHECK-NEXT: method #Encodable.encode: <Self where Self : Encodable> (Self) -> (any Encoder) throws -> () : @$s28synthesized_conformance_enum4EnumOyxGSEAASeRzSERzlSE6encode2toys7Encoder_p_tKFTW // protocol witness for Encodable.encode(to:) in conformance <A> Enum<A>
// CHECK-NEXT: conditional_conformance (T: Decodable): dependent
// CHECK-NEXT: conditional_conformance (T: Encodable): dependent
// CHECK-NEXT: }
// Witness tables for NoValues
// CHECK-LABEL: sil_witness_table hidden NoValues: CaseIterable module synthesized_conformance_enum {
// CHECK-NEXT: associated_type_protocol (AllCases: Collection): [NoValues]: specialize <NoValues> (<Element> Array<Element>: Collection module Swift)
// CHECK-NEXT: associated_type AllCases: Array<NoValues>
// CHECK-NEXT: method #CaseIterable.allCases!getter: <Self where Self : CaseIterable> (Self.Type) -> () -> Self.AllCases : @$s28synthesized_conformance_enum8NoValuesOs12CaseIterableAAsADP8allCases03AllI0QzvgZTW // protocol witness for static CaseIterable.allCases.getter in conformance NoValues
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden NoValues: Decodable module synthesized_conformance_enum {
// CHECK-NEXT: method #Decodable.init!allocator: <Self where Self : Decodable> (Self.Type) -> (any Decoder) throws -> Self : @$s28synthesized_conformance_enum8NoValuesOSeAASe4fromxs7Decoder_p_tKcfCTW // protocol witness for Decodable.init(from:) in conformance NoValues
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden NoValues: Encodable module synthesized_conformance_enum {
// CHECK-NEXT: method #Encodable.encode: <Self where Self : Encodable> (Self) -> (any Encoder) throws -> () : @$s28synthesized_conformance_enum8NoValuesOSEAASE6encode2toys7Encoder_p_tKFTW // protocol witness for Encodable.encode(to:) in conformance NoValues
// CHECK-NEXT: }
| apache-2.0 | 7c941b9209ab71a67c1075d4953230a3 | 72.87156 | 296 | 0.72839 | 3.420561 | false | false | false | false |
calebkleveter/Ether | Sources/Ether/Template/TemplateRemove.swift | 1 | 2667 | // The MIT License (MIT)
//
// Copyright (c) 2017 Caleb Kleveter
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import Helpers
import Command
public final class TemplateRemove: Command {
public var arguments: [CommandArgument] = [
CommandArgument.argument(name: "name", help: ["The name used to identify the template"])
]
public var options: [CommandOption] = []
public var help: [String] = ["Deletes a stored project template"]
public init() {}
public func run(using context: CommandContext) throws -> EventLoopFuture<Void> {
let name = try context.argument("name")
let temapletBar = context.console.loadingBar(title: "Deleting Template")
_ = temapletBar.start(on: context.container)
let user = try Process.execute("whoami")
try FileManager.default.createDirectory(
at: URL(string: "file:/Users/\(user)/Library/Application%20Support/Ether/Templates")!,
withIntermediateDirectories: true,
attributes: [:]
)
var isDir : ObjCBool = true
let directoryExists = FileManager.default.fileExists(atPath: "/Users/\(user)/Library/Application Support/Ether/Templates/\(name)", isDirectory: &isDir)
if !directoryExists { throw EtherError(identifier: "templateNotFound", reason: "No template with the name '\(name)' was found") }
_ = try Process.execute("rm", ["-rf", "/Users/\(user)/Library/Application Support/Ether/Templates/\(name)"])
temapletBar.succeed()
return context.container.future()
}
}
| mit | 63de659873e480569b76597691f12814 | 43.45 | 159 | 0.693288 | 4.590361 | false | false | false | false |
kickstarter/ios-oss | KsApi/mutations/templates/query/FetchCategoryQueryTemplate.swift | 1 | 3696 | import Apollo
import Foundation
@testable import KsApi
public enum FetchCategoryQueryTemplate {
case valid
case errored
var data: GraphAPI.FetchCategoryQuery.Data {
switch self {
case .valid:
return GraphAPI.FetchCategoryQuery.Data(unsafeResultMap: self.validResultMap)
case .errored:
return GraphAPI.FetchCategoryQuery.Data(unsafeResultMap: self.erroredResultMap)
}
}
// MARK: Private Properties
private var validResultMap: [String: Any] {
let json = """
{
"node": {
"__typename": "Category",
"analyticsName": "Comics",
"id": "Q2F0ZWdvcnktMw==",
"name": "Comics",
"subcategories": {
"__typename": "CategorySubcategoriesConnection",
"nodes": [
{
"__typename": "Category",
"parentId": "Q2F0ZWdvcnktMw==",
"totalProjectCount": 23,
"id": "Q2F0ZWdvcnktMjQ5",
"name": "Anthologies",
"analyticsName": "Anthologies",
"parentCategory": {
"__typename": "Category",
"id": "Q2F0ZWdvcnktMw==",
"name": "Comics",
"analyticsName": "Comics"
}
},
{
"__typename": "Category",
"parentId": "Q2F0ZWdvcnktMw==",
"totalProjectCount": 149,
"id": "Q2F0ZWdvcnktMjUw",
"name": "Comic Books",
"analyticsName": "Comic Books",
"parentCategory": {
"__typename": "Category",
"id": "Q2F0ZWdvcnktMw==",
"name": "Comics",
"analyticsName": "Comics"
}
},
{
"__typename": "Category",
"parentId": "Q2F0ZWdvcnktMw==",
"totalProjectCount": 0,
"id": "Q2F0ZWdvcnktMjUx",
"name": "Events",
"analyticsName": "Events",
"parentCategory": {
"__typename": "Category",
"id": "Q2F0ZWdvcnktMw==",
"name": "Comics",
"analyticsName": "Comics"
}
},
{
"__typename": "Category",
"parentId": "Q2F0ZWdvcnktMw==",
"totalProjectCount": 86,
"id": "Q2F0ZWdvcnktMjUy",
"name": "Graphic Novels",
"analyticsName": "Graphic Novels",
"parentCategory": {
"__typename": "Category",
"id": "Q2F0ZWdvcnktMw==",
"name": "Comics",
"analyticsName": "Comics"
}
},
{
"__typename": "Category",
"parentId": "Q2F0ZWdvcnktMw==",
"totalProjectCount": 12,
"id": "Q2F0ZWdvcnktMjUz",
"name": "Webcomics",
"analyticsName": "Webcomics",
"parentCategory": {
"__typename": "Category",
"id": "Q2F0ZWdvcnktMw==",
"name": "Comics",
"analyticsName": "Comics"
}
}
],
"totalCount": 5
},
"totalProjectCount": 306
}
}
"""
let data = Data(json.utf8)
var resultMap = (try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]) ?? [:]
return resultMap
}
private var erroredResultMap: [String: Any?] {
return [:]
}
}
| apache-2.0 | 6ff70a5be06315a68b3db3defc9e6a0f | 30.322034 | 105 | 0.4329 | 4.332943 | false | false | false | false |
banxi1988/BXCityPicker | Example/Pods/BXForm/Pod/Classes/Cells/LoginButtonCell.swift | 2 | 2522 | //
// LoginButtonCell.swift
// Pods
//
// Created by Haizhen Lee on 16/1/23.
//
//
import UIKit
import BXModel
import BXiOSUtils
import PinAuto
//-LoginButtonCell:stc
//login[t18,l10,r10,h50](cw,f18,text=登录):b
//reg[at10@login,bl14@login](f15,ctt,text=快速注册):b
//reset[bf10@login,y@reg](f15,ctt,text=忘记密码):b
open class LoginButtonCell : StaticTableViewCell{
open let loginButton = UIButton(type:.system)
open let regButton = UIButton(type:.system)
open let resetButton = UIButton(type:.system)
public convenience init() {
self.init(style: .default, reuseIdentifier: "LoginButtonCellCell")
}
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
open override func awakeFromNib() {
super.awakeFromNib()
commonInit()
}
var allOutlets :[UIView]{
return [loginButton,regButton,resetButton]
}
var allUIButtonOutlets :[UIButton]{
return [loginButton,regButton,resetButton]
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open func commonInit(){
staticHeight = 120
frame = CGRect(x: 0, y: 0, width: 320, height: staticHeight)
for childView in allOutlets{
contentView.addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
installConstaints()
setupAttrs()
}
open func installConstaints(){
loginButton.pa_height.eq(50).install()
loginButton.pa_trailing.eq(10).install()
loginButton.pa_top.eq(5).install()
loginButton.pa_leading.eq(10).install()
regButton.pa_below(loginButton,offset:14).install()
regButton.pa_leading.to(loginButton).offset(10).install()
resetButton.pa_centerY.to(regButton).install()
resetButton.pa_trailing.to(loginButton).offset(10).install()
}
open func setupAttrs(){
loginButton.setTitle("登录",for: UIControlState())
loginButton.setTitleColor(UIColor.white,for: UIControlState())
loginButton.titleLabel?.font = UIFont.systemFont(ofSize: 18)
regButton.setTitleColor(FormColors.tertiaryTextColor,for: .normal)
regButton.setTitle("快速注册",for: UIControlState())
regButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
resetButton.setTitleColor(FormColors.tertiaryTextColor,for: .normal)
resetButton.setTitle("忘记密码",for: UIControlState())
resetButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
}
}
| mit | 2f294000afc2eb5cddada8eb8f9abf71 | 29.268293 | 79 | 0.717969 | 3.939683 | false | false | false | false |
vl4298/mah-income | Mah Income/Mah Income/Scenes/Add Bill/List Reason/ReasonTableViewCell.swift | 1 | 994 | //
// ReasonTableViewCell.swift
// Mah Income
//
// Created by Van Luu on 4/16/17.
// Copyright © 2017 Van Luu. All rights reserved.
//
import UIKit
class ReasonTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var commentLabel: UILabel!
@IBOutlet weak var reasonStackView: UIStackView!
@IBOutlet weak var underlineButton: MM3DButton!
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
reasonStackView.isUserInteractionEnabled = false
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func prepareForReuse() {
super.prepareForReuse()
commentLabel.isHidden = false
}
func configureData(model: ReasonModel) {
titleLabel.text = model.title
if let comment = model.comment {
commentLabel.text = comment
} else {
commentLabel.isHidden = true
}
}
}
| mit | 1f8f1415029f9af2e25cdb5894316343 | 21.066667 | 63 | 0.690836 | 4.472973 | false | false | false | false |
roambotics/swift | test/Interop/Cxx/class/type-classification-non-trivial-silgen.swift | 2 | 15294 | // RUN: %target-swiftxx-frontend -I %S/Inputs -emit-silgen %s | %FileCheck %s
import TypeClassification
// Make sure that "StructWithDestructor" is marked as non-trivial by checking for a
// "destroy_addr".
// CHECK-LABEL: sil [ossa] @$s4main24testStructWithDestructoryyF
// CHECK: [[AS:%.*]] = alloc_stack [lexical] $StructWithDestructor
// CHECK: [[FN:%.*]] = function_ref @{{_ZN20StructWithDestructorC1Ev|\?\?0StructWithDestructor@@QEAA@XZ}} : $@convention(c) () -> @out StructWithDestructor
// CHECK: apply [[FN]]([[AS]]) : $@convention(c) () -> @out StructWithDestructor
// CHECK: destroy_addr [[AS]]
// CHECK: dealloc_stack %0 : $*StructWithDestructor
// CHECK-LABEL: end sil function '$s4main24testStructWithDestructoryyF'
// CHECK-LABEL: sil [clang StructWithDestructor.init] @{{_ZN20StructWithDestructorC1Ev|\?\?0StructWithDestructor@@QEAA@XZ}} : $@convention(c) () -> @out StructWithDestructor
public func testStructWithDestructor() {
let d = StructWithDestructor()
}
// Make sure that "HasMemberWithDestructor" is marked as non-trivial by checking
// for a "destroy_addr".
// CHECK-LABEL: sil [ossa] @$s4main33testStructWithSubobjectDestructoryyF : $@convention(thin) () -> ()
// CHECK: [[AS:%.*]] = alloc_stack [lexical] $StructWithSubobjectDestructor
// CHECK: [[FN:%.*]] = function_ref @{{_ZN29StructWithSubobjectDestructorC1Ev|\?\?0StructWithSubobjectDestructor@@QEAA@XZ}} : $@convention(c) () -> @out StructWithSubobjectDestructor
// CHECK: apply [[FN]]([[AS]]) : $@convention(c) () -> @out StructWithSubobjectDestructor
// CHECK: destroy_addr [[AS]]
// CHECK-LABEL: end sil function '$s4main33testStructWithSubobjectDestructoryyF'
// CHECK-LABEL: sil [clang StructWithSubobjectDestructor.init] @{{_ZN29StructWithSubobjectDestructorC1Ev|\?\?0StructWithSubobjectDestructor@@QEAA@XZ}} : $@convention(c) () -> @out StructWithSubobjectDestructor
public func testStructWithSubobjectDestructor() {
let d = StructWithSubobjectDestructor()
}
// CHECK-LABEL: sil [ossa] @$s4main37testStructWithCopyConstructorAndValueSbyF
// CHECK: [[AS:%.*]] = alloc_stack [lexical] $StructWithCopyConstructorAndValue
// CHECK: [[FN:%.*]] = function_ref @{{_ZN33StructWithCopyConstructorAndValueC1Ei|\?\?0StructWithCopyConstructorAndValue@@QEAA@H@Z}} : $@convention(c) (Int32) -> @out StructWithCopyConstructorAndValue
// CHECK: apply [[FN]]([[AS]], %{{.*}}) : $@convention(c) (Int32) -> @out StructWithCopyConstructorAndValue
// CHECK: [[OBJ_VAL_ADDR:%.*]] = struct_element_addr [[AS]] : $*StructWithCopyConstructorAndValue, #StructWithCopyConstructorAndValue.value
// CHECK: [[OBJ_VAL:%.*]] = load [trivial] [[OBJ_VAL_ADDR]] : $*Int32
// CHECK: [[IL_42:%.*]] = integer_literal $Builtin.IntLiteral, 42
// CHECK: [[MAKE_INT_FN:%.*]] = function_ref @$ss5Int32V22_builtinIntegerLiteralABBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int32.Type) -> Int32
// CHECK: [[INT_42:%.*]] = apply [[MAKE_INT_FN]]([[IL_42]], %{{.*}}) : $@convention(method) (Builtin.IntLiteral, @thin Int32.Type) -> Int32
// CHECK: [[CMP_FN:%.*]] = function_ref @$ss5Int32V2eeoiySbAB_ABtFZ : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
// CHECK: [[OUT:%.*]] = apply [[CMP_FN]]([[OBJ_VAL]], [[INT_42]], %{{.*}}) : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
// CHECK: destroy_addr [[AS]] : $*StructWithCopyConstructorAndValue
// CHECK: return [[OUT]] : $Bool
// CHECK-LABEL: end sil function '$s4main37testStructWithCopyConstructorAndValueSbyF'
// CHECK-LABEL: sil [clang StructWithCopyConstructorAndValue.init] @{{_ZN33StructWithCopyConstructorAndValueC1Ei|\?\?0StructWithCopyConstructorAndValue@@QEAA@H@Z}} : $@convention(c) (Int32) -> @out StructWithCopyConstructorAndValue
public func testStructWithCopyConstructorAndValue() -> Bool {
let obj = StructWithCopyConstructorAndValue(42)
return obj.value == 42
}
// CHECK-LABEL: sil [ossa] @$s4main46testStructWithSubobjectCopyConstructorAndValueSbyF : $@convention(thin) () -> Bool
// CHECK: [[MEMBER_0:%.*]] = alloc_stack [lexical] $StructWithCopyConstructorAndValue
// CHECK: [[MAKE_MEMBER_FN:%.*]] = function_ref @{{_ZN33StructWithCopyConstructorAndValueC1Ei|\?\?0StructWithCopyConstructorAndValue@@QEAA@H@Z}} : $@convention(c) (Int32) -> @out StructWithCopyConstructorAndValue
// CHECK: apply [[MAKE_MEMBER_FN]]([[MEMBER_0]], %{{.*}}) : $@convention(c) (Int32) -> @out StructWithCopyConstructorAndValue
// CHECK: [[AS:%.*]] = alloc_stack [lexical] $StructWithSubobjectCopyConstructorAndValue
// CHECK: [[META:%.*]] = metatype $@thin StructWithSubobjectCopyConstructorAndValue.Type
// CHECK: [[MEMBER_1:%.*]] = alloc_stack $StructWithCopyConstructorAndValue
// CHECK: copy_addr %0 to [init] [[MEMBER_1]] : $*StructWithCopyConstructorAndValue
// CHECK: [[FN:%.*]] = function_ref @$sSo42StructWithSubobjectCopyConstructorAndValueV6memberABSo0abdefG0V_tcfC : $@convention(method) (@in StructWithCopyConstructorAndValue, @thin StructWithSubobjectCopyConstructorAndValue.Type) -> @out StructWithSubobjectCopyConstructorAndValue
// CHECK: apply [[FN]]([[AS]], [[MEMBER_1]], [[META]]) : $@convention(method) (@in StructWithCopyConstructorAndValue, @thin StructWithSubobjectCopyConstructorAndValue.Type) -> @out StructWithSubobjectCopyConstructorAndValue
// CHECK: [[OBJ_MEMBER:%.*]] = struct_element_addr [[AS]] : $*StructWithSubobjectCopyConstructorAndValue, #StructWithSubobjectCopyConstructorAndValue.member
// CHECK: [[MEMBER_2:%.*]] = alloc_stack $StructWithCopyConstructorAndValue
// CHECK: copy_addr [[OBJ_MEMBER]] to [init] [[MEMBER_2]] : $*StructWithCopyConstructorAndValue
// CHECK: [[OBJ_VALUE_ADDR:%.*]] = struct_element_addr [[MEMBER_2]] : $*StructWithCopyConstructorAndValue, #StructWithCopyConstructorAndValue.value
// CHECK: [[OBJ_VALUE:%.*]] = load [trivial] [[OBJ_VALUE_ADDR]] : $*Int32
// CHECK: [[MAKE_INT:%.*]] = function_ref @$ss5Int32V22_builtinIntegerLiteralABBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int32.Type) -> Int32
// CHECK: [[INT_42:%.*]] = apply [[MAKE_INT]]({{.*}}) : $@convention(method) (Builtin.IntLiteral, @thin Int32.Type) -> Int32
// CHECK: [[ICMP:%.*]] = function_ref @$ss5Int32V2eeoiySbAB_ABtFZ : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
// CHECK: [[OUT:%.*]] = apply [[ICMP]]([[OBJ_VALUE]], [[INT_42]], %{{.*}}) : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
// CHECK: return [[OUT]] : $Bool
// CHECK-LABEL: end sil function '$s4main46testStructWithSubobjectCopyConstructorAndValueSbyF'
public func testStructWithSubobjectCopyConstructorAndValue() -> Bool {
let member = StructWithCopyConstructorAndValue(42)
let obj = StructWithSubobjectCopyConstructorAndValue(member: member)
return obj.member.value == 42
}
// StructWithSubobjectCopyConstructorAndValue.init(member:)
// CHECK-LABEL: sil shared [transparent] [serialized] [ossa] @$sSo42StructWithSubobjectCopyConstructorAndValueV6memberABSo0abdefG0V_tcfC : $@convention(method) (@in StructWithCopyConstructorAndValue, @thin StructWithSubobjectCopyConstructorAndValue.Type) -> @out StructWithSubobjectCopyConstructorAndValue
// CHECK: [[MEMBER:%.*]] = struct_element_addr %0 : $*StructWithSubobjectCopyConstructorAndValue, #StructWithSubobjectCopyConstructorAndValue.member
// CHECK: copy_addr [take] %1 to [init] [[MEMBER]] : $*StructWithCopyConstructorAndValue
// CHECK-LABEL: end sil function '$sSo42StructWithSubobjectCopyConstructorAndValueV6memberABSo0abdefG0V_tcfC'
// testStructWithCopyConstructorAndSubobjectCopyConstructorAndValue()
// CHECK-LABEL: sil [ossa] @$s4main041testStructWithCopyConstructorAndSubobjectefG5ValueSbyF : $@convention(thin) () -> Bool
// CHECK: [[MEMBER_0:%.*]] = alloc_stack [lexical] $StructWithCopyConstructorAndValue
// CHECK: [[CREATE_MEMBER_FN:%.*]] = function_ref @{{_ZN33StructWithCopyConstructorAndValueC1Ei|\?\?0StructWithCopyConstructorAndValue@@QEAA@H@Z}} : $@convention(c) (Int32) -> @out StructWithCopyConstructorAndValue
// CHECK: apply [[CREATE_MEMBER_FN]]([[MEMBER_0]], %{{.*}}) : $@convention(c) (Int32) -> @out StructWithCopyConstructorAndValue
// CHECK: [[AS:%.*]] = alloc_stack [lexical] $StructWithCopyConstructorAndSubobjectCopyConstructorAndValue
// CHECK: [[MEMBER_1:%.*]] = alloc_stack $StructWithCopyConstructorAndValue
// CHECK: copy_addr [[MEMBER_0]] to [init] [[MEMBER_1]] : $*StructWithCopyConstructorAndValue
// CHECK: [[FN:%.*]] = function_ref @{{_ZN60StructWithCopyConstructorAndSubobjectCopyConstructorAndValueC1E33StructWithCopyConstructorAndValue|\?\?0StructWithCopyConstructorAndSubobjectCopyConstructorAndValue@@QEAA@UStructWithCopyConstructorAndValue@@@Z}} : $@convention(c) (@in StructWithCopyConstructorAndValue) -> @out StructWithCopyConstructorAndSubobjectCopyConstructorAndValue
// CHECK: apply [[FN]]([[AS]], [[MEMBER_1]]) : $@convention(c) (@in StructWithCopyConstructorAndValue) -> @out StructWithCopyConstructorAndSubobjectCopyConstructorAndValue
// CHECK: [[OBJ_MEMBER_ADDR:%.*]] = struct_element_addr [[AS]] : $*StructWithCopyConstructorAndSubobjectCopyConstructorAndValue, #StructWithCopyConstructorAndSubobjectCopyConstructorAndValue.member
// CHECK: [[MEMBER_2:%.*]] = alloc_stack $StructWithCopyConstructorAndValue
// CHECK: copy_addr [[OBJ_MEMBER_ADDR]] to [init] [[MEMBER_2]] : $*StructWithCopyConstructorAndValue
// CHECK: [[OBJ_MEMBER_VALUE_ADDR:%.*]] = struct_element_addr [[MEMBER_2]] : $*StructWithCopyConstructorAndValue, #StructWithCopyConstructorAndValue.value
// CHECK: [[OBJ_MEMBER_VALUE:%.*]] = load [trivial] [[OBJ_MEMBER_VALUE_ADDR]] : $*Int32
// CHECK: [[ICMP:%.*]] = function_ref @$ss5Int32V2eeoiySbAB_ABtFZ : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
// CHECK: [[OUT:%.*]] = apply [[ICMP]]([[OBJ_MEMBER_VALUE]], %{{.*}}) : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
// CHECK: return [[OUT]] : $Bool
// CHECK-LABEL: end sil function '$s4main041testStructWithCopyConstructorAndSubobjectefG5ValueSbyF'
public func testStructWithCopyConstructorAndSubobjectCopyConstructorAndValue()
-> Bool {
let member = StructWithCopyConstructorAndValue(42)
let obj = StructWithCopyConstructorAndSubobjectCopyConstructorAndValue(
member
)
return obj.member.value == 42
}
// CHECK-LABEL: sil [ossa] @$s4main4test3objSbSo33StructWithCopyConstructorAndValueV_tF : $@convention(thin) (@in_guaranteed StructWithCopyConstructorAndValue) -> Bool
// CHECK: [[META_1:%.*]] = metatype $@thin Int32.Type
// CHECK: [[OBJ_VAL_ADDR:%.*]] = struct_element_addr %0 : $*StructWithCopyConstructorAndValue, #StructWithCopyConstructorAndValue.value
// CHECK: [[OBJ_VAL:%.*]] = load [trivial] [[OBJ_VAL_ADDR]] : $*Int32
// CHECK: [[IL_42:%.*]] = integer_literal $Builtin.IntLiteral, 42
// CHECK: [[META_2:%.*]] = metatype $@thin Int32.Type
// CHECK: [[FN:%.*]] = function_ref @$ss5Int32V22_builtinIntegerLiteralABBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int32.Type) -> Int32
// CHECK: [[INT:%.*]] = apply [[FN]]([[IL_42]], [[META_2]]) : $@convention(method) (Builtin.IntLiteral, @thin Int32.Type) -> Int32
// CHECK: [[FN_2:%.*]] = function_ref @$ss5Int32V2eeoiySbAB_ABtFZ : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
// CHECK: [[OUT:%.*]] = apply [[FN_2]]([[OBJ_VAL]], [[INT]], [[META_1]]) : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
// CHECK: return [[OUT]] : $Bool
// CHECK-LABEL: end sil function '$s4main4test3objSbSo33StructWithCopyConstructorAndValueV_tF'
public func test(obj: StructWithCopyConstructorAndValue) -> Bool {
return obj.value == 42
}
// CHECK-LABEL: sil [ossa] @$s4main4test3objSbSo42StructWithSubobjectCopyConstructorAndValueV_tF : $@convention(thin) (@in_guaranteed StructWithSubobjectCopyConstructorAndValue) -> Bool
// CHECK: [[INT_META:%.*]] = metatype $@thin Int32.Type
// CHECK: [[OBJ_MEMBER:%.*]] = struct_element_addr %0 : $*StructWithSubobjectCopyConstructorAndValue, #StructWithSubobjectCopyConstructorAndValue.member
// CHECK: [[MEMBER_TMP:%.*]] = alloc_stack $StructWithCopyConstructorAndValue
// CHECK: copy_addr [[OBJ_MEMBER]] to [init] [[MEMBER_TMP]] : $*StructWithCopyConstructorAndValue
// CHECK: [[OBJ_MEMBER_VALUE_ADDR:%.*]] = struct_element_addr [[MEMBER_TMP]] : $*StructWithCopyConstructorAndValue, #StructWithCopyConstructorAndValue.value
// CHECK: [[OBJ_MEMBER_VALUE:%.*]] = load [trivial] [[OBJ_MEMBER_VALUE_ADDR]] : $*Int32
// CHECK: destroy_addr [[MEMBER_TMP]] : $*StructWithCopyConstructorAndValue
// CHECK: [[IL_42:%.*]] = integer_literal $Builtin.IntLiteral, 42
// CHECK: [[INT_META_2:%.*]] = metatype $@thin Int32.Type
// CHECK: [[MAKE_INT_FN:%.*]] = function_ref @$ss5Int32V22_builtinIntegerLiteralABBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int32.Type) -> Int32
// CHECK: [[INT_42:%.*]] = apply [[MAKE_INT_FN]]([[IL_42]], [[INT_META_2]]) : $@convention(method) (Builtin.IntLiteral, @thin Int32.Type) -> Int32
// CHECK: [[FN:%.*]] = function_ref @$ss5Int32V2eeoiySbAB_ABtFZ : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
// CHECK: [[OUT:%.*]] = apply [[FN]]([[OBJ_MEMBER_VALUE]], [[INT_42]], [[INT_META]]) : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
// CHECK: dealloc_stack [[MEMBER_TMP]] : $*StructWithCopyConstructorAndValue
// CHECK: return [[OUT]] : $Bool
// CHECK-LABEL: end sil function '$s4main4test3objSbSo42StructWithSubobjectCopyConstructorAndValueV_tF'
public func test(obj: StructWithSubobjectCopyConstructorAndValue) -> Bool {
return obj.member.value == 42
}
// CHECK-LABEL: sil [ossa] @$s4main4test3objSbSo037StructWithCopyConstructorAndSubobjectfgH5ValueV_tF
// CHECK: [[META_INT_1:%.*]] = metatype $@thin Int32.Type
// CHECK: [[OBJ_MEMBER:%.*]] = struct_element_addr %0 : $*StructWithCopyConstructorAndSubobjectCopyConstructorAndValue, #StructWithCopyConstructorAndSubobjectCopyConstructorAndValue.member
// CHECK: [[MEMBER_TMP:%.*]] = alloc_stack $StructWithCopyConstructorAndValue
// CHECK: copy_addr [[OBJ_MEMBER]] to [init] [[MEMBER_TMP]] : $*StructWithCopyConstructorAndValue
// CHECK: [[OBJ_MEMBER_VAL_ADDR:%.*]] = struct_element_addr [[MEMBER_TMP]] : $*StructWithCopyConstructorAndValue, #StructWithCopyConstructorAndValue.value
// CHECK: [[OBJ_MEMBER_VAL:%.*]] = load [trivial] [[OBJ_MEMBER_VAL_ADDR]] : $*Int32
// CHECK: destroy_addr [[MEMBER_TMP]] : $*StructWithCopyConstructorAndValue
// CHECK: [[IL_42:%.*]] = integer_literal $Builtin.IntLiteral, 42
// CHECK: [[META_INT_2:%.*]] = metatype $@thin Int32.Type
// CHECK: [[MAKE_INT_FN:%.*]] = function_ref @$ss5Int32V22_builtinIntegerLiteralABBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int32.Type) -> Int32
// CHECK: [[INT_42:%.*]] = apply [[MAKE_INT_FN]]([[IL_42]], [[META_INT_2]]) : $@convention(method) (Builtin.IntLiteral, @thin Int32.Type) -> Int32
// CHECK: [[ICMP_FN:%.*]] = function_ref @$ss5Int32V2eeoiySbAB_ABtFZ : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
// CHECK: [[OUT:%.*]] = apply [[ICMP_FN]]([[OBJ_MEMBER_VAL]], [[INT_42]], [[META_INT_1]]) : $@convention(method) (Int32, Int32, @thin Int32.Type) -> Bool
// CHECK: dealloc_stack [[MEMBER_TMP]] : $*StructWithCopyConstructorAndValue
// CHECK: return [[OUT]] : $Bool
// CHECK-LABEL: end sil function '$s4main4test3objSbSo037StructWithCopyConstructorAndSubobjectfgH5ValueV_tF'
public func test(
obj: StructWithCopyConstructorAndSubobjectCopyConstructorAndValue
) -> Bool {
return obj.member.value == 42
}
| apache-2.0 | c4b5faf31f30fa9fe8d0be5afd6eba79 | 86.896552 | 382 | 0.727802 | 4.008912 | false | true | false | false |
lammertw/PagingDatePicker | Pod/Classes/PagingDateAndMonthPickerView.swift | 1 | 2718 | //
// PagingDateAndMonthPickerView.swift
// FareCalendar
//
// Created by Lammert Westerhoff on 22/03/16.
// Copyright © 2016 NS International B.V. All rights reserved.
//
import UIKit
public class PagingDateAndMonthPickerView: UIView {
@IBInspectable public var monthPickerHeight: CGFloat = 110.0
public var datePickerViewClass = DatePickerWithoutMonthView.self
private lazy var monthPickerView: MonthPickerView = {
let view = MonthPickerView(frame: CGRectNull)
self.addSubview(view)
return view
}()
public var transitionStyle = UIPageViewControllerTransitionStyle.Scroll
private lazy var datePickerView: PagingDatePickerView = {
let view = PagingDatePickerView(frame: CGRectNull)
view.datePickerViewClass = self.datePickerViewClass
self.addSubview(view)
return view
}()
public lazy var datePickerViewControl: PagingDateAndMonthPickerViewControl = {
let control = PagingDateAndMonthPickerViewControl()
control.monthPickerView = self.monthPickerView
control.datePickerView = self.datePickerView
return control
}()
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func layoutSubviews() {
datePickerViewControl.monthPickerView.frame = CGRectMake(0, 0, CGRectGetWidth(bounds), monthPickerHeight)
datePickerViewControl.datePickerView.frame = CGRectMake(0, monthPickerHeight, CGRectGetWidth(bounds), CGRectGetHeight(bounds) - monthPickerHeight)
}
}
public class PagingDateAndMonthPickerViewControl: NSObject {
public var datePickerViewClass = DatePickerWithoutMonthView.self {
didSet {
datePickerView?.datePickerViewClass = datePickerViewClass
}
}
@IBOutlet public var monthPickerView: MonthPickerView! {
didSet {
monthPickerView.delegate = self
}
}
@IBOutlet public var datePickerView: PagingDatePickerView! {
didSet {
datePickerView.datePickerViewClass = datePickerViewClass
datePickerView.delegate = self
}
}
}
extension PagingDateAndMonthPickerViewControl: MonthPickerViewDelegate {
public func monthPickerView(monthPickerView: MonthPickerView, didSelectDate date: NSDate) {
datePickerView.scrollToDate(date)
}
}
extension PagingDateAndMonthPickerViewControl: PagingDatePickerViewDelegate {
public func pagingDatePickerView(pagingDatePickerView: PagingDatePickerView, didPageToMonthDate date: NSDate) {
monthPickerView.scrollToDate(date, animated: true)
}
}
| mit | 193cb8a7fe9b5426c75cdf23f908a394 | 29.875 | 154 | 0.720648 | 5.165399 | false | false | false | false |
WSDOT/wsdot-ios-app | wsdot/ThemeManager.swift | 1 | 12142 | //
// File.swift
// WSDOT
//
// Created by Logan Sims on 2/2/18.
// Copyright © 2018 WSDOT. All rights reserved.
//
import Foundation
struct Colors {
static let wsdotPrimary = UIColor.init(red: 0.0/255.0, green: 123.0/255.0, blue: 95.0/255.0, alpha: 1)
static let wsdotPrimaryDark = UIColor.init(red: 0.0/255.0, green: 81.0/255.0, blue: 81.0/255.0, alpha: 1)
static let wsdotOrange = UIColor.init(red: 255.0/255.0, green: 108.0/255.0, blue: 12.0/255.0, alpha: 1)
static let wsdotDarkOrange = UIColor.init(red: 196.0/255.0, green: 59.0/255.0, blue: 0.0/255.0, alpha: 1)
static let wsdotBlue = UIColor.init(red: 0.0/255.0, green: 123.0/255.0, blue: 154.0/255.0, alpha: 1)
static let customColor = UIColor.init(red: 0.0/255.0, green: 63.0/255.0, blue: 135.0/255.0, alpha: 1)
static let tintColor = UIColor.init(red: 0.0/255.0, green: 174.0/255.0, blue: 65.0/255.0, alpha: 1)
static let yellow = UIColor.init(red: 255.0/255.0, green: 235.0/255.0, blue: 59.0/255.0, alpha: 1)
static let lightGreen = UIColor.init(red: 204.0/255.0, green: 239.0/255.0, blue: 184.0/255.0, alpha: 1)
static let lightGrey = UIColor.init(red: 242.0/255.0, green: 242.0/255.0, blue: 242.0/255.0, alpha: 1)
static let paleGrey = UIColor.init(red: 209.0/255.0, green: 213.0/255.0, blue: 219.0/255.0, alpha: 1)
// Utility Colors
static let wsdotGray100 = UIColor.init(red: 29.0/255.0, green: 37.0/255.0, blue: 45.0/255.0, alpha: 1)
static let wsdotGray80 = UIColor.init(red: 74.0/255.0, green: 81.0/255.0, blue: 87.0/255.0, alpha: 1)
static let wsdotGray60 = UIColor.init(red: 119.0/255.0, green: 124.0/255.0, blue: 129.0/255.0, alpha: 1)
static let wsdotGray40 = UIColor.init(red: 165.0/255.0, green: 168.0/255.0, blue: 171.0/255.0, alpha: 1)
static let wsdotGray20 = UIColor.init(red: 210.0/255.0, green: 211.0/255.0, blue: 213.0/255.0, alpha: 1)
static let wsdotGray10 = UIColor.init(red: 232.0/255.0, green: 233.0/255.0, blue: 234.0/255.0, alpha: 1)
static let wsdotGray5 = UIColor.init(red: 244.0/255.0, green: 244.0/255.0, blue: 255.0/255.0, alpha: 1)
static let wsdotWhite = UIColor.init(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1)
static let wsdotGreen = UIColor.init(red: 40.0/255.0, green: 167.0/255.0, blue: 69.0/255.0, alpha: 1)
static let wsdotRed = UIColor.init(red: 220.0/255.0, green: 53.0/255.0, blue: 69.0/255.0, alpha: 1)
static let wsdotYellow = UIColor.init(red: 255.0/255.0, green: 193.0/255.0, blue: 7.0/255.0, alpha: 1)
static let wsdotPurple = UIColor.init(red: 89.0/255.0, green: 49.0/255.0, blue: 95.0/255.0, alpha: 1)
// Brand-Primary
static let wsdotPrimaryBrand100 = UIColor.init(red: 0.0/255.0, green: 123.0/255.0, blue: 95.0/255.0, alpha: 1)
static let wsdotPrimaryBrand80 = UIColor.init(red: 51.0/255.0, green: 149.0/255.0, blue: 127.0/255.0, alpha: 1)
static let wsdotPrimaryBrand60 = UIColor.init(red: 102.0/255.0, green: 176.0/255.0, blue: 159.0/255.0, alpha: 1)
static let wsdotPrimaryBrand40 = UIColor.init(red: 153.0/255.0, green: 202.0/255.0, blue: 191.0/255.0, alpha: 1)
// Brand-Secondary
static let wsdotLightAccent100 = UIColor.init(red: 151.0/255.0, green: 215.0/255.0, blue: 0.0/255.0, alpha: 1)
static let wsdotLightAccentSoftened = UIColor.init(red: 173.0/255.0, green: 200.0/255.0, blue: 109.0/255.0, alpha: 1)
static let wsdotDarkAccent100 = UIColor.init(red: 0.0/255.0, green: 81.0/255.0, blue: 81.0/255.0, alpha: 1)
// Sub-Brand
static let wsdotPMS519100 = UIColor.init(red: 89.0/255.0, green: 49.0/255.0, blue: 95.0/255.0, alpha: 1)
static let wsdotPMS1585100 = UIColor.init(red: 255.0/255.0, green: 106.0/255.0, blue: 19.0/255.0, alpha: 1)
static let wsdotPMS3125100 = UIColor.init(red: 0.0/255.0, green: 174.0/255.0, blue: 199.0/255.0, alpha: 1)
static let wsdotPMS314100 = UIColor.init(red: 0.0/255.0, green: 127.0/255.0, blue: 163.0/255.0, alpha: 1)
}
enum Theme: Int {
case defaultTheme = 0, orangeTheme = 1, blueTheme = 2, customTheme = 3, emergencyTheme = 4
var mainColor: UIColor {
switch self {
case .defaultTheme:
if #available(iOS 13, *) {
// Update Navigation Bar for iOS 15
let appearance = UINavigationBarAppearance()
appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
appearance.backgroundColor = Colors.wsdotPrimary
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
return UIColor.init { (trait) -> UIColor in
return trait.userInterfaceStyle == .dark ? Colors.wsdotPrimaryDark : Colors.wsdotPrimary
}
}
return Colors.wsdotPrimary
case .orangeTheme:
if #available(iOS 13, *) {
// Update Navigation Bar for iOS 15
let appearance = UINavigationBarAppearance()
appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
appearance.backgroundColor = Colors.wsdotOrange
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
return UIColor.init { (trait) -> UIColor in
return trait.userInterfaceStyle == .dark ? Colors.wsdotDarkOrange : Colors.wsdotOrange
}
}
return Colors.wsdotOrange
case .blueTheme:
if #available(iOS 13, *) {
// Update Navigation Bar for iOS 15
let appearance = UINavigationBarAppearance()
appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
appearance.backgroundColor = Colors.wsdotBlue
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
return UIColor.init { (trait) -> UIColor in
return trait.userInterfaceStyle == .dark ? Colors.wsdotBlue : Colors.wsdotBlue
}
}
return Colors.wsdotBlue
case .customTheme:
if #available(iOS 13, *) {
// Update Navigation Bar for iOS 15
let appearance = UINavigationBarAppearance()
appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
appearance.backgroundColor = Colors.customColor
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
return UIColor.init { (trait) -> UIColor in
return trait.userInterfaceStyle == .dark ? Colors.customColor : Colors.customColor
}
}
return Colors.customColor
case .emergencyTheme:
if #available(iOS 13, *) {
// Update Navigation Bar for iOS 15
let appearance = UINavigationBarAppearance()
appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
appearance.backgroundColor = Colors.wsdotPrimary
UINavigationBar.appearance().standardAppearance = appearance
UINavigationBar.appearance().scrollEdgeAppearance = appearance
return UIColor.init { (trait) -> UIColor in
return trait.userInterfaceStyle == .dark ? Colors.wsdotPrimaryDark : Colors.wsdotPrimary
}
}
return Colors.wsdotPrimary
}
}
//Customizing the Navigation Bar
var barStyle: UIBarStyle {
switch self {
case .defaultTheme:
return .default
case .orangeTheme:
return .default
case .blueTheme:
return .default
case .customTheme:
return .default
case .emergencyTheme:
return .default
}
}
var darkColor: UIColor {
switch self {
case .defaultTheme:
return Colors.wsdotPrimary
case .orangeTheme:
return Colors.wsdotDarkOrange
case .blueTheme:
return Colors.wsdotBlue
case .customTheme:
return Colors.wsdotPrimary
case .emergencyTheme:
return Colors.wsdotPrimary
}
}
var secondaryColor: UIColor {
switch self {
case .defaultTheme:
return UIColor.white
case .orangeTheme:
return UIColor.white
case .blueTheme:
return UIColor.white
case .customTheme:
return UIColor.white
case .emergencyTheme:
return UIColor.white
}
}
var titleTextColor: UIColor {
switch self {
case .defaultTheme:
return UIColor.white
case .orangeTheme:
return UIColor.white
case .blueTheme:
return UIColor.white
case .customTheme:
return UIColor.white
case .emergencyTheme:
return UIColor.white
}
}
var linkColor: UIColor {
switch self {
case .defaultTheme:
return Colors.wsdotPrimary
case .orangeTheme:
return Colors.wsdotDarkOrange
case .blueTheme:
return Colors.wsdotBlue
case .customTheme:
return Colors.wsdotPrimary
case .emergencyTheme:
return Colors.wsdotPrimary
}
}
var bannerTextColor: UIColor {
switch self {
case .defaultTheme:
return Colors.wsdotPrimary
case .orangeTheme:
return Colors.wsdotDarkOrange
case .blueTheme:
return Colors.wsdotBlue
case .customTheme:
return Colors.wsdotPrimary
case .emergencyTheme:
return Colors.wsdotRed
}
}
}
// Enum declaration
let SelectedThemeKey = "SelectedTheme"
// This will let you use a theme in the app.
class ThemeManager {
// ThemeManager
static func currentTheme() -> Theme {
if let storedTheme = (UserDefaults.standard.value(forKey: SelectedThemeKey) as AnyObject).integerValue {
return Theme(rawValue: storedTheme)!
} else {
return .defaultTheme
}
}
static func applyTheme(theme: Theme) {
UserDefaults.standard.setValue(theme.rawValue, forKey: SelectedThemeKey)
UserDefaults.standard.synchronize()
let sharedApplication = UIApplication.shared
sharedApplication.delegate?.window??.tintColor = theme.mainColor
UIToolbar.appearance().tintColor = theme.darkColor
UITabBar.appearance().tintColor = theme.darkColor
UIProgressView.appearance().tintColor = theme.mainColor
UIPageControl.appearance().pageIndicatorTintColor = UIColor.gray
UIPageControl.appearance().currentPageIndicatorTintColor = theme.mainColor
UINavigationBar.appearance().barStyle = theme.barStyle
UINavigationBar.appearance().barTintColor = theme.mainColor
UINavigationBar.appearance().tintColor = theme.secondaryColor
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : theme.titleTextColor]
UIPopoverBackgroundView.appearance().tintColor = theme.mainColor
UITabBar.appearance().barStyle = theme.barStyle
UISwitch.appearance().onTintColor = theme.mainColor.withAlphaComponent(0.8)
UISegmentedControl.appearance().tintColor = theme.mainColor
}
}
| gpl-3.0 | bf4bb64fb983a155cad17971fe1d19ce | 38.806557 | 122 | 0.606128 | 4.072794 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.