repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
loudnate/Loop | Learn/Configuration/DateEntry.swift | 1 | 1244 | //
// DateEntry.swift
// Learn
//
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import LoopKitUI
class DateEntry {
private(set) var date: Date
let title: String
let mode: UIDatePicker.Mode
init(date: Date, title: String, mode: UIDatePicker.Mode) {
self.date = date
self.title = title
self.mode = mode
}
}
extension DateEntry: LessonCellProviding {
func registerCell(for tableView: UITableView) {
tableView.register(DateAndDurationTableViewCell.nib(), forCellReuseIdentifier: DateAndDurationTableViewCell.className)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: DateAndDurationTableViewCell.className, for: indexPath) as! DateAndDurationTableViewCell
cell.delegate = self
cell.titleLabel.text = title
cell.datePicker.isEnabled = true
cell.datePicker.datePickerMode = mode
cell.date = date
return cell
}
}
extension DateEntry: DatePickerTableViewCellDelegate {
func datePickerTableViewCellDidUpdateDate(_ cell: DatePickerTableViewCell) {
date = cell.datePicker.date
}
}
| apache-2.0 | 653eecfc387840d55b3db5cece56d1de | 27.906977 | 153 | 0.706356 | 4.93254 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Cliqz/Frontend/Browser/CliqzSearch.swift | 2 | 2857 | //
// CliqzSearch.swift
// Client
//
// Created by Mahmoud Adam on 10/26/15.
// Copyright © 2015 Mozilla. All rights reserved.
//
import UIKit
class CliqzSearch: NSObject {
fileprivate lazy var cachedData = Dictionary<String, [String : Any]>()
fileprivate var statisticsCollector = StatisticsCollector.sharedInstance
fileprivate let searchURL = "http://newbeta.cliqz.com/api/v1/results"
internal func startSearch(_ query: String, callback: @escaping ((query: String, data: [String: Any])) -> Void) {
if let data = cachedData[query] {
// let html = self.parseResponse(data, history: history)
callback((query, data))
} else {
statisticsCollector.startEvent(query)
DebugingLogger.log(">> Intiating the call the the Mixer with query: \(query)")
ConnectionManager.sharedInstance.sendRequest(.get, url: searchURL, parameters: ["q" : query], responseType: .jsonResponse, queue: DispatchQueue.main,
onSuccess: { json in
self.statisticsCollector.endEvent(query)
DebugingLogger.log("<< Received response for query: \(query)")
let jsonDict = json as! [String : Any]
self.cachedData[query] = jsonDict
// let html = self.parseResponse(jsonDict, history: history)
callback((query, jsonDict))
DebugingLogger.log("<< parsed response for query: \(query)")
},
onFailure: { (data, error) in
self.statisticsCollector.endEvent(query)
DebugingLogger.log("Request failed with error: \(error)")
if let data = data {
DebugingLogger.log("Response data: \(NSString(data: data, encoding: String.Encoding.utf8.rawValue)!)")
}
})
}
}
internal func clearCache() {
self.cachedData.removeAll()
}
fileprivate func parseResponse (_ json: NSDictionary, history: Array<Dictionary<String, String>>) -> String {
var html = "<html><head></head><body><font size='20'>"
if let results = json["result"] as? [[String:AnyObject]] {
for result in results {
var url = ""
if let u = result["url"] as? String {
url = u
}
var snippet = [String:AnyObject]()
if let s = result["snippet"] as? [String:AnyObject] {
snippet = s
}
var title = ""
if let t = snippet["title"] as? String {
title = t
}
html += "<a href='\(url)'>\(title)</a></br></br>"
}
}
for h in history {
var url = ""
if let u = h["url"] {
url = u
}
var title = ""
if let t = h["title"] {
title = t
}
html += "<a href='\(url)' style='color: #FFA500;'>\(title)</a></br></br>"
}
html += "</font></body></html>"
return html
}
}
| mpl-2.0 | 2fa5b71c84c6fb45e695892158478514 | 32.209302 | 161 | 0.570728 | 4.045326 | false | false | false | false |
StateMachineJunkie/ScrollingMarquee | ScrollingMarquee/ViewController.swift | 1 | 1166 | //
// ViewController.swift
// ScrollingMarquee
//
// Created by Michael A. Crawford on 6/8/16.
// Copyright © 2016 Crawford Design Engineering, LLC. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let sm = ScrollingMarquee(frame: CGRect(x: 0, y: 20, width: view.bounds.width, height: 44.0))
sm.delegate = self
sm.delay = 2.0
sm.text = "This is a string that is too wide for the view I've assigned it to."
sm.mode = /* .Circular */ .FullExit
sm.scrollSpeed = .Fast
self.view.addSubview(sm)
sm.startScrolling()
}
}
extension ViewController: ScrollingMarqueeDelegate {
func scrollingMarquee(marquee: ScrollingMarquee, didBeginScrollingWithDelay delay: NSTimeInterval) {
if delay > 0 {
print("Scrolling will start in \(delay) seconds")
} else {
print("Scrolling started")
}
}
func scrollingMarquee(marquee: ScrollingMarquee, didEndScrolling finished: Bool) {
print("Scrolling \(finished ? "finished" : "interrupted")")
}
}
| mit | 9b8716d2964d7efc079ca05e1486aeae | 28.871795 | 104 | 0.640343 | 4.251825 | false | false | false | false |
abu0306/CnPhoto | CnPhoto/CnPhoto/CnPhotoCollection.swift | 1 | 10261 | //
// CnPhotoCollection.swift
// photos
//
// Created by abu on 2017/8/7.
// Copyright © 2017年 abu. All rights reserved.
//
import UIKit
import Photos
private let bottomViewHeight : CGFloat = 44
enum authorNum:Int {
case first
case denied
}
class myNavigationController: UINavigationController {
override var preferredStatusBarStyle: UIStatusBarStyle{
return UIStatusBarStyle.lightContent
}
}
class CnPhotoCollection: UIViewController {
var bgColor : UIColor?
var navBgColor : UIColor?
var tintColor : UIColor?
/// 是否是单选 Default : true
var isDoublePicker = true{
didSet{
UserDefaults.standard.set(isDoublePicker, forKey: cnIsDoublePickerKey)
UserDefaults.standard.synchronize()
}
}
fileprivate var mylistView : CnPhotoList?
fileprivate var fetchResult : PHFetchResult<PHAsset>?
weak var delegate : CnPhotoProtocol?
lazy var navBarView = UIView()
lazy var bottomBgView = UIView(frame: CGRect.zero)
override func viewDidLoad() {
super.viewDidLoad()
getPhotoAlbumPermissions()
setupUI()
let ins = UserDefaults.standard.integer(forKey: cnPhotoCountKey)
if ins == 0{
UserDefaults.standard.set(9, forKey: cnPhotoCountKey)
UserDefaults.standard.synchronize()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
@objc fileprivate func btnAction() {
self.dismiss(animated: true, completion: nil)
}
fileprivate func setupUI(){
view.backgroundColor = bgColor
automaticallyAdjustsScrollViewInsets = false
title = "相册"
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : tintColor ?? UIColor.black]
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 44))
btn.setTitle("取消", for: .normal)
btn.setTitleColor(tintColor, for: .normal)
btn.addTarget(self, action: #selector(btnAction), for: .touchUpInside)
let navBarItem = UIBarButtonItem(customView: btn)
navigationItem.rightBarButtonItem = navBarItem
navBarView.frame = CGRect(x: 0, y: 0, width: cnScreenW, height: 64)
navBarView.alpha = 0.7
navBarView.backgroundColor = navBgColor
view.addSubview(navBarView)
}
fileprivate func dobulePickerImgViewUI() {
bottomBgView.backgroundColor = UIColor.clear
bottomBgView.frame = CGRect(x: 0, y: view.bounds.size.height - bottomViewHeight, width: cnScreenW, height: bottomViewHeight)
view.addSubview(bottomBgView)
let maskBgView = UIView(frame: CGRect.zero)
maskBgView.backgroundColor = UIColor.black
maskBgView.alpha = 0.6
maskBgView.frame = CGRect(x: 0, y: 0, width: cnScreenW, height: bottomViewHeight)
bottomBgView.addSubview(maskBgView)
let cancleBtn = UIButton(type: .custom)
cancleBtn.frame = CGRect(x: 15, y: 8, width: 60, height: bottomViewHeight - 16)
cancleBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
cancleBtn.setTitle("预览", for: .normal)
cancleBtn.setTitleColor(UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 0.7), for: .normal)
cancleBtn.addTarget(self, action: #selector(singlePickerAction(_:)), for: .touchUpInside)
bottomBgView.addSubview(cancleBtn)
cancleBtn.tag = cancleBtnTAG
let determineBtn = UIButton(type: .custom)
determineBtn.frame = CGRect(x: cnScreenW - 75, y: 8, width: 60, height: bottomViewHeight - 16)
determineBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
determineBtn.setTitle("完成", for: .normal)
determineBtn.backgroundColor = UIColor(red: 81.0/255.0, green: 169.0/255.0, blue: 56.0/255.0, alpha: 1)
determineBtn.setTitleColor(UIColor.white, for: .normal)
determineBtn.addTarget(self, action: #selector(singlePickerAction(_:)), for: .touchUpInside)
determineBtn.layer.cornerRadius = 3.0
determineBtn.layer.masksToBounds = true
bottomBgView.addSubview(determineBtn)
determineBtn.tag = determineBtnTAG
}
@objc fileprivate func singlePickerAction(_ sender : UIButton) {
switch sender.tag {
case cancleBtnTAG:
//预览
var localResult = [PHAsset]()
guard let doubleStatusCollection = mylistView?.doubleStatusCollection else { return }
for value in doubleStatusCollection {
guard let fr = fetchResult?[value] else {break}
localResult.append(fr)
}
let vc = CnBrowsePicture()
vc.fetchResult = localResult
vc.doubleStatusCollection = doubleStatusCollection
self.navigationController?.pushViewController(vc, animated: true)
break
default:
//完成
let delegate = (navigationController?.viewControllers.first as? CnPhotoCollection)?.delegate
var localResult = [PHAsset]()
guard let doubleStatusCollection = mylistView?.doubleStatusCollection else { return }
for value in doubleStatusCollection {
guard let fr = fetchResult?[value] else {break}
localResult.append(fr)
}
var imgArray = [UIImage]()
if (delegate?.responds(to: #selector(CnPhotoProtocol.completeSynchronousDoublePicture(_:_:)))) ?? false {
for assetValue in localResult {
CnRequestManager.getBigPictures(assetValue, completeHandler: { (img) in
imgArray.append(img)
if localResult.count == imgArray.count {
delegate?.completeSynchronousDoublePicture!(imgArray, {
self.dismiss(animated: true, completion: nil)
})
}
})
}
return
}else{
if (delegate?.responds(to: #selector(CnPhotoProtocol.completeDoublePicture(_:)))) ?? false {
for assetValue in localResult {
CnRequestManager.getBigPictures(assetValue, completeHandler: { (img) in
imgArray.append(img)
if localResult.count == imgArray.count {
delegate?.completeDoublePicture!(imgArray)
self.dismiss(animated: true, completion: nil)
}
})
}
return
}else{
fatalError("没有实现_CnPhotoProtocol协议")
}
}
break
}
}
}
extension CnPhotoCollection{
//获取相册权限
func getPhotoAlbumPermissions() {
let authorStatus = PHPhotoLibrary.authorizationStatus()
if authorStatus == PHAuthorizationStatus.restricted || authorStatus == PHAuthorizationStatus.denied{
//无权限(用户禁止)
let v = CnUserDisable(frame: CGRect(x: 0, y: 64, width: cnScreenW, height: cnScreenH - 64))
view.addSubview(v)
v.type = authorNum.denied
return
}
else{
let assetC = PHAssetCollection.fetchAssetCollections(with: PHAssetCollectionType.smartAlbum, subtype: PHAssetCollectionSubtype.smartAlbumUserLibrary, options: nil).lastObject
if assetC == nil
{
let v = CnUserDisable(frame: CGRect(x: 0, y: 64, width: cnScreenW, height: cnScreenH - 64))
view.addSubview(v)
v.type = authorNum.first
return
}
let listH : CGFloat = isDoublePicker ? (64 + bottomViewHeight) : 64
let v = CnPhotoList(frame: CGRect(x: 0, y: 64, width: cnScreenW, height: cnScreenH - listH))
v.assetCollection = assetC
view.addSubview(v)
mylistView = v
func getFetchResult(_ asset:PHAssetCollection?) {
guard let asset = asset else { return }
fetchResult = PHAsset.fetchAssets(in: asset, options: nil)
}
if isDoublePicker {
getFetchResult(assetC)
dobulePickerImgViewUI()
}
}
}
}
//MARK: - 没有或者禁用图片展示View
class CnUserDisable: UIView {
fileprivate lazy var MSgAlert = UILabel()
var type : authorNum?
override func layoutSubviews() {
setupUI()
}
func setupUI() {
backgroundColor = UIColor.white
MSgAlert.font = UIFont(name: "PingFangSC-Regular", size: 14)
MSgAlert.numberOfLines = 0
MSgAlert.textAlignment = .center
MSgAlert.textColor = UIColor(red: 102.0/255.0, green: 102.0/255.0, blue: 102.0/255.0, alpha: 1)
addSubview(MSgAlert)
var title = ""
guard let type = type else { return }
switch type {
case .denied:
title = "请在iPhone的“设置-隐私-照片”选项中,\n允许买卖时间访问你的相册。"
break
default:
title = "无照片"
break
}
MSgAlert.text = title
MSgAlert.sizeToFit()
MSgAlert.frame = CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: MSgAlert.bounds.height)
}
}
| mit | 7ed40318341c46dfdef6129873dac4f0 | 35.608696 | 187 | 0.586006 | 5.029368 | false | false | false | false |
zhaobin19918183/zhaobinCode | MapTest/MapTest/AudioDAO.swift | 1 | 3369 | //
// AudioDAO.swift
// MapTest
//
// Created by newland on 2017/12/11.
// Copyright © 2017年 newland. All rights reserved.
//
import UIKit
import CoreData
class AudioDAO: BaseDAO {
//MARK: - Create
static func createEntityWith(InitialClosure closure : (_ newEntity : AudioEntity )->() ) -> Bool
{
let entity = NSEntityDescription.insertNewObject(forEntityName: self.entityName(), into: BaseDAO.mainMOC) as! AudioEntity
closure(entity)
return self.save()
}
//MARK: 保存数据
static func creatBookListEntity(_ dicData : NSDictionary)
{
let success = AudioDAO.createEntityWith(InitialClosure: { (audioentity:AudioEntity) in
let filelong = dicData.value(forKey: "filelong") as! String
let fileName = dicData.value(forKey: "fileName") as! String
let fileTime = dicData.value(forKey: "fileTime") as! Date
let fileDistance = dicData.value(forKey: "fileDistance") as! String
let fileTimeLong = dicData.value(forKey: "fileTimeLong") as! String
let fileCoordinate = dicData.value(forKey: "fileCoordinate") as! Data
let fuileNumber = dicData.value(forKey: "fuileNumber") as! Data
let filetime1 = dicData.value(forKey: "filetime1") as! Data
let filetime2 = dicData.value(forKey: "filetime1") as! Data
let filetime3 = dicData.value(forKey: "fileTime3") as! Data
audioentity.filelong = filelong
audioentity.fileName = fileName
audioentity.fileTime = fileTime
audioentity.fileDistance = fileDistance
audioentity.fileTimeLong = fileTimeLong
audioentity.fileCoordinate = fileCoordinate
audioentity.fuileNumber = fuileNumber
audioentity.filetime1 = filetime1
audioentity.filetime2 = filetime2
audioentity.filetime3 = filetime3
})
if success == true
{
print("保存成功")
// self.navigationController?.popToRootViewControllerAnimated(true)
}
else
{
print("保存失败")
}
}
//MARK: - 全部数据
static func SearchAllDataEntity()->NSArray
{
var dataSource = NSArray()
let managedContext = BaseDAO.mainMOC
let request : NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
let entity:NSEntityDescription? = NSEntityDescription.entity(forEntityName: "BookListEntity", in: managedContext)
request.entity = entity
dataSource = try!managedContext.fetch(request) as NSArray
return dataSource
}
//MARK: - Delete
static func deleteEntityWith(Entity entity : AudioEntity) -> Bool
{
BaseDAO.mainMOC.delete(entity)
return self.save()
}
//MARK: - save
static func save() -> Bool
{
if BaseDAO.mainMOC.hasChanges
{
do
{
try BaseDAO.mainMOC.save()
}
catch
{
return false
}
return true
}else
{
return false
}
}
static func entityName() -> String
{
return "BookListEntity"
}
}
| gpl-3.0 | eda912c05adc318c307dcc05e5f73a89 | 29.309091 | 129 | 0.583383 | 4.888563 | false | false | false | false |
JesusAntonioGil/OnTheMap | OnTheMap/Model/StudentLocation.swift | 1 | 3656 | //
// StudentLocation.swift
// OnTheMap
//
// Created by Jesús Antonio Gil on 29/03/16.
// Copyright © 2016 Jesús Antonio Gil. All rights reserved.
//
import UIKit
import ObjectMapper
final class StudentLocation: NSObject {
var createdAt: String!
var firstName: String!
var lastName: String!
var latitude: Float!
var longitude: Float!
var mapString: String!
var mediaURL: String!
var objectId: String!
var uniqueKey: String!
var updatedAt: String!
}
extension StudentLocation: Mappable {
convenience init?(_ map: Map) {
self.init()
}
func mapping(map: Map) {
createdAt <- map["createdAt"]
firstName <- map["firstName"]
lastName <- map["lastName"]
latitude <- map["latitude"]
longitude <- map["longitude"]
mapString <- map["mapString"]
mediaURL <- map["mediaURL"]
objectId <- map["objectId"]
uniqueKey <- map["uniqueKey"]
updatedAt <- map["updatedAt"]
}
//MARK: Custom String Convertible
override var description: String {
return Mapper().toJSONString(self, prettyPrint: true)!
}
var dictionaryDescription: [String: AnyObject] {
return Mapper().toJSON(self)
}
}
class StudentLocationTransform: TransformType {
typealias Object = StudentLocation
typealias JSON = String
init() { }
func transformFromJSON(value: AnyObject?) -> StudentLocation? {
guard value != nil else {
return nil
}
return Mapper<StudentLocation>().map(value)
}
func transformToJSON(value: StudentLocation?) -> JSON? {
guard value != nil else {
return nil
}
return Mapper().toJSONString(value!, prettyPrint: true)!
}
}
struct StudentLocationStruct {
var createdAt: NSDate!
var firstName: String!
var lastName: String!
var latitude: Float!
var longitude: Float!
var mapString: String!
var mediaURL: String!
var objectId: String!
var uniqueKey: String!
var updatedAt: NSDate!
init(dictionary: [String: AnyObject]) {
if(dictionary["createdAt"] != nil) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let index = (dictionary["createdAt"] as! String).startIndex.advancedBy(10)
createdAt = dateFormatter.dateFromString((dictionary["createdAt"] as! String).substringToIndex(index))
}
if(dictionary["firstName"] != nil) {firstName = dictionary["firstName"] as! String }
if(dictionary["lastName"] != nil) { lastName = dictionary["lastName"] as! String }
if(dictionary["latitude"] != nil) { latitude = dictionary["latitude"] as! Float }
if(dictionary["longitude"] != nil) { longitude = dictionary["longitude"] as! Float }
if(dictionary["mapString"] != nil) { mapString = dictionary["mapString"] as! String }
if(dictionary["mediaURL"] != nil) { mediaURL = dictionary["mediaURL"] as! String }
if(dictionary["objectId"] != nil) { objectId = dictionary["objectId"] as! String }
if(dictionary["uniqueKey"] != nil) { uniqueKey = dictionary["uniqueKey"] as! String }
if(dictionary["updatedAt"] != nil) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let index = (dictionary["updatedAt"] as! String).startIndex.advancedBy(10)
updatedAt = dateFormatter.dateFromString((dictionary["updatedAt"] as! String).substringToIndex(index)) }
}
} | mit | 18a0747138c8bb3becbe24e00e147d26 | 29.705882 | 123 | 0.615658 | 4.75651 | false | false | false | false |
AnnMic/FestivalArchitect | FestivalArchitect/Classes/Editor/EditorPopupViewController.swift | 2 | 1101 | //
// EditorPopupViewController.swift
// Festival
//
// Created by Ann Michelsen on 28/09/14.
// Copyright (c) 2014 Ann Michelsen. All rights reserved.
//
import Foundation
class EditorPopupNode : CCNode {
override init()
{
super.init()
let winSize:CGRect = CCDirector.sharedDirector().view.frame
contentSize = CGSizeMake(50, 50)
// Create a colored background (Dark Grey)
let background:CCNodeColor = CCNodeColor(color: CCColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0))
background.contentSize = CGSizeMake(500, 300)
background.position = CGPoint(x: winSize.width/2-background.contentSize.width/2, y: winSize.height/2-background.contentSize.height/2)
addChild(background)
createCloseButton()
}
func createCloseButton(){
let close:CCButton = CCButton(title: "X")
close.position = CGPointMake(500, 300)
close.setTarget(self, selector: "onCloseClicked:")
addChild(close)
}
func onCloseClicked(sender:CCButton){
}
} | mit | 0d23b732fae3b64adfc348b3ed9ac60a | 26.55 | 141 | 0.633969 | 4.077778 | false | false | false | false |
andyshep/GROCloudStore | Sources/GRODefaultDataSource.swift | 1 | 7169 | //
// GRODefaultDataSource.swift
// GROCloudStore
//
// Created by Andrew Shepard on 3/15/16.
// Copyright © 2016 Andrew Shepard. All rights reserved.
//
import Foundation
import CloudKit
open class GRODefaultDataSource: CloudDataSource {
public var configuration: Configuration
init(configuration: Configuration) {
self.configuration = configuration
}
public var database: CKDatabase {
return self.container.privateCloudDatabase
}
public var container: CKContainer {
return CKContainer(identifier: self.configuration.container.identifier)
}
// MARK: - Records
public func save(withRecord record:CKRecord, completion: @escaping RecordCompletion) {
database.save(record, completionHandler: completion)
}
public func record(withRecordID recordID: CKRecord.ID, completion: @escaping RecordCompletion) {
database.fetch(withRecordID: recordID, completionHandler: completion)
}
public func records(ofType type: String, completion: @escaping RecordsCompletion) {
let query = CKQuery(recordType: type, predicate: NSPredicate(value: true))
database.perform(query, inZoneWith: nil, completionHandler: completion)
}
public func records(ofType type: String, fetched: @escaping RecordFetched, completion: QueryCompletion?) {
let query = CKQuery(recordType: type, predicate: NSPredicate(value: true))
let operation = CKQueryOperation(query: query)
operation.recordFetchedBlock = {(record: CKRecord) in
fetched(record)
}
operation.queryCompletionBlock = {(cursor: CKQueryOperation.Cursor?, error: Error?) in
if let completion = completion {
completion(cursor, error)
}
}
database.add(operation)
}
public func changes(since token: CKServerChangeToken?, completion: @escaping DatabaseChangesHandler) {
let operation = CKFetchDatabaseChangesOperation(previousServerChangeToken: token)
var changedRecordZoneIds: [CKRecordZone.ID] = []
operation.recordZoneWithIDChangedBlock = { (zoneId: CKRecordZone.ID) in
changedRecordZoneIds.append(zoneId)
}
var deletedRecordZoneIds: [CKRecordZone.ID] = []
operation.recordZoneWithIDWasDeletedBlock = { (zoneId: CKRecordZone.ID) in
deletedRecordZoneIds.append(zoneId)
}
operation.fetchDatabaseChangesCompletionBlock = { (token: CKServerChangeToken?, more: Bool, error: Error?) in
// TODO: need to handle more flag
completion(changedRecordZoneIds, deletedRecordZoneIds, token)
}
database.add(operation)
}
public func changedRecords(inZoneIds zoneIds: [CKRecordZone.ID], tokens: [CKRecordZone.ID : CKServerChangeToken]?, completion: @escaping ChangedRecordsHandler) {
let options = tokens?.optionsByRecordZoneID()
let operation = CKFetchRecordZoneChangesOperation(recordZoneIDs: zoneIds, optionsByRecordZoneID: options)
var changedRecords: [CKRecord] = []
operation.recordChangedBlock = { (record: CKRecord) in
changedRecords.append(record)
}
var deletedRecordIDs: [CKRecord.ID] = []
operation.recordWithIDWasDeletedBlock = { (recordID: CKRecord.ID, identifier: String) in
deletedRecordIDs.append(recordID)
}
var tokens: [CKRecordZone.ID: CKServerChangeToken] = [:]
operation.recordZoneFetchCompletionBlock = { (zoneID: CKRecordZone.ID, token: CKServerChangeToken?, _: Data?, _: Bool, _: Error?) in
print("record zone has changes: \(zoneID)")
tokens[zoneID] = token
}
// not used right now
operation.recordZoneChangeTokensUpdatedBlock = { (zoneID: CKRecordZone.ID, token: CKServerChangeToken?, data: Data?) in
print("record zone change token updated: \(zoneID)")
}
operation.fetchRecordZoneChangesCompletionBlock = { (error: Error?) in
completion(changedRecords, deletedRecordIDs, tokens)
}
database.add(operation)
}
public func delete(withRecordID recordID: CKRecord.ID, completion: @escaping DeleteRecordCompletion) {
database.delete(withRecordID: recordID, completionHandler: completion)
}
// MARK: - Subscriptions
public func verifySubscriptions(completion: @escaping FetchSubscriptionsCompletion) {
database.fetchAllSubscriptions(completionHandler: completion)
}
public func createSubscriptions(subscriptions: [CKSubscription], completion: @escaping CreateSubscriptionsCompletion) {
let operation = CKModifySubscriptionsOperation(subscriptionsToSave: subscriptions, subscriptionIDsToDelete: nil)
operation.modifySubscriptionsCompletionBlock = { (subscription: [CKSubscription]?, identifier: [String]?, error: Error?) -> Void in
completion(subscription?.first, error)
}
database.add(operation)
}
// MARK: - Record Zones
public func fetchRecordsZones(completion: @escaping FetchRecordZonesCompletion) -> Void {
// per wwdc, CKDatabaseSubscription and CKFetchDatabaseChangesOperation should replace
// only supporting one record zone right now.
let operation = CKFetchRecordZonesOperation.fetchAllRecordZonesOperation()
operation.qualityOfService = QualityOfService.userInitiated
operation.fetchRecordZonesCompletionBlock = {(zones, error) in
completion(zones, error)
}
database.add(operation)
}
public func createRecordZone(name: String, completion: @escaping CreateRecordZoneCompletion) -> Void {
let zoneId = CKRecordZone.ID(zoneName: name, ownerName: CKCurrentUserDefaultName)
let zone = CKRecordZone(zoneID: zoneId)
let operation = CKModifyRecordZonesOperation(recordZonesToSave: [zone], recordZoneIDsToDelete: nil)
operation.modifyRecordZonesCompletionBlock = {(zones, zoneIds, error) in
completion(zones?.first, error)
}
database.add(operation)
}
}
fileprivate extension Dictionary where Key: CKRecordZone.ID, Value: CKServerChangeToken {
func optionsByRecordZoneID() -> [CKRecordZone.ID: CKFetchRecordZoneChangesOperation.ZoneOptions]? {
var optionsByRecordZoneID: [CKRecordZone.ID: CKFetchRecordZoneChangesOperation.ZoneOptions] = [:]
for (zoneId, token) in self {
let options = CKFetchRecordZoneChangesOperation.ZoneOptions()
options.previousServerChangeToken = token
optionsByRecordZoneID[zoneId] = options
}
return (optionsByRecordZoneID.count > 0) ? optionsByRecordZoneID : nil
}
}
fileprivate extension Array where Element : Hashable {
var unique: [Element] {
return Array(Set(self))
}
}
| mit | 505a28b18643ecda47bbe1558f8253f0 | 37.956522 | 165 | 0.666713 | 5.522342 | false | false | false | false |
kitasuke/SwiftProtobufSample | Client/Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/TextFormatScanner.swift | 1 | 31486 | // Sources/SwiftProtobuf/TextFormatScanner.swift - Text format decoding
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Test format decoding engine.
///
// -----------------------------------------------------------------------------
import Foundation
private let asciiBell = UInt8(7)
private let asciiBackspace = UInt8(8)
private let asciiTab = UInt8(9)
private let asciiNewLine = UInt8(10)
private let asciiVerticalTab = UInt8(11)
private let asciiFormFeed = UInt8(12)
private let asciiCarriageReturn = UInt8(13)
private let asciiZero = UInt8(ascii: "0")
private let asciiOne = UInt8(ascii: "1")
private let asciiSeven = UInt8(ascii: "7")
private let asciiNine = UInt8(ascii: "9")
private let asciiColon = UInt8(ascii: ":")
private let asciiPeriod = UInt8(ascii: ".")
private let asciiPlus = UInt8(ascii: "+")
private let asciiComma = UInt8(ascii: ",")
private let asciiSemicolon = UInt8(ascii: ";")
private let asciiDoubleQuote = UInt8(ascii: "\"")
private let asciiSingleQuote = UInt8(ascii: "\'")
private let asciiBackslash = UInt8(ascii: "\\")
private let asciiForwardSlash = UInt8(ascii: "/")
private let asciiHash = UInt8(ascii: "#")
private let asciiUnderscore = UInt8(ascii: "_")
private let asciiQuestionMark = UInt8(ascii: "?")
private let asciiSpace = UInt8(ascii: " ")
private let asciiOpenSquareBracket = UInt8(ascii: "[")
private let asciiCloseSquareBracket = UInt8(ascii: "]")
private let asciiOpenCurlyBracket = UInt8(ascii: "{")
private let asciiCloseCurlyBracket = UInt8(ascii: "}")
private let asciiOpenAngleBracket = UInt8(ascii: "<")
private let asciiCloseAngleBracket = UInt8(ascii: ">")
private let asciiMinus = UInt8(ascii: "-")
private let asciiLowerA = UInt8(ascii: "a")
private let asciiUpperA = UInt8(ascii: "A")
private let asciiLowerB = UInt8(ascii: "b")
private let asciiLowerE = UInt8(ascii: "e")
private let asciiUpperE = UInt8(ascii: "E")
private let asciiLowerF = UInt8(ascii: "f")
private let asciiUpperF = UInt8(ascii: "F")
private let asciiLowerI = UInt8(ascii: "i")
private let asciiLowerN = UInt8(ascii: "n")
private let asciiLowerR = UInt8(ascii: "r")
private let asciiLowerT = UInt8(ascii: "t")
private let asciiLowerU = UInt8(ascii: "u")
private let asciiLowerV = UInt8(ascii: "v")
private let asciiLowerX = UInt8(ascii: "x")
private let asciiLowerY = UInt8(ascii: "y")
private let asciiLowerZ = UInt8(ascii: "z")
private let asciiUpperZ = UInt8(ascii: "Z")
private func fromHexDigit(_ c: UInt8) -> UInt8? {
if c >= asciiZero && c <= asciiNine {
return c - asciiZero
}
if c >= asciiUpperA && c <= asciiUpperF {
return c - asciiUpperA + 10
}
if c >= asciiLowerA && c <= asciiLowerF {
return c - asciiLowerA + 10
}
return nil
}
// Protobuf Text format uses C ASCII conventions for
// encoding byte sequences, including the use of octal
// and hexadecimal escapes.
private func decodeBytes(_ s: String) -> Data? {
var out = [UInt8]()
var bytes = s.utf8.makeIterator()
while let byte = bytes.next() {
switch byte {
case asciiBackslash: // "\\"
if let escaped = bytes.next() {
switch escaped {
case asciiZero...asciiSeven: // '0'...'7'
// C standard allows 1, 2, or 3 octal digits.
let savedPosition = bytes
let digit1 = escaped
let digit1Value = digit1 - asciiZero
if let digit2 = bytes.next(),
digit2 >= asciiZero, digit2 <= asciiSeven {
let digit2Value = digit2 - asciiZero
let innerSavedPosition = bytes
if let digit3 = bytes.next(),
digit3 >= asciiZero, digit3 <= asciiSeven {
let digit3Value = digit3 - asciiZero
let n = digit1Value * 64 + digit2Value * 8 + digit3Value
out.append(UInt8(n))
} else {
let n = digit1Value * 8 + digit2Value
out.append(UInt8(n))
bytes = innerSavedPosition
}
} else {
let n = digit1Value
out.append(UInt8(n))
bytes = savedPosition
}
case asciiLowerX: // 'x' hexadecimal escape
// C standard allows any number of digits after \x
// We ignore all but the last two
var n: UInt8 = 0
var count = 0
var savedPosition = bytes
while let byte = bytes.next(), let digit = fromHexDigit(byte) {
n &= 15
n = n * 16
n += digit
count += 1
savedPosition = bytes
}
bytes = savedPosition
if count > 0 {
out.append(n)
} else {
return nil // Hex escape must have at least 1 digit
}
case asciiLowerA: // \a ("alert")
out.append(asciiBell)
case asciiLowerB: // \b
out.append(asciiBackspace)
case asciiLowerF: // \f
out.append(asciiFormFeed)
case asciiLowerN: // \n
out.append(asciiNewLine)
case asciiLowerR: // \r
out.append(asciiCarriageReturn)
case asciiLowerT: // \t
out.append(asciiTab)
case asciiLowerV: // \v
out.append(asciiVerticalTab)
case asciiSingleQuote,
asciiDoubleQuote,
asciiQuestionMark,
asciiBackslash: // \' \" \? \\
out.append(escaped)
default:
return nil // Unrecognized escape
}
} else {
return nil // Input ends with backslash
}
default:
out.append(byte)
}
}
return Data(bytes: out)
}
// Protobuf Text encoding assumes that you're working directly
// in UTF-8. So this implementation converts the string to UTF8,
// then decodes it into a sequence of bytes, then converts
// it back into a string.
private func decodeString(_ s: String) -> String? {
var out = [UInt8]()
var bytes = s.utf8.makeIterator()
while let byte = bytes.next() {
switch byte {
case asciiBackslash: // backslash
if let escaped = bytes.next() {
switch escaped {
case asciiZero...asciiSeven: // 0...7
// C standard allows 1, 2, or 3 octal digits.
let savedPosition = bytes
let digit1 = escaped
let digit1Value = digit1 - asciiZero
if let digit2 = bytes.next(),
digit2 >= asciiZero && digit2 <= asciiSeven {
let digit2Value = digit2 - asciiZero
let innerSavedPosition = bytes
if let digit3 = bytes.next(),
digit3 >= asciiZero && digit3 <= asciiSeven {
let digit3Value = digit3 - asciiZero
let n = digit1Value * 64 + digit2Value * 8 + digit3Value
out.append(n)
} else {
let n = digit1Value * 8 + digit2Value
out.append(n)
bytes = innerSavedPosition
}
} else {
let n = digit1Value
out.append(n)
bytes = savedPosition
}
case asciiLowerX: // "x"
// C standard allows any number of hex digits after \x
// We ignore all but the last two
var n: UInt8 = 0
var count = 0
var savedPosition = bytes
while let byte = bytes.next(), let digit = fromHexDigit(byte) {
n &= 15
n = n * 16
n += digit
count += 1
savedPosition = bytes
}
bytes = savedPosition
if count > 0 {
out.append(n)
} else {
return nil // Hex escape must have at least 1 digit
}
case asciiLowerA: // \a
out.append(asciiBell)
case asciiLowerB: // \b
out.append(asciiBackspace)
case asciiLowerF: // \f
out.append(asciiFormFeed)
case asciiLowerN: // \n
out.append(asciiNewLine)
case asciiLowerR: // \r
out.append(asciiCarriageReturn)
case asciiLowerT: // \t
out.append(asciiTab)
case asciiLowerV: // \v
out.append(asciiVerticalTab)
case asciiDoubleQuote,
asciiSingleQuote,
asciiQuestionMark,
asciiBackslash: // " ' ? \
out.append(escaped)
default:
return nil // Unrecognized escape
}
} else {
return nil // Input ends with backslash
}
default:
out.append(byte)
}
}
// There has got to be an easier way to convert a [UInt8] into a String.
return out.withUnsafeBufferPointer { ptr in
if let addr = ptr.baseAddress {
return utf8ToString(bytes: addr, count: ptr.count)
} else {
return String()
}
}
}
///
/// TextFormatScanner has no public members.
///
internal struct TextFormatScanner {
internal var extensions: ExtensionMap?
private var p: UnsafePointer<UInt8>
private var end: UnsafePointer<UInt8>
private var doubleFormatter = DoubleFormatter()
internal var complete: Bool {
mutating get {
return p == end
}
}
internal init(utf8Pointer: UnsafePointer<UInt8>, count: Int, extensions: ExtensionMap? = nil) {
p = utf8Pointer
end = p + count
self.extensions = extensions
skipWhitespace()
}
/// Skip whitespace
private mutating func skipWhitespace() {
while p != end {
let u = p[0]
switch u {
case asciiSpace,
asciiTab,
asciiNewLine,
asciiCarriageReturn: // space, tab, NL, CR
p += 1
case asciiHash: // # comment
p += 1
while p != end {
// Skip until end of line
let c = p[0]
p += 1
if c == asciiNewLine || c == asciiCarriageReturn {
break
}
}
default:
return
}
}
}
private mutating func parseIdentifier() -> String? {
let start = p
loop: while p != end {
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ,
asciiZero...asciiNine,
asciiUnderscore:
p += 1
default:
break loop
}
}
let s = utf8ToString(bytes: start, count: p - start)
skipWhitespace()
return s
}
/// Parse the rest of an [extension_field_name] in the input, assuming the
/// initial "[" character has already been read (and is in the prefix)
/// This is also used for AnyURL, so we include "/", "."
private mutating func parseExtensionKey() -> String? {
let start = p
if p == end {
return nil
}
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ:
p += 1
default:
return nil
}
while p != end {
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ,
asciiZero...asciiNine,
asciiUnderscore,
asciiPeriod,
asciiForwardSlash:
p += 1
case asciiCloseSquareBracket: // ]
return utf8ToString(bytes: start, count: p - start)
default:
return nil
}
}
return nil
}
/// Assumes the leading quote has already been consumed
private mutating func parseQuotedString(terminator: UInt8) -> String? {
let start = p
while p != end {
let c = p[0]
if c == terminator {
let s = utf8ToString(bytes: start, count: p - start)
p += 1
skipWhitespace()
return s
}
p += 1
if c == asciiBackslash { // \
if p == end {
return nil
}
p += 1
}
}
return nil // Unterminated quoted string
}
/// Assumes the leading quote has already been consumed
private mutating func parseStringSegment(terminator: UInt8) -> String? {
let start = p
var sawBackslash = false
while p != end {
let c = p[0]
if c == terminator {
let s = utf8ToString(bytes: start, count: p - start)
p += 1
skipWhitespace()
if let s = s, sawBackslash {
return decodeString(s)
} else {
return s
}
}
p += 1
if c == asciiBackslash { // \
if p == end {
return nil
}
sawBackslash = true
p += 1
}
}
return nil // Unterminated quoted string
}
internal mutating func nextUInt() throws -> UInt64 {
if p == end {
throw TextFormatDecodingError.malformedNumber
}
let c = p[0]
p += 1
if c == asciiZero { // leading '0' precedes octal or hex
if p[0] == asciiLowerX { // 'x' => hex
p += 1
var n: UInt64 = 0
while p != end {
let digit = p[0]
let val: UInt64
switch digit {
case asciiZero...asciiNine: // 0...9
val = UInt64(digit - asciiZero)
case asciiLowerA...asciiLowerF: // a...f
val = UInt64(digit - asciiLowerA + 10)
case asciiUpperA...asciiUpperF:
val = UInt64(digit - asciiUpperA + 10)
case asciiLowerU: // trailing 'u'
p += 1
skipWhitespace()
return n
default:
skipWhitespace()
return n
}
if n > UInt64.max / 16 {
throw TextFormatDecodingError.malformedNumber
}
p += 1
n = n * 16 + val
}
skipWhitespace()
return n
} else { // octal
var n: UInt64 = 0
while p != end {
let digit = p[0]
if digit == asciiLowerU { // trailing 'u'
p += 1
skipWhitespace()
return n
}
if digit < asciiZero || digit > asciiSeven {
skipWhitespace()
return n // not octal digit
}
let val = UInt64(digit - asciiZero)
if n > UInt64.max / 8 {
throw TextFormatDecodingError.malformedNumber
}
p += 1
n = n * 8 + val
}
skipWhitespace()
return n
}
} else if c > asciiZero && c <= asciiNine { // 1...9
var n = UInt64(c - asciiZero)
while p != end {
let digit = p[0]
if digit == asciiLowerU { // trailing 'u'
p += 1
skipWhitespace()
return n
}
if digit < asciiZero || digit > asciiNine {
skipWhitespace()
return n // not a digit
}
let val = UInt64(digit - asciiZero)
if n >= UInt64.max / 10 {
if n > UInt64.max / 10 || val > UInt64.max % 10 {
throw TextFormatDecodingError.malformedNumber
}
}
p += 1
n = n * 10 + val
}
skipWhitespace()
return n
}
throw TextFormatDecodingError.malformedNumber
}
internal mutating func nextSInt() throws -> Int64 {
if p == end {
throw TextFormatDecodingError.malformedNumber
}
let c = p[0]
if c == asciiMinus { // -
p += 1
// character after '-' must be digit
let digit = p[0]
if digit < asciiZero || digit > asciiNine {
throw TextFormatDecodingError.malformedNumber
}
let n = try nextUInt()
if n >= 0x8000000000000000 { // -Int64.min
if n > 0x8000000000000000 {
// Too large negative number
throw TextFormatDecodingError.malformedNumber
} else {
return Int64.min // Special case for Int64.min
}
}
return -Int64(bitPattern: n)
} else {
let n = try nextUInt()
if n > UInt64(bitPattern: Int64.max) {
throw TextFormatDecodingError.malformedNumber
}
return Int64(bitPattern: n)
}
}
internal mutating func nextStringValue() throws -> String {
var result: String
skipWhitespace()
if p == end {
throw TextFormatDecodingError.malformedText
}
let c = p[0]
if c != asciiSingleQuote && c != asciiDoubleQuote {
throw TextFormatDecodingError.malformedText
}
p += 1
if let s = parseStringSegment(terminator: c) {
result = s
} else {
throw TextFormatDecodingError.malformedText
}
while true {
if p == end {
return result
}
let c = p[0]
if c != asciiSingleQuote && c != asciiDoubleQuote {
return result
}
p += 1
if let s = parseStringSegment(terminator: c) {
result.append(s)
} else {
throw TextFormatDecodingError.malformedText
}
}
}
internal mutating func nextBytesValue() throws -> Data {
var result: Data
skipWhitespace()
if p == end {
throw TextFormatDecodingError.malformedText
}
let c = p[0]
if c != asciiSingleQuote && c != asciiDoubleQuote {
throw TextFormatDecodingError.malformedText
}
p += 1
if let s = parseQuotedString(terminator: c), let b = decodeBytes(s) {
result = b
} else {
throw TextFormatDecodingError.malformedText
}
while true {
skipWhitespace()
if p == end {
return result
}
let c = p[0]
if c != asciiSingleQuote && c != asciiDoubleQuote {
return result
}
p += 1
if let s = parseQuotedString(terminator: c),
let b = decodeBytes(s) {
result.append(b)
} else {
throw TextFormatDecodingError.malformedText
}
}
}
// Tries to identify a sequence of UTF8 characters
// that represent a numeric floating-point value.
private mutating func tryParseFloatString() -> Double? {
guard p != end else {return nil}
let start = p
var c = p[0]
if c == asciiMinus {
p += 1
guard p != end else {p = start; return nil}
c = p[0]
}
switch c {
case asciiZero: // '0' as first character only if followed by '.'
p += 1
guard p != end else {p = start; return nil}
c = p[0]
if c != asciiPeriod {
p = start
return nil
}
case asciiPeriod: // '.' as first char only if followed by digit
p += 1
guard p != end else {p = start; return nil}
c = p[0]
if c < asciiZero || c > asciiNine {
p = start
return nil
}
case asciiOne...asciiNine:
break
default:
p = start
return nil
}
loop: while p != end {
let c = p[0]
switch c {
case asciiZero...asciiNine,
asciiPeriod,
asciiPlus,
asciiMinus,
asciiLowerE,
asciiUpperE: // 0...9, ., +, -, e, E
p += 1
case asciiLowerF: // f
// proto1 allowed floats to be suffixed with 'f'
let d = doubleFormatter.utf8ToDouble(bytes: start, count: p - start)
// Just skip the 'f'
p += 1
skipWhitespace()
return d
default:
break loop
}
}
let d = doubleFormatter.utf8ToDouble(bytes: start, count: p - start)
skipWhitespace()
return d
}
private mutating func skipOptionalKeyword(bytes: [UInt8]) -> Bool {
let start = p
for b in bytes {
if p == end {
p = start
return false
}
var c = p[0]
if c >= asciiUpperA && c <= asciiUpperZ {
// Convert to lower case
// (Protobuf text keywords are case insensitive)
c += asciiLowerA - asciiUpperA
}
if c != b {
p = start
return false
}
p += 1
}
if p == end {
return true
}
let c = p[0]
if ((c >= asciiUpperA && c <= asciiUpperZ)
|| (c >= asciiLowerA && c <= asciiLowerZ)) {
p = start
return false
}
skipWhitespace()
return true
}
// If the next token is the identifier "nan", return true.
private mutating func skipOptionalNaN() -> Bool {
return skipOptionalKeyword(bytes:
[asciiLowerN, asciiLowerA, asciiLowerN])
}
// If the next token is a recognized spelling of "infinity",
// return Float.infinity or -Float.infinity
private mutating func skipOptionalInfinity() -> Float? {
if p == end {
return nil
}
let c = p[0]
let negated: Bool
if c == asciiMinus {
negated = true
p += 1
} else {
negated = false
}
let inf = [asciiLowerI, asciiLowerN, asciiLowerF]
let infinity = [asciiLowerI, asciiLowerN, asciiLowerF, asciiLowerI,
asciiLowerN, asciiLowerI, asciiLowerT, asciiLowerY]
if (skipOptionalKeyword(bytes: inf)
|| skipOptionalKeyword(bytes: infinity)) {
return negated ? -Float.infinity : Float.infinity
}
return nil
}
internal mutating func nextFloat() throws -> Float {
if let d = tryParseFloatString() {
let n = Float(d)
if n.isFinite {
return n
}
}
if skipOptionalNaN() {
return Float.nan
}
if let inf = skipOptionalInfinity() {
return inf
}
throw TextFormatDecodingError.malformedNumber
}
internal mutating func nextDouble() throws -> Double {
if let d = tryParseFloatString() {
return d
}
if skipOptionalNaN() {
return Double.nan
}
if let inf = skipOptionalInfinity() {
return Double(inf)
}
throw TextFormatDecodingError.malformedNumber
}
internal mutating func nextBool() throws -> Bool {
skipWhitespace()
if p == end {
throw TextFormatDecodingError.malformedText
}
let c = p[0]
switch c {
case asciiZero: // 0
p += 1
return false
case asciiOne: // 1
p += 1
return true
default:
if let s = parseIdentifier() {
switch s {
case "f", "false", "False":
return false
case "t", "true", "True":
return true
default:
break
}
}
}
throw TextFormatDecodingError.malformedText
}
internal mutating func nextOptionalEnumName() throws -> String? {
skipWhitespace()
if p == end {
throw TextFormatDecodingError.malformedText
}
let c = p[0]
let start = p
switch c {
case asciiLowerA...asciiLowerZ, asciiUpperA...asciiUpperZ:
if let s = parseIdentifier() {
return s
}
default:
break
}
p = start
return nil
}
/// Any URLs are syntactically (almost) identical to extension
/// keys, so we share the code for those.
internal mutating func nextOptionalAnyURL() throws -> String? {
return try nextOptionalExtensionKey()
}
/// Returns next extension key or nil if end-of-input or
/// if next token is not an extension key.
///
/// Throws an error if the next token starts with '[' but
/// cannot be parsed as an extension key.
///
/// Note: This accepts / characters to support Any URL parsing.
/// Technically, Any URLs can contain / characters and extension
/// key names cannot. But in practice, accepting / chracters for
/// extension keys works fine, since the result just gets rejected
/// when the key is looked up.
internal mutating func nextOptionalExtensionKey() throws -> String? {
skipWhitespace()
if p == end {
return nil
}
if p[0] == asciiOpenSquareBracket { // [
p += 1
if let s = parseExtensionKey() {
if p == end || p[0] != asciiCloseSquareBracket {
throw TextFormatDecodingError.malformedText
}
// Skip ]
p += 1
skipWhitespace()
return s
} else {
throw TextFormatDecodingError.malformedText
}
}
return nil
}
/// Returns text of next regular key or nil if end-of-input.
/// This considers an extension key [keyname] to be an
/// error, so call nextOptionalExtensionKey first if you
/// want to handle extension keys.
///
/// This is only used by map parsing; we should be able to
/// rework that to use nextFieldNumber instead.
internal mutating func nextKey() throws -> String? {
skipWhitespace()
if p == end {
return nil
}
let c = p[0]
switch c {
case asciiOpenSquareBracket: // [
throw TextFormatDecodingError.malformedText
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ: // a...z, A...Z
if let s = parseIdentifier() {
return s
} else {
throw TextFormatDecodingError.malformedText
}
default:
throw TextFormatDecodingError.malformedText
}
}
/// Parse a field name, look it up, and return the corresponding
/// field number.
///
/// returns nil at end-of-input
///
/// Throws if field name cannot be parsed or if field name is
/// unknown.
///
/// This function accounts for as much as 2/3 of the total run
/// time of the entire parse.
internal mutating func nextFieldNumber(names: _NameMap) throws -> Int? {
if p == end {
return nil
}
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ: // a...z, A...Z
let start = p
p += 1
scanKeyLoop: while p != end {
let c = p[0]
switch c {
case asciiLowerA...asciiLowerZ,
asciiUpperA...asciiUpperZ,
asciiZero...asciiNine,
asciiUnderscore: // a...z, A...Z, 0...9, _
p += 1
default:
break scanKeyLoop
}
}
let key = UnsafeBufferPointer(start: start, count: p - start)
skipWhitespace()
if let fieldNumber = names.number(forProtoName: key) {
return fieldNumber
} else {
throw TextFormatDecodingError.unknownField
}
default:
break
}
throw TextFormatDecodingError.malformedText
}
private mutating func skipRequiredCharacter(_ c: UInt8) throws {
skipWhitespace()
if p != end && p[0] == c {
p += 1
skipWhitespace()
} else {
throw TextFormatDecodingError.malformedText
}
}
internal mutating func skipRequiredComma() throws {
try skipRequiredCharacter(asciiComma)
}
internal mutating func skipRequiredColon() throws {
try skipRequiredCharacter(asciiColon)
}
private mutating func skipOptionalCharacter(_ c: UInt8) -> Bool {
if p != end && p[0] == c {
p += 1
skipWhitespace()
return true
}
return false
}
internal mutating func skipOptionalColon() -> Bool {
return skipOptionalCharacter(asciiColon)
}
internal mutating func skipOptionalEndArray() -> Bool {
return skipOptionalCharacter(asciiCloseSquareBracket)
}
internal mutating func skipOptionalBeginArray() -> Bool {
return skipOptionalCharacter(asciiOpenSquareBracket)
}
internal mutating func skipOptionalObjectEnd(_ c: UInt8) -> Bool {
return skipOptionalCharacter(c)
}
internal mutating func skipOptionalSeparator() {
if p != end {
let c = p[0]
if c == asciiComma || c == asciiSemicolon { // comma or semicolon
p += 1
skipWhitespace()
}
}
}
/// Returns the character that should end this field.
/// E.g., if object starts with "{", returns "}"
internal mutating func skipObjectStart() throws -> UInt8 {
if p != end {
let c = p[0]
p += 1
skipWhitespace()
switch c {
case asciiOpenCurlyBracket: // {
return asciiCloseCurlyBracket // }
case asciiOpenAngleBracket: // <
return asciiCloseAngleBracket // >
default:
break
}
}
throw TextFormatDecodingError.malformedText
}
}
| mit | 6e3c7b049676651f71fc68de290b9bd2 | 31.161389 | 99 | 0.500572 | 5.18886 | false | false | false | false |
jkolb/midnightbacon | MidnightBacon/Modules/Submit/SubmitForm.swift | 1 | 5887 | //
// SubmitForm.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// 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 Reddit
enum SubmitFieldID : String {
case Subreddit = "subreddit"
case Title = "title"
case Text = "text"
case URL = "url"
case SendReplies = "sendReplies"
}
class SubmitField : Equatable {
let id: SubmitFieldID
init(id: SubmitFieldID) {
self.id = id
}
func isValid() -> Bool {
return true
}
}
func ==(lhs: SubmitField, rhs: SubmitField) -> Bool {
return lhs.id == rhs.id
}
class SubmitBoolField : SubmitField {
var value: Bool?
}
class SubmitKindField : SubmitField {
var value: SubmitKind?
}
class SubmitTextField : SubmitField {
var value: String?
override func isValid() -> Bool {
if let stringValue = value {
return !stringValue.isEmpty
} else {
return false
}
}
}
class SubmitLongTextField : SubmitField {
var value: String?
override func isValid() -> Bool {
if let stringValue = value {
return !stringValue.isEmpty
} else {
return false
}
}
}
class SubmitURLField : SubmitField {
var value: NSURL?
var stringValue: String? {
get {
return value?.absoluteString
}
set {
let urlString = newValue ?? ""
if urlString.isEmpty {
value = nil
} else {
value = NSURL(string: urlString)
}
}
}
override func isValid() -> Bool {
if let url = value {
let scheme = url.scheme ?? ""
let host = url.host ?? ""
return (scheme == "http" || scheme == "https") && !host.isEmpty
} else {
return false
}
}
}
class SubmitForm {
var kind: SubmitKind
var orderedFields: [SubmitField] = []
var fieldIndexByID: [SubmitFieldID:Int] = [:]
init(kind: SubmitKind) {
self.kind = kind
}
class func linkForm() -> SubmitForm {
let form = SubmitForm(kind: .LinkKind)
form.addField(SubmitTextField(id: .Subreddit))
form.addField(SubmitTextField(id: .Title))
form.addField(SubmitURLField(id: .URL))
form.addField(SubmitBoolField(id: .SendReplies))
return form
}
class func textForm() -> SubmitForm {
let form = SubmitForm(kind: .TextKind)
form.addField(SubmitTextField(id: .Subreddit))
form.addField(SubmitTextField(id: .Title))
form.addField(SubmitLongTextField(id: .Text))
form.addField(SubmitBoolField(id: .SendReplies))
return form
}
func isValid() -> Bool {
var valid = true
for field in orderedFields {
valid = valid && field.isValid()
}
return valid
}
func addField(field: SubmitField) {
fieldIndexByID[field.id] = orderedFields.count
orderedFields.append(field)
}
var count: Int {
return orderedFields.count
}
subscript(index: Int) -> SubmitField {
return orderedFields[index]
}
subscript(id: SubmitFieldID) -> SubmitField? {
if let index = indexOfFieldID(id) {
return orderedFields[index]
} else {
return nil
}
}
func indexOfFieldID(id: SubmitFieldID) -> Int? {
return fieldIndexByID[id]
}
var subredditField: SubmitTextField {
return self[.Subreddit] as! SubmitTextField
}
var titleField: SubmitTextField {
return self[.Title] as! SubmitTextField
}
var textField: SubmitLongTextField? {
return self[.Text] as? SubmitLongTextField
}
var urlField: SubmitURLField? {
return self[.URL] as? SubmitURLField
}
var sendRepliesField: SubmitBoolField {
return self[.SendReplies] as! SubmitBoolField
}
}
/*
kind one of (link, self)
two buttons next to each other that toggle the other, or a UISegmented control?
sr name of a subreddit (picker for subscribed?)
text field
title title of the submission. up to 300 characters long
text view or text field
text raw markdown text
text view
OR
url a valid URL
text field
sendreplies boolean value
switch
captcha the user's response to the CAPTCHA challenge
image + text field
??? acount chooser? have to recheck for if need captcha
api_type the string json
extension extension used for redirects
resubmit boolean value
iden the identifier of the CAPTCHA challenge
then one of (tb, comments)
*/
| mit | f88bb3ebab57d1619568145f0366dc7a | 24.707424 | 80 | 0.612366 | 4.518035 | false | false | false | false |
BrisyIOS/TodayNewsSwift3.0 | TodayNews-Swift3.0/TodayNews-Swift3.0/Classes/Home/Model/MiddleImageModel.swift | 1 | 1094 | //
// MiddleImageModel.swift
// TodayNews-Swift3.0
//
// Created by zhangxu on 2016/10/27.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
class MiddleImageModel: NSObject {
var height: Int?
var width: Int?
var url: String?
var url_list: [[String: Any]]?
// 字典转模型
class func modelWidthDic(dic: [String: Any]?) -> MiddleImageModel? {
guard let dic = dic else {
return nil;
}
let middleImageModel = MiddleImageModel();
middleImageModel.height = dic["height"] as? Int ?? 0;
middleImageModel.width = dic["width"] as? Int ?? 0;
middleImageModel.url_list = dic["url_list"] as? [[String: Any]] ?? [[:]];
let webpString = dic["url"] as? String ?? "";
if webpString.hasSuffix(".webp") {
let range: Range = webpString.range(of: ".webp")!;
middleImageModel.url = webpString.substring(to: range.lowerBound);
} else {
middleImageModel.url = webpString;
}
return middleImageModel;
}
}
| apache-2.0 | b9c8d816f806b5bc03a78b65fee9a892 | 26.717949 | 81 | 0.577243 | 4.079245 | false | false | false | false |
lYcHeeM/ZJImageBrowser | ZJImageBrowser/ZJImageBrowser/ZJImageBrowserPreviewingController.swift | 1 | 6192 | //
// ZJImageBrowserPreviewingController.swift
// ZJImageBrowser
//
// Created by luozhijun on 2017/7/11.
// Copyright © 2017年 RickLuo. All rights reserved.
//
import UIKit
import SDWebImage
import Photos
import PhotosUI
open class ZJImageBrowserPreviewingController: UIViewController {
private var imageView = UIImageView()
private var livePhotoView: UIView!
open var imageWrapper: ZJImageWrapper!
open var needsCopyAction: Bool = true
open var needsSaveAction: Bool = true
required public init(imageWrapper: ZJImageWrapper) {
super.init(nibName: nil, bundle: nil)
self.imageWrapper = imageWrapper
}
open func supposedContentSize(with image: UIImage? = nil) -> CGSize {
var usingImage = image
if usingImage == nil {
if let asset = imageWrapper.asset {
asset.image(shouldSynchronous: true, size: CGSize(width: 200, height: 200), resizeMode: .fast, completion: { (image, info) in
usingImage = image
})
} else {
usingImage = SDImageCache.shared().imageFromDiskCache(forKey: imageWrapper.highQualityImageUrl)
}
}
guard let image = usingImage else { return UIScreen.main.bounds.size }
var result = CGSize.zero
result.width = UIScreen.main.bounds.size.width
// 本以为要限制高度最大为屏幕高度, 同时按比例缩小width, 但实践发现这么做,
// 在高度超过屏幕的长图上, 会使得peek操作触发后, 图片无法充满预览区域.
// 但现在的做法也有一个缺陷, 长图无法完整显示, 超出屏幕高度的部分有可能看不到.
result.height = result.width * (image.size.height/image.size.width)
return result
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate var image: UIImage? {
didSet {
imageView.image = image
imageView.frame.size = supposedContentSize(with: image)
// 实践发现必须设置为zero才不会出现奇怪的问题.
// 本以为当imageView的高度小于view.frame.height时, 须调整y值使imageView居中,
// 但会有很大概率导致peek操作触发后, 图片显示不完全的现象.
imageView.frame.origin = .zero
}
}
override open func viewDidLoad() {
super.viewDidLoad()
view.clipsToBounds = false
view.addSubview(imageView)
if let image = imageWrapper.image {
self.image = image
return
} else if let asset = imageWrapper.asset {
let view = progressView(with: imageWrapper.progressStyle)
let fullScreenSize = UIScreen.main.bounds.size.width * UIScreen.main.scale
asset.image(shouldSynchronous: false, size: CGSize(width: fullScreenSize, height: fullScreenSize), progress: { (fraction, error, stop, info) in
view.progress = CGFloat(fraction)
}, completion: { (image, info) in
view.removeFromSuperview()
self.image = image
})
return
}
image = imageWrapper.placeholderImage
guard let url = URL(string: imageWrapper.highQualityImageUrl) else { return }
weak var weakProgressView = progressView(with: imageWrapper.progressStyle)
SDWebImageManager.shared().downloadImage(with: url, options: [.retryFailed], progress: { (receivedSize, expectedSize) in
let progress = CGFloat(receivedSize)/CGFloat(expectedSize)
weakProgressView?.progress = progress
}) { [weak self] (image, error, cacheType, finished, imageUrl) in
guard self != nil, finished else { return }
DispatchQueue.main.async(execute: {
if let usingImage = image {
self?.image = usingImage
}
weakProgressView?.removeFromSuperview()
})
}
}
private func progressView(with style: ZJProgressViewStyle) -> ZJProgressView {
let progressViewSize: CGFloat = 55
let progressViewFrame = CGRect(x: (imageView.frame.width - progressViewSize)/2, y: (imageView.frame.height - progressViewSize)/2, width: progressViewSize, height: progressViewSize)
let progressView = ZJProgressView(frame: progressViewFrame, style: style)
imageView.addSubview(progressView)
return progressView
}
@available(iOS 9.0, *)
override open var previewActionItems: [UIPreviewActionItem] {
let copyAction = UIPreviewAction(title: ZJImageBrowser.copyToPastboardActionTitle, style: .default) { (action, controller) in
UIPasteboard.general.image = self.image
}
let saveAction = UIPreviewAction(title: ZJImageBrowser.saveActionTitle, style: .default) { (action, controller) in
let status = PHPhotoLibrary.authorizationStatus()
if status == .restricted || status == .denied {
ZJImageBrowserHUD.show(message: ZJImageBrowser.albumAuthorizingFailedHint, inView: self.view, needsIndicator: false, hideAfter: 2.5)
return
}
guard let image = self.image else { return }
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
var actions = [UIPreviewAction]()
if needsCopyAction {
actions.append(copyAction)
}
if needsSaveAction {
actions.append(saveAction)
}
return actions
}
@objc private func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: Any?) {
var alertMessage = ""
if error == nil {
alertMessage = ZJImageBrowser.imageSavingSucceedHint
} else {
alertMessage = ZJImageBrowser.imageSavingFailedHint
}
ZJImageBrowserHUD.show(message: alertMessage, inView: nil, needsIndicator: false)
}
}
| mit | 2d30c36177f6aa63aa3c8395a482de48 | 40.415493 | 188 | 0.630505 | 4.761943 | false | false | false | false |
garethpaul/furni-ios | Furni/User.swift | 1 | 3252 | //
// Copyright (C) 2015 Twitter, Inc. and other contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
import Contacts
class User {
var cognitoID: String?
var twitterUserID: String?
var twitterUsername: String?
var digitsUserID: String?
var digitsPhoneNumber: String?
var fullName: String? = "Romain Huet"
var image: UIImage? = UIImage(named: "Romain")!
var postalAddress: CNPostalAddress?
var favorites: [Product] = []
// Enrich the user by fetching information from the local contact by phone number.
func populateWithLocalContact() {
guard let digitsPhoneNumber = digitsPhoneNumber else { return }
guard CNContactStore.authorizationStatusForEntityType(.Contacts) == .Authorized else { return }
let store = CNContactStore()
let fetchRequest = CNContactFetchRequest(keysToFetch: [CNContactPhoneNumbersKey, CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName), CNContactPostalAddressesKey, CNContactImageDataKey])
do {
try store.enumerateContactsWithFetchRequest(fetchRequest) { (contact, stop) in
let matchingPhoneNumbers = contact.phoneNumbers.map { $0.value as! CNPhoneNumber }.filter {
phoneNumber($0, matchesPhoneNumberString: digitsPhoneNumber)
}
guard matchingPhoneNumbers.count > 0 else {
return
}
self.fullName = CNContactFormatter.stringFromContact(contact, style: .FullName)
self.image = contact.imageData.flatMap(UIImage.init)
self.postalAddress = contact.postalAddresses.map { $0.value as! CNPostalAddress }.first
stop.memory = true
}
}
catch let error as NSError {
print("Error looking for contact: \(error)")
}
}
}
private func phoneNumber(phoneNumber: CNPhoneNumber, matchesPhoneNumberString phoneNumberString: String) -> Bool {
return phoneNumberString.rangeOfString(phoneNumber.stringValue.stringByRemovingOccurrencesOfCharacters(" )(- ")) != nil
}
// Note: This is a naive implementation that relies on global state. Avoid this in a production app.
extension Product {
var isFavorited: Bool {
get {
return AccountManager.defaultAccountManager.user?.favorites.contains { $0.id == self.id } ?? false
}
set {
guard let user = AccountManager.defaultAccountManager.user else { return }
if newValue {
user.favorites.append(self)
} else {
user.favorites = user.favorites.filter { $0.id != self.id }
}
}
}
} | apache-2.0 | 0fcab895093725d925f5c48b3a553d75 | 36.813953 | 206 | 0.666872 | 4.940729 | false | false | false | false |
mlilback/rc2SwiftClient | MacClient/session/MacFileImportSetup.swift | 1 | 6461 | //
// MacFileImporter.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Cocoa
import MJLLogger
import ReactiveSwift
import SwiftyUserDefaults
import Rc2Common
import Networking
import Model
/** Handles importing via a save panel or drag and drop. */
class MacFileImportSetup: NSObject {
var pboardReadOptions: [NSPasteboard.ReadingOptionKey: Any] {
return [NSPasteboard.ReadingOptionKey.urlReadingFileURLsOnly: true as AnyObject,
NSPasteboard.ReadingOptionKey.urlReadingContentsConformToTypes: [kUTTypePlainText, kUTTypePDF]]
}
/** Prompts the user to select files to upload.
parameter window: the parent window to display the sheet on
parameter workspace: the workspace the files will be imported into
parameter completionHandler: a closure called with an array of files to import, or nil if the user canceled the import
*/
func performFileImport(_ window: NSWindow, workspace: AppWorkspace, completionHandler:@escaping ([FileImporter.FileToImport]?) -> Void) {
let defaults = UserDefaults.standard
let panel = NSOpenPanel()
if let bmarkData = defaults[.lastImportDirectory] {
do {
panel.directoryURL = try (NSURL(resolvingBookmarkData: bmarkData, options: [], relativeTo: nil, bookmarkDataIsStale: nil) as URL)
} catch {
}
}
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.resolvesAliases = true
panel.allowsMultipleSelection = true
panel.prompt = NSLocalizedString("Import", comment: "")
panel.message = NSLocalizedString("Select Files to Import", comment: "")
panel.delegate = self
panel.treatsFilePackagesAsDirectories = true
panel.allowedFileTypes = FileType.importableFileTypes.map { $0.fileExtension }
let accessoryView = NSButton(frame: NSRect.zero)
accessoryView.setButtonType(.switch)
accessoryView.title = NSLocalizedString("Replace existing files", comment: "")
let replace = defaults[.replaceFiles]
accessoryView.state = replace ? .off : .on
panel.beginSheetModal(for: window) { result in
do {
let urlbmark = try (panel.directoryURL as NSURL?)?.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil)
defaults[.lastImportDirectory] = urlbmark
defaults[.replaceFiles] = accessoryView.state == .on
} catch let err as NSError {
Log.warn("why did we get error creating import bookmark: \(err)", .app)
}
panel.close()
if result == .OK && panel.urls.count > 0 {
let replaceFiles = accessoryView.state == .on
let files = panel.urls.map { url -> FileImporter.FileToImport in
let uname = replaceFiles ? self.uniqueFileName(url.lastPathComponent, inWorkspace: workspace) : nil
return FileImporter.FileToImport(url: url, uniqueName: uname)
}
completionHandler(files)
} else {
completionHandler(nil)
}
}
}
/** If importing via drop, call this to to see if the file is acceptable
parameter info: the drag info
returns: the drag operation to perform
*/
func validateTableViewDrop(_ info: NSDraggingInfo) -> NSDragOperation {
guard info.draggingSource == nil else { return NSDragOperation() } //don't allow local drags
guard let urls = info.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: pboardReadOptions) as? [URL],
urls.count > 0
else { return NSDragOperation() } //must have a url
let acceptableTypes = FileType.importableFileTypes.map { $0.fileExtension }
for aUrl in urls {
if !acceptableTypes.contains(aUrl.pathExtension) {
return NSDragOperation()
}
}
//must be good
return NSDragOperation.copy
}
/** If importing via drop, prompts about replacing files if there are any duplicates
parameter info: the drag info
parameter workspace: the workspace the file(s) will be imported into
parameter handler: called with the array of files to import
*/
func acceptTableViewDrop(_ info: NSDraggingInfo, workspace: AppWorkspace, window: NSWindow, handler:@escaping ([FileImporter.FileToImport]) -> Void)
{
assert(validateTableViewDrop(info) != NSDragOperation(), "validate wasn't called on drag info")
guard let urls = info.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: pboardReadOptions) as? [URL], urls.count > 0 else { return }
let existingNames: [String] = workspace.files.map { $0.name }
if urls.first(where: { aUrl in existingNames.contains(aUrl.lastPathComponent) }) != nil {
let alert = NSAlert()
alert.messageText = NSLocalizedString("Replace existing file(s)?", comment: "")
alert.informativeText = NSLocalizedString("One or more files already exist with the same name as a dropped file", comment: "")
alert.addButton(withTitle: NSLocalizedString("Replace", comment: ""))
alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
let uniqButton = alert.addButton(withTitle: NSLocalizedString("Create Unique Names", comment: ""))
uniqButton.keyEquivalent = "u"
uniqButton.keyEquivalentModifierMask = .command
alert.beginSheetModal(for: window, completionHandler: { response in
guard response != .alertSecondButtonReturn else { return }
let files = urls.map { url -> FileImporter.FileToImport in
let uname = response == .alertFirstButtonReturn ? nil : self.uniqueFileName(url.lastPathComponent, inWorkspace: workspace)
return FileImporter.FileToImport(url: url, uniqueName: uname)
}
handler(files)
})
} else {
handler(urls.map { url in FileImporter.FileToImport(url: url, uniqueName: nil) })
}
}
/** generates a unique file name (by adding a number to the end) for a file in a workspace */
func uniqueFileName(_ desiredName: String, inWorkspace workspace: AppWorkspace) -> String {
var i = 1
let nsname = NSString(string: desiredName)
let baseName = nsname.deletingPathExtension
let pathExtension = nsname.pathExtension
var useableName = desiredName
let existingNames: [String] = workspace.files.map { return $0.name }
//check if desiredName is ok
if !existingNames.contains(desiredName) {
return desiredName
}
while true {
let newName = baseName + " \(i)." + pathExtension
if !existingNames.contains(newName) {
useableName = newName
break
}
i += 1
}
return useableName
}
}
extension MacFileImportSetup: NSOpenSavePanelDelegate {
func panel(_ sender: Any, shouldEnable url: URL) -> Bool {
return FileType.fileType(withExtension: url.pathExtension) != nil || url.directoryExists()
}
}
| isc | c5c4e7ab8c305324900c9b4b50782d61 | 41.222222 | 150 | 0.736997 | 4.11465 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClientUnitTests/Spec/Hashtag/SearchInHashtagsRequestSpec.swift | 1 | 2454 | //
// SearchInHashtagsRequestSpec.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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 Quick
import Nimble
@testable import CreatubblesAPIClient
class SearchInHashtagsRequestSpec: QuickSpec {
fileprivate let page = 1
fileprivate let pageCount = 10
fileprivate let query = "lego"
override func spec() {
describe("Search in hashtags Request") {
it("Should have a proper endpoint") {
let request = SearchForHashtagRequest(page: self.page, perPage: self.pageCount, query: self.query)
expect(request.endpoint) == "popular_hashtags"
}
it("Should have proper method") {
let request = SearchForHashtagRequest(page: self.page, perPage: self.pageCount, query: self.query)
expect(request.method) == RequestMethod.get
}
it("Should have proper parameters set") {
let request = SearchForHashtagRequest(page: self.page, perPage: self.pageCount, query: self.query)
let params = request.parameters
expect(params["page"] as? Int) == self.page
expect(params["per_page"] as? Int) == self.pageCount
expect(params["filter[name]"] as? String) == self.query
}
}
}
}
| mit | e4b225b4d3a53eefdf927fc6b887d8b8 | 42.821429 | 114 | 0.669112 | 4.561338 | false | false | false | false |
mlilback/MJLCommon | Sources/MJLCommon/Keychain.swift | 1 | 3753 | //
// Keychain.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
import Security
private let SecClass: String = kSecClass as String
private let SecValueData: String = kSecValueData as String
/// simple access to the keychain. All items are stored/retrieved as kSecClassGenericPassword
public class Keychain {
let service: String
let secClass: String
/// Creates a Keychain object
/// - Parameter service: The name the item will be stored under. This should generally be your bundle identifier
public init(service: String, secClass: CFString = kSecClassGenericPassword) {
guard secClass == kSecClassInternetPassword || secClass == kSecClassGenericPassword
else { fatalError("unsupported secClass") }
self.service = service
self.secClass = secClass as String
}
/// Gets data from the keychain
/// - Parameter key: the key the data was stored under
/// - Returns: the value as a Data object. Returns nil if not found or there is an error
public func getData(key: String) -> Data? {
let query = setupQuery(key)
var dataRef: AnyObject?
let status = withUnsafeMutablePointer(to: &dataRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) }
guard status == noErr && dataRef != nil else { return nil }
return dataRef as? Data
}
/// Gets string from the keychain
/// - Parameter key: the key the data was stored under
/// - Returns: the value as a String. Returns nil if not found or there is an error
public func getString(key: String) -> String? {
guard let data = getData(key: key) else { return nil }
return String(data: data, encoding: .utf8)
}
/// Removes any
/// - Parameter key: The key the item is stored under
/// - Returns: true/false depending if successful
/// - Throws: NSError of domain NSOSStatusErrorDomain if any Kechain API call results in an error
@discardableResult public func removeKey(key: String) throws -> Bool {
let query = setupQuery(key)
let status = SecItemDelete(query as CFDictionary)
if status == noErr { return true }
throw NSError(domain: NSOSStatusErrorDomain, code: Int(status), userInfo: nil)
}
/// Sets a value in the keychain
/// - Parameters:
/// - key: the key to store the data under
/// - value: the string to store
/// - Throws: NSError of domain NSOSStatusErrorDomain if any Kechain API call results in an error
public func setString(key: String, value: String?) throws {
try setData(key: key, value: value?.data(using: .utf8))
}
/// Sets a value in the keychain
/// - Parameters:
/// - key: the key to store the data under
/// - value: the data to store
/// - Throws: NSError of domain NSOSStatusErrorDomain if any Kechain API call results in an error
public func setData(key: String, value: Data?) throws {
guard let valueToStore = value else {
try removeKey(key: key)
return
}
var query = setupQuery(key)
var status: OSStatus = noErr
if let existing = getData(key: key) {
guard existing != value else {
return
}
let values: [String:AnyObject] = [SecValueData: value as AnyObject]
status = SecItemUpdate(query as CFDictionary, values as CFDictionary)
} else {
query[SecValueData] = valueToStore as AnyObject?
status = SecItemAdd(query as CFDictionary, nil)
}
if status != errSecSuccess {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(status), userInfo: nil)
}
}
private func setupQuery(_ key: String) -> [String:AnyObject] {
var query: [String: AnyObject] = [SecClass: secClass as AnyObject]
query[kSecAttrService as String] = service as AnyObject?
query[kSecAttrAccount as String] = key as AnyObject?
query[kSecReturnData as String] = kCFBooleanTrue
return query
}
}
| isc | c642aa64d57c1321171597a8ea068e81 | 36.52 | 126 | 0.718017 | 3.978791 | false | false | false | false |
krzysztofzablocki/DetailsMatter | SwiftExample/SwiftExample/RememberView.swift | 1 | 4058 | //
// RememberView.swift
// SwiftExample
//
// Created by Krzysztof Zabłocki on 16/12/15.
// Copyright © 2015 pixle. All rights reserved.
//
import UIKit
extension UIView {
@IBInspectable var kz_borderColor: UIColor? {
get {
if let colorRef = layer.borderColor {
return UIColor(CGColor: colorRef)
}
return nil
}
set {
layer.borderColor = newValue?.CGColor
}
}
}
class RememberView: UIView, UITextFieldDelegate {
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var foldView: UIView!
@IBOutlet weak var submitButton: UIButton!
@IBOutlet weak var entryField: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
var perspectiveTransform = CATransform3DIdentity
perspectiveTransform.m34 = 1 / -900
self.layer.sublayerTransform = perspectiveTransform
entryField.delegate = self
}
@IBAction func valueChanges(check: UISwitch) {
UIView.animateWithDuration(0.7, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.2, options: .AllowAnimatedContent, animations: {
let angle = !check.on ? -90 : 0
self.foldView.layer.transform = CATransform3DMakeRotation(self.toRadian(angle), 1.0, 0, 0)
self.layoutStack()
self.frame.size.height = CGRectGetMaxY(self.submitButton.frame) + 10
}, completion: nil)
}
override func layoutSubviews() {
super.layoutSubviews()
layoutStack()
}
func foldFrame(withTop top: CGFloat) -> CGRect {
return CGRectMake(headerView.frame.origin.x, top, headerView.bounds.size.width, 80)
}
func layoutStack() {
let margin: CGFloat = 10
foldView.frame = foldFrame(withTop: CGRectGetMaxY(headerView.frame) - foldView.layer.borderWidth)
submitButton.frame.origin.y = CGRectGetMaxY(foldView.frame) + margin
}
@IBAction func submitPressed(sender: UIButton) {
if entryField.text?.characters.count > 0 {
animateButton(sender, toTitle: "Sending...", color: UIColor.grayColor())
delay(1.5, closure: { () -> () in
self.animateButton(sender, toTitle: "Sent!", color: UIColor.greenColor())
})
} else {
let translation = CAKeyframeAnimation(keyPath: "transform.translation.x");
translation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
translation.values = [-5, 5, -5, 5, -3, 3, -2, 2, 0]
let rotation = CAKeyframeAnimation(keyPath: "transform.rotation.y");
rotation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
rotation.values = [-5, 5, -5, 5, -3, 3, -2, 2, 0].map {
self.toRadian($0)
}
let shakeGroup: CAAnimationGroup = CAAnimationGroup()
shakeGroup.animations = [translation, rotation]
shakeGroup.duration = 0.6
self.layer.addAnimation(shakeGroup, forKey: "shakeIt")
}
}
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
func animateButton(button: UIButton, toTitle title: String, color: UIColor) {
let transition = CATransition()
transition.type = kCATransitionPush
transition.subtype = kCATransitionFromTop
transition.duration = 0.5
button.titleLabel?.layer.addAnimation(transition, forKey: kCATransition)
button.setTitle(title, forState: .Normal)
button.setTitleColor(color, forState: .Normal)
}
func toRadian(value: Int) -> CGFloat {
return CGFloat(Double(value) / 180.0 * M_PI)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | 277b346ddacce271034f0519da6889c3 | 34.269565 | 152 | 0.623521 | 4.56243 | false | false | false | false |
imwcl/WCLShineButton | WCLShineButton/WCLShineLayer.swift | 1 | 3758 | //
// WCLShineLayer.swift
// WCLShineButton
//
// **************************************************
// * _____ *
// * __ _ __ ___ \ / *
// * \ \/ \/ / / __\ / / *
// * \ _ / | (__ / / *
// * \/ \/ \___/ / /__ *
// * /_____/ *
// * *
// **************************************************
// Github :https://github.com/imwcl
// HomePage:https://imwcl.com
// CSDN :http://blog.csdn.net/wang631106979
//
// Created by 王崇磊 on 16/9/14.
// Copyright © 2016年 王崇磊. All rights reserved.
//
// @class WCLShineLayer
// @abstract 展示Shine的layer
// @discussion 展示Shine的layer
//
import UIKit
class WCLShineLayer: CALayer, CAAnimationDelegate {
let shapeLayer = CAShapeLayer()
var fillColor: UIColor = UIColor(rgb: (255, 102, 102)) {
willSet {
shapeLayer.strokeColor = newValue.cgColor
}
}
var params: WCLShineParams = WCLShineParams()
var displaylink: CADisplayLink?
var endAnim: (()->Void)?
//MARK: Public Methods
func startAnim() {
let anim = CAKeyframeAnimation(keyPath: "path")
anim.duration = params.animDuration * 0.1
let size = frame.size
let fromPath = UIBezierPath(arcCenter: CGPoint.init(x: size.width/2, y: size.height/2), radius: 1, startAngle: 0, endAngle: CGFloat(Double.pi) * 2.0, clockwise: false).cgPath
let toPath = UIBezierPath(arcCenter: CGPoint.init(x: size.width/2, y: size.height/2), radius: size.width/2 * CGFloat(params.shineDistanceMultiple), startAngle: 0, endAngle: CGFloat(Double.pi) * 2.0, clockwise: false).cgPath
anim.delegate = self
anim.values = [fromPath, toPath]
anim.timingFunctions = [CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)]
anim.isRemovedOnCompletion = false
anim.fillMode = CAMediaTimingFillMode.forwards
shapeLayer.add(anim, forKey: "path")
if params.enableFlashing {
startFlash()
}
}
//MARK: Initial Methods
override init() {
super.init()
initLayers()
}
override init(layer: Any) {
super.init(layer: layer)
initLayers()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Privater Methods
private func initLayers() {
shapeLayer.fillColor = UIColor.white.cgColor
shapeLayer.strokeColor = fillColor.cgColor
shapeLayer.lineWidth = 1.5
addSublayer(shapeLayer)
}
private func startFlash() {
displaylink = CADisplayLink(target: self, selector: #selector(flashAction))
if #available(iOS 10.0, *) {
displaylink?.preferredFramesPerSecond = 6
}else {
displaylink?.frameInterval = 10
}
displaylink?.add(to: .current, forMode: .common)
}
@objc private func flashAction() {
let index = Int(arc4random()%UInt32(params.colorRandom.count))
shapeLayer.strokeColor = params.colorRandom[index].cgColor
}
//MARK: CAAnimationDelegate
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
displaylink?.invalidate()
displaylink = nil
shapeLayer.removeAllAnimations()
let angleLayer = WCLShineAngleLayer(frame: bounds, params: params)
addSublayer(angleLayer)
angleLayer.startAnim()
endAnim?()
}
}
}
| mit | 392912d094d31ece16313c818d48ba83 | 32.017699 | 231 | 0.541946 | 4.431116 | false | false | false | false |
iPantry/iPantry-iOS | Pantry/Controllers/Pantry/MyPantryViewController.swift | 1 | 4115 | //
// MyPantryViewController.swift
// Pantry
//
// Created by Justin Oroz on 11/12/16.
// Copyright © 2016 Justin Oroz. All rights reserved.
//
import UIKit
import FirebaseAuth
import FirebaseDatabase
class MyPantryViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
NotificationCenter.default.addObserver(self, selector: #selector(pantry), name: .pantryListWasUpdated, object: nil)
// 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 viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .pantryListWasUpdated, object: nil)
}
@objc func pantry (notification: Notification) {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return PantryUser.current?.pantry?.list.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "itemCell", for: indexPath) as? PantryTableViewCell,
let item = PantryUser.current?.pantry?.list[indexPath.row]
else {
// TODO: Return an Error Cell
return UITableViewCell()
}
// Configure the cell...
cell.configure(from: item)
return cell
}
@IBAction func showSettings(_ sender: Any) {
let settingsStory = UIStoryboard(name: "Settings", bundle: nil)
guard let rootNav = settingsStory.instantiateViewController(withIdentifier: "settings") as? SettingsViewController
else {
return
}
UIView.beginAnimations("animation", context: nil)
UIView.setAnimationDuration(0.7)
self.navigationController?.pushViewController(rootNav, animated: false)
UIView.setAnimationTransition(.flipFromRight, for: self.navigationController!.view, cache: false)
UIView.commitAnimations()
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false 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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| agpl-3.0 | e483bfd2183dc46e813ab55eb9d5f721 | 29.474074 | 133 | 0.748906 | 4.22816 | false | false | false | false |
srn214/Floral | Floral/Pods/JXPhotoBrowser/Source/Core/Enhance/JXNumberPageControlDelegate.swift | 1 | 2225 | //
// JXNumberPageControlDelegate.swift
// JXPhotoBrowser
//
// Created by JiongXing on 2018/10/15.
//
import Foundation
/// 实现了以 数字型 为页码指示器的 Delegate.
open class JXNumberPageControlDelegate: JXPhotoBrowserBaseDelegate {
/// 字体
open var font = UIFont.systemFont(ofSize: 17)
/// 字颜色
open var textColor = UIColor.white
/// 指定Y轴从顶部往下偏移值
open lazy var offsetY: CGFloat = {
if #available(iOS 11.0, *), let window = UIApplication.shared.keyWindow {
return window.safeAreaInsets.top
}
return 20
}()
/// 数字页码指示
open lazy var pageControl: UILabel = {
let view = UILabel()
view.font = font
view.textColor = textColor
return view
}()
open override func photoBrowser(_ browser: JXPhotoBrowser, pageIndexDidChanged pageIndex: Int) {
super.photoBrowser(browser, pageIndexDidChanged: pageIndex)
layout()
}
open override func photoBrowserViewWillLayoutSubviews(_ browser: JXPhotoBrowser) {
super.photoBrowserViewWillLayoutSubviews(browser)
layout()
}
open override func photoBrowser(_ browser: JXPhotoBrowser, viewDidAppear animated: Bool) {
super.photoBrowser(browser, viewDidAppear: animated)
// 页面出来后,再显示页码指示器
// 多于一张图才添加到视图
let totalPages = browser.itemsCount
if totalPages > 1 {
browser.view.addSubview(pageControl)
}
}
open override func photoBrowserDidReloadData(_ browser: JXPhotoBrowser) {
layout()
}
//
// MARK: - Private
//
private func layout() {
guard let browser = self.browser else {
return
}
guard let superView = pageControl.superview else { return }
let totalPages = browser.itemsCount
pageControl.text = "\(browser.pageIndex + 1) / \(totalPages)"
pageControl.sizeToFit()
pageControl.center.x = superView.bounds.width / 2
pageControl.frame.origin.y = offsetY
pageControl.isHidden = totalPages <= 1
}
}
| mit | b118e74883cd5438e171dc93aadf316f | 27.04 | 100 | 0.623871 | 4.823394 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/ApplicationAutoScaling/ApplicationAutoScaling_Paginator.swift | 1 | 12861 | //===----------------------------------------------------------------------===//
//
// 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 ApplicationAutoScaling {
/// Gets information about the scalable targets in the specified namespace. You can filter the results using ResourceIds and ScalableDimension.
///
/// 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 describeScalableTargetsPaginator<Result>(
_ input: DescribeScalableTargetsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, DescribeScalableTargetsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: describeScalableTargets,
tokenKey: \DescribeScalableTargetsResponse.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 describeScalableTargetsPaginator(
_ input: DescribeScalableTargetsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (DescribeScalableTargetsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: describeScalableTargets,
tokenKey: \DescribeScalableTargetsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provides descriptive information about the scaling activities in the specified namespace from the previous six weeks. You can filter the results using ResourceId and ScalableDimension.
///
/// 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 describeScalingActivitiesPaginator<Result>(
_ input: DescribeScalingActivitiesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, DescribeScalingActivitiesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: describeScalingActivities,
tokenKey: \DescribeScalingActivitiesResponse.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 describeScalingActivitiesPaginator(
_ input: DescribeScalingActivitiesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (DescribeScalingActivitiesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: describeScalingActivities,
tokenKey: \DescribeScalingActivitiesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Describes the Application Auto Scaling scaling policies for the specified service namespace. You can filter the results using ResourceId, ScalableDimension, and PolicyNames. For more information, see Target Tracking Scaling Policies and Step Scaling Policies in the Application Auto Scaling User Guide.
///
/// 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 describeScalingPoliciesPaginator<Result>(
_ input: DescribeScalingPoliciesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, DescribeScalingPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: describeScalingPolicies,
tokenKey: \DescribeScalingPoliciesResponse.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 describeScalingPoliciesPaginator(
_ input: DescribeScalingPoliciesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (DescribeScalingPoliciesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: describeScalingPolicies,
tokenKey: \DescribeScalingPoliciesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Describes the Application Auto Scaling scheduled actions for the specified service namespace. You can filter the results using the ResourceId, ScalableDimension, and ScheduledActionNames parameters. For more information, see Scheduled Scaling in the Application Auto Scaling User Guide.
///
/// 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 describeScheduledActionsPaginator<Result>(
_ input: DescribeScheduledActionsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, DescribeScheduledActionsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: describeScheduledActions,
tokenKey: \DescribeScheduledActionsResponse.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 describeScheduledActionsPaginator(
_ input: DescribeScheduledActionsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (DescribeScheduledActionsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: describeScheduledActions,
tokenKey: \DescribeScheduledActionsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension ApplicationAutoScaling.DescribeScalableTargetsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> ApplicationAutoScaling.DescribeScalableTargetsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
resourceIds: self.resourceIds,
scalableDimension: self.scalableDimension,
serviceNamespace: self.serviceNamespace
)
}
}
extension ApplicationAutoScaling.DescribeScalingActivitiesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> ApplicationAutoScaling.DescribeScalingActivitiesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
resourceId: self.resourceId,
scalableDimension: self.scalableDimension,
serviceNamespace: self.serviceNamespace
)
}
}
extension ApplicationAutoScaling.DescribeScalingPoliciesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> ApplicationAutoScaling.DescribeScalingPoliciesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
policyNames: self.policyNames,
resourceId: self.resourceId,
scalableDimension: self.scalableDimension,
serviceNamespace: self.serviceNamespace
)
}
}
extension ApplicationAutoScaling.DescribeScheduledActionsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> ApplicationAutoScaling.DescribeScheduledActionsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
resourceId: self.resourceId,
scalableDimension: self.scalableDimension,
scheduledActionNames: self.scheduledActionNames,
serviceNamespace: self.serviceNamespace
)
}
}
| apache-2.0 | 76f683de71e97b5879762b1236606d51 | 45.767273 | 311 | 0.6662 | 5.449576 | false | false | false | false |
hejunbinlan/SwiftGraphics | Playgrounds/Very WIP/Color.playground/section-1.swift | 7 | 3303 | // Playground - noun: a place where people can play
import Cocoa
import SwiftGraphics
import SwiftGraphicsPlayground
public typealias BitmapContextParameters = (width:UInt,height:UInt,bitsPerComponent:UInt,bytesPerRow:UInt,colorSpace:CGColorSpace,bitmapInfo:CGBitmapInfo)
enum BitmapContextMode {
case RGBA_UINT8
case RGBA_UINT16
}
public func expandBitmapContextParameters(size:CGSize, bitsPerComponent:Int, colorSpace:CGColorSpaceRef, alphaInfo:CGImageAlphaInfo, bitmapInfo:CGBitmapInfo) -> BitmapContextParameters? {
let colorModel = CGColorSpaceGetModel(colorSpace)
let numberOfColorComponents:Int = {
switch colorModel.value {
case kCGColorSpaceModelMonochrome.value:
return 1
case kCGColorSpaceModelRGB.value:
return 3
case kCGColorSpaceModelCMYK.value:
return 4
default:
assert(false)
return 0
}
}()
if (bitmapInfo.rawValue & CGBitmapInfo.FloatComponents.rawValue != 0)
{
if bitsPerComponent != sizeof(Float) * 8 {
return nil
}
}
let hasAlphaComponent = alphaInfo != .None && alphaInfo != .Only
let numberOfComponents:UInt = numberOfColorComponents + (hasAlphaComponent ? 1 : 0)
let width = UInt(size.width)
let height = UInt(size.height)
let bitsPerPixel = UInt(bitsPerComponent) * numberOfComponents
let bytesPerComponent = bitsPerPixel * numberOfComponents / 8
let bytesPerRow = width * bytesPerComponent
let tuple = (width, height, UInt(bitsPerComponent), bytesPerRow, colorSpace, bitmapInfo | CGBitmapInfo(alphaInfo.rawValue))
return tuple
}
public extension CGContext {
class func bitmapContext(size:CGSize, bitsPerComponent:Int, colorSpace:CGColorSpaceRef, alphaInfo:CGImageAlphaInfo, bitmapInfo:CGBitmapInfo) -> CGContext! {
let p = expandBitmapContextParameters(size, bitsPerComponent, colorSpace, alphaInfo, bitmapInfo)!
return CGBitmapContextCreate(nil, p.width, p.height, p.bitsPerComponent, p.bytesPerRow, p.colorSpace, p.bitmapInfo)
}
}
let size = CGSize(w:10, h:10)
let colorSpace = CGColorSpaceCreateDeviceRGB()
// class func bitmapContext(size:CGSize, bitsPerComponent:UInt, colorSpace:CGColorSpaceRef, alphaInfo:CGImageAlphaInfo, bitmapInfo:CGBitmapInfo) -> CGContext! {
let alphaInfo = CGImageAlphaInfo.NoneSkipLast
let bitmapInfo = CGBitmapInfo() // CGBitmapInfo.FloatComponents
typealias ComponentType = UInt8
print(validParametersForBitmapContext(colorSpace:colorSpace, bitsPerPixel:sizeof(ComponentType) * 8 * 4, bitsPerComponent:sizeof(ComponentType) * 8, alphaInfo:alphaInfo, bitmapInfo:bitmapInfo))
let context = CGContextRef.bitmapContext(size, bitsPerComponent:sizeof(ComponentType) * 8, colorSpace: colorSpace, alphaInfo: alphaInfo, bitmapInfo: bitmapInfo)
CGContextSetAllowsAntialiasing(context, false)
context.setFillColor(CGColor.redColor())
CGContextFillRect(context, CGRect(size:size))
CGContextSetBlendMode(context, kCGBlendModeCopy)
context.setFillColor(CGColor.greenColor())
CGContextFillRect(context, CGRect(size:size))
let data = UnsafePointer <ComponentType> (CGBitmapContextGetData(context))
data[0]
data[1]
data[2]
data[3]
context.nsimage
| bsd-2-clause | ffd7f04707047c90c5c6bbc74c6008a5 | 30.457143 | 193 | 0.74175 | 4.843109 | false | false | false | false |
ringly/IOS-Pods-DFU-Library | iOSDFULibrary/Classes/Implementation/LegacyDFU/DFU/LegacyDFUExecutor.swift | 1 | 6439 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
internal class LegacyDFUExecutor : DFUExecutor, LegacyDFUPeripheralDelegate {
typealias DFUPeripheralType = LegacyDFUPeripheral
internal let initiator : DFUServiceInitiator
internal let peripheral : LegacyDFUPeripheral
internal var firmware : DFUFirmware
internal var error : (error: DFUError, message: String)?
/// Retry counter for peripheral invalid state issue
private let MaxRetryCount = 1
private var invalidStateRetryCount: Int
/// The DFU control point characteristic UUID to search for
internal let controlPointCharacteristicUUID: CBUUID
/// The DFU packet characteristic UUID to search for
internal let packetCharacteristicUUID: CBUUID
// MARK: - Initialization
required init(_ initiator:DFUServiceInitiator, controlPointCharacteristicUUID: CBUUID, packetCharacteristicUUID: CBUUID) {
self.initiator = initiator
self.peripheral = LegacyDFUPeripheral(initiator, controlPointCharacteristicUUID: controlPointCharacteristicUUID, packetCharacteristicUUID: packetCharacteristicUUID)
self.firmware = initiator.file!
self.controlPointCharacteristicUUID = controlPointCharacteristicUUID
self.packetCharacteristicUUID = packetCharacteristicUUID
self.invalidStateRetryCount = MaxRetryCount
self.peripheral.delegate = self
}
// MARK: - DFU Peripheral Delegate methods
func peripheralDidBecomeReady() {
if firmware.initPacket == nil && peripheral.isInitPacketRequired() {
error(.extendedInitPacketRequired, didOccurWithMessage: "The init packet is required by the target device")
return
}
DispatchQueue.main.async(execute: {
self.delegate?.dfuStateDidChange(to: .starting)
})
peripheral.enableControlPoint()
}
func peripheralDidEnableControlPoint() {
// Check whether the target is in application or bootloader mode
if peripheral.isInApplicationMode(initiator.forceDfu) {
DispatchQueue.main.async(execute: {
self.delegate?.dfuStateDidChange(to: .enablingDfuMode)
})
peripheral.jumpToBootloader()
} else {
// The device is ready to proceed with DFU
peripheral.sendStartDfu(withFirmwareType: firmware.currentPartType, andSize: firmware.currentPartSize)
}
}
func peripheralDidFailToStartDfuWithType() {
// The DFU target has an old implementation of DFU Bootloader, that allows only the application
// to be updated.
if firmware.currentPartType == FIRMWARE_TYPE_APPLICATION {
// Try using the old DFU Start command, without type
peripheral.sendStartDfu(withFirmwareSize: firmware.currentPartSize)
} else {
// Operation can not be continued
error(.remoteLegacyDFUNotSupported, didOccurWithMessage: "Updating Softdevice or Bootloader is not supported")
}
}
func peripheralDidStartDfu() {
// Check if the init packet is present for this part
if let initPacket = firmware.initPacket {
peripheral.sendInitPacket(initPacket)
return
}
sendFirmware()
}
func peripheralDidReceiveInitPacket() {
sendFirmware()
}
func peripheralDidReceiveFirmware() {
DispatchQueue.main.async(execute: {
self.delegate?.dfuStateDidChange(to: .validating)
})
peripheral.validateFirmware()
}
func peripheralDidVerifyFirmware() {
DispatchQueue.main.async(execute: {
self.delegate?.dfuStateDidChange(to: .disconnecting)
})
peripheral.activateAndReset()
}
func peripheralDidReportInvalidState() {
if invalidStateRetryCount > 0 {
logWith(.warning, message: "Retrying...")
invalidStateRetryCount -= 1
peripheral.connect()
} else {
error(.remoteLegacyDFUInvalidState, didOccurWithMessage: "Peripheral is in an invalid state, please try to reset and start over again.")
}
}
// MARK: - Private methods
/**
Sends the current part of the firmware to the target DFU device.
*/
private func sendFirmware() {
DispatchQueue.main.async(execute: {
self.delegate?.dfuStateDidChange(to: .uploading)
})
// First the service will send the number of packets of firmware data to be received
// by the DFU target before sending a new Packet Receipt Notification.
// After receiving status Success it will send the firmware.
peripheral.sendFirmware(firmware, withPacketReceiptNotificationNumber: initiator.packetReceiptNotificationParameter, andReportProgressTo: progressDelegate)
}
}
| bsd-3-clause | f5ef432960e354aa50ef49f2e773f6c6 | 42.506757 | 172 | 0.702904 | 5.58941 | false | false | false | false |
pinterest/tulsi | src/Tulsi/main.swift | 1 | 4429 | // Copyright 2016 The Tulsi Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Cocoa
import TulsiGenerator
private func main() {
// Parse the commandline parameters to see if the app should operate in headless mode or not.
let commandlineParser = TulsiCommandlineParser()
let consoleLogger = EventLogger(verboseLevel: commandlineParser.arguments.verboseLevel,
logToFile: commandlineParser.arguments.logToFile)
consoleLogger.startLogging()
if !commandlineParser.commandlineSentinalFound {
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
exit(0)
}
let version = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "unknown"
LogMessage.postSyslog("Tulsi CLI: version \(version)")
let queue = DispatchQueue(label: "com.google.Tulsi.xcodeProjectGenerator", attributes: [])
queue.async {
do {
switch commandlineParser.mode {
case .invalid:
print("Missing mode parameter. Please see the help message.")
exit(2)
case .tulsiProjectCreator:
let generator = HeadlessTulsiProjectCreator(arguments: commandlineParser.arguments)
try generator.generate()
case .xcodeProjectGenerator:
let generator = HeadlessXcodeProjectGenerator(arguments: commandlineParser.arguments)
try generator.generate()
}
} catch HeadlessModeError.invalidConfigPath(let reason) {
print("Invalid \(TulsiCommandlineParser.ParamGeneratorConfigLong) param: \(reason)")
exit(11)
} catch HeadlessModeError.invalidConfigFileContents(let reason) {
print("Failed to read the given generator config: \(reason)")
exit(12)
} catch HeadlessModeError.explicitOutputOptionRequired {
print("The \(TulsiCommandlineParser.ParamOutputFolderLong) option is required for the selected config")
exit(13)
} catch HeadlessModeError.invalidBazelPath {
print("The path to the bazel binary is invalid")
exit(14)
} catch HeadlessModeError.generationFailed {
print("Xcode project generation failed")
exit(15)
} catch HeadlessModeError.invalidWorkspaceRootOverride {
print("The parameter given as the workspace root path is not a valid directory")
exit(16)
} catch HeadlessModeError.invalidProjectFileContents(let reason) {
print("Failed to read the given project: \(reason)")
exit(20)
} catch HeadlessModeError.missingBazelPath {
print("The path to the bazel binary must be specified")
exit(21)
} catch HeadlessModeError.missingWORKSPACEFile(let path) {
print("The workspace root at '\(path)' does not contain a Bazel WORKSPACE file.")
exit(21)
} catch HeadlessModeError.missingBuildTargets {
print("At least one build target must be specified with the \(TulsiCommandlineParser.ParamBuildTargetLong) parameter.")
exit(22)
} catch HeadlessModeError.invalidProjectBundleName {
print("The parameter given to \(TulsiCommandlineParser.ParamCreateTulsiProj) is invalid. " +
"It must be the name of the .tulsiproj bundle to be created, without any other " +
"path elements.")
exit(23)
} catch HeadlessModeError.bazelTargetProcessingFailed {
print("Failed to identify any valid build targets.")
exit(24)
} catch let e as NSError {
print("An unexpected exception occurred: \(e.localizedDescription)")
exit(126)
} catch {
print("An unexpected exception occurred")
exit(127)
}
// Ideally this would go just after generator.generate() inside the do block, but doing so trips
// up the coverage tool as exit is @noreturn. It is important that all catch blocks exit with
// non-zero codes so that they do not reach this.
exit(0)
}
dispatchMain()
}
// MARK: - Application entrypoint
main()
| apache-2.0 | e69c97be977017e77f498275f2932b28 | 40.392523 | 125 | 0.708964 | 4.762366 | false | false | false | false |
iOSWizards/MVUIHacks | MVUIHacks/Classes/Designable/DesignableView.swift | 1 | 2143 | //
// DesignableView.swift
// MV UI Hacks
//
// Created by Evandro Harrison Hoffmann on 06/07/2016.
// Copyright © 2016 It's Day Off. All rights reserved.
//
import UIKit
enum ShapeType: Int {
case `default` = 0
case hexagon = 1
case hexagonVertical = 2
}
@IBDesignable
open class DesignableView: UIView {
// MARK: - Shapes
@IBInspectable open var shapeType: Int = 0{
didSet{
updateShape(shapeType)
}
}
@IBInspectable var autoRadius:Bool = false {
didSet {
if autoRadius {
cornerRadius = layer.frame.height / 2
}
}
}
open func updateShape(_ shapeType: Int){
switch shapeType {
case ShapeType.hexagon.rawValue:
self.addHexagonalMask(0)
break
case ShapeType.hexagonVertical.rawValue:
self.addHexagonalMask(CGFloat(Double.pi/2))
break
default:
break
}
}
@IBInspectable open var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable open var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable open var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = true
}
}
// MARK: - Colors
@IBInspectable open var gradientTopColor: UIColor = UIColor.clear {
didSet{
self.addGradientLayer(gradientTopColor, bottomColor: gradientBottomColor)
}
}
@IBInspectable open var gradientBottomColor: UIColor = UIColor.clear {
didSet{
self.addGradientLayer(gradientTopColor, bottomColor: gradientBottomColor)
}
}
open override func layoutSubviews() {
addGradientLayer(gradientTopColor, bottomColor: gradientBottomColor)
updateShape(shapeType)
if autoRadius {
cornerRadius = layer.frame.height / 2
}
}
}
| mit | 7a1455bd9ebeba4b20c1f08795ad637d | 23.067416 | 85 | 0.578898 | 4.981395 | false | false | false | false |
akaralar/siesta | Source/Siesta/Request/NetworkRequest.swift | 3 | 8629 | //
// NetworkRequest.swift
// Siesta
//
// Created by Paul on 2015/12/15.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
internal final class NetworkRequest: RequestWithDefaultCallbacks, CustomDebugStringConvertible
{
// Basic metadata
private let resource: Resource
private let requestDescription: String
internal var config: Configuration
{ return resource.configuration(for: underlyingRequest) }
// Networking
private let requestBuilder: (Void) -> URLRequest
private let underlyingRequest: URLRequest
internal var networking: RequestNetworking? // present only after start()
internal var underlyingNetworkRequestCompleted = false // so tests can wait for it to finish
// Progress
private var progressTracker: ProgressTracker
var progress: Double
{ return progressTracker.progress }
// Result
private var responseCallbacks = CallbackGroup<ResponseInfo>()
private var wasCancelled: Bool = false
var isCompleted: Bool
{
DispatchQueue.mainThreadPrecondition()
return responseCallbacks.completedValue != nil
}
// MARK: Managing request
init(resource: Resource, requestBuilder: @escaping (Void) -> URLRequest)
{
self.resource = resource
self.requestBuilder = requestBuilder // for repeated()
self.underlyingRequest = requestBuilder()
self.requestDescription =
LogCategory.enabled.contains(.network) || LogCategory.enabled.contains(.networkDetails)
? debugStr([underlyingRequest.httpMethod, underlyingRequest.url])
: ""
progressTracker = ProgressTracker(isGet: underlyingRequest.httpMethod == "GET") // URLRequest automatically uppercases method
}
func start() -> Self
{
DispatchQueue.mainThreadPrecondition()
guard self.networking == nil else
{
debugLog(.networkDetails, [requestDescription, "already started"])
return self
}
guard !wasCancelled else
{
debugLog(.network, [requestDescription, "will not start because it was already cancelled"])
underlyingNetworkRequestCompleted = true
return self
}
debugLog(.network, [requestDescription])
let networking = resource.service.networkingProvider.startRequest(underlyingRequest)
{
res, data, err in
DispatchQueue.main.async
{ self.responseReceived(underlyingResponse: res, body: data, error: err) }
}
self.networking = networking
progressTracker.start(
networking,
reportingInterval: config.progressReportingInterval)
return self
}
func cancel()
{
DispatchQueue.mainThreadPrecondition()
guard !isCompleted else
{
debugLog(.network, ["cancel() called but request already completed:", requestDescription])
return
}
debugLog(.network, ["Cancelled", requestDescription])
networking?.cancel()
// Prevent start() from have having any effect if it hasn't been called yet
wasCancelled = true
broadcastResponse(ResponseInfo.cancellation)
}
func repeated() -> Request
{
return NetworkRequest(resource: resource, requestBuilder: requestBuilder)
}
// MARK: Callbacks
internal func addResponseCallback(_ callback: @escaping ResponseCallback) -> Self
{
responseCallbacks.addCallback(callback)
return self
}
func onProgress(_ callback: @escaping (Double) -> Void) -> Self
{
progressTracker.callbacks.addCallback(callback)
return self
}
// MARK: Response handling
// Entry point for response handling. Triggered by RequestNetworking completion callback.
private func responseReceived(underlyingResponse: HTTPURLResponse?, body: Data?, error: Error?)
{
DispatchQueue.mainThreadPrecondition()
underlyingNetworkRequestCompleted = true
debugLog(.network, ["Response: ", underlyingResponse?.statusCode ?? error, "←", requestDescription])
debugLog(.networkDetails, ["Raw response headers:", underlyingResponse?.allHeaderFields])
debugLog(.networkDetails, ["Raw response body:", body?.count ?? 0, "bytes"])
let responseInfo = interpretResponse(underlyingResponse, body, error)
if shouldIgnoreResponse(responseInfo.response)
{ return }
transformResponse(responseInfo, then: broadcastResponse)
}
private func isError(httpStatusCode: Int?) -> Bool
{
guard let httpStatusCode = httpStatusCode else
{ return false }
return httpStatusCode >= 400
}
private func interpretResponse(
_ underlyingResponse: HTTPURLResponse?,
_ body: Data?,
_ error: Error?)
-> ResponseInfo
{
if isError(httpStatusCode: underlyingResponse?.statusCode) || error != nil
{
return ResponseInfo(
response: .failure(RequestError(response: underlyingResponse, content: body, cause: error)))
}
else if underlyingResponse?.statusCode == 304
{
if let entity = resource.latestData
{
return ResponseInfo(response: .success(entity), isNew: false)
}
else
{
return ResponseInfo(
response: .failure(RequestError(
userMessage: NSLocalizedString("No data available", comment: "userMessage"),
cause: RequestError.Cause.NoLocalDataFor304())))
}
}
else
{
return ResponseInfo(response: .success(Entity<Any>(response: underlyingResponse, content: body ?? Data())))
}
}
private func transformResponse(
_ rawInfo: ResponseInfo,
then afterTransformation: @escaping (ResponseInfo) -> Void)
{
let processor = config.pipeline.makeProcessor(rawInfo.response, resource: resource)
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async
{
let processedInfo =
rawInfo.isNew
? ResponseInfo(response: processor(), isNew: true)
: rawInfo
DispatchQueue.main.async
{ afterTransformation(processedInfo) }
}
}
private func broadcastResponse(_ newInfo: ResponseInfo)
{
DispatchQueue.mainThreadPrecondition()
if shouldIgnoreResponse(newInfo.response)
{ return }
progressTracker.complete()
responseCallbacks.notifyOfCompletion(newInfo)
}
private func shouldIgnoreResponse(_ newResponse: Response) -> Bool
{
guard let existingResponse = responseCallbacks.completedValue?.response else
{ return false }
// We already received a response; don't broadcast another one.
if !existingResponse.isCancellation
{
debugLog(.network,
[
"WARNING: Received response for request that was already completed:", requestDescription,
"This may indicate a bug in the NetworkingProvider you are using, or in Siesta.",
"Please file a bug report: https://github.com/bustoutsolutions/siesta/issues/new",
"\n Previously received:", existingResponse,
"\n New response:", newResponse
])
}
else if !newResponse.isCancellation
{
// Sometimes the network layer sends a cancellation error. That’s not of interest if we already knew
// we were cancelled. If we received any other response after cancellation, log that we ignored it.
debugLog(.networkDetails,
[
"Received response, but request was already cancelled:", requestDescription,
"\n New response:", newResponse
])
}
return true
}
// MARK: Debug
var debugDescription: String
{
return "Request:"
+ String(UInt(bitPattern: ObjectIdentifier(self)), radix: 16)
+ "("
+ requestDescription
+ ")"
}
}
| mit | d7709bbf20539969432065a252ec787c | 32.297297 | 134 | 0.606911 | 5.894737 | false | false | false | false |
proversity-org/edx-app-ios | Source/Core/Code/Operation.swift | 2 | 1770 | //
// Operation.swift
// edX
//
// Created by Akiva Leffert on 6/18/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
/// Standard stub subclass of NSOperation.
/// Needed to give an indirection for classes that use features that prevent them from exposing methods
/// to Objective-C, like generics.
open class OEXOperation : Foundation.Operation {
fileprivate var _executing : Bool = false
fileprivate var _finished : Bool = false
open override var isExecuting:Bool {
get { return _executing }
set {
willChangeValue(forKey: "isExecuting")
_executing = newValue
didChangeValue(forKey: "isExecuting")
}
}
open override var isFinished:Bool {
get { return _finished }
set {
willChangeValue(forKey: "isFinished")
_finished = newValue
didChangeValue(forKey: "isFinished")
}
}
/// Subclasses with generic arguments can't have methods seen by Objective-C and hence NSOperation.
/// This class doesn't have generic arguments, so it's safe for other things to subclass.
@objc open override func start() {
self.isExecuting = true
self.isFinished = false
performWithDoneAction {[weak self] in
self?.isExecuting = false
self?.isFinished = true
}
}
open override func cancel() {
self.isExecuting = false
self.isFinished = true
}
/// Subclasses should implement this since they might not be able to implement -start directly if they
/// have generic arguments. Call doneAction when your task is done
open func performWithDoneAction(_ doneAction : @escaping() -> Void) {
}
}
| apache-2.0 | 8523c5650e02c8b602f747ceff377096 | 30.052632 | 106 | 0.630508 | 4.985915 | false | false | false | false |
apple/swift-nio | Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift | 1 | 46275 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Atomics
import DequeModule
import NIOConcurrencyHelpers
/// The delegate of the ``NIOAsyncWriter``. It is the consumer of the yielded writes to the ``NIOAsyncWriter``.
/// Furthermore, the delegate gets informed when the ``NIOAsyncWriter`` terminated.
///
/// - Important: The methods on the delegate are called while a lock inside of the ``NIOAsyncWriter`` is held. This is done to
/// guarantee the ordering of the writes. However, this means you **MUST NOT** call ``NIOAsyncWriter/Sink/setWritability(to:)``
/// from within ``NIOAsyncWriterSinkDelegate/didYield(contentsOf:)`` or ``NIOAsyncWriterSinkDelegate/didTerminate(error:)``.
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public protocol NIOAsyncWriterSinkDelegate: Sendable {
/// The `Element` type of the delegate and the writer.
associatedtype Element: Sendable
/// This method is called once a sequence was yielded to the ``NIOAsyncWriter``.
///
/// If the ``NIOAsyncWriter`` was writable when the sequence was yielded, the sequence will be forwarded
/// right away to the delegate. If the ``NIOAsyncWriter`` was _NOT_ writable then the sequence will be buffered
/// until the ``NIOAsyncWriter`` becomes writable again. All buffered writes, while the ``NIOAsyncWriter`` is not writable,
/// will be coalesced into a single sequence.
///
/// - Important: You **MUST NOT** call ``NIOAsyncWriter/Sink/setWritability(to:)`` from within this method.
func didYield(contentsOf sequence: Deque<Element>)
/// This method is called once the ``NIOAsyncWriter`` is terminated.
///
/// Termination happens if:
/// - The ``NIOAsyncWriter`` is deinited and all yielded elements have been delivered to the delegate.
/// - ``NIOAsyncWriter/finish()`` is called and all yielded elements have been delivered to the delegate.
/// - ``NIOAsyncWriter/finish(error:)`` is called and all yielded elements have been delivered to the delegate.
/// - ``NIOAsyncWriter/Sink/finish()`` or ``NIOAsyncWriter/Sink/finish(error:)`` is called.
///
/// - Note: This is guaranteed to be called _exactly_ once.
///
/// - Parameter error: The error that terminated the ``NIOAsyncWriter``. If the writer was terminated without an
/// error this value is `nil`. This can be either the error passed to ``NIOAsyncWriter/finish(error:)`` or
/// to ``NIOAsyncWriter/Sink/finish(error:)``.
///
/// - Important: You **MUST NOT** call ``NIOAsyncWriter/Sink/setWritability(to:)`` from within this method.
func didTerminate(error: Error?)
}
/// Errors thrown by the ``NIOAsyncWriter``.
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public struct NIOAsyncWriterError: Error, Hashable, CustomStringConvertible {
@usableFromInline
internal enum _Code: String, Hashable, Sendable {
case alreadyFinished
}
@usableFromInline
let _code: _Code
@usableFromInline
var file: String
@usableFromInline
var line: Int
@inlinable
init(_code: _Code, file: String, line: Int) {
self._code = _code
self.file = file
self.line = line
}
@inlinable
public static func == (lhs: NIOAsyncWriterError, rhs: NIOAsyncWriterError) -> Bool {
return lhs._code == rhs._code
}
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(self._code)
}
/// Indicates that the ``NIOAsyncWriter`` has already finished and is not accepting any more writes.
@inlinable
public static func alreadyFinished(file: String = #fileID, line: Int = #line) -> Self {
.init(_code: .alreadyFinished, file: file, line: line)
}
@inlinable
public var description: String {
"NIOAsyncWriterError.\(self._code.rawValue)"
}
}
/// A ``NIOAsyncWriter`` is a type used to bridge elements from the Swift Concurrency domain into
/// a synchronous world. The `Task`s that are yielding to the ``NIOAsyncWriter`` are the producers.
/// Whereas the ``NIOAsyncWriterSinkDelegate`` is the consumer.
///
/// Additionally, the ``NIOAsyncWriter`` allows the consumer to set the writability by calling ``NIOAsyncWriter/Sink/setWritability(to:)``.
/// This allows the implementation of flow control on the consumer side. Any call to ``NIOAsyncWriter/yield(contentsOf:)`` or ``NIOAsyncWriter/yield(_:)``
/// will suspend if the ``NIOAsyncWriter`` is not writable and will be resumed after the ``NIOAsyncWriter`` becomes writable again
/// or if the ``NIOAsyncWriter`` has finished.
///
/// - Note: It is recommended to never directly expose this type from APIs, but rather wrap it. This is due to the fact that
/// this type has two generic parameters where at least the `Delegate` should be known statically and it is really awkward to spell out this type.
/// Moreover, having a wrapping type allows to optimize this to specialized calls if all generic types are known.
///
/// - Note: This struct has reference semantics. Once all copies of a writer have been dropped ``NIOAsyncWriterSinkDelegate/didTerminate(error:)`` will be called.
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public struct NIOAsyncWriter<
Element,
Delegate: NIOAsyncWriterSinkDelegate
>: Sendable where Delegate.Element == Element {
/// Simple struct for the return type of ``NIOAsyncWriter/makeWriter(elementType:isWritable:delegate:)``.
///
/// This struct contains two properties:
/// 1. The ``sink`` which should be retained by the consumer and is used to set the writability.
/// 2. The ``writer`` which is the actual ``NIOAsyncWriter`` and should be passed to the producer.
public struct NewWriter {
/// The ``sink`` which **MUST** be retained by the consumer and is used to set the writability.
public let sink: Sink
/// The ``writer`` which is the actual ``NIOAsyncWriter`` and should be passed to the producer.
public let writer: NIOAsyncWriter
@inlinable
/* fileprivate */ internal init(
sink: Sink,
writer: NIOAsyncWriter
) {
self.sink = sink
self.writer = writer
}
}
/// This class is needed to hook the deinit to observe once all references to the ``NIOAsyncWriter`` are dropped.
@usableFromInline
/* fileprivate */ internal final class InternalClass: Sendable {
@usableFromInline
internal let _storage: Storage
@inlinable
init(storage: Storage) {
self._storage = storage
}
@inlinable
deinit {
_storage.writerDeinitialized()
}
}
@usableFromInline
/* private */ internal let _internalClass: InternalClass
@inlinable
/* private */ internal var _storage: Storage {
self._internalClass._storage
}
/// Initializes a new ``NIOAsyncWriter`` and a ``NIOAsyncWriter/Sink``.
///
/// - Important: This method returns a struct containing a ``NIOAsyncWriter/Sink`` and
/// a ``NIOAsyncWriter``. The sink MUST be held by the caller and is used to set the writability.
/// The writer MUST be passed to the actual producer and MUST NOT be held by the
/// caller. This is due to the fact that deiniting the sequence is used as part of a trigger to terminate the underlying sink.
///
/// - Parameters:
/// - elementType: The element type of the sequence.
/// - isWritable: The initial writability state of the writer.
/// - delegate: The delegate of the writer.
/// - Returns: A ``NIOAsyncWriter/NewWriter``.
@inlinable
public static func makeWriter(
elementType: Element.Type = Element.self,
isWritable: Bool,
delegate: Delegate
) -> NewWriter {
let writer = Self(
isWritable: isWritable,
delegate: delegate
)
let sink = Sink(storage: writer._storage)
return .init(sink: sink, writer: writer)
}
@inlinable
/* private */ internal init(
isWritable: Bool,
delegate: Delegate
) {
let storage = Storage(
isWritable: isWritable,
delegate: delegate
)
self._internalClass = .init(storage: storage)
}
/// Yields a sequence of new elements to the ``NIOAsyncWriter``.
///
/// If the ``NIOAsyncWriter`` is writable the sequence will get forwarded to the ``NIOAsyncWriterSinkDelegate`` immediately.
/// Otherwise, the sequence will be buffered and the call to ``NIOAsyncWriter/yield(contentsOf:)`` will get suspended until the ``NIOAsyncWriter``
/// becomes writable again. If the calling `Task` gets cancelled at any point the call to ``NIOAsyncWriter/yield(contentsOf:)``
/// will be resumed.
///
/// If the ``NIOAsyncWriter/finish()`` or ``NIOAsyncWriter/finish(error:)`` method is called while a call to
/// ``NIOAsyncWriter/yield(contentsOf:)`` is suspended then the call will be resumed and the yielded sequence will be kept buffered.
///
/// If the ``NIOAsyncWriter/Sink/finish()`` or ``NIOAsyncWriter/Sink/finish(error:)`` method is called while
/// a call to ``NIOAsyncWriter/yield(contentsOf:)`` is suspended then the call will be resumed with an error and the
/// yielded sequence is dropped.
///
/// This can be called more than once and from multiple `Task`s at the same time.
///
/// - Parameter contentsOf: The sequence to yield.
@inlinable
public func yield<S: Sequence>(contentsOf sequence: S) async throws where S.Element == Element {
try await self._storage.yield(contentsOf: sequence)
}
/// Yields an element to the ``NIOAsyncWriter``.
///
/// If the ``NIOAsyncWriter`` is writable the element will get forwarded to the ``NIOAsyncWriterSinkDelegate`` immediately.
/// Otherwise, the element will be buffered and the call to ``NIOAsyncWriter/yield(_:)`` will get suspended until the ``NIOAsyncWriter``
/// becomes writable again. If the calling `Task` gets cancelled at any point the call to ``NIOAsyncWriter/yield(_:)``
/// will be resumed.
///
/// If the ``NIOAsyncWriter/finish()`` or ``NIOAsyncWriter/finish(error:)`` method is called while a call to
/// ``NIOAsyncWriter/yield(_:)`` is suspended then the call will be resumed and the yielded sequence will be kept buffered.
///
/// If the ``NIOAsyncWriter/Sink/finish()`` or ``NIOAsyncWriter/Sink/finish(error:)`` method is called while
/// a call to ``NIOAsyncWriter/yield(_:)`` is suspended then the call will be resumed with an error and the
/// yielded sequence is dropped.
///
/// This can be called more than once and from multiple `Task`s at the same time.
///
/// - Parameter element: The element to yield.
@inlinable
public func yield(_ element: Element) async throws {
try await self.yield(contentsOf: CollectionOfOne(element))
}
/// Finishes the writer.
///
/// Calling this function signals the writer that any suspended calls to ``NIOAsyncWriter/yield(contentsOf:)``
/// or ``NIOAsyncWriter/yield(_:)`` will be resumed. Any subsequent calls to ``NIOAsyncWriter/yield(contentsOf:)``
/// or ``NIOAsyncWriter/yield(_:)`` will throw.
///
/// Any element that have been yielded elements before the writer has been finished which have not been delivered yet are continued
/// to be buffered and will be delivered once the writer becomes writable again.
///
/// - Note: Calling this function more than once has no effect.
@inlinable
public func finish() {
self._storage.writerFinish(error: nil)
}
/// Finishes the writer.
///
/// Calling this function signals the writer that any suspended calls to ``NIOAsyncWriter/yield(contentsOf:)``
/// or ``NIOAsyncWriter/yield(_:)`` will be resumed. Any subsequent calls to ``NIOAsyncWriter/yield(contentsOf:)``
/// or ``NIOAsyncWriter/yield(_:)`` will throw.
///
/// Any element that have been yielded elements before the writer has been finished which have not been delivered yet are continued
/// to be buffered and will be delivered once the writer becomes writable again.
///
/// - Note: Calling this function more than once has no effect.
/// - Parameter error: The error indicating why the writer finished.
@inlinable
public func finish(error: Error) {
self._storage.writerFinish(error: error)
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension NIOAsyncWriter {
/// The underlying sink of the ``NIOAsyncWriter``. This type allows to set the writability of the ``NIOAsyncWriter``.
///
/// - Important: Once all copies to the ``NIOAsyncWriter/Sink`` are destroyed the ``NIOAsyncWriter`` will get finished.
public struct Sink {
/// This class is needed to hook the deinit to observe once all references to the ``NIOAsyncWriter/Sink`` are dropped.
@usableFromInline
/* fileprivate */ internal final class InternalClass: Sendable {
@usableFromInline
/* fileprivate */ internal let _storage: Storage
@inlinable
init(storage: Storage) {
self._storage = storage
}
@inlinable
deinit {
// We need to call finish here to resume any suspended continuation.
self._storage.sinkFinish(error: nil)
}
}
@usableFromInline
/* private */ internal let _internalClass: InternalClass
@inlinable
/* private */ internal var _storage: Storage {
self._internalClass._storage
}
@inlinable
init(storage: Storage) {
self._internalClass = .init(storage: storage)
}
/// Sets the writability of the ``NIOAsyncWriter``.
///
/// If the writer becomes writable again all suspended yields will be resumed and the produced elements will be forwarded via
/// the ``NIOAsyncWriterSinkDelegate/didYield(contentsOf:)`` method. If the writer becomes unwritable all
/// subsequent calls to ``NIOAsyncWriterSinkDelegate/didYield(contentsOf:)`` will suspend.
///
/// - Parameter writability: The new writability of the ``NIOAsyncWriter``.
@inlinable
public func setWritability(to writability: Bool) {
self._storage.setWritability(to: writability)
}
/// Finishes the sink which will result in the ``NIOAsyncWriter`` being finished.
///
/// Calling this function signals the writer that any suspended or subsequent calls to ``NIOAsyncWriter/yield(contentsOf:)``
/// or ``NIOAsyncWriter/yield(_:)`` will return a ``NIOAsyncWriterError/alreadyFinished(file:line:)`` error.
///
/// - Note: Calling this function more than once has no effect.
@inlinable
public func finish() {
self._storage.sinkFinish(error: nil)
}
/// Finishes the sink which will result in the ``NIOAsyncWriter`` being finished.
///
/// Calling this function signals the writer that any suspended or subsequent calls to ``NIOAsyncWriter/yield(contentsOf:)``
/// or ``NIOAsyncWriter/yield(_:)`` will return the passed error parameter.
///
/// - Note: Calling this function more than once has no effect.
@inlinable
public func finish(error: Error) {
self._storage.sinkFinish(error: error)
}
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension NIOAsyncWriter {
/// This is the underlying storage of the writer. The goal of this is to synchronize the access to all state.
@usableFromInline
/* fileprivate */ internal final class Storage: @unchecked Sendable {
/// Internal type to generate unique yield IDs.
///
/// This type has reference semantics.
@usableFromInline
struct YieldIDGenerator {
/// A struct representing a unique yield ID.
@usableFromInline
struct YieldID: Equatable, Sendable {
@usableFromInline
/* private */ internal var value: UInt64
@inlinable
init(value: UInt64) {
self.value = value
}
@inlinable
static func == (lhs: Self, rhs: Self) -> Bool {
lhs.value == rhs.value
}
}
@usableFromInline
/* private */ internal let _yieldIDCounter = ManagedAtomic<UInt64>(0)
@inlinable
func generateUniqueYieldID() -> YieldID {
// Using relaxed is fine here since we do not need any strict ordering just a
// unique ID for every yield.
.init(value: self._yieldIDCounter.loadThenWrappingIncrement(ordering: .relaxed))
}
}
/// The lock that protects our state.
@usableFromInline
/* private */ internal let _lock = NIOLock()
/// The counter used to assign an ID to all our yields.
@usableFromInline
/* private */ internal let _yieldIDGenerator = YieldIDGenerator()
/// The state machine.
@usableFromInline
/* private */ internal var _stateMachine: StateMachine
@inlinable
/* fileprivate */ internal init(
isWritable: Bool,
delegate: Delegate
) {
self._stateMachine = .init(isWritable: isWritable, delegate: delegate)
}
@inlinable
/* fileprivate */ internal func writerDeinitialized() {
self._lock.withLock {
let action = self._stateMachine.writerDeinitialized()
switch action {
case .callDidTerminate(let delegate):
// We are calling the delegate while holding lock. This can lead to potential crashes
// if the delegate calls `setWritability` reentrantly. However, we call this
// out in the docs of the delegate
delegate.didTerminate(error: nil)
case .none:
break
}
}
}
@inlinable
/* fileprivate */ internal func setWritability(to writability: Bool) {
self._lock.withLock {
let action = self._stateMachine.setWritability(to: writability)
switch action {
case .callDidYieldAndResumeContinuations(let delegate, let elements, let suspendedYields):
// We are calling the delegate while holding lock. This can lead to potential crashes
// if the delegate calls `setWritability` reentrantly. However, we call this
// out in the docs of the delegate
delegate.didYield(contentsOf: elements)
// It is safe to resume the continuations while holding the lock since resume
// is immediately returning and just enqueues the Job on the executor
suspendedYields.forEach { $0.continuation.resume() }
case .callDidYieldAndDidTerminate(let delegate, let elements):
// We are calling the delegate while holding lock. This can lead to potential crashes
// if the delegate calls `setWritability` reentrantly. However, we call this
// out in the docs of the delegate
delegate.didYield(contentsOf: elements)
delegate.didTerminate(error: nil)
case .none:
return
}
}
}
@inlinable
/* fileprivate */ internal func yield<S: Sequence>(contentsOf sequence: S) async throws where S.Element == Element {
let yieldID = self._yieldIDGenerator.generateUniqueYieldID()
try await withTaskCancellationHandler {
// We are manually locking here to hold the lock across the withCheckedContinuation call
self._lock.lock()
let action = self._stateMachine.yield(contentsOf: sequence, yieldID: yieldID)
switch action {
case .callDidYield(let delegate):
// We are calling the delegate while holding lock. This can lead to potential crashes
// if the delegate calls `setWritability` reentrantly. However, we call this
// out in the docs of the delegate
// We are allocating a new Deque for every write here
delegate.didYield(contentsOf: Deque(sequence))
self._lock.unlock()
case .returnNormally:
self._lock.unlock()
return
case .throwError(let error):
self._lock.unlock()
throw error
case .suspendTask:
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
self._stateMachine.yield(
contentsOf: sequence,
continuation: continuation,
yieldID: yieldID
)
self._lock.unlock()
}
}
} onCancel: {
self._lock.withLock {
let action = self._stateMachine.cancel(yieldID: yieldID)
switch action {
case .resumeContinuation(let continuation):
// It is safe to resume the continuations while holding the lock since resume
// is immediately returning and just enqueues the Job on the executor
continuation.resume()
case .none:
break
}
}
}
}
@inlinable
/* fileprivate */ internal func writerFinish(error: Error?) {
self._lock.withLock {
let action = self._stateMachine.writerFinish()
switch action {
case .callDidTerminate(let delegate):
// We are calling the delegate while holding lock. This can lead to potential crashes
// if the delegate calls `setWritability` reentrantly. However, we call this
// out in the docs of the delegate
delegate.didTerminate(error: error)
case .resumeContinuations(let suspendedYields):
// It is safe to resume the continuations while holding the lock since resume
// is immediately returning and just enqueues the Job on the executor
suspendedYields.forEach { $0.continuation.resume() }
case .none:
break
}
}
}
@inlinable
/* fileprivate */ internal func sinkFinish(error: Error?) {
self._lock.withLock {
let action = self._stateMachine.sinkFinish(error: error)
switch action {
case .callDidTerminate(let delegate, let error):
// We are calling the delegate while holding lock. This can lead to potential crashes
// if the delegate calls `setWritability` reentrantly. However, we call this
// out in the docs of the delegate
delegate.didTerminate(error: error)
case .resumeContinuationsWithErrorAndCallDidTerminate(let delegate, let suspendedYields, let error):
// We are calling the delegate while holding lock. This can lead to potential crashes
// if the delegate calls `setWritability` reentrantly. However, we call this
// out in the docs of the delegate
delegate.didTerminate(error: error)
// It is safe to resume the continuations while holding the lock since resume
// is immediately returning and just enqueues the Job on the executor
suspendedYields.forEach { $0.continuation.resume(throwing: error) }
case .none:
break
}
}
}
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension NIOAsyncWriter {
@usableFromInline
/* private */ internal struct StateMachine {
@usableFromInline
typealias YieldID = Storage.YieldIDGenerator.YieldID
/// This is a small helper struct to encapsulate the two different values for a suspended yield.
@usableFromInline
/* private */ internal struct SuspendedYield {
/// The yield's ID.
@usableFromInline
var yieldID: YieldID
/// The yield's produced sequence of elements.
/// The yield's continuation.
@usableFromInline
var continuation: CheckedContinuation<Void, Error>
@inlinable
init(yieldID: YieldID, continuation: CheckedContinuation<Void, Error>) {
self.yieldID = yieldID
self.continuation = continuation
}
}
/// The current state of our ``NIOAsyncWriter``.
@usableFromInline
/* private */ internal enum State {
/// The initial state before either a call to ``NIOAsyncWriter/yield(contentsOf:)`` or
/// ``NIOAsyncWriter/finish(completion:)`` happened.
case initial(
isWritable: Bool,
delegate: Delegate
)
/// The state after a call to ``NIOAsyncWriter/yield(contentsOf:)``.
case streaming(
isWritable: Bool,
cancelledYields: [YieldID],
suspendedYields: [SuspendedYield],
elements: Deque<Element>,
delegate: Delegate
)
/// The state once the writer finished and there are still elements that need to be delivered. This can happen if:
/// 1. The ``NIOAsyncWriter`` was deinited
/// 2. ``NIOAsyncWriter/finish(completion:)`` was called.
case writerFinished(
elements: Deque<Element>,
delegate: Delegate
)
/// The state once the sink has been finished or the writer has been finished and all elements
/// have been delivered to the delegate.
case finished(sinkError: Error?)
/// Internal state to avoid CoW.
case modifying
}
/// The state machine's current state.
@usableFromInline
/* private */ internal var _state: State
@inlinable
init(
isWritable: Bool,
delegate: Delegate
) {
self._state = .initial(isWritable: isWritable, delegate: delegate)
}
/// Actions returned by `writerDeinitialized()`.
@usableFromInline
enum WriterDeinitializedAction {
/// Indicates that ``NIOAsyncWriterSinkDelegate/didTerminate(completion:)`` should be called.
case callDidTerminate(Delegate)
/// Indicates that nothing should be done.
case none
}
@inlinable
/* fileprivate */ internal mutating func writerDeinitialized() -> WriterDeinitializedAction {
switch self._state {
case .initial(_, let delegate):
// The writer deinited before writing anything.
// We can transition to finished and inform our delegate
self._state = .finished(sinkError: nil)
return .callDidTerminate(delegate)
case .streaming(_, _, let suspendedYields, let elements, let delegate):
// The writer got deinited after we started streaming.
// This is normal and we need to transition to finished
// and call the delegate. However, we should not have
// any suspended yields because they MUST strongly retain
// the writer.
precondition(suspendedYields.isEmpty, "We have outstanding suspended yields")
precondition(elements.isEmpty, "We have buffered elements")
// We have no elements left and can transition to finished directly
self._state = .finished(sinkError: nil)
return .callDidTerminate(delegate)
case .finished, .writerFinished:
// We are already finished nothing to do here
return .none
case .modifying:
preconditionFailure("Invalid state")
}
}
/// Actions returned by `setWritability()`.
@usableFromInline
enum SetWritabilityAction {
/// Indicates that ``NIOAsyncWriterSinkDelegate/didYield(contentsOf:)`` should be called
/// and all continuations should be resumed.
case callDidYieldAndResumeContinuations(Delegate, Deque<Element>, [SuspendedYield])
/// Indicates that ``NIOAsyncWriterSinkDelegate/didYield(contentsOf:)`` and
/// ``NIOAsyncWriterSinkDelegate/didTerminate(error:)``should be called.
case callDidYieldAndDidTerminate(Delegate, Deque<Element>)
/// Indicates that nothing should be done.
case none
}
@inlinable
/* fileprivate */ internal mutating func setWritability(to newWritability: Bool) -> SetWritabilityAction {
switch self._state {
case .initial(_, let delegate):
// We just need to store the new writability state
self._state = .initial(isWritable: newWritability, delegate: delegate)
return .none
case .streaming(let isWritable, let cancelledYields, let suspendedYields, let elements, let delegate):
if isWritable == newWritability {
// The writability didn't change so we can just early exit here
return .none
}
if newWritability {
// We became writable again. This means we have to resume all the continuations
// and yield the values.
self._state = .streaming(
isWritable: newWritability,
cancelledYields: cancelledYields,
suspendedYields: [],
elements: .init(),
delegate: delegate
)
// We are taking the whole array of suspended yields and the deque of elements
// and allocate a new empty one.
// As a performance optimization we could always keep multiple arrays/deques and
// switch between them but I don't think this is the performance critical part.
return .callDidYieldAndResumeContinuations(delegate, elements, suspendedYields)
} else {
// We became unwritable nothing really to do here
precondition(suspendedYields.isEmpty, "No yield should be suspended at this point")
precondition(elements.isEmpty, "No element should be buffered at this point")
self._state = .streaming(
isWritable: newWritability,
cancelledYields: cancelledYields,
suspendedYields: suspendedYields,
elements: elements,
delegate: delegate
)
return .none
}
case .writerFinished(let elements, let delegate):
if !newWritability {
// We are not writable so we can't deliver the outstanding elements
return .none
}
self._state = .finished(sinkError: nil)
return .callDidYieldAndDidTerminate(delegate, elements)
case .finished:
// We are already finished nothing to do here
return .none
case .modifying:
preconditionFailure("Invalid state")
}
}
/// Actions returned by `yield()`.
@usableFromInline
enum YieldAction {
/// Indicates that ``NIOAsyncWriterSinkDelegate/didYield(contentsOf:)`` should be called.
case callDidYield(Delegate)
/// Indicates that the calling `Task` should get suspended.
case suspendTask
/// Indicates that the method should just return.
case returnNormally
/// Indicates the given error should be thrown.
case throwError(Error)
@inlinable
init(isWritable: Bool, delegate: Delegate) {
if isWritable {
self = .callDidYield(delegate)
} else {
self = .suspendTask
}
}
}
@inlinable
/* fileprivate */ internal mutating func yield<S: Sequence>(
contentsOf sequence: S,
yieldID: YieldID
) -> YieldAction where S.Element == Element {
switch self._state {
case .initial(let isWritable, let delegate):
// We can transition to streaming now
self._state = .streaming(
isWritable: isWritable,
cancelledYields: [],
suspendedYields: [],
elements: .init(),
delegate: delegate
)
return .init(isWritable: isWritable, delegate: delegate)
case .streaming(let isWritable, var cancelledYields, let suspendedYields, var elements, let delegate):
if let index = cancelledYields.firstIndex(of: yieldID) {
// We already marked the yield as cancelled. We have to remove it and
// throw an error.
self._state = .modifying
cancelledYields.remove(at: index)
if isWritable {
// We are writable so we can yield the elements right away and then
// return normally.
self._state = .streaming(
isWritable: isWritable,
cancelledYields: cancelledYields,
suspendedYields: suspendedYields,
elements: elements,
delegate: delegate
)
return .callDidYield(delegate)
} else {
// We are not writable so we are just going to enqueue the writes
// and return normally. We are not suspending the yield since the Task
// is marked as cancelled.
elements.append(contentsOf: sequence)
self._state = .streaming(
isWritable: isWritable,
cancelledYields: cancelledYields,
suspendedYields: suspendedYields,
elements: elements,
delegate: delegate
)
return .returnNormally
}
} else {
// Yield hasn't been marked as cancelled.
// This means we can either call the delegate or suspend
return .init(isWritable: isWritable, delegate: delegate)
}
case .writerFinished:
// We are already finished and still tried to write something
return .throwError(NIOAsyncWriterError.alreadyFinished())
case .finished(let sinkError):
// We are already finished and still tried to write something
return .throwError(sinkError ?? NIOAsyncWriterError.alreadyFinished())
case .modifying:
preconditionFailure("Invalid state")
}
}
/// This method is called as a result of the above `yield` method if it decided that the task needs to get suspended.
@inlinable
/* fileprivate */ internal mutating func yield<S: Sequence>(
contentsOf sequence: S,
continuation: CheckedContinuation<Void, Error>,
yieldID: YieldID
) where S.Element == Element {
switch self._state {
case .streaming(let isWritable, let cancelledYields, var suspendedYields, var elements, let delegate):
// We have a suspended yield at this point that hasn't been cancelled yet.
// We need to store the yield now.
self._state = .modifying
let suspendedYield = SuspendedYield(
yieldID: yieldID,
continuation: continuation
)
suspendedYields.append(suspendedYield)
elements.append(contentsOf: sequence)
self._state = .streaming(
isWritable: isWritable,
cancelledYields: cancelledYields,
suspendedYields: suspendedYields,
elements: elements,
delegate: delegate
)
case .initial, .finished, .writerFinished:
preconditionFailure("This should have already been handled by `yield()`")
case .modifying:
preconditionFailure("Invalid state")
}
}
/// Actions returned by `cancel()`.
@usableFromInline
enum CancelAction {
case resumeContinuation(CheckedContinuation<Void, Error>)
/// Indicates that nothing should be done.
case none
}
@inlinable
/* fileprivate */ internal mutating func cancel(
yieldID: YieldID
) -> CancelAction {
switch self._state {
case .initial(let isWritable, let delegate):
// We got a cancel before the yield happened. This means we
// need to transition to streaming and store our cancelled state.
self._state = .streaming(
isWritable: isWritable,
cancelledYields: [yieldID],
suspendedYields: [],
elements: .init(),
delegate: delegate
)
return .none
case .streaming(let isWritable, var cancelledYields, var suspendedYields, let elements, let delegate):
if let index = suspendedYields.firstIndex(where: { $0.yieldID == yieldID }) {
self._state = .modifying
// We have a suspended yield for the id. We need to resume the continuation now.
// Removing can be quite expensive if it produces a gap in the array.
// Since we are not expecting a lot of elements in this array it should be fine
// to just remove. If this turns out to be a performance pitfall, we can
// swap the elements before removing. So that we always remove the last element.
let suspendedYield = suspendedYields.remove(at: index)
// We are keeping the elements that the yield produced.
self._state = .streaming(
isWritable: isWritable,
cancelledYields: cancelledYields,
suspendedYields: suspendedYields,
elements: elements,
delegate: delegate
)
return .resumeContinuation(suspendedYield.continuation)
} else {
self._state = .modifying
// There is no suspended yield. This can mean that we either already yielded
// or that the call to `yield` is coming afterwards. We need to store
// the ID here. However, if the yield already happened we will never remove the
// stored ID. The only way to avoid doing this would be storing every ID
cancelledYields.append(yieldID)
self._state = .streaming(
isWritable: isWritable,
cancelledYields: cancelledYields,
suspendedYields: suspendedYields,
elements: elements,
delegate: delegate
)
return .none
}
case .writerFinished, .finished:
// We are already finished and there is nothing to do
return .none
case .modifying:
preconditionFailure("Invalid state")
}
}
/// Actions returned by `writerFinish()`.
@usableFromInline
enum WriterFinishAction {
/// Indicates that ``NIOAsyncWriterSinkDelegate/didTerminate(completion:)`` should be called.
case callDidTerminate(Delegate)
/// Indicates that all continuations should be resumed.
case resumeContinuations([SuspendedYield])
/// Indicates that nothing should be done.
case none
}
@inlinable
/* fileprivate */ internal mutating func writerFinish() -> WriterFinishAction {
switch self._state {
case .initial(_, let delegate):
// Nothing was ever written so we can transition to finished
self._state = .finished(sinkError: nil)
return .callDidTerminate(delegate)
case .streaming(_, _, let suspendedYields, let elements, let delegate):
// We are currently streaming and the writer got finished.
if elements.isEmpty {
// We have no elements left and can transition to finished directly
self._state = .finished(sinkError: nil)
return .callDidTerminate(delegate)
} else {
// There are still elements left which we need to deliver once we become writable again
self._state = .writerFinished(
elements: elements,
delegate: delegate
)
// We are not resuming the continuations with the error here since their elements
// are still queued up. If they try to yield again they will run into an alreadyFinished error
return .resumeContinuations(suspendedYields)
}
case .writerFinished, .finished:
// We are already finished and there is nothing to do
return .none
case .modifying:
preconditionFailure("Invalid state")
}
}
/// Actions returned by `sinkFinish()`.
@usableFromInline
enum SinkFinishAction {
/// Indicates that ``NIOAsyncWriterSinkDelegate/didTerminate(completion:)`` should be called.
case callDidTerminate(Delegate, Error?)
/// Indicates that ``NIOAsyncWriterSinkDelegate/didTerminate(completion:)`` should be called and all
/// continuations should be resumed with the given error.
case resumeContinuationsWithErrorAndCallDidTerminate(Delegate, [SuspendedYield], Error)
/// Indicates that nothing should be done.
case none
}
@inlinable
/* fileprivate */ internal mutating func sinkFinish(error: Error?) -> SinkFinishAction {
switch self._state {
case .initial(_, let delegate):
// Nothing was ever written so we can transition to finished
self._state = .finished(sinkError: error)
return .callDidTerminate(delegate, error)
case .streaming(_, _, let suspendedYields, _, let delegate):
// We are currently streaming and the writer got finished.
// We can transition to finished and need to resume all continuations.
self._state = .finished(sinkError: error)
return .resumeContinuationsWithErrorAndCallDidTerminate(
delegate,
suspendedYields,
error ?? NIOAsyncWriterError.alreadyFinished()
)
case .writerFinished(_, let delegate):
// The writer already finished and we were waiting to become writable again
// The Sink finished before we became writable so we can drop the elements and
// transition to finished
self._state = .finished(sinkError: error)
return .callDidTerminate(delegate, error)
case .finished:
// We are already finished and there is nothing to do
return .none
case .modifying:
preconditionFailure("Invalid state")
}
}
}
}
| apache-2.0 | a1a5ae4cda2fc6031b9ee9a421b06dca | 42.409944 | 162 | 0.581761 | 5.816365 | false | false | false | false |
ciscospark/spark-ios-sdk-example | KitchenSink/VideoAudioSetupViewController.swift | 1 | 19676 | // Copyright 2016-2017 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 UIKit
import SparkSDK
class VideoAudioSetupViewController: BaseViewController {
// MARK: - UI outlets variables
@IBOutlet weak var audioView: UIView!
@IBOutlet weak var audioImage: UIImageView!
@IBOutlet weak var audioVideoView: UIView!
@IBOutlet weak var audioVideoImage: UIImageView!
@IBOutlet weak var loudSpeakerSwitch: UISwitch!
@IBOutlet weak var cameraSetupView: UIView!
@IBOutlet weak var videoSetupView: UIView!
@IBOutlet weak var frontCameraView: UIView!
@IBOutlet weak var backCameraView: UIView!
@IBOutlet weak var frontImage: UIImageView!
@IBOutlet weak var backImage: UIImageView!
@IBOutlet weak var loudSpeakerLabel: UILabel!
@IBOutlet weak var bandwidthTitleLabel: UILabel!
@IBOutlet weak var bandWidthLabel: UILabel!
@IBOutlet weak var bandwidthImg: UIImageView!
@IBOutlet weak var selfViewHiddenHelpLabelHeight: NSLayoutConstraint!
@IBOutlet weak var selfViewHiddenHelpLabel: KSLabel!
@IBOutlet weak var videoSetupBackoundViewTop: NSLayoutConstraint!
@IBOutlet weak var videoSetupBackoundView: UIView!
@IBOutlet var videoSetupBackroundViewBottom: NSLayoutConstraint!
@IBOutlet weak var selfViewCloseView: UIView!
@IBOutlet weak var selfViewCloseImage: UIImageView!
@IBOutlet weak var videoViewHiddenHelpLabel: KSLabel!
@IBOutlet weak var videoViewhiddenHelpLabelHeight: NSLayoutConstraint!
@IBOutlet weak var selfViewSetupHeight: NSLayoutConstraint!
@IBOutlet weak var videoViewHeight: NSLayoutConstraint!
@IBOutlet var labelFontCollection: [UILabel]!
@IBOutlet var widthScaleConstraintCollection: [NSLayoutConstraint]!
@IBOutlet var heightScaleConstraintCollection: [NSLayoutConstraint]!
@IBOutlet weak var preview: MediaRenderView!
@IBOutlet weak var bandwidthBackView: UIView!
private let uncheckImage = UIImage.fontAwesomeIcon(name: .squareO, textColor: UIColor.titleGreyColor(), size: CGSize.init(width: 33 * Utils.HEIGHT_SCALE, height: 33 * Utils.HEIGHT_SCALE))
private let arrowImage = UIImage.fontAwesomeIcon(name: .angleRight, textColor: UIColor.titleGreyColor(), size: CGSize.init(width: 33 * Utils.HEIGHT_SCALE, height: 33 * Utils.HEIGHT_SCALE))
private let checkImage = UIImage.fontAwesomeIcon(name: .checkSquareO, textColor: UIColor.titleGreyColor(), size: CGSize.init(width: 33 * Utils.HEIGHT_SCALE, height: 33 * Utils.HEIGHT_SCALE))
private let selfViewSetupHeightContant = 320 * Utils.HEIGHT_SCALE
private let selfViewSetupHelpLabelHeightContant = 54 * Utils.HEIGHT_SCALE
private let videoViewSetupHeightContant = 420 * Utils.HEIGHT_SCALE
private let videoViewSetupHelpLabelHeightContant = 54 * Utils.HEIGHT_SCALE
override var navigationTitle: String? {
get {
return "Video/Audio setup"
}
set(newValue) {
title = newValue
}
}
/// saparkSDK reperesent for the SparkSDK API instance
var sparkSDK: Spark?
// MARK: - Life cycle
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
//note:make sure stopPreview before calling
sparkSDK?.phone.stopPreview()
}
// MARK: - UI Implemetation
override func initView() {
for label in labelFontCollection {
label.font = UIFont.labelLightFont(ofSize: label.font.pointSize * Utils.HEIGHT_SCALE)
}
for heightConstraint in heightScaleConstraintCollection {
heightConstraint.constant *= Utils.HEIGHT_SCALE
}
for widthConstraint in widthScaleConstraintCollection {
widthConstraint.constant *= Utils.WIDTH_SCALE
}
//navigation bar init
let nextButton = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 44, height: 44))
let nextImage = UIImage.fontAwesomeIcon(name: .phone, textColor: UIColor.buttonGreenNormal(), size: CGSize.init(width: 32 * Utils.WIDTH_SCALE , height: 44))
let nextLightImage = UIImage.fontAwesomeIcon(name: .phone, textColor: UIColor.buttonGreenHightlight(), size: CGSize.init(width: 32 * Utils.WIDTH_SCALE, height: 44))
nextButton.setImage(nextImage, for: .normal)
nextButton.setImage(nextLightImage, for: .highlighted)
nextButton.addTarget(self, action: #selector(gotoInitiateCallView), for: .touchUpInside)
let rightView = UIView.init(frame:CGRect.init(x: 0, y: 0, width: 44, height: 44))
rightView.addSubview(nextButton)
let rightButtonItem = UIBarButtonItem.init(customView: rightView)
let fixBarSpacer = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
fixBarSpacer.width = -10 * (2 - Utils.WIDTH_SCALE)
navigationItem.rightBarButtonItems = [fixBarSpacer,rightButtonItem]
//checkbox init
var tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(handleCapGestureEvent(sender:)))
audioView.addGestureRecognizer(tapGesture)
tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(handleCapGestureEvent(sender:)))
audioVideoView.addGestureRecognizer(tapGesture)
updateCallCapStatus()
if(globalVideoSetting.sparkSDK == nil){
globalVideoSetting.sparkSDK = self.sparkSDK
}
videoViewHeight.constant = CGFloat(globalVideoSetting.isVideoEnabled() ? videoViewSetupHeightContant:0)
videoSetupView.alpha = globalVideoSetting.isVideoEnabled() ? 1:0
videoViewHiddenHelpLabel.alpha = globalVideoSetting.isVideoEnabled() ? 0:1
videoViewhiddenHelpLabelHeight.constant = CGFloat(globalVideoSetting.isVideoEnabled() ? 0:videoViewSetupHelpLabelHeightContant)
view.removeConstraint(videoSetupBackroundViewBottom)
videoSetupBackroundViewBottom = NSLayoutConstraint.init(item: videoSetupBackoundView, attribute: .bottom, relatedBy: .equal, toItem: globalVideoSetting.isVideoEnabled() ? videoSetupView:loudSpeakerLabel, attribute: .bottom, multiplier: 1, constant: globalVideoSetting.isVideoEnabled() ? 0:-(videoSetupBackoundViewTop.constant))
view.addConstraint(videoSetupBackroundViewBottom)
view.layoutIfNeeded()
tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(handleCameraGestureEvent(sender:)))
frontCameraView.addGestureRecognizer(tapGesture)
tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(handleCameraGestureEvent(sender:)))
backCameraView.addGestureRecognizer(tapGesture)
tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(handleCameraGestureEvent(sender:)))
selfViewCloseView.addGestureRecognizer(tapGesture)
updateCameraStatus(false)
updateLoudspeakerStatus()
//bandwidth label
bandwidthImg.image = arrowImage
tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(handleCameraBandwidthGestureEvent(sender:)))
bandwidthBackView.addGestureRecognizer(tapGesture)
updateBandwidthView()
}
// MARK: hand checkbox change
@IBAction func loudSpeakerSwitchChange(_ sender: Any) {
let speakerSwitch = sender as! UISwitch
globalVideoSetting.isLoudSpeaker = speakerSwitch.isOn
}
@objc func handleCapGestureEvent(sender:UITapGestureRecognizer) {
if let view = sender.view {
if view == audioView {
globalVideoSetting.setVideoEnabled(false)
updateVideoView(true)
}
else if view == audioVideoView {
globalVideoSetting.setVideoEnabled(true)
updateVideoView(false)
}
updateCallCapStatus()
}
}
@objc func handleCameraGestureEvent(sender:UITapGestureRecognizer) {
if let view = sender.view {
if view == frontCameraView {
globalVideoSetting.facingMode = .user
globalVideoSetting.isSelfViewShow = true
}
else if view == selfViewCloseView {
// Ture is sending Video stream to remote,false is not.Default is true
globalVideoSetting.isSelfViewShow = false
}
else {
globalVideoSetting.facingMode = .environment
globalVideoSetting.isSelfViewShow = true
}
updateCameraStatus()
}
}
@objc func handleCameraBandwidthGestureEvent(sender: UITapGestureRecognizer){
let alertController = UIAlertController(title: "Band Width", message: nil, preferredStyle: .actionSheet)
let action1 = UIAlertAction(title: "177Kbs", style: .default, handler: { (action) -> Void in
globalVideoSetting.bandWidth = 177000
self.updateBandwidthView()
})
let action2 = UIAlertAction(title: "384Kbps", style: .default, handler: { (action) -> Void in
globalVideoSetting.bandWidth = 384000
self.updateBandwidthView()
})
let action3 = UIAlertAction(title: "768Kbs", style: .default, handler: { (action) -> Void in
globalVideoSetting.bandWidth = 768000
self.updateBandwidthView()
})
let action4 = UIAlertAction(title: "2Mbps", style: .default, handler: { (action) -> Void in
globalVideoSetting.bandWidth = 2000000
self.updateBandwidthView()
})
let action5 = UIAlertAction(title: "3Mbps", style: .default, handler: { (action) -> Void in
globalVideoSetting.bandWidth = 3000000
self.updateBandwidthView()
})
let action6 = UIAlertAction(title: "4Mbps", style: .default, handler: { (action) -> Void in
globalVideoSetting.bandWidth = 4000000
self.updateBandwidthView()
})
let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
})
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
alertController.addAction(action4)
alertController.addAction(action5)
alertController.addAction(action6)
alertController.addAction(cancelButton)
self.navigationController!.present(alertController, animated: true, completion: nil)
}
func updateBandwidthView(){
var bandWidthStr : String = ""
if let bandwidth = sparkSDK?.phone.videoMaxBandwidth{
switch Int(bandwidth) {
case 177000 :
bandWidthStr = "177Kbps "
break
case 384000 :
bandWidthStr = "384Kbps "
break
case 768000 :
bandWidthStr = "768Kbps "
break
case 2000000 :
bandWidthStr = "2Mbps "
break
case 3000000 :
bandWidthStr = "3Mbps "
break
case 4000000:
bandWidthStr = "4Mbps "
break
default:
bandWidthStr = "720p "
break
}
bandWidthLabel.text = bandWidthStr
}else{
bandWidthLabel.text = ""
}
}
func updateCallCapStatus() {
if !globalVideoSetting.isVideoEnabled() {
audioImage.image = checkImage
audioVideoImage.image = uncheckImage
} else {
audioImage.image = uncheckImage
audioVideoImage.image = checkImage
}
}
func updateCameraStatus(_ animation:Bool = true) {
if animation {
updateSelfSetupView(!globalVideoSetting.isSelfViewShow)
}
else {
selfViewHiddenHelpLabelHeight.constant = CGFloat(globalVideoSetting.isSelfViewShow ? 0:selfViewSetupHelpLabelHeightContant)
selfViewHiddenHelpLabel.alpha = globalVideoSetting.isSelfViewShow ? 0:1
cameraSetupView.alpha = globalVideoSetting.isSelfViewShow ? 1:0
selfViewSetupHeight.constant = CGFloat(globalVideoSetting.isSelfViewShow ? selfViewSetupHeightContant:0)
}
if !globalVideoSetting.isSelfViewShow {
frontImage.image = uncheckImage
backImage.image = uncheckImage
selfViewCloseImage.image = checkImage
//note:stopPreview stream will not sent to remote side
sparkSDK?.phone.stopPreview()
}
else if globalVideoSetting.facingMode == .user {
frontImage.image = checkImage
backImage.image = uncheckImage
selfViewCloseImage.image = uncheckImage
//note:when change the facing mode ,please stop previous preview stream
sparkSDK?.phone.stopPreview()
sparkSDK?.phone.startPreview(view: self.preview)
}
else {
frontImage.image = uncheckImage
backImage.image = checkImage
selfViewCloseImage.image = uncheckImage
//note:when change the facing mode ,please stop previous preview stream
sparkSDK?.phone.stopPreview()
sparkSDK?.phone.startPreview(view: self.preview)
}
}
func updateLoudspeakerStatus() {
loudSpeakerSwitch.isOn = globalVideoSetting.isLoudSpeaker
}
func updateVideoView(_ isHidden:Bool) {
var firstView:UIView?
var firstConstraint:NSLayoutConstraint?
var firstConstant:CGFloat?
var secondView:UIView?
var secondConstraint:NSLayoutConstraint?
var secondConstant:CGFloat?
let backoundViewBottom:NSLayoutConstraint?
if isHidden {
firstView = videoSetupView
firstConstraint = videoViewHeight
firstConstant = 0
secondView = videoViewHiddenHelpLabel
secondConstraint = videoViewhiddenHelpLabelHeight
secondConstant = videoViewSetupHelpLabelHeightContant
backoundViewBottom = NSLayoutConstraint.init(item: videoSetupBackoundView, attribute: .bottom, relatedBy: .equal, toItem: loudSpeakerLabel, attribute: .bottom, multiplier: 1, constant: -(videoSetupBackoundViewTop.constant))
}
else {
firstView = videoViewHiddenHelpLabel
firstConstraint = videoViewhiddenHelpLabelHeight
firstConstant = 0
secondView = videoSetupView
secondConstraint = videoViewHeight
secondConstant = videoViewSetupHeightContant
backoundViewBottom = NSLayoutConstraint.init(item: videoSetupBackoundView, attribute: .bottom, relatedBy: .equal, toItem: videoSetupView, attribute: .bottom, multiplier: 1, constant: 0)
}
expandedView(withAnim: { [weak self] in
if let strongSelf = self {
firstView?.alpha = 0
firstConstraint?.constant = firstConstant ?? 0
if isHidden {
strongSelf.view.removeConstraint(strongSelf.videoSetupBackroundViewBottom)
strongSelf.videoSetupBackroundViewBottom = backoundViewBottom
strongSelf.view.addConstraint(strongSelf.videoSetupBackroundViewBottom)
}
}
}){ [weak self] in
if let strongSelf = self {
strongSelf.expandedView(withAnim:{
secondView?.alpha = 1
secondConstraint?.constant = secondConstant ?? 0
if !isHidden {
strongSelf.view.removeConstraint(strongSelf.videoSetupBackroundViewBottom)
strongSelf.videoSetupBackroundViewBottom = backoundViewBottom
strongSelf.view.addConstraint(strongSelf.videoSetupBackroundViewBottom)
}
}
)
}
}
}
func updateSelfSetupView(_ isHidden:Bool) {
var firstView:UIView?
var firstConstraint:NSLayoutConstraint?
var firstConstant:CGFloat?
var secondView:UIView?
var secondConstraint:NSLayoutConstraint?
var secondConstant:CGFloat?
if isHidden {
firstView = cameraSetupView
firstConstraint = selfViewSetupHeight
firstConstant = 0
secondView = selfViewHiddenHelpLabel
secondConstraint = selfViewHiddenHelpLabelHeight
secondConstant = selfViewSetupHelpLabelHeightContant
}
else {
firstView = selfViewHiddenHelpLabel
firstConstraint = selfViewHiddenHelpLabelHeight
firstConstant = 0
secondView = cameraSetupView
secondConstraint = selfViewSetupHeight
secondConstant = selfViewSetupHeightContant
}
expandedView(withAnim: { [weak self] in
if let _ = self {
firstView?.alpha = 0
firstConstraint?.constant = firstConstant ?? 0
}
}){ [weak self] in
if let strongSelf = self {
strongSelf.expandedView(withAnim:{
secondView?.alpha = 1
secondConstraint?.constant = secondConstant ?? 0
}
)
}
}
}
private func expandedView(withAnim animations:@escaping () -> Swift.Void,completion: (() -> Swift.Void)? = nil) {
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10.0, options: .curveEaseIn, animations: { [weak self] in
if let strongSelf = self {
animations()
strongSelf.view.layoutIfNeeded()
}
}, completion: { finished in
if let finishedCompletion = completion {
finishedCompletion()
}
})
}
@objc func gotoInitiateCallView() {
if let initiateCallViewController = (storyboard?.instantiateViewController(withIdentifier: "InitiateCallViewController") as? InitiateCallViewController) {
initiateCallViewController.sparkSDK = self.sparkSDK
navigationController?.pushViewController(initiateCallViewController, animated: true)
}
}
}
| mit | df5bf87fd142e68a98942a2fd20bb769 | 44.232184 | 336 | 0.651352 | 5.670317 | false | false | false | false |
szpnygo/firefox-ios | Sync/Info.swift | 23 | 2409 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
public class InfoCollections {
private let collections: [String: Timestamp]
init(collections: [String: Timestamp]) {
self.collections = collections
}
public class func fromJSON(json: JSON) -> InfoCollections? {
if let dict = json.asDictionary {
var coll = [String: Timestamp]()
for (key, value) in dict {
if let value = value.asDouble {
coll[key] = Timestamp(value * 1000)
} else {
return nil // Invalid, so bail out.
}
}
return InfoCollections(collections: coll)
}
return nil
}
public func collectionNames() -> [String] {
return self.collections.keys.array
}
public func modified(collection: String) -> Timestamp? {
return self.collections[collection]
}
// Two I/Cs are the same if they have the same modified times for a set of
// collections. If no collections are specified, they're considered the same
// if the other I/C has the same values for this I/C's collections, and
// they have the same collection array.
public func same(other: InfoCollections, collections: [String]?) -> Bool {
if let collections = collections {
return collections.every({ self.modified($0) == other.modified($0) })
}
// Same collections?
let ours = self.collectionNames()
let theirs = other.collectionNames()
return ours.sameElements(theirs, f: ==) && same(other, collections: ours)
}
}
extension Array {
// Laughably inefficient, but good enough for a handful of items.
func sameElements(arr: [T], f: (T, T) -> Bool) -> Bool {
return self.count == arr.count && every { arr.contains($0, f: f) }
}
func contains(x: T, f: (T, T) -> Bool) -> Bool {
for y in self {
if f(x, y) {
return true
}
}
return false
}
func every(f: (T) -> Bool) -> Bool {
for x in self {
if !f(x) {
return false
}
}
return true
}
}
| mpl-2.0 | 15aaf9b7d223f3076f9e89791eb0fc89 | 30.285714 | 81 | 0.565795 | 4.271277 | false | false | false | false |
stephentyrone/swift | test/Driver/opt-record-bitstream.swift | 3 | 1528 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -c -O -wmo -save-optimization-record=bitstream -save-optimization-record-path %t/optrecordmod.opt.bitstream %s -module-name optrecordmod -o %t/opt-record.o 2>&1 | %FileCheck -allow-empty %s
// RUN: llvm-bcanalyzer -dump %t/optrecordmod.opt.bitstream | %FileCheck -check-prefix=BITSTREAM %s
// RUN: otool -l %t/opt-record.o | %FileCheck -check-prefix=OBJ %s
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos
// Ensure we emitted the appropriate section
// OBJ: sectname __remarks
// CHECK-NOT: remark
var a: Int = 1
#sourceLocation(file: "custom.swift", line: 2000)
func foo() {
a = 2
}
#sourceLocation() // reset
public func bar() {
foo()
// BITSTREAM: <Remark NumWords=13 BlockCodeSize=4>
// BITSTREAM-NEXT: <Remark header abbrevid=4 op0=1 op1=0 op2=1 op3=2/>
// BITSTREAM-NEXT: <Remark debug location abbrevid=5 op0=3 op1=[[@LINE-3]] op2=3/>
// BITSTREAM-NEXT: <Argument with debug location abbrevid=7 op0=4 op1=5 op2=6 op3=2000 op4=6/>
// BITSTREAM-NEXT: <Argument abbrevid=8 op0=7 op1=8/>
// BITSTREAM-NEXT: <Argument with debug location abbrevid=7 op0=9 op1=10 op2=3 op3=[[@LINE-7]] op4=13/>
// BITSTREAM-NEXT: <Argument abbrevid=8 op0=7 op1=11/>
// BITSTREAM-NEXT: <Argument abbrevid=8 op0=12 op1=13/>
// BITSTREAM-NEXT: <Argument abbrevid=8 op0=7 op1=14/>
// BITSTREAM-NEXT: <Argument abbrevid=8 op0=15 op1=16/>
// BITSTREAM-NEXT: <Argument abbrevid=8 op0=7 op1=17/>
// BITSTREAM-NEXT: </Remark>
}
| apache-2.0 | 605d1b33f6605e69e1ded33dc65f7a66 | 41.444444 | 220 | 0.680628 | 2.87218 | false | false | false | false |
jonathan-stone/slidingmessage | slidingmessage/SlidingMessage.swift | 1 | 9833 | //
// SlidingMessage.swift
//
// Created by Jonathan Stone on 6/10/15.
// Copyright (c) 2015-2017 Jonathan Stone. All rights reserved.
//
import UIKit
open class SlidingMessage: NSObject
{
// Controls:
var view: UIView!
var parentView: UIView!
var errorMessageLabel: UILabel!
var errorMessageDismissButton: UIButton!
var imageView: UIImageView!
var positionBelowControl: UIView?
var font: UIFont?
// Constraints:
var mainViewTopSpaceConstraint: NSLayoutConstraint!
// Variables:
var hideSlidingMessageAfterDelayTimer: Timer?
fileprivate var timeIntervalBeforeAutoHiding:TimeInterval = 10
var minimumHeight:CGFloat = 100
public init(
parentView: UIView,
autoHideDelaySeconds: Double,
backgroundColor: UIColor,
foregroundColor: UIColor,
minimumHeight: CGFloat,
positionBelowControl: UIView?,
font: UIFont?)
{
super.init()
self.parentView = parentView
timeIntervalBeforeAutoHiding = autoHideDelaySeconds
self.minimumHeight = minimumHeight
self.positionBelowControl = positionBelowControl
self.font = font
initSubviews()
self.view.backgroundColor = backgroundColor
self.errorMessageLabel.textColor = foregroundColor
self.view.isHidden = true
}
open func show(_ message: String)
{
DispatchQueue.main.async(execute: { () -> Void in
self.stopAutohideTimer() // If it was already running, reset the autohide timer
self.view.isHidden = false
// Set text to the error message.
self.errorMessageLabel.text = message
// Begin with message out of view, above the top edge of the parent view:
self.parentView.layoutIfNeeded()
self.mainViewTopSpaceConstraint.constant = -self.view.frame.size.height
self.parentView.layoutIfNeeded()
// Animate moving down from the top of the view:
UIView.animate(
withDuration: 0.8,
delay: 0,
options: [.curveEaseIn, .curveEaseOut, .allowUserInteraction],
animations: self.animateSlidingDown,
completion: { (done) -> Void in
self.startAutohideTimer()
})
})
}
open class func getStandardVerticalSpacing(_ topControl: UIView, bottomControl: UIView)->CGFloat
{
let views = ["topview": topControl, "bottomview" : bottomControl]
let constraints = NSLayoutConstraint.constraints(
withVisualFormat: "[topview]-[bottomview]",
options: NSLayoutFormatOptions(),
metrics: nil,
views: views)
return constraints[0].constant
}
fileprivate func animateSlidingDown()
{
var topOfSlidingMessage: CGFloat = 0
if let controlAbove = self.positionBelowControl
{
let origin = self.parentView.convert(controlAbove.bounds.origin, from: controlAbove)
let vspacing = SlidingMessage.getStandardVerticalSpacing(controlAbove, bottomControl: self.view)
topOfSlidingMessage = origin.y + controlAbove.frame.size.height + vspacing
}
else
{
topOfSlidingMessage = self.parentView.frame.height - self.view.frame.height
}
self.mainViewTopSpaceConstraint.constant = topOfSlidingMessage
self.parentView.layoutIfNeeded()
}
fileprivate func initSubviews()
{
self.view = UIView()
parentView.addSubview(self.view)
addMessageLabel()
addCloseButtonVisualHint()
// Button must be added last. Covers entire view.
addCloseButton()
// Add constraints
setConstraints()
parentView.layoutIfNeeded()
}
fileprivate func addMessageLabel()
{
self.errorMessageLabel = LabelWithAutoWrap(font: self.font)
self.view.addSubview(errorMessageLabel)
}
fileprivate func addCloseButtonVisualHint()
{
if let image = loadCloseButtonImage()
{
self.imageView = UIImageView(image: image)
self.view.addSubview(imageView)
}
}
fileprivate func addCloseButton()
{
self.errorMessageDismissButton = makeDismissButton()
self.view.addSubview(errorMessageDismissButton)
}
fileprivate func loadCloseButtonImage()->UIImage?
{
let frameworkBundle = Bundle(for: type(of: self))
return UIImage(named: "XButton", in: frameworkBundle, compatibleWith: nil)
}
fileprivate func makeDismissButton()->UIButton
{
let button = UIButton()
button.addTarget(self, action: #selector(SlidingMessage.errorMessageDismissButtonPressed(_:)), for: UIControlEvents.touchUpInside)
return button
}
fileprivate func setConstraints()
{
let views: [String: UIView] = [
"view": view,
"label": errorMessageLabel,
"image": imageView,
"button": errorMessageDismissButton
]
for control in views.values
{
control.translatesAutoresizingMaskIntoConstraints = false
}
let mainViewHConstraint = NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: NSLayoutFormatOptions(),
metrics: nil, views: views)
parentView.addConstraints(mainViewHConstraint)
let mainViewTopConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: parentView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0 /*32*/)
parentView.addConstraint(mainViewTopConstraint)
self.mainViewTopSpaceConstraint = mainViewTopConstraint
let mainViewVConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: self.minimumHeight)
parentView.addConstraint(mainViewVConstraint)
let imageAspectRatioConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: imageView, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 1)
imageView.addConstraint(imageAspectRatioConstraint)
let imageTopConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
view.addConstraint(imageTopConstraint)
let labelVertConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-[label]-|",
options: NSLayoutFormatOptions(),
metrics: nil, views: views)
view.addConstraints(labelVertConstraints)
let subviewsHorzConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[image]-32.0-[label]-|",
options: NSLayoutFormatOptions(), metrics: nil, views: views)
view.addConstraints(subviewsHorzConstraints)
// An invisible button overlays the entire control. Users will be drawn to tap the X button, but tapping anywhere will dismiss. The X button is just a cue to tell them it can be dismissed.
let buttonHorzConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[button]|",
options: NSLayoutFormatOptions(), metrics: nil, views: views)
view.addConstraints(buttonHorzConstraints)
let buttonVertConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[button]|",
options: NSLayoutFormatOptions(), metrics: nil, views: views)
view.addConstraints(buttonVertConstraints)
}
@objc func errorMessageDismissButtonPressed(_ sender: UIButton!)
{
hide()
}
func startAutohideTimer()
{
if (timeIntervalBeforeAutoHiding > 0)
{
if #available(iOS 10.0, *) {
self.hideSlidingMessageAfterDelayTimer = Timer.scheduledTimer(
withTimeInterval: timeIntervalBeforeAutoHiding,
repeats: false,
block: { (theTimer) in
self.autoHideTimerFired(theTimer)
}
)
} else {
// Fallback on earlier versions
self.hideSlidingMessageAfterDelayTimer = Timer.scheduledTimer(
timeInterval: timeIntervalBeforeAutoHiding,
target: self,
selector: #selector(self.autoHideTimerFired),
userInfo: nil,
repeats: false)
}
}
}
@objc func autoHideTimerFired(_ timer: Timer)
{
stopAutohideTimer()
self.hide()
}
func stopAutohideTimer()
{
self.hideSlidingMessageAfterDelayTimer?.invalidate()
self.hideSlidingMessageAfterDelayTimer = nil
}
func hide()
{
stopAutohideTimer()
UIView.animate(withDuration: 0.3,
delay: 0,
options: UIViewAnimationOptions.curveEaseInOut,
// options: UIViewAnimationOptions.TransitionCrossDissolve,
animations: { () -> Void in
// Use this to slide up and away instead of fading out:
// self.mainViewTopSpaceConstraint.constant = -self.view.frame.size.height
self.view.alpha = 0
// self.view.layoutIfNeeded()
}, completion: {(done)->Void in
self.view.isHidden = true
self.view.alpha = 1.0
})
}
}
| mit | 083b7b0c22beece445fb719e3658e514 | 35.418519 | 252 | 0.639479 | 5.514863 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Online/Views/InitialActivityIndicatorView.swift | 1 | 2313 | //
// InitialActivityIndicatorView.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/19/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
class InitialActivityIndicatorView: UIView {
fileprivate var indicatorView: NVActivityIndicatorView!
fileprivate(set) weak var sourceView: UIView?
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
private func configure() {
indicatorView = NVActivityIndicatorView(
frame: .zero,
type: .lineScale,
color: .toolbarImage,
padding: nil
)
indicatorView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(indicatorView)
NSLayoutConstraint.activate([
indicatorView.centerXAnchor.constraint(equalTo: centerXAnchor),
indicatorView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -79),
indicatorView.widthAnchor.constraint(equalToConstant: 40),
indicatorView.widthAnchor.constraint(equalTo: indicatorView.heightAnchor)
])
}
}
extension InitialActivityIndicatorView {
func startAnimating(in view: UIView?) {
let sourceView = view ?? getWindow()
self.sourceView = sourceView
self.translatesAutoresizingMaskIntoConstraints = false
sourceView.addSubview(self)
NSLayoutConstraint.activate([
topAnchor.constraint(equalTo: sourceView.topAnchor),
bottomAnchor.constraint(equalTo: sourceView.bottomAnchor),
leadingAnchor.constraint(equalTo: sourceView.leadingAnchor),
trailingAnchor.constraint(equalTo: sourceView.trailingAnchor)
])
sourceView.layoutIfNeeded()
indicatorView.startAnimating()
}
func stopAnimating() {
indicatorView.stopAnimating()
self.removeFromSuperview()
}
private func getWindow() -> UIView {
let applicationDelegate = UIApplication.shared.delegate as! AppDelegate
return applicationDelegate.window!
}
}
| mit | b545948ab0db356a04e5466155ee914b | 27.85 | 90 | 0.646447 | 5.857868 | false | false | false | false |
groue/GRDB.swift | GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift | 1 | 2222 | extension ValueObservation {
/// Notifies only values that don’t match the previously observed value, as
/// evaluated by a provided closure.
///
/// - parameter predicate: A closure to evaluate whether two values are
/// equivalent, for purposes of filtering. Return true from this closure
/// to indicate that the second element is a duplicate of the first.
public func removeDuplicates(by predicate: @escaping (Reducer.Value, Reducer.Value) -> Bool)
-> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
{
mapReducer { ValueReducers.RemoveDuplicates($0, predicate: predicate) }
}
}
extension ValueObservation where Reducer.Value: Equatable {
/// Notifies only values that don’t match the previously observed value.
public func removeDuplicates()
-> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
{
mapReducer { ValueReducers.RemoveDuplicates($0, predicate: ==) }
}
}
extension ValueReducers {
/// A `ValueReducer` that notifies only values that don’t match the
/// previously observed value.
///
/// See ``ValueObservation/removeDuplicates()``.
public struct RemoveDuplicates<Base: _ValueReducer>: _ValueReducer {
private var base: Base
private var previousValue: Base.Value?
private var predicate: (Base.Value, Base.Value) -> Bool
init(_ base: Base, predicate: @escaping (Base.Value, Base.Value) -> Bool) {
self.base = base
self.predicate = predicate
}
public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? {
guard let value = try base._value(fetched) else {
return nil
}
if let previousValue = previousValue, predicate(previousValue, value) {
// Don't notify consecutive identical values
return nil
}
self.previousValue = value
return value
}
}
}
extension ValueReducers.RemoveDuplicates: _DatabaseValueReducer where Base: _DatabaseValueReducer {
public func _fetch(_ db: Database) throws -> Base.Fetched {
try base._fetch(db)
}
}
| mit | af302f8c49a753caa8644868c84ca495 | 37.877193 | 99 | 0.648014 | 4.924444 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS | Aztec/Classes/Processor/RegexProcessor.swift | 2 | 1457 | import Foundation
open class RegexProcessor: Processor {
public typealias ReplaceRegex = (NSTextCheckingResult, String) -> String?
public let regex: NSRegularExpression
public let replacer: ReplaceRegex
public init(regex: NSRegularExpression, replacer: @escaping ReplaceRegex) {
self.regex = regex
self.replacer = replacer
}
public func process(_ text: String) -> String {
let matches = regex.matches(in: text, options: [], range: text.utf16NSRange(from: text.startIndex ..< text.endIndex))
var replacements = [(NSRange, String)]()
for match in matches {
if let replacement = replacer(match, text) {
replacements.append((match.range, replacement))
}
}
let resultText = replace(matches: replacements, in: text)
return resultText
}
func replace(matches: [(NSRange, String)], in text: String) -> String {
let mutableString = NSMutableString(string: text)
var offset = 0
for (range, replacement) in matches {
let lengthBefore = mutableString.length
let offsetRange = NSRange(location: range.location + offset, length: range.length)
mutableString.replaceCharacters(in: offsetRange, with: replacement)
let lengthAfter = mutableString.length
offset += (lengthAfter - lengthBefore)
}
return mutableString as String
}
}
| mpl-2.0 | 811e3ab60fb5f56e77a9b72dfe74e6e9 | 36.358974 | 125 | 0.642416 | 4.955782 | false | false | false | false |
songzhw/2iOS | iOS_Swift/iOS_Swift/images/DrawingViewController.swift | 1 | 8070 | import UIKit
class DrawingViewController: UIViewController {
@IBOutlet weak var ivPath: UIImageView!
@IBOutlet weak var ivBezierPath: UIImageView!
@IBOutlet weak var ivCliping: UIImageView!
@IBOutlet weak var ivGradient: UIImageView!
@IBOutlet weak var ivPattern: UIImageView!
@IBOutlet weak var ivPattern2: UIImageView!
@IBOutlet weak var ivTransform: UIImageView!
@IBOutlet weak var ivShadow: UIImageView!
@IBOutlet weak var ivErase: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
drawPath()
drawBezierPath()
drawClip() // 图是圆形的, 而且中间还有一个小圆区域被挖了出来
drawGraident()
drawPattern()
drawPattern2()
drawTransform()
drawShadow()
drawErase()
}
func drawErase(){
let render = UIGraphicsImageRenderer(size: CGSize(width: 150, height: 150))
ivErase.image = render.image { (arg) in
let context = UIGraphicsGetCurrentContext()!
context.setFillColor(UIColor.blue.cgColor)
context.fill(CGRect(x: 0, y: 0, width: 150, height: 150))
context.clear(CGRect(x: 0, y: 0, width: 50, height: 50))
}
}
func drawShadow(){
let arrow = drawArrow()
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 150, height: 150))
ivShadow.image = renderer.image(actions: { _ in
let ctx = UIGraphicsGetCurrentContext()!
ctx.setShadow(offset: CGSize(width: 8, height: 8), blur: 22)
// ctx.beginTransparencyLayer(auxiliaryInfo: nil)
arrow.draw(at: CGPoint(x: 0, y: 0))
for i in 0..<3 {
ctx.translateBy(x: 20, y: 100)
ctx.rotate(by: 30 * .pi / 180.0)
ctx.translateBy(x: -20, y: -100)
arrow.draw(at: CGPoint(x: 0, y: 0))
}
// ctx.endTransparencyLayer()
})
}
func drawTransform(){
let arrow = drawArrow()
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 150, height: 150))
ivTransform.image = renderer.image(actions: { _ in
let ctx = UIGraphicsGetCurrentContext()!
arrow.draw(at: CGPoint(x: 0, y: 0))
for i in 0..<3 {
ctx.translateBy(x: 20, y: 100)
ctx.rotate(by: 30 * .pi / 180.0)
ctx.translateBy(x: -20, y: -100)
arrow.draw(at: CGPoint(x: 0, y: 0))
}
})
}
func drawArrow() -> UIImage{
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 40, height: 100))
return renderer.image { (_) in
let p = UIBezierPath()
// 画底部的矩形. 其实这是线, 只不过是很粗的线
UIColor.blue.set()
p.move(to: CGPoint(x: 20, y: 100))
p.addLine(to: CGPoint(x: 20, y: 19))
p.lineWidth = 20;
p.stroke()
// 画顶上的三角形
UIColor.orange.set()
p.removeAllPoints()
p.move(to: CGPoint(x:0, y:25))
p.addLine(to: CGPoint(x: 20, y: 0))
p.addLine(to: CGPoint(x: 40, y: 25))
p.fill()
// clear就是要挖掉一块出来. (snip a triangle out of the rect)
p.removeAllPoints() // 若不加这句, 那顶上三角也不见了(被.clear给弄消失了)
p.move(to: CGPoint(x:10, y:101))
p.addLine(to: CGPoint(x: 20, y: 90))
p.addLine(to: CGPoint(x: 30, y: 101))
p.fill(with:.clear, alpha:1.0)
}
}
func drawPattern2(){
let bg = UIColor(patternImage: #imageLiteral(resourceName: "brick"));
ivPattern2.backgroundColor = bg
}
func drawPattern() {
let stripRender = UIGraphicsImageRenderer(size: CGSize(width: 10, height: 10))
let stripImage = stripRender.image { (arg) in
let ctx = arg.cgContext
ctx.setFillColor(UIColor.red.cgColor)
ctx.fill(CGRect(x: 0, y: 0, width: 10, height: 5))
ctx.setFillColor(UIColor.blue.cgColor)
ctx.fill(CGRect(x: 0, y: 5, width: 10, height: 5))
}
let stripPattern = UIColor(patternImage: stripImage)
stripPattern.setFill()
ivPattern.backgroundColor = stripPattern
}
func drawGraident(){
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 150, height: 150))
let image = renderer.image { _ in
guard let ctx = UIGraphicsGetCurrentContext() else {return}
ctx.saveGState()
let colorSpace = CGColorSpaceCreateDeviceRGB()
let startColor = UIColor.red
guard let startColorComponents = startColor.cgColor.components else { return }
let endColor = UIColor.blue
guard let endColorComponents = endColor.cgColor.components else { return }
let colorComponents: [CGFloat]
= [startColorComponents[0], startColorComponents[1], startColorComponents[2], startColorComponents[3], endColorComponents[0], endColorComponents[1], endColorComponents[2], endColorComponents[3]]
let locations:[CGFloat] = [0.0, 1.0]
guard let gradient = CGGradient(colorSpace:colorSpace, colorComponents: colorComponents, locations: locations, count: 2) else { return }
let startPoint = CGPoint(x: 0, y: 00)
let endPoint = CGPoint(x: 150, y: 150)
ctx.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: UInt32(0)))
ctx.restoreGState()
}
ivGradient.image = image
}
func drawClip(){
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 150, height: 150))
let image = renderer.image { _ in
let p1 = UIBezierPath(ovalIn: CGRect(x:0, y:0, width: 150, height: 150))
p1.usesEvenOddFillRule = true
let p2 = UIBezierPath(ovalIn: CGRect(x:30, y:30, width:90, height: 90))
p1.append(p2)
p1.addClip()
let westLake = UIImage(named: "wlake")!
westLake.draw(in: CGRect(x: 0, y: 0, width: 150, height: 150))
}
ivCliping.image = image
print("szw size = \(ivCliping.frame)")
}
func drawBezierPath(){
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 150, height: 150))
let image = renderer.image { _ in
let p = UIBezierPath()
// 画底部的矩形. 其实这是线, 只不过是很粗的线
UIColor.blue.set()
p.move(to: CGPoint(x: 100, y: 100))
p.addLine(to: CGPoint(x: 100, y: 19))
p.lineWidth = 20;
p.stroke()
// 画顶上的三角形
UIColor.orange.set()
p.removeAllPoints()
p.move(to: CGPoint(x:80, y:25))
p.addLine(to: CGPoint(x: 100, y: 0))
p.addLine(to: CGPoint(x: 120, y: 25))
p.fill()
// clear就是要挖掉一块出来. (snip a triangle out of the rect)
p.removeAllPoints() // 若不加这句, 那顶上三角也不见了(被.clear给弄消失了)
p.move(to: CGPoint(x:90, y:101))
p.addLine(to: CGPoint(x: 100, y: 90))
p.addLine(to: CGPoint(x: 110, y: 101))
p.fill(with:.clear, alpha:1.0)
}
ivBezierPath.image = image
}
func drawPath(){
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 150, height: 150))
let image = renderer.image { _ in
let ctx = UIGraphicsGetCurrentContext()!
// 画底部的矩形. 其实这是线, 只不过是很粗的线
ctx.setStrokeColor(UIColor.blue.cgColor)
ctx.move(to: CGPoint(x: 100, y: 100))
ctx.addLine(to: CGPoint(x: 100, y: 19))
ctx.setLineWidth(20)
ctx.strokePath()
// 画顶上的三角形
ctx.setFillColor(UIColor.orange.cgColor)
ctx.move(to: CGPoint(x:80, y:25))
ctx.addLine(to: CGPoint(x: 100, y: 0))
ctx.addLine(to: CGPoint(x: 120, y: 25))
ctx.fillPath() // 这一行与下面的ctx.fillPath()重复了, 可以删除吗? : 不可以. 每次ctx.move()都是重置了, 要是这里没这行, 那顶上的三角形就画不出来!
// clear就是要挖掉一块出来. (snip a triangle out of the rect)
ctx.move(to: CGPoint(x:90, y:101))
ctx.addLine(to: CGPoint(x: 100, y: 90))
ctx.addLine(to: CGPoint(x: 110, y: 101))
ctx.setBlendMode(.clear)
ctx.fillPath()
}
ivPath.image = image
}
}
| apache-2.0 | 28f974825b0689157a366d8f83d7436c | 31.965517 | 202 | 0.619901 | 3.560521 | false | false | false | false |
proxpero/Placeholder | Placeholder/Cache.swift | 1 | 1277 | //
// Cache.swift
// Placeholder
//
// Created by Todd Olsen on 4/7/17.
// Copyright © 2017 proxpero. All rights reserved.
//
import Foundation
/// A class to manage caching `Resource`s.
public final class Cache {
// The private implementation of the cached memory.
private var storage: FileStorage
/// Initialize with a `FileStorage` object. Default is `FileStorage()`
public init(storage: FileStorage = FileStorage()) {
self.storage = storage
}
/// Try to load a resource of type A from the cache,
/// return `nil` if it is not there. Only resources
/// with a `method` value of `.get` are supported.
public func load<A>(_ resource: Resource<A>) -> A? {
guard case .get = resource.method else { return nil }
let data = storage[resource.cacheKey]
return data.flatMap(resource.parse)
}
/// Place the `data` of `resource` in the cache.
public func save<A>(_ data: Data, for resource: Resource<A>) {
guard case .get = resource.method else { return }
storage[resource.cacheKey] = data
}
}
extension Resource {
/// A unique key to act as an address for the resource in a cache.
var cacheKey: String {
return "cache." + url.absoluteString.md5
}
}
| mit | de98f27c64d774e58af358a489594512 | 26.73913 | 74 | 0.640282 | 4 | false | false | false | false |
proxpero/Placeholder | Placeholder/AppCoordinator.swift | 1 | 6220 |
import UIKit
/// A class to encapsulate the logic involved in presenting view controllers
/// and wiring view models to views. This is nice because it keeps the view
/// controllers isolated and dumb.
final class AppCoordinator {
// Keep a reference to the window's navigation controller.
var navigationController: UINavigationController!
// The webservice will automatically cache responses it makes on the network.
private let webservice = CachedWebservice.shared
// The URL host of the service.
private let urlProvider = URLProvider(host: "jsonplaceholder.typicode.com")
init(window: UIWindow) {
// Set the url info on the `Route`.
Route.urlProvider = urlProvider
// Create an ItemsViewController for users.
let usersViewController = ItemsViewController() { (user: User) in
return CellDescriptor(
reuseIdentifier: "UserCell",
configure: user.configureCell
)
}
// The first screen displays all the users.
usersViewController.title = "Users"
// Set a callback to display a selected album.
usersViewController.didSelect = showAlbums
// Grab the users asynchronously from the network.
webservice.load(User.all).onResult { result in
if case .success(let users) = result {
// If the users are there, populate the `items` property
// of the generic view controller, which will reload the
// table view.
usersViewController.items = users
}
}
// Initialize a navigation controller with the view controller.
navigationController = UINavigationController(rootViewController: usersViewController)
// Set the nav controller as the window's rootVC
window.rootViewController = navigationController
}
/// Push the albums view controlller populated with albums for the selected user.
func showAlbums(for user: User) {
// Initialize the view controller with 0 albums, a 'profile' navigation item,
// and a function to configure the album cells with an album.
let albumsViewController = ItemsViewController(navigationItemTitle: "Profile") { (album: Album) in
return CellDescriptor(
reuseIdentifier: "AlbumCell",
configure: album.configureCell
)
}
// Set the title.
albumsViewController.title = user.name
// Set the callback for showing the thumbnails view controller
// when an album row is tapped.
albumsViewController.didSelect = showThumbnails
// Set the callback for showing the user's profile.
albumsViewController.didTapButton = { self.showProfile(for: user) }
// Grab the albums for the user asynchronously from the network using ReactiveJSON.
webservice.load(user.albums).onResult { result in
if case .success(let albums) = result {
albumsViewController.items = albums
}
}
// Push the view controller.
navigationController.pushViewController(albumsViewController, animated: true)
}
/// Show the selected user's profile view controller, modally.
func showProfile(for user: User) {
// Instantiate the view controller from the "Main" storyboard.
let userProfileViewController = UIStoryboard.main.instantiate(UserProfileViewController.self)
// Set the user.
userProfileViewController.user = user
// Set the callback to handle dismissing the view controller.
userProfileViewController.dismiss = {
self.navigationController.dismiss(animated: true, completion: nil)
}
// Create a new navigation controller
let nav = UINavigationController(rootViewController: userProfileViewController)
// Have the main navigation controller present the profile nav controller.
navigationController.present(nav, animated: true, completion: nil)
}
/// Show the thumbnails of the selected album in a table view
func showThumbnails(for album: Album) {
// Initialize a table view controller with a cell configuration function.
let thumbnailsViewController = ItemsViewController() { (photo: Photo) in
return CellDescriptor(
reuseIdentifier: "PhotoCell",
configure: photo.configureCell
)
}
// Set the title.
thumbnailsViewController.title = album.title
// Set a callback to display the selected photo when the user selects a row.
thumbnailsViewController.didSelect = showPhoto
// Grab the photos in the album asynchronously from the network.
webservice.load(album.photos).onResult { result in
if case .success(let photos) = result {
thumbnailsViewController.items = photos
}
}
// Push the view controller.
navigationController.pushViewController(thumbnailsViewController, animated: true)
}
/// Display the selected photo.
func showPhoto(_ photo: Photo) {
// Instantiate the photo view controller from the "Main" storyboard.
let photoViewController = UIStoryboard.main.instantiate(PhotoViewController.self)
// Set the `phototitle` property (not the vc title)
photoViewController.photoTitle = photo.title
// Set the photoImage property to a placeholder while
// the real image loads.
photoViewController.photoImage = UIImage.placeholder(with: .lightGray, size: photoViewController.view.bounds.maximumSquare)
// Asyncronously load the (possibly cached) image. Update on the
// main queue.
webservice.load(photo.imageResource).onResult { result in
if case .success(let image) = result {
DispatchQueue.main.async {
photoViewController.photoImage = image
}
}
}
// Push the view controller.
navigationController.pushViewController(photoViewController, animated: true)
}
}
| mit | 60b7ac25bb8787eed375d33bca5a8119 | 36.926829 | 131 | 0.656431 | 5.644283 | false | false | false | false |
dsay/POPDataSource | DataSources/Example/Models/TextFieldDataSource.swift | 1 | 3578 | import POPDataSource
import ReactiveCocoa
import ReactiveSwift
class TextFieldDataSource:
TableViewDataSource,
DataContainable,
CellContainable,
CellConfigurator,
CellSelectable
{
struct Actions {
static let changed = "changed"
static let begin = "begin"
static let end = "end"
static let exit = "exit"
}
// private weak var cell: TextFieldTableViewCell?
var data: [String] {
return [""]
}
var selectors: [DataSource
.Action: (TextFieldTableViewCell, IndexPath, String) -> ()] = [:]
func reuseIdentifier() -> String {
return TextFieldTableViewCell.identifier
}
func configurateCell(_ cell: TextFieldTableViewCell, item: String, at indexPath: IndexPath) {
cell.textField?.text = item
cell.textField?.autocorrectionType = .no
cell.textField?.autocapitalizationType = .words
cell.textField?.isSecureTextEntry = false
cell.textField?.returnKeyType = .next
cell.textField?.keyboardType = .default
cell.show?.isHidden = true
_ = cell.textField?.reactive.controlEvents(.editingChanged).observeValues
{ [unowned cell, weak self] (_) in
cell.editing()
self?.invoke(.custom(Actions.changed))? (cell, indexPath, item)
}
_ = cell.textField?.reactive.controlEvents(.editingDidBegin).observeValues
{ [unowned cell, weak self] (_) in
cell.editing()
self?.invoke(.custom(Actions.begin))? (cell, indexPath, item)
}
_ = cell.textField?.reactive.controlEvents(.editingDidEnd).observeValues
{ [unowned cell, weak self] (_) in
cell.normal()
self?.invoke(.custom(Actions.end))? (cell, indexPath, item)
}
_ = cell.textField?.reactive.controlEvents(.editingDidEndOnExit).observeValues
{ [unowned cell, weak self] (_) in
self?.invoke(.custom(Actions.end))? (cell, indexPath, item)
self?.invoke(.custom(Actions.exit))? (cell, indexPath, item)
}
}
}
class NameDataSource: TextFieldDataSource {
override func configurateCell(_ cell: TextFieldTableViewCell, item: String, at indexPath: IndexPath) {
super.configurateCell(cell, item: item, at: indexPath)
cell.textField?.placeholder = "Name"
}
}
class SurnameDataSource: TextFieldDataSource {
override func configurateCell(_ cell: TextFieldTableViewCell, item: String, at indexPath: IndexPath) {
super.configurateCell(cell, item: item, at: indexPath)
cell.textField?.placeholder = "Surname"
}
}
class EmailDataSource: TextFieldDataSource {
override func configurateCell(_ cell: TextFieldTableViewCell, item: String, at indexPath: IndexPath) {
super.configurateCell(cell, item: item, at: indexPath)
cell.textField?.placeholder = "Email"
cell.textField?.keyboardType = .emailAddress
cell.textField?.autocapitalizationType = .none
}
}
class PasswordDataSource: TextFieldDataSource {
override func configurateCell(_ cell: TextFieldTableViewCell, item: String, at indexPath: IndexPath) {
super.configurateCell(cell, item: item, at: indexPath)
cell.textField?.placeholder = "Password"
cell.textField?.autocapitalizationType = .none
cell.textField?.returnKeyType = .done
cell.textField?.isSecureTextEntry = true
cell.show?.isHidden = false
}
}
| mit | e0f3e12539bf50312a0950854a9316ee | 35.141414 | 106 | 0.640302 | 5.018233 | false | true | false | false |
AboutObjectsTraining/swift-ios-2015-07-kop | SwiftLabs/ImplictlyUnwrappedOptionals.playground/Contents.swift | 1 | 450 |
var hello: String! = "Hello"
print(hello)
hello = nil
print(hello)
// print(hello.lowercaseString) // Illegal!
print("Got here")
let things: [Any] = [123, "Hey!", 1.5]
let otherThings: Array<Any> = [1, 1.5, "Two"]
print(things)
let firstObj = things[0] as! Int
let sum = firstObj + 3
if let first = things[0] as? Int {
print("\(first + 3)")
}
if things[0] is Int {
print("Is Int")
}
// let otherSum = things[0] + 12 // Illegal! | mit | fc2598fd0730ab3558cd3e503bccd9a8 | 12.666667 | 45 | 0.604444 | 2.694611 | false | false | false | false |
StYaphet/firefox-ios | Sync/SyncTelemetryUtils.swift | 2 | 11880 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Account
import Storage
import SwiftyJSON
import SyncTelemetry
fileprivate let log = Logger.syncLogger
public let PrefKeySyncEvents = "sync.telemetry.events"
public enum SyncReason: String {
case startup = "startup"
case scheduled = "scheduled"
case backgrounded = "backgrounded"
case user = "user"
case syncNow = "syncNow"
case didLogin = "didLogin"
case push = "push"
case engineEnabled = "engineEnabled"
case clientNameChanged = "clientNameChanged"
}
public enum SyncPingReason: String {
case shutdown = "shutdown"
case schedule = "schedule"
case idChanged = "idchanged"
}
public protocol Stats {
func hasData() -> Bool
}
private protocol DictionaryRepresentable {
func asDictionary() -> [String: Any]
}
public struct SyncUploadStats: Stats {
var sent: Int = 0
var sentFailed: Int = 0
public func hasData() -> Bool {
return sent > 0 || sentFailed > 0
}
}
extension SyncUploadStats: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
return [
"sent": sent,
"failed": sentFailed
]
}
}
public struct SyncDownloadStats: Stats {
var applied: Int = 0
var succeeded: Int = 0
var failed: Int = 0
var newFailed: Int = 0
var reconciled: Int = 0
public func hasData() -> Bool {
return applied > 0 ||
succeeded > 0 ||
failed > 0 ||
newFailed > 0 ||
reconciled > 0
}
}
extension SyncDownloadStats: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
return [
"applied": applied,
"succeeded": succeeded,
"failed": failed,
"newFailed": newFailed,
"reconciled": reconciled
]
}
}
public struct ValidationStats: Stats, DictionaryRepresentable {
let problems: [ValidationProblem]
let took: Int64
let checked: Int?
public func hasData() -> Bool {
return !problems.isEmpty
}
func asDictionary() -> [String: Any] {
var dict: [String: Any] = [
"problems": problems.map { $0.asDictionary() },
"took": took
]
if let checked = self.checked {
dict["checked"] = checked
}
return dict
}
}
public struct ValidationProblem: DictionaryRepresentable {
let name: String
let count: Int
func asDictionary() -> [String: Any] {
return ["name": name, "count": count]
}
}
public class StatsSession {
var took: Int64 = 0
var when: Timestamp?
private var startUptimeNanos: UInt64?
public func start(when: UInt64 = Date.now()) {
self.when = when
self.startUptimeNanos = DispatchTime.now().uptimeNanoseconds
}
public func hasStarted() -> Bool {
return startUptimeNanos != nil
}
public func end() -> Self {
guard let startUptime = startUptimeNanos else {
assertionFailure("SyncOperationStats called end without first calling start!")
return self
}
// Casting to Int64 should be safe since we're using uptime since boot in both cases.
// Convert to milliseconds as stated in the sync ping format
took = (Int64(DispatchTime.now().uptimeNanoseconds) - Int64(startUptime)) / 1000000
return self
}
}
// Stats about a single engine's sync.
public class SyncEngineStatsSession: StatsSession {
public var validationStats: ValidationStats?
private(set) var uploadStats: SyncUploadStats
private(set) var downloadStats: SyncDownloadStats
public init(collection: String) {
self.uploadStats = SyncUploadStats()
self.downloadStats = SyncDownloadStats()
}
public func recordDownload(stats: SyncDownloadStats) {
self.downloadStats.applied += stats.applied
self.downloadStats.succeeded += stats.succeeded
self.downloadStats.failed += stats.failed
self.downloadStats.newFailed += stats.newFailed
self.downloadStats.reconciled += stats.reconciled
}
public func recordUpload(stats: SyncUploadStats) {
self.uploadStats.sent += stats.sent
self.uploadStats.sentFailed += stats.sentFailed
}
}
extension SyncEngineStatsSession: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
var dict: [String: Any] = [
"took": took,
]
if downloadStats.hasData() {
dict["incoming"] = downloadStats.asDictionary()
}
if uploadStats.hasData() {
dict["outgoing"] = uploadStats.asDictionary()
}
if let validation = self.validationStats, validation.hasData() {
dict["validation"] = validation.asDictionary()
}
return dict
}
}
// Stats and metadata for a sync operation.
public class SyncOperationStatsSession: StatsSession {
public let why: SyncReason
public var uid: String?
public var deviceID: String?
fileprivate let didLogin: Bool
public init(why: SyncReason, uid: String, deviceID: String?) {
self.why = why
self.uid = uid
self.deviceID = deviceID
self.didLogin = (why == .didLogin)
}
}
extension SyncOperationStatsSession: DictionaryRepresentable {
func asDictionary() -> [String: Any] {
let whenValue = when ?? 0
return [
"when": whenValue,
"took": took,
"didLogin": didLogin,
"why": why.rawValue
]
}
}
public enum SyncPingError: MaybeErrorType {
case failedToRestoreScratchpad
public var description: String {
switch self {
case .failedToRestoreScratchpad: return "Failed to restore Scratchpad from prefs"
}
}
}
public enum SyncPingFailureReasonName: String {
case httpError = "httperror"
case unexpectedError = "unexpectederror"
case sqlError = "sqlerror"
case otherError = "othererror"
}
public protocol SyncPingFailureFormattable {
var failureReasonName: SyncPingFailureReasonName { get }
}
public struct SyncPing: SyncTelemetryPing {
public private(set) var payload: JSON
public static func from(result: SyncOperationResult,
remoteClientsAndTabs: RemoteClientsAndTabs,
prefs: Prefs,
why: SyncPingReason) -> Deferred<Maybe<SyncPing>> {
// Grab our token so we can use the hashed_fxa_uid and clientGUID from our scratchpad for
// our ping's identifiers
return RustFirefoxAccounts.shared.syncAuthState.token(Date.now(), canBeExpired: false) >>== { (token, kSync) in
let scratchpadPrefs = prefs.branch("sync.scratchpad")
guard let scratchpad = Scratchpad.restoreFromPrefs(scratchpadPrefs, syncKeyBundle: KeyBundle.fromKSync(kSync)) else {
return deferMaybe(SyncPingError.failedToRestoreScratchpad)
}
var ping: [String: Any] = pingCommonData(
why: why,
hashedUID: token.hashedFxAUID,
hashedDeviceID: (scratchpad.clientGUID + token.hashedFxAUID).sha256.hexEncodedString
)
// TODO: We don't cache our sync pings so if it fails, it fails. Once we add
// some kind of caching we'll want to make sure we don't dump the events if
// the ping has failed.
let pickledEvents = prefs.arrayForKey(PrefKeySyncEvents) as? [Data] ?? []
let events = pickledEvents.compactMap(Event.unpickle).map { $0.toArray() }
ping["events"] = events
prefs.setObject(nil, forKey: PrefKeySyncEvents)
return dictionaryFrom(result: result, storage: remoteClientsAndTabs, token: token) >>== { syncDict in
// TODO: Split the sync ping metadata from storing a single sync.
ping["syncs"] = [syncDict]
return deferMaybe(SyncPing(payload: JSON(ping)))
}
}
}
static func pingCommonData(why: SyncPingReason, hashedUID: String, hashedDeviceID: String) -> [String: Any] {
return [
"version": 1,
"why": why.rawValue,
"uid": hashedUID,
"deviceID": hashedDeviceID,
"os": [
"name": "iOS",
"version": UIDevice.current.systemVersion,
"locale": Locale.current.identifier
]
]
}
// Generates a single sync ping payload that is stored in the 'syncs' list in the sync ping.
private static func dictionaryFrom(result: SyncOperationResult,
storage: RemoteClientsAndTabs,
token: TokenServerToken) -> Deferred<Maybe<[String: Any]>> {
return connectedDevices(fromStorage: storage, token: token) >>== { devices in
guard let stats = result.stats else {
return deferMaybe([String: Any]())
}
var dict = stats.asDictionary()
if let engineResults = result.engineResults.successValue {
dict["engines"] = SyncPing.enginePingDataFrom(engineResults: engineResults)
} else if let failure = result.engineResults.failureValue {
var errorName: SyncPingFailureReasonName
if let formattableFailure = failure as? SyncPingFailureFormattable {
errorName = formattableFailure.failureReasonName
} else {
errorName = .unexpectedError
}
dict["failureReason"] = [
"name": errorName.rawValue,
"error": "\(type(of: failure))",
]
}
dict["devices"] = devices
return deferMaybe(dict)
}
}
// Returns a list of connected devices formatted for use in the 'devices' property in the sync ping.
private static func connectedDevices(fromStorage storage: RemoteClientsAndTabs,
token: TokenServerToken) -> Deferred<Maybe<[[String: Any]]>> {
func dictionaryFrom(client: RemoteClient) -> [String: Any]? {
var device = [String: Any]()
if let os = client.os {
device["os"] = os
}
if let version = client.version {
device["version"] = version
}
if let guid = client.guid {
device["id"] = (guid + token.hashedFxAUID).sha256.hexEncodedString
}
return device
}
return storage.getClients() >>== { deferMaybe($0.compactMap(dictionaryFrom)) }
}
private static func enginePingDataFrom(engineResults: EngineResults) -> [[String: Any]] {
return engineResults.map { result in
let (name, status) = result
var engine: [String: Any] = [
"name": name
]
// For complete/partial results, extract out the collect stats
// and add it to engine information. For syncs that were not able to
// start, return why and a reason.
switch status {
case .completed(let stats):
engine.merge(with: stats.asDictionary())
case .partial(let stats):
engine.merge(with: stats.asDictionary())
case .notStarted(let reason):
engine.merge(with: [
"status": reason.telemetryId
])
}
return engine
}
}
}
| mpl-2.0 | 3b3562244f2f3c4fc3c511609a63f131 | 31.195122 | 129 | 0.597054 | 4.90099 | false | false | false | false |
mike-neko/Kanagata | Kanagata/JSONData.swift | 1 | 19815 | ////////////////////////////////////////////////////////////////////////////////////
//
// JSONData.swift
// Kanagata
//
// MIT License
//
// Copyright (c) 2018 mike-neko
//
// 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
/// JSONのデータクラス
public class JSONData {
public typealias Key = String
typealias ObjectDictionary = [Key: JSONData]
typealias ObjectDefine = (Key, ValueType)
public typealias ExceptionType = JSON.ExceptionType
// MARK: - Property
/// キー
public let key: Key
var data: Value // 値
let type: ValueType // フォーマット
/// `null`が入っていれば`true`、入っていなければ`false`。エラーの場合も`false`
public var isNull: Bool { return data.isNull }
/// データが存在すれば`true`、エラーデータであれば`false`
public var exists: Bool { return data.exists }
private var objectDefine: ObjectDefine { return (key, type) }
/// JSONデータの配列を取得する。`array`であれば`JSONData`の配列を取得し、それ以外は空の配列が取得される
public var array: [JSONData] {
guard case .array(let list) = data else { return [] }
return list
}
// MARK: - Method
init(key: Key, data: Value, type: ValueType) {
self.key = key
self.data = data
self.type = type
}
/// objectから指定したキーのJSONデータを取得する
///
/// - Parameter key: 取得対象のキー
/// - returns: 指定したキーのデータ。キーが存在しない時は`ExceptionType.notFound`。objectでは無い時は`ExceptionType.notObject`
public subscript(key: Key) -> JSONData {
get {
if case .object(let objs) = data {
return objs[key] ?? JSONData(key: key,
data: .error(.notFound(parent: self, accessKey: key)), type: .forWrap)
}
return JSONData(key: key, data: .error(.notObject(data: self, accessKey: key)), type: .forWrap)
}
set {
guard case .object(var objs) = data else {
JSON.errorList.append(.notObject(data: self, accessKey: key))
return
}
guard let child = objs[key] else {
JSON.errorList.append(.notFound(parent: self, accessKey: key))
return
}
switch newValue.data {
case .assignment(let valueObj):
let newData: Value
if valueObj is NSNull && (newValue.type.canNullable || child.type.canNothing) {
newData = .null
} else if let val = Value(type: child.type, value: valueObj) {
newData = val
} else {
JSON.errorList.append(.typeUnmatch(key: objectDefine.0, type: objectDefine.1, value: newValue))
return
}
objs[key] = JSONData(key: child.key, data: newData, type: child.type)
data = .object(objs)
default:
JSON.errorList.append(.typeUnmatch(key: objectDefine.0, type: objectDefine.1, value: newValue))
return
}
}
}
/// objectから指定したキーのJSONデータを`String`型で取得する
///
/// - Parameters:
/// - key: 取得対象のキー
/// - value: 指定したキーでデータが取得できなかった場合のデフォルト値
/// - returns: 指定したキーのデータ。キーが存在しない、objectでは無い、または指定した`String`型ではなかった時はデフォルト値
public subscript(key: Key, default value: String) -> String {
return self[key].value(default: value)
}
/// objectから指定したキーのJSONデータを`Int`型で取得する
///
/// - Parameters:
/// - key: 取得対象のキー
/// - value: 指定したキーでデータが取得できなかった場合のデフォルト値
/// - returns: 指定したキーのデータ。キーが存在しない、objectでは無い、または指定した`Int`型ではなかった時はデフォルト値
public subscript(key: Key, default value: Int) -> Int {
return self[key].value(default: value)
}
/// objectから指定したキーのJSONデータを`Double`型で取得する
///
/// - Parameters:
/// - key: 取得対象のキー
/// - value: 指定したキーでデータが取得できなかった場合のデフォルト値
/// - returns: 指定したキーのデータ。キーが存在しない、objectでは無い、または指定した`Double`型ではなかった時はデフォルト値
public subscript(key: Key, default value: Double) -> Double {
return self[key].value(default: value)
}
/// objectから指定したキーのJSONデータを`Bool`型で取得する
///
/// - Parameters:
/// - key: 取得対象のキー
/// - value: 指定したキーでデータが取得できなかった場合のデフォルト値
/// - returns: 指定したキーのデータ。キーが存在しない、objectでは無い、または指定した`Bool`型ではなかった時はデフォルト値
public subscript(key: Key, default value: Bool) -> Bool {
return self[key].value(default: value)
}
/// arrayから指定したインデックスのJSONデータを取得する
///
/// - Parameter index: 取得対象のインデックス
/// - returns: 指定したインデックスのデータ。インデックスが存在しない時は`ExceptionType.outOfRange`。arrayでは無い時は`ExceptionType.notArray`
public subscript(index: Int) -> JSONData {
get {
if case .array(let arr) = data {
guard arr.indices.contains(index) else {
return JSONData(key: key, data: .error(.outOfRange(parent: self, index: index)), type: .forWrap)
}
return arr[index]
}
return JSONData(key: key, data: .error(.notArray(data: self)), type: .forWrap)
}
set {
guard case .array(var arr) = data else {
JSON.errorList.append(.notArray(data: self))
return
}
guard arr.indices.contains(index) else {
JSON.errorList.append(.outOfRange(parent: self, index: index))
return
}
let element = arr[index]
switch newValue.data {
case .assignment(let valueObj):
let newData: Value
if valueObj is NSNull && (newValue.type.canNullable || element.type.canNothing) {
newData = .null
} else if let val = Value(type: element.type, value: valueObj) {
newData = val
} else {
JSON.errorList.append(.typeUnmatch(key: objectDefine.0, type: objectDefine.1, value: newValue))
return
}
arr[index] = JSONData(key: element.key, data: newData, type: element.type)
data = .array(arr)
default:
JSON.errorList.append(.typeUnmatch(key: objectDefine.0, type: objectDefine.1, value: newValue))
return
}
}
}
/// arrayから指定したインデックスのJSONデータを`String`型で取得する
///
/// - Parameters:
/// - index: 取得対象のインデックス
/// - value: 指定したインデックスでデータが取得できなかった場合のデフォルト値
/// - returns: 指定したインデックスのデータ。インデックスが存在しない、arrayでは無い、または指定した`String`型ではなかった時はデフォルト値
public subscript(index: Int, default value: String) -> String {
return self[index].value(default: value)
}
/// arrayから指定したインデックスのJSONデータを`Int`型で取得する
///
/// - Parameters:
/// - index: 取得対象のインデックス
/// - value: 指定したインデックスでデータが取得できなかった場合のデフォルト値
/// - returns: 指定したインデックスのデータ。インデックスが存在しない、arrayでは無い、または指定した`Int`型ではなかった時はデフォルト値
public subscript(index: Int, default value: Int) -> Int {
return self[index].value(default: value)
}
/// arrayから指定したインデックスのJSONデータを`Double`型で取得する
///
/// - Parameters:
/// - index: 取得対象のインデックス
/// - value: 指定したインデックスでデータが取得できなかった場合のデフォルト値
/// - returns: 指定したインデックスのデータ。インデックスが存在しない、arrayでは無い、または指定した`Double`型ではなかった時はデフォルト値
public subscript(index: Int, default value: Double) -> Double {
return self[index].value(default: value)
}
/// arrayから指定したインデックスのJSONデータを`Bool`型で取得する
///
/// - Parameters:
/// - index: 取得対象のインデックス
/// - value: 指定したインデックスでデータが取得できなかった場合のデフォルト値
/// - returns: 指定したインデックスのデータ。インデックスが存在しない、arrayでは無い、または指定した`Bool`型ではなかった時はデフォルト値
public subscript(index: Int, default value: Bool) -> Bool {
return self[index].value(default: value)
}
/// JSONデータからStringを取得する
///
/// - throws: `JSON.ExceptionType.typeUnmatch` : 型が一致しなかった場合
/// - returns: Stringの取得データ
public func stringValue() throws -> String {
switch data {
case .string(let val): return val
case .error(let error): throw error
default: throw ExceptionType.typeUnmatch(key: objectDefine.0,
type: objectDefine.1, value: (try? data.toAny()) as Any)
}
}
/// JSONデータからIntを取得する
///
/// - throws: `JSON.ExceptionType.typeUnmatch` : 型が一致しなかった場合
/// - returns: Intの取得データ
public func intValue() throws -> Int {
switch data {
case .int(let val): return val
case .error(let error): throw error
default: throw ExceptionType.typeUnmatch(key: objectDefine.0,
type: objectDefine.1, value: (try? data.toAny()) as Any)
}
}
/// JSONデータからDoubleを取得する
///
/// - throws: `JSON.ExceptionType.typeUnmatch` : 型が一致しなかった場合
/// - returns: Doubleの取得データ
public func doubleValue() throws -> Double {
switch data {
case .double(let val): return val
case .error(let error): throw error
default: throw ExceptionType.typeUnmatch(key: objectDefine.0,
type: objectDefine.1, value: (try? data.toAny()) as Any)
}
}
/// JSONデータからBoolを取得する
///
/// - throws: `JSON.ExceptionType.typeUnmatch` : 型が一致しなかった場合
/// - returns: Boolの取得データ
public func boolValue() throws -> Bool {
switch data {
case .bool(let val): return val
case .error(let error): throw error
default: throw ExceptionType.typeUnmatch(key: objectDefine.0,
type: objectDefine.1, value: (try? data.toAny()) as Any)
}
}
/// JSONデータからStringを取得する。型が違うなどで取得に失敗した場合は指定されたデフォルト値を返す
///
/// - parameter default: 取得失敗時に返すデフォルト値
/// - returns: Stringの取得データ。存在しない場合はデフォルト値
public func value(default: String = JSON.Default.stringValue) -> String { return String(json: self) ?? `default` }
/// JSONデータからIntを取得する。型が違うなどで取得に失敗した場合は指定されたデフォルト値を返す
///
/// - parameter default: 取得失敗時に返すデフォルト値
/// - returns: Intの取得データ。存在しない場合はデフォルト値
public func value(default: Int = JSON.Default.intValue) -> Int { return Int(json: self) ?? `default` }
/// JSONデータからDoubleを取得する。型が違うなどで取得に失敗した場合は指定されたデフォルト値を返す
///
/// - parameter default: 取得失敗時に返すデフォルト値
/// - returns: Doubleの取得データ。存在しない場合はデフォルト値
public func value(default: Double = JSON.Default.doubleValue) -> Double { return Double(json: self) ?? `default` }
/// JSONデータからBoolを取得する。型が違うなどで取得に失敗した場合は指定されたデフォルト値を返す
///
/// - parameter default: 取得失敗時に返すデフォルト値
/// - returns: Boolの取得データ。存在しない場合はデフォルト値
public func value(default: Bool = JSON.Default.boolValue) -> Bool { return Bool(json: self) ?? `default` }
func appended(define: ObjectDefine, newData: Any) -> Value? {
guard case .object(var objs) = data else {
JSON.errorList.append(.notObject(data: self, accessKey: define.0))
return nil
}
var value: Value
if let val = Value(type: define.1, value: newData) {
value = val
} else if newData is NSNull && define.1.canNothing {
value = .null
} else {
JSON.errorList.append(.typeUnmatch(key: define.0, type: define.1, value: newData))
return nil
}
objs[define.0] = JSONData(key: define.0, data: value, type: define.1)
return .object(objs)
}
func toAny() throws -> Any {
guard let data = try? data.toAny() else {
throw ExceptionType.includeErrorData(data: self)
}
return data
}
/// JSONにobjectを追加する。データ内容が定義と一致しない場合は追加されない
///
/// - parameter key: 追加するobjectのキー名
/// - parameter type: 追加するobjectの値のタイプ
/// - parameter data: 追加するデータ
public func append(key: JSONData.Key, type: JSONData.ValueType, data: Any) {
if let val = appended(define: (key, type), newData: data) {
self.data = val
}
}
/// JSONにarrayを追加する。データ内容が定義と一致しない場合は追加されない
///
/// - parameter array: 追加する配列データ
public func append(array: [Any]) {
var arr = [JSONData]()
if case .array(let list) = self.data {
arr = list
}
switch type {
case .array(let def), .arrayOrNull(let def), .arrayOrNothing(let def):
for ele in array as [Any] {
let val: Value
if let item = Value(type: def, value: ele) {
val = item
} else if ele is NSNull && def.canNothing {
val = .null
} else {
JSON.errorList.append(.typeUnmatch(key: objectDefine.0, type: objectDefine.1, value: ele))
return
}
arr += [JSONData(key: "", data: val, type: def)]
}
self.data = .array(arr)
default:
JSON.errorList.append(.notArray(data: self))
return
}
}
func removed(value: Value, forKey: Key) -> Value? {
guard case .object(var objs) = value else {
JSON.errorList.append(.notObject(data: self, accessKey: forKey))
return nil
}
guard objs.removeValue(forKey: forKey) != nil else {
JSON.errorList.append(.notFound(parent: self, accessKey: forKey))
return nil
}
return .object(objs)
}
/// JSONから指定したキーのobjectを削除する。指定したキーが存在しない場合は何もされない
///
/// - parameter forKey: 削除したいobjectのキー
public func removeValue(forKey: Key) {
guard let newData = removed(value: data, forKey: forKey) else { return }
data = newData
}
/// arrayから指定したインデックスのデータを削除する。指定したインデックスが存在しない場合は何もされない
///
/// - parameter at: arrayから削除したいデータのインデックス
@discardableResult
public func remove(at: Int) -> JSONData? {
guard case .array(var arr) = data else {
JSON.errorList.append(.notArray(data: self))
return nil
}
guard arr.indices.contains(at) else {
JSON.errorList.append(.outOfRange(parent: self, index: at))
return nil
}
let child = arr.remove(at: at)
data = .array(arr)
return child
}
/// JSONのobjectを全て削除する
public func removeAll() {
switch data {
case .object(var objs):
objs.removeAll()
data = .object(objs)
case .array(var arr):
arr.removeAll()
data = .array(arr)
default:
JSON.errorList.append(.notSupportOperation(data: self))
}
}
// MARK: - Static
/// 値からJSONデータを作成する。JSONデータの内容の設定時に利用
///
/// - parameter value: 値
/// - returns: JSONデータ
public static func value(_ value: Any) -> JSONData {
return JSONData(key: "", data: .assignment(value), type: .forWrap)
}
/// `null`のJSONデータを作成する。JSONデータの内容の設定時に利用。読み取り専用
public static var null: JSONData {
return JSONData(key: "", data: .assignment(NSNull()), type: .forWrap)
}
}
| mit | 8dbd5d0f3f8cff466e517a265fde76ac | 35.068889 | 118 | 0.581788 | 4.382019 | false | false | false | false |
Miguel-Herrero/Swift | Poke-Search/Poke-Search/ViewController.swift | 1 | 5696 | //
// ViewController.swift
// Poke-Search
//
// Created by Miguel Herrero on 23/12/16.
// Copyright © 2016 Miguel Herrero. All rights reserved.
//
import UIKit
import MapKit
import GeoFire
import FirebaseDatabase
class ViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
fileprivate let locationManager = CLLocationManager()
var mapHasCenteredOnce = false
var geoFire: GeoFire!
var geoFireRef: FIRDatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
mapView.userTrackingMode = .follow
geoFireRef = FIRDatabase.database().reference()
geoFire = GeoFire(firebaseRef: geoFireRef)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
locationAuthStatus()
}
func createSighting(for location: CLLocation, with pokemonId: Int) {
geoFire.setLocation(location, forKey: "\(pokemonId)")
}
func showSightingsOnMap(location: CLLocation) {
let circleQuery = geoFire!.query(at: location, withRadius: 2)
_ = circleQuery?.observe(.keyEntered, with: { (key, location) in
if let key = key, let location = location {
let annotation = PokeAnnotation(coordinate: location.coordinate, pokemonNumber: Int(key)!)
self.mapView.addAnnotation(annotation)
}
})
}
@IBAction func spotRandomPokemon(_ sender: UIButton) {
let location = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude)
let rand = arc4random_uniform(151) + 1
createSighting(for: location, with: Int(rand))
}
}
extension ViewController: MKMapViewDelegate, CLLocationManagerDelegate {
fileprivate func locationAuthStatus() {
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
mapView.showsUserLocation = true
} else {
locationManager.requestWhenInUseAuthorization()
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if (status == .authorizedWhenInUse) {
mapView.showsUserLocation = true
}
}
fileprivate func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 2000, 2000)
mapView.setRegion(coordinateRegion, animated: true)
}
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
if let location = userLocation.location {
if !mapHasCenteredOnce {
centerMapOnLocation(location: location)
mapHasCenteredOnce = true
}
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var annotationView: MKAnnotationView?
let annotationIdentifier = "Pokemon"
if annotation.isKind(of: MKUserLocation.self) {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "User")
annotationView?.image = UIImage(named: "ash")
} else if let dequedAnnotation = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
annotationView = dequedAnnotation
annotationView?.annotation = annotation
} else {
let annotation = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
annotation.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
annotationView = annotation
}
if let annotationView = annotationView, let annotation = annotation as? PokeAnnotation {
annotationView.canShowCallout = true
annotationView.image = UIImage(named: "\(annotation.pokemonNumber)")
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
button.setImage(UIImage(named: "map"), for: .normal)
annotationView.rightCalloutAccessoryView = button
}
return annotationView
}
func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
let location = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude)
showSightingsOnMap(location: location)
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if let annotation = view.annotation as? PokeAnnotation {
let place = MKPlacemark(coordinate: annotation.coordinate)
let destination = MKMapItem(placemark: place)
destination.name = "Pokemon Sighting"
let regionDistance: CLLocationDistance = 1000
let regionSpan = MKCoordinateRegionMakeWithDistance(annotation.coordinate, regionDistance, regionDistance)
let options = [MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span),
MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving] as [String : Any]
MKMapItem.openMaps(with: [destination], launchOptions: options)
}
}
}
| gpl-3.0 | cd10b557895615148436070f8065af5e | 37.221477 | 129 | 0.658999 | 5.913811 | false | false | false | false |
danielsanfr/hackatruck-apps-project | HACKATRUCK Apps/AppsSearchTableViewController.swift | 1 | 4085 | //
// AppsSearchTableViewController.swift
// HACKATRUCK Apps
//
// Created by Student on 3/9/17.
// Copyright © 2017 Daniel San. All rights reserved.
//
import UIKit
import Parse
class AppsSearchTableViewController: UITableViewController {
var apps = [App]()
var category: Category?
override func viewDidLoad() {
super.viewDidLoad()
let query = PFQuery(className: "App")
if let cat = category {
title = cat.name
query.whereKey("category", equalTo: cat)
}
query.includeKey("category").findObjectsInBackground { (apps, error) in
if let e = error {
AlertHelper.showAlert(self, title: "Ocorreu um erro", message: e.localizedDescription, confirmText: "OK")
return
}
if let appList = apps as? [App] {
self.apps = appList
self.tableView.reloadData()
}
}
// 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 numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return apps.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "appListCellIdentifier", for: indexPath)
if let appCell = cell as? AppTableViewCell {
appCell.bind(apps[indexPath.row])
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showAppDetailIdentifier" {
if let viewController = segue.destination as? AppDetailViewController {
if let row = self.tableView.indexPathForSelectedRow?.row {
viewController.app = apps[row]
}
}
}
}
}
| unlicense | 595b2aebf5f596f2094c18b2383ba6b6 | 33.610169 | 137 | 0.628795 | 5.331593 | false | false | false | false |
ECP-CANDLE/Supervisor | workflows/cp1/swift/workflow.swift | 1 | 11970 |
/*
XCORR SWIFT
Main cross-correlation workflow
*/
import assert;
import files;
import io;
import python;
import unix;
import sys;
import string;
import EQR;
import location;
import math;
string FRAMEWORK = "keras";
string xcorr_root = getenv("XCORR_ROOT");
string preprocess_rnaseq = getenv("PREPROP_RNASEQ");
string emews_root = getenv("EMEWS_PROJECT_ROOT");
string turbine_output = getenv("TURBINE_OUTPUT");
printf("TURBINE_OUTPUT: " + turbine_output);
string db_file = argv("db_file");
string cache_dir = argv("cache_dir");
string xcorr_data_dir = argv("xcorr_data_dir");
string gpus = argv("gpus", "");
string resident_work_ranks = getenv("RESIDENT_WORK_RANKS");
string r_ranks[] = split(resident_work_ranks,",");
int propose_points = toint(argv("pp", "3"));
int max_budget = toint(argv("mb", "110"));
int max_iterations = toint(argv("it", "5"));
int design_size = toint(argv("ds", "10"));
string param_set = argv("param_set_file");
string exp_id = argv("exp_id");
int benchmark_timeout = toint(argv("benchmark_timeout", "-1"));
string restart_file = argv("restart_file", "DISABLED");
string r_file = argv("r_file", "mlrMBO1.R");
string restart_number = argv("restart_number", "1");
string site = argv("site");
if (restart_file != "DISABLED") {
assert(restart_number != "1",
"If you are restarting, you must increment restart_number!");
}
// for subset of studies, comment '#' out study name in studiesN.txt
string studies1[] = file_lines(input(emews_root + "/data/studies1.txt"));
string studies2[] = file_lines(input(emews_root + "/data/studies2.txt"));
string rna_seq_data = argv("rna_seq_data"); //"%s/test_data/combined_rnaseq_data_lincs1000_%s.bz2" % (xcorr_root, preprocess_rnaseq);
string drug_response_data = argv("drug_response_data"); //xcorr_root + "/test_data/rescaled_combined_single_drug_growth_100K";
int cutoffs[][] = [[2000, 1000]]; //,
// [100, 50],
// [400, 200],
// [200, 50],
// [400, 50],
// [400, 100]];
string update_param_template =
"""
# template vals: param string, train_source, preprocess_rnaseq, gpus, feature_file, cache_dir, run_dir
import json
params = json.loads('%s')
# --cell_feature_subset_path $FEATURES --train_sources $STUDY1 --preprocess_rnaseq $PREPROP_RNASEQ
params['train_sources'] = '%s'
params['preprocess_rnaseq'] = '%s'
gpus = '%s'
if len(gpus) > 0:
params['gpus'] = gpus.replace(',', ' ')
cell_feature_subset_path = '%s'
if len(cell_feature_subset_path) > 0:
params['cell_feature_subset_path'] = cell_feature_subset_path
# GDSC_NCI60_1600_800_features.txt
# GDSC_NCI60_2000_1000.h5
import os
ex_data_f = os.path.basename(params['cell_feature_subset_path'])
idx = ex_data_f.rfind('_features')
ex_data_f = ex_data_f[:idx]
else:
ex_data_f = params['train_sources']
params['use_landmark_genes'] = True
cache_dir = '%s'
params['use_exported_data'] ='{}/{}.h5'.format(cache_dir, ex_data_f)
params['warmup_lr'] = True
params['reduce_lr'] = True
params['no_feature_source'] = True
params['no_response_source'] = True
params['save_path'] = '%s'
params['cp'] = True
params_json = json.dumps(params)
""";
string log_corr_template =
"""
from xcorr_db import xcorr_db, setup_db
global DB
DB = setup_db('%s')
feature_file = '%s'
if len(feature_file) > 0:
features = DB.scan_features_file(feature_file)
else:
# if no feature file, then use all the features
id_to_names, _ = DB.read_feature_names()
features = id_to_names.values()
study1 = '%s'
study2 = '%s'
if len(study2) == 0:
studies = [study1]
else:
studies = [study1, study2]
record_id = DB.insert_xcorr_record(studies=studies,
features=features,
cutoff_corr=%d, cutoff_xcorr=%d)
""";
(string hpo_id) insert_hpo(string xcorr_record_id)
{
hpo_template =
"""
from xcorr_db import xcorr_db, setup_db
global DB
DB = setup_db('%s')
hpo_id = DB.insert_hpo_record(%s)
""";
code = hpo_template % (db_file, xcorr_record_id);
hpo_id = python_persist(code, "str(hpo_id)");
}
(string run_id) insert_hpo_run(string hpo_id, string param_string, string run_directory)
{
run_template =
"""
from xcorr_db import xcorr_db, setup_db
global DB
DB = setup_db('%s')
run_id = DB.insert_hpo_run(%s, '%s', '%s')
""";
code = run_template % (db_file, hpo_id, param_string, run_directory);
run_id = python_persist(code, "str(run_id)");
}
(void o) update_hpo_run(string run_id, string result)
{
update_template =
"""
from xcorr_db import xcorr_db, setup_db
global DB
DB = setup_db('%s')
hpo_id = DB.update_hpo_run(%s, %s)
""";
code = update_template % (db_file, run_id, result);
python_persist(code, "'ignore'") =>
o = propagate();
}
(string record_id)
compute_feature_correlation(string study1, string study2,
int corr_cutoff, int xcorr_cutoff,
string features_file)
{
xcorr_template =
"""
rna_seq_data = '%s'
drug_response_data = '%s'
study1 = '%s'
study2 = '%s'
correlation_cutoff = %d
cross_correlation_cutoff = %d
features_file = '%s'
import uno_xcorr
if uno_xcorr.gene_df is None:
uno_xcorr.init_uno_xcorr(rna_seq_data, drug_response_data)
uno_xcorr.coxen_feature_selection(study1, study2,
correlation_cutoff,
cross_correlation_cutoff,
output_file=features_file)
""";
log_code = log_corr_template % (db_file, features_file, study1, study2,
corr_cutoff, xcorr_cutoff);
// xcorr_code = xcorr_template % (rna_seq_data, drug_response_data,
// study1, study2,
// corr_cutoff, xcorr_cutoff,
// features_file);
// python_persist(xcorr_code) =>
record_id = python_persist(log_code, "str(record_id)");
}
(void v) loop(string hpo_db_id, int init_prio, int modulo_prio, int mlr_instance_id, location ME, string feature_file,
string train_source)
{
for (boolean b = true, int iteration = 1;
b;
b=c, iteration = iteration + 1)
{
string params = EQR_get(ME);
boolean c;
if (params == "DONE")
{
string finals = EQR_get(ME);
string fname = "%s/%i_final_res.Rds" % (turbine_output, mlr_instance_id);
printf("See results in %s", fname) =>
// printf("Results: %s", finals) =>
v = propagate(finals) =>
c = false;
}
else if (params == "EQR_ABORT")
{
printf("EQR aborted: see output for R error") =>
string why = EQR_get(ME);
printf("%s", why) =>
// v = propagate(why) =>
c = false;
}
else
{
int prio = init_prio - iteration * modulo_prio;
string param_array[] = split(params, ";");
string results[];
string hpo_runs[];
foreach param, sample in param_array
{
string run_id = "%00i_%00i_%000i_%0000i" %
(mlr_instance_id, restart_number,iteration,sample);
string run_dir = "%s/run/%s" % (turbine_output, run_id);
int idx = (iteration * size(param_array)) + sample;
param_code = update_param_template %
(param, train_source, preprocess_rnaseq,
gpus, feature_file, cache_dir, run_dir);
string updated_param = python_persist(param_code, "params_json");
// TODO DB: insert updated_param with mlr_instance_id and record
//printf("Updated Params: %s", updated_param);
//printf("XXX %s: %i", feature_file, prio);
//string run_db_id = insert_hpo_run(hpo_db_id, updated_param, run_dir) =>
string result = obj_prio(updated_param, run_id, prio);
//result = "0.234";
hpo_runs[sample] = "%i|%s|%s|%s|%f|%s" % (idx, hpo_db_id, updated_param, run_dir, clock(), result);
if (result == "inf") {
results[sample] = "999999999";
} else {
results[sample] = result;
}
// update_hpo_run(run_db_id, results[j]);
// TODO DB: insert result with record_id
}
string out_string = join(hpo_runs,"\n");
fname = "%s/hpo_log/%00i_%00i_hpo_runs.txt" %
(turbine_output, mlr_instance_id, iteration);
file out <fname> = write(out_string);
string result = join(results, ";");
// printf(result);
EQR_put(ME, result) => c = true;
}
}
}
// These must agree with the arguments to the objective function in mlrMBO.R,
// except param.set.file is removed and processed by the mlrMBO.R algorithm wrapper.
string algo_params_template =
"""
param.set.file='%s',
max.budget = %d,
max.iterations = %d,
design.size=%d,
propose.points=%d,
restart.file = '%s'
""";
// (void o) start(int ME_rank, string record_id, string feature_file, string study1) {
// printf("starting %s, %s, %s on %i", record_id, feature_file, study1, ME_rank) =>
// o = propagate();
// }
(int done) start(int init_prio, int modulo_prio, int ME_rank, string record_id, string feature_file, string study1) {
location ME = locationFromRank(ME_rank);
int mlr_instance_id = abs_integer(init_prio);
// algo_params is the string of parameters used to initialize the
// R algorithm. We pass these as R code: a comma separated string
// of variable=value assignments.
string algo_params = algo_params_template %
(param_set, max_budget, max_iterations, design_size,
propose_points, restart_file);
// DB: insert algo params with mlr_instance_id
string algorithm = emews_root+"/../common/R/"+r_file;
string hpo_db_id = insert_hpo(record_id) =>
EQR_init_script(ME, algorithm) =>
EQR_get(ME) =>
EQR_put(ME, algo_params) =>
loop(hpo_db_id, init_prio, modulo_prio, mlr_instance_id, ME, feature_file, study1) => {
EQR_stop(ME) =>
EQR_delete_R(ME);
done = 1;
}
}
(int keys[]) sort_keys(string params[][]) {
sort_code =
"""
key_string = '%s'
keys = [int(x) for x in key_string.split(',')]
keys.sort()
result = ",".join([str(x) for x in keys])
""";
string k[] = keys_string(params);
string code = sort_code % (join(k, ","));
result = python_persist(code, "result");
foreach val, i in split(result, ",")
{
keys[i] = string2int(val);
}
}
main() {
string params[][];
foreach study1, i in studies1
{
foreach study2 in studies2
{
if (study1 != study2)
{
foreach cutoff in cutoffs
{
printf("Study1: %s, Study2: %s, cc: %d, ccc: %d",
study1, study2, cutoff[0], cutoff[1]);
fname = "%s/%s_%s_%d_%d_features.txt" %
(xcorr_data_dir, study1, study2, cutoff[0], cutoff[1]);
printf(fname);
string record_id = compute_feature_correlation(study1, study2, cutoff[0], cutoff[1], fname);
int h = string2int(record_id);
params[h] = [record_id, fname, study1];
}
}
}
// for each of the studies, run against full features, no xcorr
string log_code = log_corr_template % (db_file, "", study1, "", -1, -1);
string record_id = python_persist(log_code, "str(record_id)");
// give full features key value guaranteed to be lower than the record_ids
// of the xcorr studies
params[-(i + 1)] = [record_id, "", study1];
}
int ME_ranks[];
foreach r_rank, i in r_ranks
{
ME_ranks[i] = toint(r_rank);
}
printf("size(ME_ranks): %i", size(ME_ranks));
printf("size(params): %i", size(params));
assert(size(ME_ranks) == size(params), "Number of ME ranks must equal number of xcorrs");
int keys[] = sort_keys(params);
int modulo_prio = size(ME_ranks);
foreach idx, r in keys
{
string ps[] = params[idx];
int rank = ME_ranks[r];
// initial priority, modulo priority, rank, record_id, feature file name, study1 name
start(-(r + 1), modulo_prio, rank, ps[0], ps[1], ps[2]);
}
}
| mit | 4c2af37151ec565c0de82bab82bc8da7 | 28.925 | 133 | 0.60142 | 3.169182 | false | false | false | false |
austinzheng/swift-compiler-crashes | fixed/00041-szone-malloc-should-clear.swift | 12 | 408 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// http://www.openradar.me/18176436
protocol A {
typealias E
}
struct B<T : A> {
let h: T
let i: T.E
}
protocol C {
typealias F
func g<T where T.E == F>(f: B<T>)
}
struct D : C {
typealias F = Int
func g<T where T.E == F>(f: B<T>) {
}
}
| mit | 0f8aabe1a59d4ce566a88327d00612bf | 19.4 | 87 | 0.607843 | 3.022222 | false | false | false | false |
immanuel/radio-scanner | RadioScanner/PlaylistTableViewController.swift | 1 | 2952 | //
// PlaylistTableViewController.swift
// RadioScanner
//
// Created by Immanuel Thomas on 9/23/16.
// Copyright © 2016 Immanuel Thomas. All rights reserved.
//
import UIKit
class PlaylistTableViewController: UITableViewController, UINavigationControllerDelegate {
var playlists = [SPTPartialPlaylist]()
var selectedPlaylist : SPTPartialPlaylist?
override func viewDidLoad() {
super.viewDidLoad()
// 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()
navigationController?.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return playlists.count
}
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
if let controller = viewController as? StationTableViewController {
controller.selectedPlaylist = selectedPlaylist
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "PlaylistTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! PlaylistTableViewCell
// Configure the cell...
let playlist = playlists[indexPath.row]
cell.PlaylistName.text = playlist.name
// TODO: Checkmark the current selected playlist
/*
if (some condition to initially checkmark a row)
cell.accessoryType = .Checkmark
tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.Bottom)
} else {
cell.accessoryType = .None
}
*/
return cell
}
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.accessoryType = .None
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
cell.accessoryType = .Checkmark
selectedPlaylist = playlists[indexPath.row]
}
}
}
| mit | d1ed99e59593856300e1d18a56a1b6d3 | 31.788889 | 150 | 0.683836 | 6.010183 | false | false | false | false |
everald/JetPack | Sources/Measures/Angle.swift | 2 | 1523 | private let degreesPerRadian = 180.0 / .pi
private let radiansPerDegree = .pi / 180.0
public struct Angle: Measure {
public static let name = MeasuresStrings.Measure.angle
public static let rawUnit = AngleUnit.degrees
public var rawValue: Double
public init(_ value: Double, unit: AngleUnit) {
precondition(!value.isNaN, "Value must not be NaN.")
switch unit {
case .degrees: rawValue = value
case .radians: rawValue = value * degreesPerRadian
}
}
public init(degrees: Double) {
self.init(degrees, unit: .degrees)
}
public init(radians: Double) {
self.init(radians, unit: .radians)
}
public init(rawValue: Double) {
self.rawValue = rawValue
}
public var degrees: Double {
return rawValue
}
public var radians: Double {
return degrees * radiansPerDegree
}
public func valueInUnit(_ unit: AngleUnit) -> Double {
switch unit {
case .degrees: return degrees
case .radians: return radians
}
}
}
public enum AngleUnit: Unit {
case degrees
case radians
}
extension AngleUnit {
public var abbreviation: String {
switch self {
case .degrees: return MeasuresStrings.Unit.Degree.abbreviation
case .radians: return MeasuresStrings.Unit.Radian.abbreviation
}
}
public var name: PluralizedString {
switch self {
case .degrees: return MeasuresStrings.Unit.Degree.name
case .radians: return MeasuresStrings.Unit.Radian.name
}
}
public var symbol: String? {
switch self {
case .degrees: return "°"
case .radians: return "㎭"
}
}
}
| mit | 578ab15d166802cc83af4e7496e71843 | 16.078652 | 64 | 0.705921 | 3.438914 | false | false | false | false |
citrusbyte/Healthy-Baby | M2XDemo/PreKickViewController.swift | 1 | 1924 | //
// PreKickViewController.swift
// M2XDemo
//
// Created by Luis Floreani on 12/9/14.
// Copyright (c) 2014 citrusbyte.com. All rights reserved.
//
import Foundation
import Foundation
class PreKickViewController : HBBaseViewController, AddKickViewControllerDelegate {
@IBOutlet var startCountingButton: UIButton!
@IBOutlet var startCountingBackgroundView: UIView!
@IBOutlet var header1Label: UILabel!
@IBOutlet var header2Label: UILabel!
var deviceId: String?
weak var delegate: AddKickViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
assert(deviceId != nil, "deviceId can't be nil")
header1Label.textColor = Colors.grayColor
header2Label.textColor = Colors.lightGrayColor
startCountingBackgroundView.layer.cornerRadius = startCountingBackgroundView.bounds.size.width/2
startCountingButton.titleLabel!.textAlignment = .Center
startCountingButton.setTitleColor(Colors.kickColor, forState:.Normal)
startCountingButton.titleLabel!.font = UIFont(name:"Proxima Nova", size:26.0)
view.backgroundColor = Colors.backgroundColor
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let dc = segue.destinationViewController as? AddKickViewController {
dc.deviceId = deviceId
dc.delegate = self
}
}
func needsKicksRefresh() {
self.delegate?.needsKicksRefresh()
}
@IBAction func touchDown(sender: AnyObject?) {
startCountingBackgroundView.backgroundColor = UIColor.lightGrayColor();
}
@IBAction func touchUp(sender: AnyObject?) {
startCountingBackgroundView.backgroundColor = UIColor.whiteColor();
}
@IBAction func dismissFromSegue(segue: UIStoryboardSegue) {
dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | 2a691d02b5639554e73f9d1c8f4f1d78 | 31.066667 | 104 | 0.704782 | 4.946015 | false | false | false | false |
Tobiaswk/XLForm | Examples/Swift/SwiftExample/Others/CustomCells/XLFormCustomCell.swift | 3 | 2481 | //
// XLFormCustomCell.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.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.
let XLFormRowDescriptorTypeCustom = "XLFormRowDescriptorTypeCustom"
class XLFormCustomCell : XLFormBaseCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func configure() {
super.configure()
}
override func update() {
super.update()
// override
if let string = rowDescriptor?.value as? String {
textLabel?.text = string
}
else {
textLabel?.text = "Am a custom cell, select me!"
}
}
override func formDescriptorCellDidSelected(withForm controller: XLFormViewController!) {
// custom code here
// i.e new behaviour when cell has been selected
if let string = rowDescriptor?.value as? String , string == "Am a custom cell, select me!" {
self.rowDescriptor?.value = string
}
else {
self.rowDescriptor?.value = "I can do any custom behaviour..."
}
update()
controller.tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
}
}
| mit | e53f5d011b3d0eb47f7b06fe766b1ae1 | 36.029851 | 100 | 0.680774 | 4.725714 | false | false | false | false |
laszlokorte/reform-swift | ReformMath/ReformMath/LineSegment2d.swift | 1 | 557 | //
// LineSegment2d.swift
// ReformMath
//
// Created by Laszlo Korte on 21.09.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
public struct LineSegment2d : Equatable {
public let from: Vec2d
public let to: Vec2d
public init(from: Vec2d, to: Vec2d) {
self.from = from
self.to = to
}
}
public func ==(lhs: LineSegment2d, rhs: LineSegment2d) -> Bool {
return lhs.from == rhs.from && lhs.to == rhs.to
}
extension LineSegment2d {
public var length : Double {
return (to-from).length
}
} | mit | 1fd49a407cd434d553390b1dc23dd026 | 19.62963 | 64 | 0.625899 | 3.289941 | false | false | false | false |
efeconirulez/be-focus | be #focused/TeacherVC.swift | 1 | 1893 | //
// TeacherVC.swift
// be #focused
//
// Created by Efe Helvaci on 08/02/2017.
// Copyright © 2017 efehelvaci. All rights reserved.
//
import UIKit
class TeacherVC: UIViewController {
@IBOutlet var timer: UIButton!
@IBOutlet var hourglass: UIImageView!
@IBOutlet var arrow: UIImageView!
@IBOutlet var informativeLabel: UILabel!
@IBOutlet var informativeLabel1: UILabel!
@IBOutlet var informativeLabel2: UILabel!
@IBOutlet var seed: UIImageView!
@IBOutlet var button: UIButton!
@IBOutlet var subview: UIView!
@IBOutlet var arrowTop: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 1.5, delay: 0, options: [.autoreverse, .repeat], animations: {
self.arrow.frame = CGRect(x: self.arrow.frame.origin.x, y: self.arrow.frame.origin.y+50, width: self.arrow.frame.size.width, height: self.arrow.frame.size.height)
}, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonClicked(_ sender: Any) {
if button.titleLabel!.text! == "Next" {
button.setTitle("Let's do it!", for: .normal)
timer.alpha = 0
hourglass.alpha = 0
arrow.alpha = 0
informativeLabel.alpha = 0
informativeLabel1.alpha = 1.0
informativeLabel2.alpha = 1.0
seed.alpha = 1.0
} else {
UserDefaults.standard.set(true, forKey: "didShowIntroduction")
dismiss(animated: false, completion: nil)
}
}
}
| apache-2.0 | 3109810cf07a859a47af23bb47ef6858 | 29.516129 | 174 | 0.621564 | 4.4 | false | false | false | false |
catloafsoft/AudioKit | Examples/iOS/AnalogSynthX/AnalogSynthX/SynthViewController.swift | 1 | 24391 | //
// SynthViewController.swift
// Swift Synth
//
// Created by Matthew Fecher on 1/8/16.
// Copyright © 2016 AudioKit. All rights reserved.
//
import UIKit
import AudioKit
class SynthViewController: UIViewController {
// *********************************************************
// MARK: - Instance Properties
// *********************************************************
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var octavePositionLabel: UILabel!
@IBOutlet weak var oscMixKnob: KnobMedium!
@IBOutlet weak var osc1SemitonesKnob: KnobMedium!
@IBOutlet weak var osc2SemitonesKnob: KnobMedium!
@IBOutlet weak var osc2DetuneKnob: KnobMedium!
@IBOutlet weak var lfoAmtKnob: KnobMedium!
@IBOutlet weak var lfoRateKnob: KnobMedium!
@IBOutlet weak var crushAmtKnob: KnobMedium!
@IBOutlet weak var delayTimeKnob: KnobMedium!
@IBOutlet weak var delayMixKnob: KnobMedium!
@IBOutlet weak var reverbAmtKnob: KnobMedium!
@IBOutlet weak var reverbMixKnob: KnobMedium!
@IBOutlet weak var cutoffKnob: KnobLarge!
@IBOutlet weak var rezKnob: KnobSmall!
@IBOutlet weak var subMixKnob: KnobSmall!
@IBOutlet weak var fmMixKnob: KnobSmall!
@IBOutlet weak var fmModKnob: KnobSmall!
@IBOutlet weak var noiseMixKnob: KnobSmall!
@IBOutlet weak var morphKnob: KnobSmall!
@IBOutlet weak var masterVolKnob: KnobSmall!
@IBOutlet weak var attackSlider: VerticalSlider!
@IBOutlet weak var decaySlider: VerticalSlider!
@IBOutlet weak var sustainSlider: VerticalSlider!
@IBOutlet weak var releaseSlider: VerticalSlider!
@IBOutlet weak var vco1Toggle: UIButton!
@IBOutlet weak var vco2Toggle: UIButton!
@IBOutlet weak var bitcrushToggle: UIButton!
@IBOutlet weak var filterToggle: UIButton!
@IBOutlet weak var delayToggle: UIButton!
@IBOutlet weak var reverbToggle: UIButton!
@IBOutlet weak var fattenToggle: UIButton!
@IBOutlet weak var holdToggle: UIButton!
@IBOutlet weak var monoToggle: UIButton!
@IBOutlet weak var audioPlot: AKOutputWaveformPlot!
@IBOutlet weak var plotToggle: UIButton!
enum ControlTag: Int {
case Cutoff = 101
case Rez = 102
case Vco1Waveform = 103
case Vco2Waveform = 104
case Vco1Semitones = 105
case Vco2Semitones = 106
case Vco2Detune = 107
case OscMix = 108
case SubMix = 109
case FmMix = 110
case FmMod = 111
case LfoWaveform = 112
case Morph = 113
case NoiseMix = 114
case LfoAmt = 115
case LfoRate = 116
case CrushAmt = 117
case DelayTime = 118
case DelayMix = 119
case ReverbAmt = 120
case ReverbMix = 121
case MasterVol = 122
case adsrAttack = 123
case adsrDecay = 124
case adsrSustain = 125
case adsrRelease = 126
}
var keyboardOctavePosition: Int = 0
var lastKey: UIButton?
var monoMode: Bool = false
var holdMode: Bool = false
var midiNotesHeld = [Int]()
let blackKeys = [49, 51, 54, 56, 58, 61, 63, 66, 68, 70]
var conductor = Conductor.sharedInstance
// *********************************************************
// MARK: - viewDidLoad
// *********************************************************
override func viewDidLoad() {
super.viewDidLoad()
// Create WaveformSegmentedViews
createWaveFormSegmentViews()
// Set Delegates
setDelegates()
// Set Preset Control Values
setDefaultValues()
// Greeting
statusLabel.text = String.randomGreeting()
}
// *********************************************************
// MARK: - Defaults/Presets
// *********************************************************
func setDefaultValues() {
// Set Preset Values
conductor.masterVolume.volume = 25.0 // Master Volume
conductor.core.offset1 = 0 // VCO1 Semitones
conductor.core.offset2 = 0 // VCO2 Semitones
conductor.core.detune = 0.0 // VCO2 Detune (Hz)
conductor.core.vcoBalance = 0.5 // VCO1/VCO2 Mix
conductor.core.subOscMix = 0.0 // SubOsc Mix
conductor.core.fmOscMix = 0.0 // FM Mix
conductor.core.fmMod = 0.0 // FM Modulation Amt
conductor.core.morph = 0.0 // Morphing between waveforms
conductor.core.noiseMix = 0.0 // Noise Mix
conductor.filterSection.lfoAmplitude = 0.0 // LFO Amp (Hz)
conductor.filterSection.lfoRate = 1.4 // LFO Rate
conductor.filterSection.resonance = 0.5 // Filter Q/Rez
conductor.bitCrusher.sampleRate = 2000.0 // Bitcrush SampleRate
conductor.multiDelay.time = 0.5 // Delay (seconds)
conductor.multiDelay.mix = 0.5 // Dry/Wet
conductor.reverb.feedback = 0.88 // Amt
conductor.reverbMixer.balance = 0.4 // Dry/Wet
cutoffKnob.value = 0.36 // Cutoff Knob Position
// ADSR
conductor.core.attackDuration = 0.1
conductor.core.decayDuration = 0.1
conductor.core.sustainLevel = 0.66
conductor.core.releaseDuration = 0.5
// Update Knob & Slider UI Values
setupKnobValues()
setupSliderValues()
// Update Toggle Presets
displayModeToggled(plotToggle)
vco1Toggled(vco1Toggle)
vco2Toggled(vco2Toggle)
filterToggled(filterToggle)
delayToggled(delayToggle)
reverbToggled(reverbToggle)
}
func setupKnobValues() {
osc1SemitonesKnob.minimum = -12
osc1SemitonesKnob.maximum = 12
osc1SemitonesKnob.value = Double(conductor.core.offset1)
osc2SemitonesKnob.minimum = -12
osc2SemitonesKnob.maximum = 12
osc2SemitonesKnob.value = Double(conductor.core.offset2)
osc2DetuneKnob.minimum = -4
osc2DetuneKnob.maximum = 4
osc2DetuneKnob.value = conductor.core.detune
subMixKnob.maximum = 4.5
subMixKnob.value = conductor.core.subOscMix
fmMixKnob.maximum = 1.25
fmMixKnob.value = conductor.core.fmOscMix
fmModKnob.maximum = 15
morphKnob.minimum = -0.99
morphKnob.maximum = 0.99
morphKnob.value = conductor.core.morph
noiseMixKnob.value = conductor.core.noiseMix
oscMixKnob.value = conductor.core.vcoBalance
lfoAmtKnob.maximum = 1200
lfoAmtKnob.value = conductor.filterSection.lfoAmplitude
lfoRateKnob.maximum = 5
lfoRateKnob.value = conductor.filterSection.lfoRate
rezKnob.maximum = 0.99
rezKnob.value = conductor.filterSection.resonance
crushAmtKnob.minimum = 0
crushAmtKnob.maximum = 1950
crushAmtKnob.knobValue = CGFloat((crushAmtKnob.maximum - conductor.bitCrusher.sampleRate) + 50)
delayTimeKnob.value = conductor.multiDelay.time
delayMixKnob.value = conductor.multiDelay.mix
reverbAmtKnob.maximum = 0.99
reverbAmtKnob.value = conductor.reverb.feedback
reverbMixKnob.value = conductor.reverbMixer.balance
masterVolKnob.maximum = 30.0
masterVolKnob.value = conductor.masterVolume.volume
// Calculate cutoff freq based on knob position
conductor.filterSection.cutoffFrequency = cutoffFreqFromValue(Double(cutoffKnob.value))
}
func setupSliderValues() {
attackSlider.maxValue = 2
attackSlider.currentValue = CGFloat(conductor.core.attackDuration)
decaySlider.maxValue = 2
decaySlider.currentValue = CGFloat(conductor.core.decayDuration)
sustainSlider.currentValue = CGFloat(conductor.core.sustainLevel)
releaseSlider.maxValue = 2
releaseSlider.currentValue = CGFloat(conductor.core.releaseDuration)
}
//*****************************************************************
// MARK: - IBActions
//*****************************************************************
@IBAction func vco1Toggled(sender: UIButton) {
if sender.selected {
sender.selected = false
statusLabel.text = "VCO 1 Off"
conductor.core.vco1On = false
} else {
sender.selected = true
statusLabel.text = "VCO 1 On"
conductor.core.vco1On = true
}
}
@IBAction func vco2Toggled(sender: UIButton) {
if sender.selected {
sender.selected = false
statusLabel.text = "VCO 2 Off"
conductor.core.vco2On = false
} else {
sender.selected = true
statusLabel.text = "VCO 2 On"
conductor.core.vco2On = true
}
}
@IBAction func crusherToggled(sender: UIButton) {
if sender.selected {
sender.selected = false
statusLabel.text = "Bitcrush Off"
conductor.bitCrusher.bypass()
} else {
sender.selected = true
statusLabel.text = "Bitcrush On"
conductor.bitCrusher.start()
}
}
@IBAction func filterToggled(sender: UIButton) {
if sender.selected {
sender.selected = false
statusLabel.text = "Filter Off"
conductor.filterSection.output.stop()
} else {
sender.selected = true
statusLabel.text = "Filter On"
conductor.filterSection.output.start()
}
}
@IBAction func delayToggled(sender: UIButton) {
if sender.selected {
sender.selected = false
statusLabel.text = "Delay Off"
conductor.multiDelayMixer.balance = 0
} else {
sender.selected = true
statusLabel.text = "Delay On"
conductor.multiDelayMixer.balance = 1
}
}
@IBAction func reverbToggled(sender: UIButton) {
if sender.selected {
sender.selected = false
statusLabel.text = "Reverb Off"
conductor.reverb.bypass()
} else {
sender.selected = true
statusLabel.text = "Reverb On"
conductor.reverb.start()
}
}
@IBAction func stereoFattenToggled(sender: UIButton) {
if sender.selected {
sender.selected = false
statusLabel.text = "Stereo Fatten Off"
conductor.fatten.mix = 0
} else {
sender.selected = true
statusLabel.text = "Stereo Fatten On"
conductor.fatten.mix = 1
}
}
// Keyboard
@IBAction func octaveDownPressed(sender: UIButton) {
guard keyboardOctavePosition > -2 else {
statusLabel.text = "How low can you go? This low."
return
}
keyboardOctavePosition += -1
octavePositionLabel.text = String(keyboardOctavePosition)
redisplayHeldKeys()
}
@IBAction func octaveUpPressed(sender: UIButton) {
guard keyboardOctavePosition < 3 else {
statusLabel.text = "Captain, she can't go any higher!"
return
}
keyboardOctavePosition += 1
octavePositionLabel.text = String(keyboardOctavePosition)
redisplayHeldKeys()
}
@IBAction func holdModeToggled(sender: UIButton) {
if sender.selected {
sender.selected = false
statusLabel.text = "Hold Mode Off"
holdMode = false
turnOffHeldKeys()
} else {
sender.selected = true
statusLabel.text = "Hold Mode On"
holdMode = true
}
}
@IBAction func monoModeToggled(sender: UIButton) {
if sender.selected {
sender.selected = false
statusLabel.text = "Mono Mode Off"
monoMode = false
} else {
sender.selected = true
statusLabel.text = "Mono Mode On"
monoMode = true
turnOffHeldKeys()
}
}
// Universal
@IBAction func midiPanicPressed(sender: RoundedButton) {
turnOffHeldKeys()
statusLabel.text = "All Notes Off"
}
@IBAction func displayModeToggled(sender: UIButton) {
if sender.selected {
sender.selected = false
statusLabel.text = "Wave Display Filled Off"
audioPlot.shouldFill = false
} else {
sender.selected = true
statusLabel.text = "Wave Display Filled On"
audioPlot.shouldFill = true
}
}
// About App
@IBAction func audioKitHomepage(sender: UIButton) {
openURL("http://audiokit.io")
}
@IBAction func buildThisSynth(sender: RoundedButton) {
openURL("http://audiokit.io/examples/AnalogSynthX")
}
//*****************************************************************
// MARK: - 🎹 Key Presses
//*****************************************************************
@IBAction func keyPressed(sender: UIButton) {
let key = sender
// Turn off last key press in Mono
if monoMode {
if let lastKey = lastKey {
turnOffKey(lastKey)
}
}
// Toggle key if in Hold mode
if holdMode {
if midiNotesHeld.contains(midiNoteFromTag(key.tag)) {
turnOffKey(key)
return
}
}
turnOnKey(key)
lastKey = key
}
@IBAction func keyReleased(sender: UIButton) {
let key = sender
if holdMode && monoMode {
toggleMonoKeyHeld(key)
} else if holdMode && !monoMode {
toggleKeyHeld(key)
} else {
turnOffKey(key)
}
}
// *********************************************************
// MARK: - 🎹 Key UI/UX Helpers
// *********************************************************
func turnOnKey(key: UIButton) {
updateKeyToDownPosition(key)
let midiNote = midiNoteFromTag(key.tag)
statusLabel.text = "Key Pressed: \(noteNameFromMidiNote(midiNote))"
conductor.core.playNote(midiNote, velocity: 127)
}
func turnOffKey(key: UIButton) {
updateKeyToUpPosition(key)
statusLabel.text = "Key Released"
conductor.core.stopNote(midiNoteFromTag(key.tag))
}
func turnOffHeldKeys() {
updateAllKeysToUpPosition()
for note in 0...127 {
conductor.core.stopNote(note)
}
midiNotesHeld.removeAll(keepCapacity: false)
}
func updateAllKeysToUpPosition() {
// Key up all keys shown on display
for tag in 248...272 {
guard let key = self.view.viewWithTag(tag) as? UIButton else {
return
}
updateKeyToUpPosition(key)
}
}
func redisplayHeldKeys() {
// Determine new keyboard bounds
let lowerMidiNote = 48 + (keyboardOctavePosition * 12)
let upperMidiNote = lowerMidiNote + 24
statusLabel.text = "Keyboard Range: \(noteNameFromMidiNote(lowerMidiNote)) to \(noteNameFromMidiNote(upperMidiNote))"
guard !monoMode else {
turnOffHeldKeys()
return
}
// Refresh keyboard
updateAllKeysToUpPosition()
// Check notes currently in view and turn on if held
for note in lowerMidiNote...upperMidiNote {
if midiNotesHeld.contains(note) {
let keyTag = (note - (keyboardOctavePosition * 12)) + 200
guard let key = self.view.viewWithTag(keyTag) as? UIButton else {
return
}
updateKeyToDownPosition(key)
}
}
}
func toggleKeyHeld(key: UIButton) {
if let i = midiNotesHeld.indexOf(midiNoteFromTag(key.tag)) {
midiNotesHeld.removeAtIndex(i)
} else {
midiNotesHeld.append(midiNoteFromTag(key.tag))
}
}
func toggleMonoKeyHeld(key: UIButton) {
if midiNotesHeld.contains(midiNoteFromTag(key.tag)) {
midiNotesHeld.removeAll()
} else {
midiNotesHeld.removeAll()
midiNotesHeld.append(midiNoteFromTag(key.tag))
}
}
func updateKeyToUpPosition(key: UIButton) {
let index = key.tag - 200
if blackKeys.contains(index) {
key.setImage(UIImage(named: "blackkey"), forState: .Normal)
} else {
key.setImage(UIImage(named: "whitekey"), forState: .Normal)
}
}
func updateKeyToDownPosition(key: UIButton) {
let index = key.tag - 200
if blackKeys.contains(index) {
key.setImage(UIImage(named: "blackkey_selected"), forState: .Normal)
} else {
key.setImage(UIImage(named: "whitekey_selected"), forState: .Normal)
}
}
func midiNoteFromTag(tag: Int) -> Int {
return (tag - 200) + (keyboardOctavePosition * 12)
}
}
//*****************************************************************
// MARK: - 🎛 Knob Delegates
//*****************************************************************
extension SynthViewController: KnobSmallDelegate, KnobMediumDelegate, KnobLargeDelegate {
func updateKnobValue(value: Double, tag: Int) {
switch (tag) {
// VCOs
case ControlTag.Vco1Semitones.rawValue:
let intValue = Int(floor(value))
statusLabel.text = "Semitones: \(intValue)"
conductor.core.offset1 = intValue
case ControlTag.Vco2Semitones.rawValue:
let intValue = Int(floor(value))
statusLabel.text = "Semitones: \(intValue)"
conductor.core.offset2 = intValue
case ControlTag.Vco2Detune.rawValue:
statusLabel.text = "Detune: \(value.decimalString) Hz"
conductor.core.detune = value
case ControlTag.OscMix.rawValue:
statusLabel.text = "OscMix: \(value.decimalString)"
conductor.core.vcoBalance = value
case ControlTag.Morph.rawValue:
statusLabel.text = "Morph Waveform: \(value.decimalString)"
conductor.core.morph = value
// Additional OSCs
case ControlTag.SubMix.rawValue:
statusLabel.text = "Sub Osc: \(subMixKnob.knobValue.percentageString)"
conductor.core.subOscMix = value
case ControlTag.FmMix.rawValue:
statusLabel.text = "FM Amt: \(fmMixKnob.knobValue.percentageString)"
conductor.core.fmOscMix = value
case ControlTag.FmMod.rawValue:
statusLabel.text = "FM Mod: \(fmModKnob.knobValue.percentageString)"
conductor.core.fmMod = value
case ControlTag.NoiseMix.rawValue:
statusLabel.text = "Noise Amt: \(noiseMixKnob.knobValue.percentageString)"
conductor.core.noiseMix = value
// LFO
case ControlTag.LfoAmt.rawValue:
statusLabel.text = "LFO Amp: \(value.decimalString) Hz"
conductor.filterSection.lfoAmplitude = value
case ControlTag.LfoRate.rawValue:
statusLabel.text = "LFO Rate: \(value.decimalString)"
conductor.filterSection.lfoRate = value
// Filter
case ControlTag.Cutoff.rawValue:
let cutOffFrequency = cutoffFreqFromValue(value)
statusLabel.text = "Cutoff: \(cutOffFrequency.decimalString) Hz"
conductor.filterSection.cutoffFrequency = cutOffFrequency
case ControlTag.Rez.rawValue:
statusLabel.text = "Rez: \(value.decimalString)"
conductor.filterSection.resonance = value
// Crusher
case ControlTag.CrushAmt.rawValue:
let crushAmt = (crushAmtKnob.maximum - value) + 50
statusLabel.text = "Bitcrush: \(crushAmt.decimalString) Sample Rate"
conductor.bitCrusher.sampleRate = crushAmt
conductor.bitCrusher.bitDepth = 8
// Delay
case ControlTag.DelayTime.rawValue:
statusLabel.text = "Delay Time: \(value.decimal1000String) ms"
conductor.multiDelay.time = value
case ControlTag.DelayMix.rawValue:
statusLabel.text = "Delay Mix: \(value.decimalString)"
conductor.multiDelay.mix = value
// Reverb
case ControlTag.ReverbAmt.rawValue:
if value == 0.99 {
statusLabel.text = "Reverb Size: Grand Canyon!"
} else {
statusLabel.text = "Reverb Size: \(reverbAmtKnob.knobValue.percentageString)"
}
conductor.reverb.feedback = value
case ControlTag.ReverbMix.rawValue:
statusLabel.text = "Reverb Mix: \(value.decimalString)"
conductor.reverbMixer.balance = value
// Master
case ControlTag.MasterVol.rawValue:
statusLabel.text = "Master Vol: \(masterVolKnob.knobValue.percentageString)"
conductor.masterVolume.volume = value
default:
break
}
}
}
//*****************************************************************
// MARK: - 🎚Slider Delegate (ADSR)
//*****************************************************************
extension SynthViewController: VerticalSliderDelegate {
func sliderValueDidChange(value: Double, tag: Int) {
switch (tag) {
case ControlTag.adsrAttack.rawValue:
statusLabel.text = "Attack: \(value.decimalString) sec"
conductor.core.attackDuration = value
case ControlTag.adsrDecay.rawValue:
statusLabel.text = "Decay: \(value.decimalString) sec"
conductor.core.decayDuration = value
case ControlTag.adsrSustain.rawValue:
statusLabel.text = "Sustain: \(sustainSlider.currentValue.percentageString)"
conductor.core.sustainLevel = value
case ControlTag.adsrRelease.rawValue:
statusLabel.text = "Release: \(value.decimalString) sec"
conductor.core.releaseDuration = value
default:
break
}
}
}
//*****************************************************************
// MARK: - WaveformSegmentedView Delegate
//*****************************************************************
extension SynthViewController: SMSegmentViewDelegate {
// SMSegment Delegate
func segmentView(segmentView: SMBasicSegmentView, didSelectSegmentAtIndex index: Int) {
switch (segmentView.tag) {
case ControlTag.Vco1Waveform.rawValue:
conductor.core.waveform1 = Double(index)
statusLabel.text = "VCO1 Waveform Changed"
case ControlTag.Vco2Waveform.rawValue:
conductor.core.waveform2 = Double(index)
statusLabel.text = "VCO2 Waveform Changed"
case ControlTag.LfoWaveform.rawValue:
statusLabel.text = "LFO Waveform Changed"
conductor.filterSection.lfoIndex = min(Double(index), 3)
default:
break
}
}
}
| mit | 758e9c2dfa43f7aa69be2754815c1dd5 | 33.578723 | 648 | 0.54865 | 5.214545 | false | false | false | false |
mindogo/Krautreporter-iOS | Krautreporter/Pods/ICSPullToRefresh/ICSPullToRefresh/ICSPullToRefresh.swift | 1 | 7801 | //
// ICSPullToRefresh.swift
// ICSPullToRefresh
//
// Created by LEI on 3/15/15.
// Copyright (c) 2015 TouchingAPP. All rights reserved.
//
import UIKit
private var pullToRefreshViewKey: Void?
private let observeKeyContentOffset = "contentOffset"
private let observeKeyFrame = "frame"
private let ICSPullToRefreshViewHeight: CGFloat = 60
public typealias ActionHandler = () -> ()
public extension UIScrollView{
public var pullToRefreshView: PullToRefreshView? {
get {
return objc_getAssociatedObject(self, &pullToRefreshViewKey) as? PullToRefreshView
}
set(newValue) {
self.willChangeValueForKey("ICSPullToRefreshView")
objc_setAssociatedObject(self, &pullToRefreshViewKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN))
self.didChangeValueForKey("ICSPullToRefreshView")
}
}
public var showsPullToRefresh: Bool {
return pullToRefreshView != nil ? pullToRefreshView!.hidden : false
}
public func addPullToRefreshHandler(actionHandler: ActionHandler){
if pullToRefreshView == nil {
pullToRefreshView = PullToRefreshView(frame: CGRect(x: CGFloat(0), y: -ICSPullToRefreshViewHeight, width: self.bounds.width, height: ICSPullToRefreshViewHeight))
addSubview(pullToRefreshView!)
}
pullToRefreshView?.actionHandler = actionHandler
pullToRefreshView?.scrollViewOriginContentTopInset = contentInset.top
setShowsPullToRefresh(true)
}
public func triggerPullToRefresh() {
pullToRefreshView?.state = .Triggered
pullToRefreshView?.startAnimating()
}
public func setShowsPullToRefresh(showsToPullToRefresh: Bool) {
if pullToRefreshView == nil {
return
}
pullToRefreshView!.hidden = !showsToPullToRefresh
if showsToPullToRefresh{
addPullToRefreshObservers()
}else{
removePullToRefreshObservers()
}
}
func addPullToRefreshObservers() {
if pullToRefreshView?.isObserving != nil && !pullToRefreshView!.isObserving{
addObserver(pullToRefreshView!, forKeyPath: observeKeyContentOffset, options:.New, context: nil)
addObserver(pullToRefreshView!, forKeyPath: observeKeyFrame, options:.New, context: nil)
pullToRefreshView!.isObserving = true
}
}
func removePullToRefreshObservers() {
if pullToRefreshView?.isObserving != nil && pullToRefreshView!.isObserving{
removeObserver(pullToRefreshView!, forKeyPath: observeKeyContentOffset)
removeObserver(pullToRefreshView!, forKeyPath: observeKeyFrame)
pullToRefreshView!.isObserving = false
}
}
}
public class PullToRefreshView: UIView {
public var actionHandler: ActionHandler?
public var isObserving: Bool = false
var triggeredByUser: Bool = false
public var scrollView: UIScrollView? {
return self.superview as? UIScrollView
}
public var scrollViewOriginContentTopInset: CGFloat = 0
public enum State {
case Stopped
case Triggered
case Loading
case All
}
public var state: State = .Stopped {
willSet {
if state != newValue {
self.setNeedsLayout()
switch newValue{
case .Stopped:
resetScrollViewContentInset()
case .Loading:
setScrollViewContentInsetForLoading()
if state == .Triggered {
actionHandler?()
}
default:
break
}
}
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
initViews()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initViews()
}
public func startAnimating() {
if scrollView == nil {
return
}
scrollView?.setContentOffset(CGPoint(x: scrollView!.contentOffset.x, y: -(scrollView!.contentInset.top + bounds.height)), animated: true)
triggeredByUser = true
state = .Loading
}
public func stopAnimating() {
state = .Stopped
if triggeredByUser {
scrollView?.setContentOffset(CGPoint(x: scrollView!.contentOffset.x, y: -scrollView!.contentInset.top), animated: true)
}
}
public override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if keyPath == observeKeyContentOffset {
srollViewDidScroll(change[NSKeyValueChangeNewKey]?.CGPointValue())
} else if keyPath == observeKeyFrame {
setNeedsLayout()
}
}
private func srollViewDidScroll(contentOffset: CGPoint?) {
if scrollView == nil || contentOffset == nil{
return
}
if state != .Loading {
let scrollOffsetThreshold = frame.origin.y - scrollViewOriginContentTopInset
if !scrollView!.dragging && state == .Triggered {
state = .Loading
} else if contentOffset!.y < scrollOffsetThreshold && scrollView!.dragging && state == .Stopped {
state = .Triggered
} else if contentOffset!.y >= scrollOffsetThreshold && state != .Stopped {
state == .Stopped
}
}
}
private func setScrollViewContentInset(contentInset: UIEdgeInsets) {
UIView.animateWithDuration(0.3, delay: 0, options: .AllowUserInteraction | .BeginFromCurrentState, animations: { [unowned self] () -> Void in
scrollView?.contentInset = contentInset
}, completion: nil)
}
private func resetScrollViewContentInset() {
if scrollView == nil {
return
}
var currentInset = scrollView!.contentInset
currentInset.top = scrollViewOriginContentTopInset
setScrollViewContentInset(currentInset)
}
private func setScrollViewContentInsetForLoading() {
if scrollView == nil {
return
}
let offset = max(scrollView!.contentOffset.y * -1, 0)
var currentInset = scrollView!.contentInset
currentInset.top = min(offset, scrollViewOriginContentTopInset + bounds.height)
setScrollViewContentInset(currentInset)
}
public override func layoutSubviews() {
super.layoutSubviews()
defaultView.frame = self.bounds
activityIndicator.center = defaultView.center
switch state {
case .Stopped:
activityIndicator.stopAnimating()
case .Loading:
activityIndicator.startAnimating()
default:
break
}
}
public override func willMoveToSuperview(newSuperview: UIView?) {
if superview != nil && newSuperview == nil {
if scrollView?.showsPullToRefresh != nil && scrollView!.showsPullToRefresh{
scrollView?.removePullToRefreshObservers()
}
}
}
// MARK: Basic Views
func initViews() {
addSubview(defaultView)
defaultView.addSubview(activityIndicator)
}
lazy var defaultView: UIView = {
let view = UIView()
return view
}()
lazy var activityIndicator: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
activityIndicator.hidesWhenStopped = false
return activityIndicator
}()
} | mit | f9d927abe333b4484ccf0e244406b646 | 32.2 | 173 | 0.625048 | 5.905375 | false | false | false | false |
bigtreenono/NSPTools | RayWenderlich/Introduction to Swift/6 . Control Flow/DemoControlFlow.playground/section-1.swift | 1 | 1711 | // Playground - noun: a place where people can play
import UIKit
for var i = 0; i < 10; i++ {
//println(i)
}
for i in 1 ..< 10 {
//println(i)
}
var counter = 10
//while (counter > 0) {
// println(counter)
// counter -= 1
//}
//do {
// println(counter)
// counter -= 1
//} while (counter > 0)
let movies = ["Star Wars", "Raiders of the Lost Ark", "Aliens"]
for movie in movies {
//println(movie)
}
let movieTypes = ["Star Wars" : "Action", "Raiders of the Lost Ark" : "Adventure", "Aliens" : "Sci-fi"]
for (key, value) in movieTypes {
//println("The key is '\(key)'. The value is '\(value)'")
}
for (_, value) in movieTypes {
//println("\(value)")
}
var name = "Brian"
if name == "Brian" {
//println("Your name is Brian")
}
//while (counter > 0) {
// if counter > 5 {
// println("\(counter) - Greater than five")
// } else if counter > 2 {
// println("\(counter) - Greater than two")
// } else {
// println("\(counter) - default")
// }
// counter -= 1
//}
//while (counter > 0) {
// switch(counter) {
// case 6...10:
// println("\(counter) - Greater than five")
// case 3...5:
// println("\(counter) - Greater than two")
// default:
// println("\(counter) - default")
// }
// counter -= 1
//}
let names = ["Ray", "Vicki", "Brian", "Greg", "Mic", "Christine"]
for name in names {
print(name)
switch(name) {
case "Vicki":
fallthrough
case "Ray":
print(" - Founded Razeware")
case let employee where employee.rangeOfString("i") != nil:
print(" - Has an 'i' in their name.")
case let nameLength where count(nameLength) > 3 && count(nameLength) < 5:
print("- Hi Greg!")
default:
print(" - Cheers")
}
println("")
}
| mit | dc52c5b2f820a7b21009131fb05a40b8 | 18.666667 | 103 | 0.568089 | 3.055357 | false | false | false | false |
HongliYu/firefox-ios | Account/FxADevice.swift | 4 | 2859 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import SwiftyJSON
public struct FxADevicePushParams {
let callback: String
let publicKey: String
let authKey: String
}
public class FxADevice: RemoteDevice {
let pushParams: FxADevicePushParams?
fileprivate init(name: String, id: String?, type: String?, isCurrentDevice: Bool = false, push: FxADevicePushParams?, lastAccessTime: Timestamp?, availableCommands: JSON?) {
self.pushParams = push
super.init(id: id, name: name, type: type, isCurrentDevice: isCurrentDevice, lastAccessTime: lastAccessTime, availableCommands: availableCommands)
}
static func forRegister(_ name: String, type: String, availableCommands: JSON, push: FxADevicePushParams?) -> FxADevice {
return FxADevice(name: name, id: nil, type: type, push: push, lastAccessTime: nil, availableCommands: availableCommands)
}
static func forUpdate(_ name: String, id: String, availableCommands: JSON, push: FxADevicePushParams?) -> FxADevice {
return FxADevice(name: name, id: id, type: nil, push: push, lastAccessTime: nil, availableCommands: availableCommands)
}
func toJSON() -> JSON {
var parameters = [String: Any]()
parameters["name"] = name
parameters["id"] = id
parameters["type"] = type
parameters["availableCommands"] = availableCommands?.dictionaryObject
if let push = self.pushParams {
parameters["pushCallback"] = push.callback
parameters["pushPublicKey"] = push.publicKey
parameters["pushAuthKey"] = push.authKey
}
return JSON(parameters)
}
static func fromJSON(_ json: JSON) -> FxADevice? {
guard json.error == nil,
let id = json["id"].string,
let name = json["name"].string else {
return nil
}
let isCurrentDevice = json["isCurrentDevice"].bool ?? false
let lastAccessTime = json["lastAccessTime"].uInt64
let type = json["type"].string
let availableCommands = json["availableCommands"]
let push: FxADevicePushParams?
if let pushCallback = json["pushCallback"].string,
let publicKey = json["pushPublicKey"].string, publicKey != "",
let authKey = json["pushAuthKey"].string, authKey != "" {
push = FxADevicePushParams(callback: pushCallback, publicKey: publicKey, authKey: authKey)
} else {
push = nil
}
return FxADevice(name: name, id: id, type: type, isCurrentDevice: isCurrentDevice, push: push, lastAccessTime: lastAccessTime, availableCommands: availableCommands)
}
}
| mpl-2.0 | e734b1d1337173f5712a261c40ca2b27 | 41.044118 | 177 | 0.66142 | 4.87884 | false | false | false | false |
everlof/RestKit-n-Django-Sample | Project_iOS/Cite/UIView+Extension.swift | 1 | 2730 | //
// UIView+Extension.swift
// Cite
//
// Created by David Everlöf on 11/08/16.
//
//
import Foundation
extension UIView {
func addBorder(edges edges: UIRectEdge, colour: UIColor = UIColor.whiteColor(), weight: CGFloat = 1) -> [UIView] {
let thickness = weight / UIScreen.mainScreen().scale
var borders = [UIView]()
func border() -> UIView {
let border = UIView(frame: CGRectZero)
border.backgroundColor = colour
border.translatesAutoresizingMaskIntoConstraints = false
return border
}
if edges.contains(.Top) || edges.contains(.All) {
let top = border()
addSubview(top)
addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("V:|-(0)-[top(==thickness)]",
options: [],
metrics: ["thickness": thickness],
views: ["top": top]))
addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("H:|-(0)-[top]-(0)-|",
options: [],
metrics: nil,
views: ["top": top]))
borders.append(top)
}
if edges.contains(.Left) || edges.contains(.All) {
let left = border()
addSubview(left)
addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("H:|-(0)-[left(==thickness)]",
options: [],
metrics: ["thickness": thickness],
views: ["left": left]))
addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("V:|-(0)-[left]-(0)-|",
options: [],
metrics: nil,
views: ["left": left]))
borders.append(left)
}
if edges.contains(.Right) || edges.contains(.All) {
let right = border()
addSubview(right)
addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("H:[right(==thickness)]-(0)-|",
options: [],
metrics: ["thickness": thickness],
views: ["right": right]))
addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("V:|-(0)-[right]-(0)-|",
options: [],
metrics: nil,
views: ["right": right]))
borders.append(right)
}
if edges.contains(.Bottom) || edges.contains(.All) {
let bottom = border()
addSubview(bottom)
addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("V:[bottom(==thickness)]-(0)-|",
options: [],
metrics: ["thickness": thickness],
views: ["bottom": bottom]))
addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("H:|-(0)-[bottom]-(0)-|",
options: [],
metrics: nil,
views: ["bottom": bottom]))
borders.append(bottom)
}
return borders
}
} | mit | ee9968c7cf3e9051539c5f8d767bd05a | 29.333333 | 116 | 0.575302 | 4.934901 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Variable Delay.xcplaygroundpage/Contents.swift | 1 | 1025 | //: ## Variable Delay
//: When you smoothly vary effect parameters, you get completely new kinds of effects.
import AudioKitPlaygrounds
import AudioKit
let file = try AKAudioFile(readFileName: playgroundAudioFiles[0])
let player = try AKAudioPlayer(file: file)
player.looping = true
var delay = AKVariableDelay(player)
delay.rampTime = 0.2
AudioKit.output = delay
var time = 0.0
let timeStep = 0.1
let modulation = AKPeriodicFunction(every: timeStep) {
// Vary the delay time between 0.0 and 0.2 in a sinusoid at 2 hz
let delayModulationHz = 0.1
let delayModulation = (1.0 - cos(2 * 3.14 * delayModulationHz * time)) * 0.1
delay.time = delayModulation
let feedbackModulationHz = 0.21
let feedbackModulation = (1.0 - sin(2 * 3.14 * feedbackModulationHz * time)) * 0.5
delay.feedback = feedbackModulation
time += timeStep
}
AudioKit.start(withPeriodicFunctions: modulation)
player.play()
modulation.start()
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
| mit | 31a9f9a19fac6c2c122ca37ffd8ed530 | 28.285714 | 86 | 0.742439 | 3.824627 | false | false | false | false |
jacobwhite/firefox-ios | Client/Frontend/Browser/TabLocationView.swift | 1 | 19039 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import SnapKit
import XCGLogger
private let log = Logger.browserLogger
protocol TabLocationViewDelegate {
func tabLocationViewDidTapLocation(_ tabLocationView: TabLocationView)
func tabLocationViewDidLongPressLocation(_ tabLocationView: TabLocationView)
func tabLocationViewDidTapReaderMode(_ tabLocationView: TabLocationView)
func tabLocationViewDidTapShield(_ tabLocationView: TabLocationView)
func tabLocationViewDidTapPageOptions(_ tabLocationView: TabLocationView, from button: UIButton)
func tabLocationViewDidLongPressPageOptions(_ tabLocationVIew: TabLocationView)
func tabLocationViewDidBeginDragInteraction(_ tabLocationView: TabLocationView)
/// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
@discardableResult func tabLocationViewDidLongPressReaderMode(_ tabLocationView: TabLocationView) -> Bool
func tabLocationViewLocationAccessibilityActions(_ tabLocationView: TabLocationView) -> [UIAccessibilityCustomAction]?
}
private struct TabLocationViewUX {
static let HostFontColor = UIColor.black
static let BaseURLFontColor = UIColor.gray
static let Spacing: CGFloat = 8
static let StatusIconSize: CGFloat = 18
static let TPIconSize: CGFloat = 24
static let ButtonSize: CGFloat = 44
static let URLBarPadding = 4
}
class TabLocationView: UIView, TabEventHandler {
var delegate: TabLocationViewDelegate?
var longPressRecognizer: UILongPressGestureRecognizer!
var tapRecognizer: UITapGestureRecognizer!
private var contentView: UIStackView!
private var tabObservers: TabObservers!
@objc dynamic var baseURLFontColor: UIColor = TabLocationViewUX.BaseURLFontColor {
didSet { updateTextWithURL() }
}
var url: URL? {
didSet {
let wasHidden = lockImageView.isHidden
lockImageView.isHidden = url?.scheme != "https"
if wasHidden != lockImageView.isHidden {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
}
updateTextWithURL()
pageOptionsButton.isHidden = (url == nil)
if url == nil {
trackingProtectionButton.isHidden = true
}
setNeedsUpdateConstraints()
}
}
deinit {
unregister(tabObservers)
}
var readerModeState: ReaderModeState {
get {
return readerModeButton.readerModeState
}
set (newReaderModeState) {
if newReaderModeState != self.readerModeButton.readerModeState {
let wasHidden = readerModeButton.isHidden
self.readerModeButton.readerModeState = newReaderModeState
readerModeButton.isHidden = (newReaderModeState == ReaderModeState.unavailable)
separatorLine.isHidden = readerModeButton.isHidden
if wasHidden != readerModeButton.isHidden {
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
if !readerModeButton.isHidden {
// Delay the Reader Mode accessibility announcement briefly to prevent interruptions.
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, Strings.ReaderModeAvailableVoiceOverAnnouncement)
}
}
}
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.readerModeButton.alpha = newReaderModeState == .unavailable ? 0 : 1
})
}
}
}
lazy var placeholder: NSAttributedString = {
let placeholderText = NSLocalizedString("Search or enter address", comment: "The text shown in the URL bar on about:home")
return NSAttributedString(string: placeholderText, attributes: [NSAttributedStringKey.foregroundColor: UIColor.gray])
}()
lazy var urlTextField: UITextField = {
let urlTextField = DisplayTextField()
// Prevent the field from compressing the toolbar buttons on the 4S in landscape.
urlTextField.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 250), for: .horizontal)
urlTextField.attributedPlaceholder = self.placeholder
urlTextField.accessibilityIdentifier = "url"
urlTextField.accessibilityActionsSource = self
urlTextField.font = UIConstants.DefaultChromeFont
urlTextField.backgroundColor = .clear
// Remove the default drop interaction from the URL text field so that our
// custom drop interaction on the BVC can accept dropped URLs.
if #available(iOS 11, *) {
if let dropInteraction = urlTextField.textDropInteraction {
urlTextField.removeInteraction(dropInteraction)
}
}
return urlTextField
}()
fileprivate lazy var lockImageView: UIImageView = {
let lockImageView = UIImageView(image: UIImage.templateImageNamed("lock_verified"))
lockImageView.tintColor = UIColor.Defaults.LockGreen
lockImageView.isAccessibilityElement = true
lockImageView.contentMode = .center
lockImageView.accessibilityLabel = NSLocalizedString("Secure connection", comment: "Accessibility label for the lock icon, which is only present if the connection is secure")
return lockImageView
}()
lazy var trackingProtectionButton: UIButton = {
let trackingProtectionButton = UIButton()
trackingProtectionButton.setImage(UIImage.templateImageNamed("tracking-protection"), for: .normal)
trackingProtectionButton.addTarget(self, action: #selector(didPressTPShieldButton(_:)), for: .touchUpInside)
trackingProtectionButton.tintColor = .gray
trackingProtectionButton.imageView?.contentMode = .scaleAspectFill
trackingProtectionButton.isHidden = true
return trackingProtectionButton
}()
fileprivate lazy var readerModeButton: ReaderModeButton = {
let readerModeButton = ReaderModeButton(frame: .zero)
readerModeButton.addTarget(self, action: #selector(tapReaderModeButton), for: .touchUpInside)
readerModeButton.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(longPressReaderModeButton)))
readerModeButton.isAccessibilityElement = true
readerModeButton.isHidden = true
readerModeButton.imageView?.contentMode = .scaleAspectFit
readerModeButton.contentHorizontalAlignment = .left
readerModeButton.accessibilityLabel = NSLocalizedString("Reader View", comment: "Accessibility label for the Reader View button")
readerModeButton.accessibilityIdentifier = "TabLocationView.readerModeButton"
readerModeButton.accessibilityCustomActions = [UIAccessibilityCustomAction(name: NSLocalizedString("Add to Reading List", comment: "Accessibility label for action adding current page to reading list."), target: self, selector: #selector(readerModeCustomAction))]
return readerModeButton
}()
lazy var pageOptionsButton: ToolbarButton = {
let pageOptionsButton = ToolbarButton(frame: .zero)
pageOptionsButton.setImage(UIImage.templateImageNamed("menu-More-Options"), for: .normal)
pageOptionsButton.addTarget(self, action: #selector(didPressPageOptionsButton), for: .touchUpInside)
pageOptionsButton.isAccessibilityElement = true
pageOptionsButton.isHidden = true
pageOptionsButton.imageView?.contentMode = .left
pageOptionsButton.accessibilityLabel = NSLocalizedString("Page Options Menu", comment: "Accessibility label for the Page Options menu button")
pageOptionsButton.accessibilityIdentifier = "TabLocationView.pageOptionsButton"
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressPageOptionsButton))
pageOptionsButton.addGestureRecognizer(longPressGesture)
return pageOptionsButton
}()
lazy var separatorLine: UIView = {
let line = UIView()
line.layer.cornerRadius = 2
line.isHidden = true
return line
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.tabObservers = registerFor(.didChangeContentBlocking, queue: .main)
longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressLocation))
longPressRecognizer.delegate = self
tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapLocation))
tapRecognizer.delegate = self
addGestureRecognizer(longPressRecognizer)
addGestureRecognizer(tapRecognizer)
let spaceView = UIView()
spaceView.snp.makeConstraints { make in
make.width.equalTo(TabLocationViewUX.Spacing)
}
// The lock and TP icons have custom spacing.
// TODO: Once we cut ios10 support we can use UIstackview.setCustomSpacing
let iconStack = UIStackView(arrangedSubviews: [spaceView, lockImageView, trackingProtectionButton])
iconStack.spacing = TabLocationViewUX.Spacing / 2
let subviews = [iconStack, urlTextField, readerModeButton, separatorLine, pageOptionsButton]
contentView = UIStackView(arrangedSubviews: subviews)
contentView.distribution = .fill
contentView.alignment = .center
addSubview(contentView)
contentView.snp.makeConstraints { make in
make.edges.equalTo(self)
}
lockImageView.snp.makeConstraints { make in
make.width.equalTo(TabLocationViewUX.StatusIconSize)
make.height.equalTo(TabLocationViewUX.ButtonSize)
}
trackingProtectionButton.snp.makeConstraints { make in
make.width.equalTo(TabLocationViewUX.TPIconSize)
make.height.equalTo(TabLocationViewUX.ButtonSize)
}
pageOptionsButton.snp.makeConstraints { make in
make.size.equalTo(TabLocationViewUX.ButtonSize)
}
separatorLine.snp.makeConstraints { make in
make.width.equalTo(1)
make.height.equalTo(26)
}
readerModeButton.snp.makeConstraints { make in
// The reader mode button only has the padding on one side.
// The buttons "contentHorizontalAlignment" helps make the button still look centered
make.size.equalTo(TabLocationViewUX.ButtonSize - 10)
}
// Setup UIDragInteraction to handle dragging the location
// bar for dropping its URL into other apps.
if #available(iOS 11, *) {
let dragInteraction = UIDragInteraction(delegate: self)
dragInteraction.allowsSimultaneousRecognitionDuringLift = true
self.addInteraction(dragInteraction)
}
}
func tabDidChangeContentBlockerStatus(_ tab: Tab) {
assertIsMainThread("UI changes must be on the main thread")
guard #available(iOS 11.0, *), let blocker = tab.contentBlocker as? ContentBlockerHelper else { return }
switch blocker.status {
case .Blocking:
self.trackingProtectionButton.setImage(UIImage.templateImageNamed("tracking-protection"), for: .normal)
self.trackingProtectionButton.isHidden = false
case .Disabled, .NoBlockedURLs:
self.trackingProtectionButton.isHidden = true
case .Whitelisted:
self.trackingProtectionButton.setImage(UIImage.templateImageNamed("tracking-protection-off"), for: .normal)
self.trackingProtectionButton.isHidden = false
}
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var accessibilityElements: [Any]? {
get {
return [lockImageView, urlTextField, readerModeButton, pageOptionsButton].filter { !$0.isHidden }
}
set {
super.accessibilityElements = newValue
}
}
@objc func tapReaderModeButton() {
delegate?.tabLocationViewDidTapReaderMode(self)
}
@objc func longPressReaderModeButton(_ recognizer: UILongPressGestureRecognizer) {
if recognizer.state == .began {
delegate?.tabLocationViewDidLongPressReaderMode(self)
}
}
@objc func didPressPageOptionsButton(_ button: UIButton) {
delegate?.tabLocationViewDidTapPageOptions(self, from: button)
}
@objc func didLongPressPageOptionsButton(_ recognizer: UILongPressGestureRecognizer) {
delegate?.tabLocationViewDidLongPressPageOptions(self)
}
@objc func longPressLocation(_ recognizer: UITapGestureRecognizer) {
if recognizer.state == .began {
delegate?.tabLocationViewDidLongPressLocation(self)
}
}
@objc func tapLocation(_ recognizer: UITapGestureRecognizer) {
delegate?.tabLocationViewDidTapLocation(self)
}
@objc func didPressTPShieldButton(_ button: UIButton) {
delegate?.tabLocationViewDidTapShield(self)
}
@objc func readerModeCustomAction() -> Bool {
return delegate?.tabLocationViewDidLongPressReaderMode(self) ?? false
}
fileprivate func updateTextWithURL() {
if let host = url?.host, AppConstants.MOZ_PUNYCODE {
urlTextField.text = url?.absoluteString.replacingOccurrences(of: host, with: host.asciiHostToUTF8())
} else {
urlTextField.text = url?.absoluteString
}
// remove https:// (the scheme) from the url when displaying
if let scheme = url?.scheme, let range = url?.absoluteString.range(of: "\(scheme)://") {
urlTextField.text = url?.absoluteString.replacingCharacters(in: range, with: "")
}
}
}
extension TabLocationView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// When long pressing a button make sure the textfield's long press gesture is not triggered
return !(otherGestureRecognizer.view is UIButton)
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
// If the longPressRecognizer is active, fail the tap recognizer to avoid conflicts.
return gestureRecognizer == longPressRecognizer && otherGestureRecognizer == tapRecognizer
}
}
@available(iOS 11.0, *)
extension TabLocationView: UIDragInteractionDelegate {
func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] {
// Ensure we actually have a URL in the location bar and that the URL is not local.
guard let url = self.url, !url.isLocal, let itemProvider = NSItemProvider(contentsOf: url) else {
return []
}
UnifiedTelemetry.recordEvent(category: .action, method: .drag, object: .locationBar)
let dragItem = UIDragItem(itemProvider: itemProvider)
return [dragItem]
}
func dragInteraction(_ interaction: UIDragInteraction, sessionWillBegin session: UIDragSession) {
delegate?.tabLocationViewDidBeginDragInteraction(self)
}
}
extension TabLocationView: AccessibilityActionsSource {
func accessibilityCustomActionsForView(_ view: UIView) -> [UIAccessibilityCustomAction]? {
if view === urlTextField {
return delegate?.tabLocationViewLocationAccessibilityActions(self)
}
return nil
}
}
extension TabLocationView: Themeable {
func applyTheme(_ theme: Theme) {
backgroundColor = UIColor.TextField.Background.colorFor(theme)
urlTextField.textColor = UIColor.Browser.Tint.colorFor(theme)
readerModeButton.selectedTintColor = UIColor.TextField.ReaderModeButtonSelected.colorFor(theme)
readerModeButton.unselectedTintColor = UIColor.TextField.ReaderModeButtonUnselected.colorFor(theme)
pageOptionsButton.selectedTintColor = UIColor.TextField.PageOptionsSelected.colorFor(theme)
pageOptionsButton.unselectedTintColor = UIColor.TextField.PageOptionsUnselected.colorFor(theme)
pageOptionsButton.tintColor = pageOptionsButton.unselectedTintColor
separatorLine.backgroundColor = UIColor.TextField.Separator.colorFor(theme)
}
}
class ReaderModeButton: UIButton {
var selectedTintColor: UIColor?
var unselectedTintColor: UIColor?
override init(frame: CGRect) {
super.init(frame: frame)
adjustsImageWhenHighlighted = false
setImage(UIImage.templateImageNamed("reader"), for: .normal)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var isSelected: Bool {
didSet {
self.tintColor = (isHighlighted || isSelected) ? selectedTintColor : unselectedTintColor
}
}
override open var isHighlighted: Bool {
didSet {
self.tintColor = (isHighlighted || isSelected) ? selectedTintColor : unselectedTintColor
}
}
override var tintColor: UIColor! {
didSet {
self.imageView?.tintColor = self.tintColor
}
}
var _readerModeState: ReaderModeState = ReaderModeState.unavailable
var readerModeState: ReaderModeState {
get {
return _readerModeState
}
set (newReaderModeState) {
_readerModeState = newReaderModeState
switch _readerModeState {
case .available:
self.isEnabled = true
self.isSelected = false
case .unavailable:
self.isEnabled = false
self.isSelected = false
case .active:
self.isEnabled = true
self.isSelected = true
}
}
}
}
private class DisplayTextField: UITextField {
weak var accessibilityActionsSource: AccessibilityActionsSource?
override var accessibilityCustomActions: [UIAccessibilityCustomAction]? {
get {
return accessibilityActionsSource?.accessibilityCustomActionsForView(self)
}
set {
super.accessibilityCustomActions = newValue
}
}
fileprivate override var canBecomeFirstResponder: Bool {
return false
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: TabLocationViewUX.Spacing, dy: 0)
}
}
| mpl-2.0 | 7701c36fd5d1086074fbed5553d09488 | 42.074661 | 270 | 0.693629 | 5.933001 | false | false | false | false |
ikesyo/swift-corelibs-foundation | Foundation/NumberFormatter.swift | 1 | 27937 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
internal let kCFNumberFormatterNoStyle = CFNumberFormatterStyle.noStyle
internal let kCFNumberFormatterDecimalStyle = CFNumberFormatterStyle.decimalStyle
internal let kCFNumberFormatterCurrencyStyle = CFNumberFormatterStyle.currencyStyle
internal let kCFNumberFormatterPercentStyle = CFNumberFormatterStyle.percentStyle
internal let kCFNumberFormatterScientificStyle = CFNumberFormatterStyle.scientificStyle
internal let kCFNumberFormatterSpellOutStyle = CFNumberFormatterStyle.spellOutStyle
internal let kCFNumberFormatterOrdinalStyle = CFNumberFormatterStyle.ordinalStyle
internal let kCFNumberFormatterCurrencyISOCodeStyle = CFNumberFormatterStyle.currencyISOCodeStyle
internal let kCFNumberFormatterCurrencyPluralStyle = CFNumberFormatterStyle.currencyPluralStyle
internal let kCFNumberFormatterCurrencyAccountingStyle = CFNumberFormatterStyle.currencyAccountingStyle
#endif
extension NumberFormatter {
public enum Style : UInt {
case none
case decimal
case currency
case percent
case scientific
case spellOut
case ordinal
case currencyISOCode
case currencyPlural
case currencyAccounting
}
public enum PadPosition : UInt {
case beforePrefix
case afterPrefix
case beforeSuffix
case afterSuffix
}
public enum RoundingMode : UInt {
case ceiling
case floor
case down
case up
case halfEven
case halfDown
case halfUp
}
}
open class NumberFormatter : Formatter {
typealias CFType = CFNumberFormatter
private var _currentCfFormatter: CFType?
private var _cfFormatter: CFType {
if let obj = _currentCfFormatter {
return obj
} else {
#if os(OSX) || os(iOS)
let numberStyle = CFNumberFormatterStyle(rawValue: CFIndex(self.numberStyle.rawValue))!
#else
let numberStyle = CFNumberFormatterStyle(self.numberStyle.rawValue)
#endif
let obj = CFNumberFormatterCreate(kCFAllocatorSystemDefault, locale._cfObject, numberStyle)!
_setFormatterAttributes(obj)
if let format = _format {
CFNumberFormatterSetFormat(obj, format._cfObject)
}
_currentCfFormatter = obj
return obj
}
}
// this is for NSUnitFormatter
open var formattingContext: Context = .unknown // default is NSFormattingContextUnknown
// Report the used range of the string and an NSError, in addition to the usual stuff from Formatter
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func objectValue(_ string: String, range: inout NSRange) throws -> Any? { NSUnimplemented() }
open override func string(for obj: Any) -> String? {
//we need to allow Swift's numeric types here - Int, Double et al.
guard let number = _SwiftValue.store(obj) as? NSNumber else { return nil }
return string(from: number)
}
// Even though NumberFormatter responds to the usual Formatter methods,
// here are some convenience methods which are a little more obvious.
open func string(from number: NSNumber) -> String? {
return CFNumberFormatterCreateStringWithNumber(kCFAllocatorSystemDefault, _cfFormatter, number._cfObject)._swiftObject
}
open func number(from string: String) -> NSNumber? {
var range = CFRange(location: 0, length: string.length)
let number = withUnsafeMutablePointer(to: &range) { (rangePointer: UnsafeMutablePointer<CFRange>) -> NSNumber? in
#if os(OSX) || os(iOS)
let parseOption = allowsFloats ? 0 : CFNumberFormatterOptionFlags.parseIntegersOnly.rawValue
#else
let parseOption = allowsFloats ? 0 : CFOptionFlags(kCFNumberFormatterParseIntegersOnly)
#endif
let result = CFNumberFormatterCreateNumberFromString(kCFAllocatorSystemDefault, _cfFormatter, string._cfObject, rangePointer, parseOption)
return result?._nsObject
}
return number
}
open class func localizedString(from num: NSNumber, number nstyle: Style) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = nstyle
return numberFormatter.string(for: num)!
}
internal func _reset() {
_currentCfFormatter = nil
}
internal func _setFormatterAttributes(_ formatter: CFNumberFormatter) {
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyCode, value: _currencyCode?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterDecimalSeparator, value: _decimalSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyDecimalSeparator, value: _currencyDecimalSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterAlwaysShowDecimalSeparator, value: _alwaysShowsDecimalSeparator._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterGroupingSeparator, value: _groupingSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterUseGroupingSeparator, value: _usesGroupingSeparator._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPercentSymbol, value: _percentSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterZeroSymbol, value: _zeroSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNaNSymbol, value: _notANumberSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterInfinitySymbol, value: _positiveInfinitySymbol._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinusSign, value: _minusSign?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPlusSign, value: _plusSign?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencySymbol, value: _currencySymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterExponentSymbol, value: _exponentSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinIntegerDigits, value: _minimumIntegerDigits._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxIntegerDigits, value: _maximumIntegerDigits._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinFractionDigits, value: _minimumFractionDigits._bridgeToObjectiveC()._cfObject)
if _minimumFractionDigits <= 0 {
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxFractionDigits, value: _maximumFractionDigits._bridgeToObjectiveC()._cfObject)
}
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterGroupingSize, value: _groupingSize._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterSecondaryGroupingSize, value: _secondaryGroupingSize._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterRoundingMode, value: _roundingMode.rawValue._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterRoundingIncrement, value: _roundingIncrement?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterFormatWidth, value: _formatWidth._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPaddingCharacter, value: _paddingCharacter?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPaddingPosition, value: _paddingPosition.rawValue._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMultiplier, value: _multiplier?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPositivePrefix, value: _positivePrefix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPositiveSuffix, value: _positiveSuffix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNegativePrefix, value: _negativePrefix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterNegativeSuffix, value: _negativeSuffix?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterPerMillSymbol, value: _percentSymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterInternationalCurrencySymbol, value: _internationalCurrencySymbol?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterCurrencyGroupingSeparator, value: _currencyGroupingSeparator?._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterIsLenient, value: _lenient._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterUseSignificantDigits, value: _usesSignificantDigits._cfObject)
if _usesSignificantDigits {
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMinSignificantDigits, value: _minimumSignificantDigits._bridgeToObjectiveC()._cfObject)
_setFormatterAttribute(formatter, attributeName: kCFNumberFormatterMaxSignificantDigits, value: _maximumSignificantDigits._bridgeToObjectiveC()._cfObject)
}
}
internal func _setFormatterAttribute(_ formatter: CFNumberFormatter, attributeName: CFString, value: AnyObject?) {
if let value = value {
CFNumberFormatterSetProperty(formatter, attributeName, value)
}
}
// Attributes of a NumberFormatter
internal var _numberStyle: Style = .none
open var numberStyle: Style {
get {
return _numberStyle
}
set {
switch newValue {
case .none, .ordinal, .spellOut:
_usesSignificantDigits = false
case .currency, .currencyPlural, .currencyISOCode, .currencyAccounting:
_usesSignificantDigits = false
_usesGroupingSeparator = true
_minimumFractionDigits = 2
case .decimal:
_usesGroupingSeparator = true
_maximumFractionDigits = 3
if _minimumIntegerDigits == 0 {
_minimumIntegerDigits = 1
}
if _groupingSize == 0 {
_groupingSize = 3
}
default:
_usesSignificantDigits = true
_usesGroupingSeparator = true
}
_reset()
_numberStyle = newValue
}
}
internal var _locale: Locale = Locale.current
/*@NSCopying*/ open var locale: Locale! {
get {
return _locale
}
set {
_reset()
_locale = newValue
}
}
internal var _generatesDecimalNumbers: Bool = false
open var generatesDecimalNumbers: Bool {
get {
return _generatesDecimalNumbers
}
set {
_reset()
_generatesDecimalNumbers = newValue
}
}
internal var _negativeFormat: String!
open var negativeFormat: String! {
get {
return _negativeFormat
}
set {
_reset()
_negativeFormat = newValue
}
}
internal var _textAttributesForNegativeValues: [String : Any]?
open var textAttributesForNegativeValues: [String : Any]? {
get {
return _textAttributesForNegativeValues
}
set {
_reset()
_textAttributesForNegativeValues = newValue
}
}
internal var _positiveFormat: String!
open var positiveFormat: String! {
get {
return _positiveFormat
}
set {
_reset()
_positiveFormat = newValue
}
}
internal var _textAttributesForPositiveValues: [String : Any]?
open var textAttributesForPositiveValues: [String : Any]? {
get {
return _textAttributesForPositiveValues
}
set {
_reset()
_textAttributesForPositiveValues = newValue
}
}
internal var _allowsFloats: Bool = true
open var allowsFloats: Bool {
get {
return _allowsFloats
}
set {
_reset()
_allowsFloats = newValue
}
}
internal var _decimalSeparator: String!
open var decimalSeparator: String! {
get {
return _decimalSeparator
}
set {
_reset()
_decimalSeparator = newValue
}
}
internal var _alwaysShowsDecimalSeparator: Bool = false
open var alwaysShowsDecimalSeparator: Bool {
get {
return _alwaysShowsDecimalSeparator
}
set {
_reset()
_alwaysShowsDecimalSeparator = newValue
}
}
internal var _currencyDecimalSeparator: String!
open var currencyDecimalSeparator: String! {
get {
return _currencyDecimalSeparator
}
set {
_reset()
_currencyDecimalSeparator = newValue
}
}
internal var _usesGroupingSeparator: Bool = false
open var usesGroupingSeparator: Bool {
get {
return _usesGroupingSeparator
}
set {
_reset()
_usesGroupingSeparator = newValue
}
}
internal var _groupingSeparator: String!
open var groupingSeparator: String! {
get {
return _groupingSeparator
}
set {
_reset()
_groupingSeparator = newValue
}
}
//
internal var _zeroSymbol: String?
open var zeroSymbol: String? {
get {
return _zeroSymbol
}
set {
_reset()
_zeroSymbol = newValue
}
}
internal var _textAttributesForZero: [String : Any]?
open var textAttributesForZero: [String : Any]? {
get {
return _textAttributesForZero
}
set {
_reset()
_textAttributesForZero = newValue
}
}
internal var _nilSymbol: String = ""
open var nilSymbol: String {
get {
return _nilSymbol
}
set {
_reset()
_nilSymbol = newValue
}
}
internal var _textAttributesForNil: [String : Any]?
open var textAttributesForNil: [String : Any]? {
get {
return _textAttributesForNil
}
set {
_reset()
_textAttributesForNil = newValue
}
}
internal var _notANumberSymbol: String!
open var notANumberSymbol: String! {
get {
return _notANumberSymbol
}
set {
_reset()
_notANumberSymbol = newValue
}
}
internal var _textAttributesForNotANumber: [String : Any]?
open var textAttributesForNotANumber: [String : Any]? {
get {
return _textAttributesForNotANumber
}
set {
_reset()
_textAttributesForNotANumber = newValue
}
}
internal var _positiveInfinitySymbol: String = "+∞"
open var positiveInfinitySymbol: String {
get {
return _positiveInfinitySymbol
}
set {
_reset()
_positiveInfinitySymbol = newValue
}
}
internal var _textAttributesForPositiveInfinity: [String : Any]?
open var textAttributesForPositiveInfinity: [String : Any]? {
get {
return _textAttributesForPositiveInfinity
}
set {
_reset()
_textAttributesForPositiveInfinity = newValue
}
}
internal var _negativeInfinitySymbol: String = "-∞"
open var negativeInfinitySymbol: String {
get {
return _negativeInfinitySymbol
}
set {
_reset()
_negativeInfinitySymbol = newValue
}
}
internal var _textAttributesForNegativeInfinity: [String : Any]?
open var textAttributesForNegativeInfinity: [String : Any]? {
get {
return _textAttributesForNegativeInfinity
}
set {
_reset()
_textAttributesForNegativeInfinity = newValue
}
}
//
internal var _positivePrefix: String!
open var positivePrefix: String! {
get {
return _positivePrefix
}
set {
_reset()
_positivePrefix = newValue
}
}
internal var _positiveSuffix: String!
open var positiveSuffix: String! {
get {
return _positiveSuffix
}
set {
_reset()
_positiveSuffix = newValue
}
}
internal var _negativePrefix: String!
open var negativePrefix: String! {
get {
return _negativePrefix
}
set {
_reset()
_negativePrefix = newValue
}
}
internal var _negativeSuffix: String!
open var negativeSuffix: String! {
get {
return _negativeSuffix
}
set {
_reset()
_negativeSuffix = newValue
}
}
internal var _currencyCode: String!
open var currencyCode: String! {
get {
return _currencyCode
}
set {
_reset()
_currencyCode = newValue
}
}
internal var _currencySymbol: String!
open var currencySymbol: String! {
get {
return _currencySymbol
}
set {
_reset()
_currencySymbol = newValue
}
}
internal var _internationalCurrencySymbol: String!
open var internationalCurrencySymbol: String! {
get {
return _internationalCurrencySymbol
}
set {
_reset()
_internationalCurrencySymbol = newValue
}
}
internal var _percentSymbol: String!
open var percentSymbol: String! {
get {
return _percentSymbol
}
set {
_reset()
_percentSymbol = newValue
}
}
internal var _perMillSymbol: String!
open var perMillSymbol: String! {
get {
return _perMillSymbol
}
set {
_reset()
_perMillSymbol = newValue
}
}
internal var _minusSign: String!
open var minusSign: String! {
get {
return _minusSign
}
set {
_reset()
_minusSign = newValue
}
}
internal var _plusSign: String!
open var plusSign: String! {
get {
return _plusSign
}
set {
_reset()
_plusSign = newValue
}
}
internal var _exponentSymbol: String!
open var exponentSymbol: String! {
get {
return _exponentSymbol
}
set {
_reset()
_exponentSymbol = newValue
}
}
//
internal var _groupingSize: Int = 0
open var groupingSize: Int {
get {
return _groupingSize
}
set {
_reset()
_groupingSize = newValue
}
}
internal var _secondaryGroupingSize: Int = 0
open var secondaryGroupingSize: Int {
get {
return _secondaryGroupingSize
}
set {
_reset()
_secondaryGroupingSize = newValue
}
}
internal var _multiplier: NSNumber?
/*@NSCopying*/ open var multiplier: NSNumber? {
get {
return _multiplier
}
set {
_reset()
_multiplier = newValue
}
}
internal var _formatWidth: Int = 0
open var formatWidth: Int {
get {
return _formatWidth
}
set {
_reset()
_formatWidth = newValue
}
}
internal var _paddingCharacter: String!
open var paddingCharacter: String! {
get {
return _paddingCharacter
}
set {
_reset()
_paddingCharacter = newValue
}
}
//
internal var _paddingPosition: PadPosition = .beforePrefix
open var paddingPosition: PadPosition {
get {
return _paddingPosition
}
set {
_reset()
_paddingPosition = newValue
}
}
internal var _roundingMode: RoundingMode = .halfEven
open var roundingMode: RoundingMode {
get {
return _roundingMode
}
set {
_reset()
_roundingMode = newValue
}
}
internal var _roundingIncrement: NSNumber! = 0
/*@NSCopying*/ open var roundingIncrement: NSNumber! {
get {
return _roundingIncrement
}
set {
_reset()
_roundingIncrement = newValue
}
}
internal var _minimumIntegerDigits: Int = 0
open var minimumIntegerDigits: Int {
get {
return _minimumIntegerDigits
}
set {
_reset()
_minimumIntegerDigits = newValue
}
}
internal var _maximumIntegerDigits: Int = 42
open var maximumIntegerDigits: Int {
get {
return _maximumIntegerDigits
}
set {
_reset()
_maximumIntegerDigits = newValue
}
}
internal var _minimumFractionDigits: Int = 0
open var minimumFractionDigits: Int {
get {
return _minimumFractionDigits
}
set {
_reset()
_minimumFractionDigits = newValue
}
}
internal var _maximumFractionDigits: Int = 0
open var maximumFractionDigits: Int {
get {
return _maximumFractionDigits
}
set {
_reset()
_maximumFractionDigits = newValue
}
}
internal var _minimum: NSNumber?
/*@NSCopying*/ open var minimum: NSNumber? {
get {
return _minimum
}
set {
_reset()
_minimum = newValue
}
}
internal var _maximum: NSNumber?
/*@NSCopying*/ open var maximum: NSNumber? {
get {
return _maximum
}
set {
_reset()
_maximum = newValue
}
}
internal var _currencyGroupingSeparator: String!
open var currencyGroupingSeparator: String! {
get {
return _currencyGroupingSeparator
}
set {
_reset()
_currencyGroupingSeparator = newValue
}
}
internal var _lenient: Bool = false
open var isLenient: Bool {
get {
return _lenient
}
set {
_reset()
_lenient = newValue
}
}
internal var _usesSignificantDigits: Bool = false
open var usesSignificantDigits: Bool {
get {
return _usesSignificantDigits
}
set {
_reset()
_usesSignificantDigits = newValue
}
}
internal var _minimumSignificantDigits: Int = 1
open var minimumSignificantDigits: Int {
get {
return _minimumSignificantDigits
}
set {
_reset()
_usesSignificantDigits = true
_minimumSignificantDigits = newValue
}
}
internal var _maximumSignificantDigits: Int = 6
open var maximumSignificantDigits: Int {
get {
return _maximumSignificantDigits
}
set {
_reset()
_usesSignificantDigits = true
_maximumSignificantDigits = newValue
}
}
internal var _partialStringValidationEnabled: Bool = false
open var isPartialStringValidationEnabled: Bool {
get {
return _partialStringValidationEnabled
}
set {
_reset()
_partialStringValidationEnabled = newValue
}
}
//
internal var _hasThousandSeparators: Bool = false
open var hasThousandSeparators: Bool {
get {
return _hasThousandSeparators
}
set {
_reset()
_hasThousandSeparators = newValue
}
}
internal var _thousandSeparator: String!
open var thousandSeparator: String! {
get {
return _thousandSeparator
}
set {
_reset()
_thousandSeparator = newValue
}
}
//
internal var _localizesFormat: Bool = true
open var localizesFormat: Bool {
get {
return _localizesFormat
}
set {
_reset()
_localizesFormat = newValue
}
}
//
internal var _format: String?
open var format: String {
get {
return _format ?? "#;0;#"
}
set {
_reset()
_format = newValue
}
}
//
internal var _attributedStringForZero: NSAttributedString = NSAttributedString(string: "0")
/*@NSCopying*/ open var attributedStringForZero: NSAttributedString {
get {
return _attributedStringForZero
}
set {
_reset()
_attributedStringForZero = newValue
}
}
internal var _attributedStringForNil: NSAttributedString = NSAttributedString(string: "")
/*@NSCopying*/ open var attributedStringForNil: NSAttributedString {
get {
return _attributedStringForNil
}
set {
_reset()
_attributedStringForNil = newValue
}
}
internal var _attributedStringForNotANumber: NSAttributedString = NSAttributedString(string: "NaN")
/*@NSCopying*/ open var attributedStringForNotANumber: NSAttributedString {
get {
return _attributedStringForNotANumber
}
set {
_reset()
_attributedStringForNotANumber = newValue
}
}
internal var _roundingBehavior: NSDecimalNumberHandler = NSDecimalNumberHandler.default
/*@NSCopying*/ open var roundingBehavior: NSDecimalNumberHandler {
get {
return _roundingBehavior
}
set {
_reset()
_roundingBehavior = newValue
}
}
}
| apache-2.0 | f1c9cce994786a90a09add536a543627 | 29.594743 | 166 | 0.598181 | 5.948254 | false | false | false | false |
google/iosched-ios | Source/IOsched/Application/AppDelegate.swift | 1 | 6042 | //
// Copyright (c) 2017 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 MaterialComponents
import GoogleSignIn
import FirebaseAuth
import FirebaseCore
import FirebaseFirestore
import UserNotifications
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var mdcWindow: MDCOverlayWindow?
var window: UIWindow? {
get {
mdcWindow = mdcWindow ?? MDCOverlayWindow(frame: UIScreen.main.bounds)
return mdcWindow
}
set {}
}
private(set) lazy var app: Application = {
return Application.sharedInstance
}()
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Firebase setup
FirebaseApp.configure()
// Uncomment this line to enable debug logging from Firebase.
// FirebaseConfiguration.shared.setLoggerLevel(.debug)
var launchedFromShortcut = false
if let shortcutItem = launchOptions?[.shortcutItem] as? UIApplicationShortcutItem {
launchedFromShortcut = true
_ = handleShortcutItem(shortcutItem: shortcutItem)
}
// Auth
app.analytics.setUserProperty("false", forName: "user_logged_in")
_ = SignIn.sharedInstance.addGoogleSignInHandler(self) { [weak self] in
guard let self = self else { return }
self.app.serviceLocator.userState.registerForFCM()
self.app.serviceLocator.userState.updateUserRegistrationStatus()
self.app.analytics.setUserProperty("true", forName: "user_logged_in")
}
_ = SignIn.sharedInstance.addGoogleSignOutHandler(self) { [weak self] in
guard let self = self else { return }
self.app.serviceLocator.userState.updateUserRegistrationStatus()
}
SignIn.sharedInstance.signInSilently { (_, error) in
guard error == nil else {
print("While trying to silently sign in, an error ocurred: \(error!)")
return
}
}
// UI setup
Application.sharedInstance.configureMainInterface(in: self.window)
self.window?.makeKeyAndVisible()
// Notification setup
self.app.setupNotifications(for: application, with: self)
// Update conference data
app.serviceLocator.updateConferenceData { [weak self] in
self?.app.registerImFeelingLuckyShortcut()
}
registerForTimeZoneNotifications()
return !launchedFromShortcut
}
func application(_ application: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool {
let sourceApplication = options[.sourceApplication] as? String
return GIDSignIn.sharedInstance().handle(url,
sourceApplication: sourceApplication,
annotation: [:])
}
func applicationDidBecomeActive(_ application: UIApplication) {
if let user = Auth.auth().currentUser {
Firestore.firestore().setLastVisitedDate(for: user)
}
}
}
@available(iOS 10.0, *)
extension AppDelegate: UNUserNotificationCenterDelegate {
public func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Play sound and show alert to the user
completionHandler([.alert, .sound])
}
public func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
// Determine the user action
if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
if let sessionID = response.notification.request.content.userInfo["sessionId"] as? String {
print(sessionID)
Application.sharedInstance.navigateToDeepLink(uniqueIdPath: sessionID)
}
}
completionHandler()
}
}
// MARK: Notification handling
@available(iOS 9.0, *)
extension AppDelegate {
func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
if application.applicationState == .active {
let title = notification.alertTitle
let message = notification.alertBody
let alertController = MDCAlertController(title: title, message: message)
let okAction = MDCAlertAction(title: "OK") { _ in
if let sessionID = notification.userInfo?["sessionId"] as? String {
print(sessionID)
Application.sharedInstance.navigateToDeepLink(uniqueIdPath: sessionID)
}
}
let dismissAction = MDCAlertAction(title: "Dismiss")
alertController.addAction(okAction)
alertController.addAction(dismissAction)
application.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
}
}
}
// MARK: - Time zone change handling
extension AppDelegate {
func registerForTimeZoneNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(timeZoneDidChange),
name: .NSSystemTimeZoneDidChange,
object: nil)
}
@objc private func timeZoneDidChange() {
NotificationCenter.default.post(name: .timezoneUpdate, object: nil)
}
}
| apache-2.0 | 552f40be6a13c5d30ef0eef49e6c10f1 | 34.127907 | 134 | 0.681066 | 5.244792 | false | false | false | false |
touchopia/HackingWithSwift | project21/Project21/ViewController.swift | 1 | 2886 | //
// ViewController.swift
// Project21
//
// Created by TwoStraws on 18/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import UIKit
import UserNotifications
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Register", style: .plain, target: self, action: #selector(registerLocal))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Schedule", style: .plain, target: self, action: #selector(scheduleLocal))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func registerLocal() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Yay!")
} else {
print("D'oh")
}
}
}
func scheduleLocal() {
registerCategories()
let center = UNUserNotificationCenter.current()
// not required, but useful for testing!
center.removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent()
content.title = "Late wake up call"
content.body = "The early bird catches the worm, but the second mouse gets the cheese."
content.categoryIdentifier = "alarm"
content.userInfo = ["customData": "fizzbuzz"]
content.sound = UNNotificationSound.default()
var dateComponents = DateComponents()
dateComponents.hour = 10
dateComponents.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
func registerCategories() {
let center = UNUserNotificationCenter.current()
center.delegate = self
let show = UNNotificationAction(identifier: "show", title: "Tell me more…", options: .foreground)
let category = UNNotificationCategory(identifier: "alarm", actions: [show], intentIdentifiers: [])
center.setNotificationCategories([category])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// pull out the buried userInfo dictionary
let userInfo = response.notification.request.content.userInfo
if let customData = userInfo["customData"] as? String {
print("Custom data received: \(customData)")
switch response.actionIdentifier {
case UNNotificationDefaultActionIdentifier:
// the user swiped to unlock; do nothing
print("Default identifier")
case "show":
print("Show more information…")
break
default:
break
}
}
// you need to call the completion handler when you're done
completionHandler()
}
}
| unlicense | a889c7b17a29c2818db199a12b9ba340 | 28.397959 | 174 | 0.741409 | 4.391768 | false | false | false | false |
alexth/CDVDictionary | Dictionary/Dictionary/ViewControllers/AlphabetViewController.swift | 1 | 2805 | //
// AlphabetViewController.swift
// Dictionary
//
// Created by Alex Golub on 9/25/16.
// Copyright © 2016 Alex Golub. All rights reserved.
//
import UIKit
final class AlphabetViewController: UIViewController {
@IBOutlet weak var alphabetTableView: UITableView!
private struct Constants {
static let alphabetTableViewHeaderFooterHeight = CGFloat(0.01)
}
var navigationTitle = ""
var dictionaryName = ""
private var sourceArray = [String]()
private var displayDictionary = [String: String]()
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupData(plistName: dictionaryName)
setupNavigationBar()
setupTableView()
}
// MARK: - Utils
private func setupData(plistName: String) {
guard let data = PlistReaderUtils().read(plistName) else {
return
}
sourceArray = data.sourceArray
displayDictionary = data.displayDictionary
alphabetTableView.reloadData()
}
private func setupTableView() {
alphabetTableView.rowHeight = UITableViewAutomaticDimension
alphabetTableView.estimatedRowHeight = 56.0
}
private func setupNavigationBar() {
guard let navigationBar = navigationController?.navigationBar else { return }
NavigationBarStyleUtils().style(navigationBar: navigationBar)
title = navigationTitle
}
}
extension AlphabetViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sourceArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "alphabetCell", for: indexPath) as? DictionaryCell else {
fatalError("ERROR! Unable to dequeue DictionaryCell")
}
let letter = sourceArray[indexPath.row]
guard let translation = displayDictionary[letter] else {
fatalError("ERROR! Unable to get value for key from dictionary")
}
cell.updateCellWith(letter: letter,
translation: translation,
indexPathRow: indexPath.row)
return cell
}
}
extension AlphabetViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return Constants.alphabetTableViewHeaderFooterHeight
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return Constants.alphabetTableViewHeaderFooterHeight
}
}
| mit | d746a69925eed1f21dceffd7531a28e2 | 29.150538 | 128 | 0.676534 | 5.641851 | false | false | false | false |
MikotoZero/SwiftyJSON | Source/SwiftyJSON/SwiftyJSON.swift | 1 | 40227 | // SwiftyJSON.swift
//
// Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang
//
// 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
// MARK: - Error
// swiftlint:disable line_length
public enum SwiftyJSONError: Int, Swift.Error {
case unsupportedType = 999
case indexOutOfBounds = 900
case elementTooDeep = 902
case wrongType = 901
case notExist = 500
case invalidJSON = 490
}
extension SwiftyJSONError: CustomNSError {
/// return the error domain of SwiftyJSONError
public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" }
/// return the error code of SwiftyJSONError
public var errorCode: Int { return self.rawValue }
/// return the userInfo of SwiftyJSONError
public var errorUserInfo: [String: Any] {
switch self {
case .unsupportedType:
return [NSLocalizedDescriptionKey: "It is an unsupported type."]
case .indexOutOfBounds:
return [NSLocalizedDescriptionKey: "Array Index is out of bounds."]
case .wrongType:
return [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]
case .notExist:
return [NSLocalizedDescriptionKey: "Dictionary key does not exist."]
case .invalidJSON:
return [NSLocalizedDescriptionKey: "JSON is invalid."]
case .elementTooDeep:
return [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop."]
}
}
}
// MARK: - JSON Content
/// Store raw value of JSON object
private indirect enum Content {
case bool(Bool)
case number(NSNumber)
case string(String)
case array([Any])
case dictionary([String: Any])
case null
case unknown
}
extension Content {
var type: Type {
switch self {
case .bool: return .bool
case .number: return .number
case .string: return .string
case .array: return .array
case .dictionary: return .dictionary
case .null: return .null
case .unknown: return .unknown
}
}
var rawValue: Any {
switch self {
case .bool(let bool): return bool
case .number(let number): return number
case .string(let string): return string
case .array(let array): return array
case .dictionary(let dictionary): return dictionary
case .null, .unknown: return NSNull()
}
}
}
extension Content {
init(_ rawValue: Any) {
switch unwrap(rawValue) {
case let value as NSNumber:
if value.isBool {
self = .bool(value.boolValue)
} else {
self = .number(value)
}
case let value as String:
self = .string(value)
case let value as [Any]:
self = .array(value)
case let value as [String: Any]:
self = .dictionary(value)
case _ as NSNull:
self = .null
case nil:
self = .null
default:
self = .unknown
}
}
}
/// Private method to unwarp an object recursively
private func unwrap(_ object: Any) -> Any {
switch object {
case let json as JSON:
return unwrap(json.object)
case let array as [Any]:
return array.map(unwrap)
case let dictionary as [String: Any]:
return dictionary.mapValues(unwrap)
default:
return object
}
}
// MARK: - JSON Type
/**
JSON's type definitions.
See http://www.json.org
*/
public enum Type: Int {
case number
case string
case bool
case array
case dictionary
case null
case unknown
}
// MARK: - JSON Base
public struct JSON {
/// Private content
private var content: Content = .null
/// Error in JSON, fileprivate setter
public private(set) var error: SwiftyJSONError?
/// JSON type, fileprivate setter
public var type: Type { content.type }
/// Object in JSON
public var object: Any {
get {
content.rawValue
}
set {
content = Content(newValue)
error = content.type == .unknown ? SwiftyJSONError.unsupportedType : nil
}
}
public static var null: JSON = .init(content: .null, error: nil)
}
// MARK: - Constructor
extension JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `[]` by default.
- returns: The created JSON
*/
public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws {
let object: Any = try JSONSerialization.jsonObject(with: data, options: opt)
self.init(jsonObject: object)
}
/**
Creates a JSON object
- note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)`
- parameter object: the object
- returns: the created JSON object
*/
public init(_ object: Any) {
switch object {
case let object as Data:
do {
try self.init(data: object)
} catch {
self.init(jsonObject: NSNull())
}
case let json as JSON:
self = json
self.error = nil
default:
self.init(jsonObject: object)
}
}
/**
Parses the JSON string into a JSON object
- parameter jsonString: the JSON string
- returns: the created JSON object
*/
public init(parseJSON jsonString: String) {
if let data = jsonString.data(using: .utf8) {
self.init(data)
} else {
self = .null
}
}
/**
Creates a JSON using the object.
- parameter jsonObject: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
private init(jsonObject: Any) {
self.object = jsonObject
}
}
// MARK: - Merge
extension JSON {
/**
Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added,
present values getting overwritten, array values getting appended and nested JSONs getting merged the same way.
- parameter other: The JSON which gets merged into this JSON
- throws `ErrorWrongType` if the other JSONs differs in type on the top level.
*/
public mutating func merge(with other: JSON) throws {
try self.merge(with: other, typecheck: true)
}
/**
Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added,
present values getting overwritten, array values getting appended and nested JSONS getting merged the same way.
- parameter other: The JSON which gets merged into this JSON
- throws `ErrorWrongType` if the other JSONs differs in type on the top level.
- returns: New merged JSON
*/
public func merged(with other: JSON) throws -> JSON {
var merged = self
try merged.merge(with: other, typecheck: true)
return merged
}
/**
Private woker function which does the actual merging
Typecheck is set to true for the first recursion level to prevent total override of the source JSON
*/
private mutating func merge(with other: JSON, typecheck: Bool) throws {
if type == other.type {
switch type {
case .dictionary:
for (key, _) in other {
try self[key].merge(with: other[key], typecheck: false)
}
case .array:
self = JSON((arrayObject ?? []) + (other.arrayObject ?? []))
default:
self = other
}
} else {
if typecheck {
throw SwiftyJSONError.wrongType
} else {
self = other
}
}
}
}
// MARK: - Index
public enum Index<T: Any>: Comparable {
case array(Int)
case dictionary(DictionaryIndex<String, T>)
case null
static public func == (lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)): return left == right
case (.dictionary(let left), .dictionary(let right)): return left == right
case (.null, .null): return true
default: return false
}
}
static public func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)): return left < right
case (.dictionary(let left), .dictionary(let right)): return left < right
default: return false
}
}
static public func <= (lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)): return left <= right
case (.dictionary(let left), .dictionary(let right)): return left <= right
case (.null, .null): return true
default: return false
}
}
static public func >= (lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)): return left >= right
case (.dictionary(let left), .dictionary(let right)): return left >= right
case (.null, .null): return true
default: return false
}
}
}
public typealias JSONIndex = Index<JSON>
public typealias JSONRawIndex = Index<Any>
extension JSON: Swift.Collection {
public typealias Index = JSONRawIndex
public var startIndex: Index {
switch content {
case .array(let arr): return .array(arr.startIndex)
case .dictionary(let dic): return .dictionary(dic.startIndex)
default: return .null
}
}
public var endIndex: Index {
switch content {
case .array(let arr): return .array(arr.endIndex)
case .dictionary(let dic): return .dictionary(dic.endIndex)
default: return .null
}
}
public func index(after i: Index) -> Index {
switch (content, i) {
case (.array(let value), .array(let idx)):
return .array(value.index(after: idx))
case (.dictionary(let value), .dictionary(let idx)):
return .dictionary(value.index(after: idx))
default: return .null
}
}
public subscript (position: Index) -> (String, JSON) {
switch (content, position) {
case (.array(let value), .array(let idx)):
return ("\(idx)", JSON(value[idx]))
case (.dictionary(let value), .dictionary(let idx)):
return (value[idx].key, JSON(value[idx].value))
default: return ("", JSON.null)
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public enum JSONKey {
case index(Int)
case key(String)
}
public protocol JSONSubscriptType {
var jsonKey: JSONKey { get }
}
extension Int: JSONSubscriptType {
public var jsonKey: JSONKey {
return JSONKey.index(self)
}
}
extension String: JSONSubscriptType {
public var jsonKey: JSONKey {
return JSONKey.key(self)
}
}
extension JSON {
/// If `type` is `.array`, return json whose object is `array[index]`, otherwise return null json with error.
private subscript(index index: Int) -> JSON {
get {
switch content {
case .array(let value) where value.indices.contains(index):
return JSON(value[index])
case .array:
return .init(content: .null, error: .indexOutOfBounds)
default:
return .init(content: .null, error: self.error ?? .wrongType)
}
}
set {
guard
case .array(let rawArray) = content,
rawArray.indices.contains(index),
newValue.error == nil
else { return }
var copy = rawArray
copy[index] = newValue.object
content = .array(copy)
}
}
/// If `type` is `.dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error.
private subscript(key key: String) -> JSON {
get {
switch content {
case .dictionary(let value):
if let o = value[key] {
return JSON(o)
} else {
return .init(content: .null, error: .notExist)
}
default:
return .init(content: .null, error: self.error ?? SwiftyJSONError.wrongType)
}
}
set {
guard
newValue.error == nil,
case .dictionary(let rawDictionary) = content
else {
return
}
var copy = rawDictionary
copy[key] = newValue.object
content = .dictionary(copy)
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
private subscript(sub sub: JSONSubscriptType) -> JSON {
get {
switch sub.jsonKey {
case .index(let index): return self[index: index]
case .key(let key): return self[key: key]
}
}
set {
switch sub.jsonKey {
case .index(let index): self[index: index] = newValue
case .key(let key): self[key: key] = newValue
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
Example:
```
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
```
The same as: let name = json[9]["list"]["person"]["name"]
- parameter path: The target json's path.
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [JSONSubscriptType]) -> JSON {
get {
return path.reduce(self) { $0[sub: $1] }
}
set {
switch path.count {
case 0: return
case 1: self[sub: path[0]].object = newValue.object
default:
var aPath = path
aPath.remove(at: 0)
var nextJSON = self[sub: path[0]]
nextJSON[aPath] = newValue
self[sub: path[0]] = nextJSON
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: JSONSubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: Swift.ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
extension JSON: Swift.ExpressibleByIntegerLiteral {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
extension JSON: Swift.ExpressibleByBooleanLiteral {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
extension JSON: Swift.ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
extension JSON: Swift.ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, Any)...) {
let dictionary = elements.reduce(into: [String: Any](), { $0[$1.0] = $1.1})
self.init(dictionary)
}
}
extension JSON: Swift.ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Any...) {
self.init(elements)
}
}
// MARK: - Raw
extension JSON: Swift.RawRepresentable {
public init?(rawValue: Any) {
let json = JSON(rawValue)
guard json.type != .unknown else { return nil }
self = json
}
public var rawValue: Any {
return object
}
public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data {
guard JSONSerialization.isValidJSONObject(object) else {
throw SwiftyJSONError.invalidJSON
}
return try JSONSerialization.data(withJSONObject: object, options: opt)
}
public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? {
do {
return try _rawString(encoding, options: [.jsonSerialization: opt])
} catch {
print("Could not serialize object to JSON because:", error.localizedDescription)
return nil
}
}
public func rawString(_ options: [writingOptionsKeys: Any]) -> String? {
let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8
let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10
do {
return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth)
} catch {
print("Could not serialize object to JSON because:", error.localizedDescription)
return nil
}
}
private func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? {
guard maxObjectDepth > 0 else { throw SwiftyJSONError.invalidJSON }
switch content {
case .dictionary:
do {
if !(options[.castNilToNSNull] as? Bool ?? false) {
let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted
let data = try rawData(options: jsonOption)
return String(data: data, encoding: encoding)
}
guard let dict = object as? [String: Any?] else {
return nil
}
let body = try dict.keys.map { key throws -> String in
guard let value = dict[key] else {
return "\"\(key)\": null"
}
guard let unwrappedValue = value else {
return "\"\(key)\": null"
}
let nestedValue = JSON(unwrappedValue)
guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else {
throw SwiftyJSONError.elementTooDeep
}
if nestedValue.type == .string {
return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\""
} else {
return "\"\(key)\": \(nestedString)"
}
}
return "{\(body.joined(separator: ","))}"
} catch _ {
return nil
}
case .array:
do {
if !(options[.castNilToNSNull] as? Bool ?? false) {
let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted
let data = try rawData(options: jsonOption)
return String(data: data, encoding: encoding)
}
guard let array = object as? [Any?] else {
return nil
}
let body = try array.map { value throws -> String in
guard let unwrappedValue = value else {
return "null"
}
let nestedValue = JSON(unwrappedValue)
guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else {
throw SwiftyJSONError.invalidJSON
}
if nestedValue.type == .string {
return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\""
} else {
return nestedString
}
}
return "[\(body.joined(separator: ","))]"
} catch _ {
return nil
}
case .string(let value): return value
case .number(let value): return value.stringValue
case .bool(let value): return value.description
case .null: return "null"
default: return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible {
public var description: String {
return rawString(options: .prettyPrinted) ?? "unknown"
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
guard case .array(let value) = content else { return nil }
return value.map(JSON.init(_:))
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
return self.array ?? []
}
//Optional [Any]
public var arrayObject: [Any]? {
get {
guard case .array(let value) = content else { return nil }
return value
}
set {
self = .init(content: newValue != nil ? .array(newValue!) : .null, error: nil)
}
}
}
// MARK: - Dictionary
extension JSON {
//Optional [String : JSON]
public var dictionary: [String: JSON]? {
guard case .dictionary(let value) = content else { return nil }
return value.mapValues(JSON.init(_:))
}
//Non-optional [String : JSON]
public var dictionaryValue: [String: JSON] {
return dictionary ?? [:]
}
//Optional [String : Any]
public var dictionaryObject: [String: Any]? {
get {
guard case .dictionary(let value) = content else { return nil }
return value
}
set {
self = .init(content: newValue != nil ? .dictionary(newValue!) : .null, error: nil)
}
}
}
// MARK: - Bool
extension JSON { // : Swift.Bool
//Optional bool
public var bool: Bool? {
get {
guard case .bool(let value) = content else { return nil }
return value
}
set {
self = .init(content: newValue != nil ? .bool(newValue!) : .null, error: nil)
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch content {
case .bool(let value): return value
case .number(let value): return value.boolValue
case .string(let value): return ["true", "y", "t", "yes", "1"].contains { value.caseInsensitiveCompare($0) == .orderedSame }
default: return false
}
}
set {
self = .init(content: .bool(newValue), error: nil)
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
guard case .string(let value) = content else { return nil }
return value
}
set {
self = .init(content: newValue != nil ? .string(newValue!) : .null, error: nil)
}
}
//Non-optional string
public var stringValue: String {
get {
switch content {
case .string(let value): return value
case .number(let value): return value.stringValue
case .bool(let value): return String(value)
default: return ""
}
}
set {
self = .init(content: .string(newValue), error: nil)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch content {
case .number(let value): return value
case .bool(let value): return NSNumber(value: value ? 1 : 0)
default: return nil
}
}
set {
self = .init(content: newValue != nil ? .number(newValue!) : .null, error: nil)
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch content {
case .string(let value):
let decimal = NSDecimalNumber(string: value)
return decimal == .notANumber ? .zero : decimal
case .number(let value): return value
case .bool(let value): return NSNumber(value: value ? 1 : 0)
default: return NSNumber(value: 0.0)
}
}
set {
self = .init(content: .number(newValue), error: nil)
}
}
}
// MARK: - Null
extension JSON {
public var null: NSNull? {
set {
self = .null
}
get {
switch content {
case .null: return NSNull()
default: return nil
}
}
}
public func exists() -> Bool {
if let errorValue = error, (400...1000).contains(errorValue.errorCode) {
return false
}
return true
}
}
// MARK: - URL
extension JSON {
//Optional URL
public var url: URL? {
get {
switch content {
case .string(let value):
// Check for existing percent escapes first to prevent double-escaping of % character
if value.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil {
return Foundation.URL(string: value)
} else if let encodedString_ = value.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
// We have to use `Foundation.URL` otherwise it conflicts with the variable name.
return Foundation.URL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self = .init(content: newValue != nil ? .string(newValue!.absoluteString) : .null, error: nil)
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get { number?.doubleValue }
set { number = newValue.map(NSNumber.init(value:)) }
}
public var doubleValue: Double {
get { numberValue.doubleValue }
set { numberValue = NSNumber(value: newValue) }
}
public var float: Float? {
get { number?.floatValue }
set { number = newValue.map(NSNumber.init(value:)) }
}
public var floatValue: Float {
get { numberValue.floatValue }
set { numberValue = NSNumber(value: newValue) }
}
public var int: Int? {
get { number?.intValue }
set { number = newValue.map(NSNumber.init(value:)) }
}
public var intValue: Int {
get { numberValue.intValue }
set { numberValue = NSNumber(value: newValue) }
}
public var uInt: UInt? {
get { number?.uintValue }
set { number = newValue.map(NSNumber.init(value:)) }
}
public var uIntValue: UInt {
get { numberValue.uintValue }
set { numberValue = NSNumber(value: newValue) }
}
public var int8: Int8? {
get { number?.int8Value }
set { number = newValue.map(NSNumber.init(value:)) }
}
public var int8Value: Int8 {
get { numberValue.int8Value }
set { numberValue = NSNumber(value: newValue) }
}
public var uInt8: UInt8? {
get { number?.uint8Value }
set { number = newValue.map(NSNumber.init(value:)) }
}
public var uInt8Value: UInt8 {
get { numberValue.uint8Value }
set { numberValue = NSNumber(value: newValue) }
}
public var int16: Int16? {
get { number?.int16Value }
set { number = newValue.map(NSNumber.init(value:)) }
}
public var int16Value: Int16 {
get { numberValue.int16Value }
set { numberValue = NSNumber(value: newValue) }
}
public var uInt16: UInt16? {
get { number?.uint16Value }
set { number = newValue.map(NSNumber.init(value:)) }
}
public var uInt16Value: UInt16 {
get { numberValue.uint16Value }
set { numberValue = NSNumber(value: newValue) }
}
public var int32: Int32? {
get { number?.int32Value }
set { number = newValue.map(NSNumber.init(value:)) }
}
public var int32Value: Int32 {
get { numberValue.int32Value }
set { numberValue = NSNumber(value: newValue) }
}
public var uInt32: UInt32? {
get { number?.uint32Value }
set { number = newValue.map(NSNumber.init(value:)) }
}
public var uInt32Value: UInt32 {
get { numberValue.uint32Value }
set { numberValue = NSNumber(value: newValue) }
}
public var int64: Int64? {
get { number?.int64Value }
set { number = newValue.map(NSNumber.init(value:)) }
}
public var int64Value: Int64 {
get { numberValue.int64Value }
set { numberValue = NSNumber(value: newValue) }
}
public var uInt64: UInt64? {
get { number?.uint64Value }
set { number = newValue.map(NSNumber.init(value:)) }
}
public var uInt64Value: UInt64 {
get { numberValue.uint64Value }
set { numberValue = NSNumber(value: newValue) }
}
}
// MARK: - Comparable
extension Content: Comparable {
static func == (lhs: Content, rhs: Content) -> Bool {
switch (lhs, rhs) {
case let (.number(l), .number(r)): return l == r
case let (.string(l), .string(r)): return l == r
case let (.bool(l), .bool(r)): return l == r
case let (.array(l), .array(r)): return l as NSArray == r as NSArray
case let (.dictionary(l), .dictionary(r)): return l as NSDictionary == r as NSDictionary
case (.null, .null): return true
default: return false
}
}
static func <= (lhs: Content, rhs: Content) -> Bool {
switch (lhs, rhs) {
case let (.number(l), .number(r)): return l <= r
case let (.string(l), .string(r)): return l <= r
case let (.bool(l), .bool(r)): return l == r
case let (.array(l), .array(r)): return l as NSArray == r as NSArray
case let (.dictionary(l), .dictionary(r)): return l as NSDictionary == r as NSDictionary
case (.null, .null): return true
default: return false
}
}
static func >= (lhs: Content, rhs: Content) -> Bool {
switch (lhs, rhs) {
case let (.number(l), .number(r)): return l >= r
case let (.string(l), .string(r)): return l >= r
case let (.bool(l), .bool(r)): return l == r
case let (.array(l), .array(r)): return l as NSArray == r as NSArray
case let (.dictionary(l), .dictionary(r)): return l as NSDictionary == r as NSDictionary
case (.null, .null): return true
default: return false
}
}
static func > (lhs: Content, rhs: Content) -> Bool {
switch (lhs, rhs) {
case let (.number(l), .number(r)): return l > r
case let (.string(l), .string(r)): return l > r
default: return false
}
}
static func < (lhs: Content, rhs: Content) -> Bool {
switch (lhs, rhs) {
case let (.number(l), .number(r)): return l < r
case let (.string(l), .string(r)): return l < r
default: return false
}
}
}
extension JSON: Swift.Comparable {
public static func == (lhs: JSON, rhs: JSON) -> Bool {
return lhs.content == rhs.content
}
public static func <= (lhs: JSON, rhs: JSON) -> Bool {
return lhs.content <= rhs.content
}
public static func >= (lhs: JSON, rhs: JSON) -> Bool {
return lhs.content >= rhs.content
}
public static func < (lhs: JSON, rhs: JSON) -> Bool {
return lhs.content < rhs.content
}
public static func > (lhs: JSON, rhs: JSON) -> Bool {
return lhs.content > rhs.content
}
}
private let trueNumber = NSNumber(value: true)
private let falseNumber = NSNumber(value: false)
private let trueObjCType = String(cString: trueNumber.objCType)
private let falseObjCType = String(cString: falseNumber.objCType)
// MARK: - NSNumber: Comparable
private extension NSNumber {
var isBool: Bool {
let objCType = String(cString: self.objCType)
if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) {
return true
} else {
return false
}
}
}
private func == (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true): return false
case (true, false): return false
default: return lhs.compare(rhs) == .orderedSame
}
}
private func != (lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
private func < (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true): return false
case (true, false): return false
default: return lhs.compare(rhs) == .orderedAscending
}
}
private func > (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true): return false
case (true, false): return false
default: return lhs.compare(rhs) == ComparisonResult.orderedDescending
}
}
private func <= (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true): return false
case (true, false): return false
default: return lhs.compare(rhs) != .orderedDescending
}
}
private func >= (lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true): return false
case (true, false): return false
default: return lhs.compare(rhs) != .orderedAscending
}
}
public enum writingOptionsKeys {
case jsonSerialization
case castNilToNSNull
case maxObjextDepth
case encoding
}
// MARK: - JSON: Codable
extension JSON: Codable {
public init(from decoder: Decoder) throws {
guard
let container = try? decoder.singleValueContainer(),
!container.decodeNil()
else {
self = .null
return
}
if let value = try? container.decode(Bool.self) {
self = .init(content: .bool(value), error: nil)
} else if let value = try? container.decode(Int.self) {
self = .init(content: .number(value as NSNumber), error: nil)
} else if let value = try? container.decode(Int8.self) {
self = .init(content: .number(value as NSNumber), error: nil)
} else if let value = try? container.decode(Int16.self) {
self = .init(content: .number(value as NSNumber), error: nil)
} else if let value = try? container.decode(Int32.self) {
self = .init(content: .number(value as NSNumber), error: nil)
} else if let value = try? container.decode(Int64.self) {
self = .init(content: .number(value as NSNumber), error: nil)
} else if let value = try? container.decode(UInt.self) {
self = .init(content: .number(value as NSNumber), error: nil)
} else if let value = try? container.decode(UInt8.self) {
self = .init(content: .number(value as NSNumber), error: nil)
} else if let value = try? container.decode(UInt16.self) {
self = .init(content: .number(value as NSNumber), error: nil)
} else if let value = try? container.decode(UInt32.self) {
self = .init(content: .number(value as NSNumber), error: nil)
} else if let value = try? container.decode(UInt64.self) {
self = .init(content: .number(value as NSNumber), error: nil)
} else if let value = try? container.decode(Double.self) {
self = .init(content: .number(value as NSNumber), error: nil)
} else if let value = try? container.decode(String.self) {
self = .init(content: .string(value), error: nil)
} else if let value = try? container.decode([JSON].self) {
self = .init(value)
} else if let value = try? container.decode([String: JSON].self) {
self = .init(value)
} else {
self = .null
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if object is NSNull {
try container.encodeNil()
return
}
switch object {
case let intValue as Int:
try container.encode(intValue)
case let int8Value as Int8:
try container.encode(int8Value)
case let int32Value as Int32:
try container.encode(int32Value)
case let int64Value as Int64:
try container.encode(int64Value)
case let uintValue as UInt:
try container.encode(uintValue)
case let uint8Value as UInt8:
try container.encode(uint8Value)
case let uint16Value as UInt16:
try container.encode(uint16Value)
case let uint32Value as UInt32:
try container.encode(uint32Value)
case let uint64Value as UInt64:
try container.encode(uint64Value)
case let doubleValue as Double:
try container.encode(doubleValue)
case let boolValue as Bool:
try container.encode(boolValue)
case let stringValue as String:
try container.encode(stringValue)
case is [Any]:
let jsonValueArray = array ?? []
try container.encode(jsonValueArray)
case is [String: Any]:
let jsonValueDictValue = dictionary ?? [:]
try container.encode(jsonValueDictValue)
default:
break
}
}
}
| mit | 9ac910b52874b861ae9715f2678c2854 | 30.159566 | 266 | 0.573595 | 4.404095 | false | false | false | false |
karstengresch/rw_studies | Apprentice/Checklists10/Checklists10/Checklists10/Checklist10ViewController.swift | 1 | 5539 | //
// ViewController.swift
// Checklists10
//
// Created by Karsten Gresch on 17.10.16.
// Copyright © 2016 Closure One. All rights reserved.
//
import UIKit
class Checklist10ViewController: UITableViewController, Checklist10ItemDetailViewControllerDelegate {
var checklist10: Checklist10?
/*
required init?(coder aDecoder: NSCoder) {
checklist10?.checklist10Items = [Checklist10Item]()
super.init(coder: aDecoder)
// print("Documents folder is \(documentsDirectory())")
// print("Data file path is \(dataFilePath())")
// loadChecklist10Items()
}
*/
override func viewDidLoad() {
super.viewDidLoad()
if let checklist10Init = checklist10 {
title = checklist10Init.name
}
}
/*
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
dataModel10.saveChecklist10s()
}
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Delegate Implementation
// MARK: IBAction and Outlet methods
// MARK: TV Data Source related
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (checklist10?.checklist10Items.count)!
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("cellForRowAt indexPath: \(indexPath )")
// from prototype cell
let cell = tableView.dequeueReusableCell(withIdentifier: "Checklist10Item", for: indexPath)
let checklist10Item = checklist10?.checklist10Items[indexPath.row]
let label = cell.viewWithTag(1000) as! UILabel
label.text = checklist10Item?.text
configureCheckmark(for: cell, with: checklist10Item!)
return cell
}
// MARK: TV delegate related
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("didSelectRowAt indexPath: \(indexPath )")
if let cell = tableView.cellForRow(at: indexPath) {
let checklist10Item = checklist10?.checklist10Items[indexPath.row]
checklist10Item?.toggleChecked()
configureCheckmark(for: cell, with: checklist10Item!)
}
tableView.deselectRow(at: indexPath, animated: true)
// saveChecklist10Items()
}
// MARK Individual methods
func configureCheckmark(for cell: UITableViewCell, with checklist10Item: Checklist10Item) {
print("configureCheckmark cell: \(cell) checklist10Item: \(checklist10Item)")
let label = cell.viewWithTag(1001) as! UILabel
label.textColor = view.tintColor
if checklist10Item.checked {
label.text = "√"
} else {
label.text = ""
}
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
checklist10?.checklist10Items.remove(at: indexPath.row)
let indexPaths = [indexPath]
tableView.deleteRows(at: indexPaths, with: .automatic)
}
func configureText(for cell: UITableViewCell,
with checklist10Item: Checklist10Item) {
let label = cell.viewWithTag(1000) as! UILabel
// label.text = checklist10Item.text
label.text = "\(checklist10Item.checklist10ItemId): \(checklist10Item.text)"
}
func checklist10ItemDetailViewControllerDidCancel(_ controller: Checklist10ItemDetailViewController) -> () {
dismiss(animated: true, completion: nil)
}
func checklist10ItemDetailViewController(_ controller: Checklist10ItemDetailViewController, didFinishAdding checklist10Item: Checklist10Item) -> () {
let newRowIndex = checklist10?.checklist10Items.count
checklist10?.checklist10Items.append(checklist10Item)
let indexPath = IndexPath(row: newRowIndex!, section: 0)
let indexPaths = [indexPath]
tableView.insertRows(at: indexPaths, with: .automatic)
dismiss(animated: true, completion: nil)
}
func checklist10ItemDetailViewController(_ controller: Checklist10ItemDetailViewController, didFinishEditing checklist10Item: Checklist10Item) -> () {
if let index = checklist10?.checklist10Items.index(of: checklist10Item) {
let indexPath = IndexPath(row: index, section: 0)
if let cell = tableView.cellForRow(at: indexPath)
{
print("Calling: configureText")
configureText(for: cell, with: checklist10Item)
}
}
dismiss(animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "AddChecklist10Item" {
let navigationController = segue.destination as! UINavigationController
let controller = navigationController.topViewController as! Checklist10ItemDetailViewController
// TODO - broken: "Cannot assign value of type 'Checklist10ItemDetailViewController' to type 'Checklist10ItemDetailViewControllerDelegate?'"
controller.delegate = self
} else if segue.identifier == "EditChecklist10Item" {
let navigationController = segue.destination as! UINavigationController
let controller = navigationController.topViewController as! Checklist10ItemDetailViewController
controller.delegate = self
if let indexPath = tableView.indexPath(for: sender as! UITableViewCell) {
controller.checklist10ItemToEdit = checklist10?.checklist10Items[indexPath.row]
}
}
}
}
| unlicense | 1fe7b867760037a8d10f1d98b71b6738 | 31.374269 | 152 | 0.708815 | 4.890459 | false | false | false | false |
pmlbrito/WeatherExercise | WeatherExercise/Data/Models/LocationModel.swift | 1 | 1735 | //
// LocationModel.swift
// WeatherExercise
//
// Created by Pedro Brito on 11/05/2017.
// Copyright © 2017 BringGlobal. All rights reserved.
//
import Foundation
open class LocationModel: NSObject, NSCoding {
var locationName: String?
var latitude: Double
var longitude: Double
override init() {
self.latitude = 0.0
self.longitude = 0.0
self.locationName = ""
}
init(lat: Double?, lon: Double?){
self.latitude = lat ?? 0.0
self.longitude = lon ?? 0.0
}
convenience init(lat: Double?, lon: Double?, location: String?){
self.init(lat: lat, lon: lon)
self.locationName = location ?? ""
}
//MARK: NSCoding and Serialization
required convenience public init(coder aDecoder: NSCoder) {
let latitude = aDecoder.decodeDouble(forKey: "latitude")
let longitude = aDecoder.decodeDouble(forKey: "longitude")
let location = aDecoder.decodeObject(forKey: "locationName") as? String
self.init(lat: latitude, lon: longitude, location: location)
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(latitude, forKey: "latitude")
aCoder.encode(longitude, forKey: "longitude")
aCoder.encode(locationName, forKey: "locationName")
}
func getId() -> String {
//just for simplicity sake
return self.getQueryCoordinates()
}
func getQueryCoordinates() -> String {
return String(format:"lat=%.9f&lon=%.9f", self.latitude, self.longitude)
}
func getCoordinatesText() -> String {
return String(format:"geo: latitude=%.9f, lon=%.9f", self.latitude, self.longitude)
}
}
| mit | db73728a47c6d9dfc6550d9a3dfddec0 | 26.967742 | 91 | 0.618224 | 4.292079 | false | false | false | false |
natecook1000/swift | test/stdlib/NSStringAPI.swift | 2 | 61062 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
// FIXME: rdar://problem/31311598
// UNSUPPORTED: OS=ios
// UNSUPPORTED: OS=tvos
// UNSUPPORTED: OS=watchos
//
// Tests for the NSString APIs as exposed by String
//
import StdlibUnittest
import Foundation
import StdlibUnittestFoundationExtras
// The most simple subclass of NSString that CoreFoundation does not know
// about.
class NonContiguousNSString : NSString {
required init(coder aDecoder: NSCoder) {
fatalError("don't call this initializer")
}
required init(itemProviderData data: Data, typeIdentifier: String) throws {
fatalError("don't call this initializer")
}
override init() {
_value = []
super.init()
}
init(_ value: [UInt16]) {
_value = value
super.init()
}
@objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any {
// Ensure that copying this string produces a class that CoreFoundation
// does not know about.
return self
}
@objc override var length: Int {
return _value.count
}
@objc override func character(at index: Int) -> unichar {
return _value[index]
}
var _value: [UInt16]
}
let temporaryFileContents =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,\n" +
"sed do eiusmod tempor incididunt ut labore et dolore magna\n" +
"aliqua.\n"
func createNSStringTemporaryFile()
-> (existingPath: String, nonExistentPath: String) {
let existingPath =
createTemporaryFile("NSStringAPIs.", ".txt", temporaryFileContents)
let nonExistentPath = existingPath + "-NoNeXiStEnT"
return (existingPath, nonExistentPath)
}
var NSStringAPIs = TestSuite("NSStringAPIs")
NSStringAPIs.test("Encodings") {
let availableEncodings: [String.Encoding] = String.availableStringEncodings
expectNotEqual(0, availableEncodings.count)
let defaultCStringEncoding = String.defaultCStringEncoding
expectTrue(availableEncodings.contains(defaultCStringEncoding))
expectNotEqual("", String.localizedName(of: .utf8))
}
NSStringAPIs.test("NSStringEncoding") {
// Make sure NSStringEncoding and its values are type-compatible.
var enc: String.Encoding
enc = .windowsCP1250
enc = .utf32LittleEndian
enc = .utf32BigEndian
enc = .ascii
enc = .utf8
expectEqual(.utf8, enc)
}
NSStringAPIs.test("localizedStringWithFormat(_:...)") {
let world: NSString = "world"
expectEqual("Hello, world!%42", String.localizedStringWithFormat(
"Hello, %@!%%%ld", world, 42))
withOverriddenLocaleCurrentLocale("en_US") {
expectEqual("0.5", String.localizedStringWithFormat("%g", 0.5))
}
withOverriddenLocaleCurrentLocale("uk") {
expectEqual("0,5", String.localizedStringWithFormat("%g", 0.5))
}
}
NSStringAPIs.test("init(contentsOfFile:encoding:error:)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
do {
let content = try String(
contentsOfFile: existingPath, encoding: .ascii)
expectEqual(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
content._lines[0])
} catch {
expectUnreachableCatch(error)
}
do {
let _ = try String(
contentsOfFile: nonExistentPath, encoding: .ascii)
expectUnreachable()
} catch {
}
}
NSStringAPIs.test("init(contentsOfFile:usedEncoding:error:)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
do {
var usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
let content = try String(
contentsOfFile: existingPath, usedEncoding: &usedEncoding)
expectNotEqual(0, usedEncoding.rawValue)
expectEqual(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
content._lines[0])
} catch {
expectUnreachableCatch(error)
}
let usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
do {
_ = try String(contentsOfFile: nonExistentPath)
expectUnreachable()
} catch {
expectEqual(0, usedEncoding.rawValue)
}
}
NSStringAPIs.test("init(contentsOf:encoding:error:)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
let existingURL = URL(string: "file://" + existingPath)!
let nonExistentURL = URL(string: "file://" + nonExistentPath)!
do {
let content = try String(
contentsOf: existingURL, encoding: .ascii)
expectEqual(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
content._lines[0])
} catch {
expectUnreachableCatch(error)
}
do {
_ = try String(contentsOf: nonExistentURL, encoding: .ascii)
expectUnreachable()
} catch {
}
}
NSStringAPIs.test("init(contentsOf:usedEncoding:error:)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
let existingURL = URL(string: "file://" + existingPath)!
let nonExistentURL = URL(string: "file://" + nonExistentPath)!
do {
var usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
let content = try String(
contentsOf: existingURL, usedEncoding: &usedEncoding)
expectNotEqual(0, usedEncoding.rawValue)
expectEqual(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
content._lines[0])
} catch {
expectUnreachableCatch(error)
}
var usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
do {
_ = try String(contentsOf: nonExistentURL, usedEncoding: &usedEncoding)
expectUnreachable()
} catch {
expectEqual(0, usedEncoding.rawValue)
}
}
NSStringAPIs.test("init(cString_:encoding:)") {
expectOptionalEqual("foo, a basmati bar!",
String(cString:
"foo, a basmati bar!", encoding: String.defaultCStringEncoding))
}
NSStringAPIs.test("init(utf8String:)") {
let s = "foo あいう"
let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100)
var i = 0
for b in s.utf8 {
up[i] = b
i += 1
}
up[i] = 0
let cstr = UnsafeMutableRawPointer(up)
.bindMemory(to: CChar.self, capacity: 100)
expectOptionalEqual(s, String(utf8String: cstr))
up.deallocate()
}
NSStringAPIs.test("canBeConvertedToEncoding(_:)") {
expectTrue("foo".canBeConverted(to: .ascii))
expectFalse("あいう".canBeConverted(to: .ascii))
}
NSStringAPIs.test("capitalized") {
expectEqual("Foo Foo Foo Foo", "foo Foo fOO FOO".capitalized)
expectEqual("Жжж", "жжж".capitalized)
}
NSStringAPIs.test("localizedCapitalized") {
if #available(OSX 10.11, iOS 9.0, *) {
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectEqual(
"Foo Foo Foo Foo",
"foo Foo fOO FOO".localizedCapitalized)
expectEqual("Жжж", "жжж".localizedCapitalized)
return ()
}
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
withOverriddenLocaleCurrentLocale("en") {
expectEqual("Iii Iii", "iii III".localizedCapitalized)
}
// U+0069 LATIN SMALL LETTER I
// to upper case in Turkish locale:
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
withOverriddenLocaleCurrentLocale("tr") {
expectEqual("\u{0130}ii Iıı", "iii III".localizedCapitalized)
}
}
}
/// Checks that executing the operation in the locale with the given
/// `localeID` (or if `localeID` is `nil`, the current locale) gives
/// the expected result, and that executing the operation with a nil
/// locale gives the same result as explicitly passing the system
/// locale.
///
/// - Parameter expected: the expected result when the operation is
/// executed in the given localeID
func expectLocalizedEquality(
_ expected: String,
_ op: (_: Locale?) -> String,
_ localeID: String? = nil,
_ message: @autoclosure () -> String = "",
showFrame: Bool = true,
stackTrace: SourceLocStack = SourceLocStack(),
file: String = #file, line: UInt = #line
) {
let trace = stackTrace.pushIf(showFrame, file: file, line: line)
let locale = localeID.map {
Locale(identifier: $0)
} ?? Locale.current
expectEqual(
expected, op(locale),
message(), stackTrace: trace)
}
NSStringAPIs.test("capitalizedString(with:)") {
expectLocalizedEquality(
"Foo Foo Foo Foo",
{ loc in "foo Foo fOO FOO".capitalized(with: loc) })
expectLocalizedEquality("Жжж", { loc in "жжж".capitalized(with: loc) })
expectEqual(
"Foo Foo Foo Foo",
"foo Foo fOO FOO".capitalized(with: nil))
expectEqual("Жжж", "жжж".capitalized(with: nil))
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
expectLocalizedEquality(
"Iii Iii",
{ loc in "iii III".capitalized(with: loc) }, "en")
// U+0069 LATIN SMALL LETTER I
// to upper case in Turkish locale:
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
expectLocalizedEquality(
"İii Iıı",
{ loc in "iii III".capitalized(with: loc) }, "tr")
}
NSStringAPIs.test("caseInsensitiveCompare(_:)") {
expectEqual(ComparisonResult.orderedSame,
"abCD".caseInsensitiveCompare("AbCd"))
expectEqual(ComparisonResult.orderedAscending,
"abCD".caseInsensitiveCompare("AbCdE"))
expectEqual(ComparisonResult.orderedSame,
"абвг".caseInsensitiveCompare("АбВг"))
expectEqual(ComparisonResult.orderedAscending,
"абВГ".caseInsensitiveCompare("АбВгД"))
}
NSStringAPIs.test("commonPrefix(with:options:)") {
expectEqual("ab",
"abcd".commonPrefix(with: "abdc", options: []))
expectEqual("abC",
"abCd".commonPrefix(with: "abce", options: .caseInsensitive))
expectEqual("аб",
"абвг".commonPrefix(with: "абгв", options: []))
expectEqual("абВ",
"абВг".commonPrefix(with: "абвд", options: .caseInsensitive))
}
NSStringAPIs.test("compare(_:options:range:locale:)") {
expectEqual(ComparisonResult.orderedSame,
"abc".compare("abc"))
expectEqual(ComparisonResult.orderedAscending,
"абв".compare("где"))
expectEqual(ComparisonResult.orderedSame,
"abc".compare("abC", options: .caseInsensitive))
expectEqual(ComparisonResult.orderedSame,
"абв".compare("абВ", options: .caseInsensitive))
do {
let s = "abcd"
let r = s.index(after: s.startIndex)..<s.endIndex
expectEqual(ComparisonResult.orderedSame,
s.compare("bcd", range: r))
}
do {
let s = "абвг"
let r = s.index(after: s.startIndex)..<s.endIndex
expectEqual(ComparisonResult.orderedSame,
s.compare("бвг", range: r))
}
expectEqual(ComparisonResult.orderedSame,
"abc".compare("abc", locale: Locale.current))
expectEqual(ComparisonResult.orderedSame,
"абв".compare("абв", locale: Locale.current))
}
NSStringAPIs.test("completePath(into:caseSensitive:matchesInto:filterTypes)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
do {
let count = nonExistentPath.completePath(caseSensitive: false)
expectEqual(0, count)
}
do {
var outputName = "None Found"
let count = nonExistentPath.completePath(
into: &outputName, caseSensitive: false)
expectEqual(0, count)
expectEqual("None Found", outputName)
}
do {
var outputName = "None Found"
var outputArray: [String] = ["foo", "bar"]
let count = nonExistentPath.completePath(
into: &outputName, caseSensitive: false, matchesInto: &outputArray)
expectEqual(0, count)
expectEqual("None Found", outputName)
expectEqual(["foo", "bar"], outputArray)
}
do {
let count = existingPath.completePath(caseSensitive: false)
expectEqual(1, count)
}
do {
var outputName = "None Found"
let count = existingPath.completePath(
into: &outputName, caseSensitive: false)
expectEqual(1, count)
expectEqual(existingPath, outputName)
}
do {
var outputName = "None Found"
var outputArray: [String] = ["foo", "bar"]
let count = existingPath.completePath(
into: &outputName, caseSensitive: false, matchesInto: &outputArray)
expectEqual(1, count)
expectEqual(existingPath, outputName)
expectEqual([existingPath], outputArray)
}
do {
var outputName = "None Found"
let count = existingPath.completePath(
into: &outputName, caseSensitive: false, filterTypes: ["txt"])
expectEqual(1, count)
expectEqual(existingPath, outputName)
}
}
NSStringAPIs.test("components(separatedBy:) (NSCharacterSet)") {
expectEqual([""], "".components(
separatedBy: CharacterSet.decimalDigits))
expectEqual(
["абв", "", "あいう", "abc"],
"абв12あいう3abc".components(
separatedBy: CharacterSet.decimalDigits))
expectEqual(
["абв", "", "あいう", "abc"],
"абв\u{1F601}\u{1F602}あいう\u{1F603}abc"
.components(
separatedBy: CharacterSet(charactersIn: "\u{1F601}\u{1F602}\u{1F603}")))
// Performs Unicode scalar comparison.
expectEqual(
["abcし\u{3099}def"],
"abcし\u{3099}def".components(
separatedBy: CharacterSet(charactersIn: "\u{3058}")))
}
NSStringAPIs.test("components(separatedBy:) (String)") {
expectEqual([""], "".components(separatedBy: "//"))
expectEqual(
["абв", "あいう", "abc"],
"абв//あいう//abc".components(separatedBy: "//"))
// Performs normalization.
expectEqual(
["abc", "def"],
"abcし\u{3099}def".components(separatedBy: "\u{3058}"))
}
NSStringAPIs.test("cString(usingEncoding:)") {
expectNil("абв".cString(using: .ascii))
let expectedBytes: [UInt8] = [ 0xd0, 0xb0, 0xd0, 0xb1, 0xd0, 0xb2, 0 ]
let expectedStr: [CChar] = expectedBytes.map { CChar(bitPattern: $0) }
expectEqual(expectedStr,
"абв".cString(using: .utf8)!)
}
NSStringAPIs.test("data(usingEncoding:allowLossyConversion:)") {
expectNil("あいう".data(using: .ascii, allowLossyConversion: false))
do {
let data = "あいう".data(using: .utf8)!
let expectedBytes: [UInt8] = [
0xe3, 0x81, 0x82, 0xe3, 0x81, 0x84, 0xe3, 0x81, 0x86
]
expectEqualSequence(expectedBytes, data)
}
}
NSStringAPIs.test("init(data:encoding:)") {
let bytes: [UInt8] = [0xe3, 0x81, 0x82, 0xe3, 0x81, 0x84, 0xe3, 0x81, 0x86]
let data = Data(bytes: bytes)
expectNil(String(data: data, encoding: .nonLossyASCII))
expectEqualSequence(
"あいう",
String(data: data, encoding: .utf8)!)
}
NSStringAPIs.test("decomposedStringWithCanonicalMapping") {
expectEqual("abc", "abc".decomposedStringWithCanonicalMapping)
expectEqual("\u{305f}\u{3099}くてん", "だくてん".decomposedStringWithCanonicalMapping)
expectEqual("\u{ff80}\u{ff9e}クテン", "ダクテン".decomposedStringWithCanonicalMapping)
}
NSStringAPIs.test("decomposedStringWithCompatibilityMapping") {
expectEqual("abc", "abc".decomposedStringWithCompatibilityMapping)
expectEqual("\u{30bf}\u{3099}クテン", "ダクテン".decomposedStringWithCompatibilityMapping)
}
NSStringAPIs.test("enumerateLines(_:)") {
var lines: [String] = []
"abc\n\ndefghi\njklm".enumerateLines {
(line: String, stop: inout Bool)
in
lines.append(line)
if lines.count == 3 {
stop = true
}
}
expectEqual(["abc", "", "defghi"], lines)
}
NSStringAPIs.test("enumerateLinguisticTagsIn(_:scheme:options:orthography:_:") {
let s: String = "Абв. Глокая куздра штеко будланула бокра и кудрячит бокрёнка. Абв."
let startIndex = s.index(s.startIndex, offsetBy: 5)
let endIndex = s.index(s.startIndex, offsetBy: 62)
var tags: [String] = []
var tokens: [String] = []
var sentences: [String] = []
let range = startIndex..<endIndex
let scheme: NSLinguisticTagScheme = .tokenType
s.enumerateLinguisticTags(in: range,
scheme: scheme.rawValue,
options: [],
orthography: nil) {
(tag: String, tokenRange: Range<String.Index>, sentenceRange: Range<String.Index>, stop: inout Bool)
in
tags.append(tag)
tokens.append(String(s[tokenRange]))
sentences.append(String(s[sentenceRange]))
if tags.count == 3 {
stop = true
}
}
expectEqual([
NSLinguisticTag.word.rawValue,
NSLinguisticTag.whitespace.rawValue,
NSLinguisticTag.word.rawValue
], tags)
expectEqual(["Глокая", " ", "куздра"], tokens)
let sentence = String(s[startIndex..<endIndex])
expectEqual([sentence, sentence, sentence], sentences)
}
NSStringAPIs.test("enumerateSubstringsIn(_:options:_:)") {
let s = "え\u{304b}\u{3099}お\u{263a}\u{fe0f}😀😊"
let startIndex = s.index(s.startIndex, offsetBy: 1)
let endIndex = s.index(s.startIndex, offsetBy: 5)
do {
var substrings: [String] = []
// FIXME(strings): this API should probably change to accept a Substring?
// instead of a String? and a range.
s.enumerateSubstrings(in: startIndex..<endIndex,
options: String.EnumerationOptions.byComposedCharacterSequences) {
(substring: String?, substringRange: Range<String.Index>,
enclosingRange: Range<String.Index>, stop: inout Bool)
in
substrings.append(substring!)
expectEqual(substring, String(s[substringRange]))
expectEqual(substring, String(s[enclosingRange]))
}
expectEqual(["\u{304b}\u{3099}", "お", "☺️", "😀"], substrings)
}
do {
var substrings: [String] = []
s.enumerateSubstrings(in: startIndex..<endIndex,
options: [.byComposedCharacterSequences, .substringNotRequired]) {
(substring_: String?, substringRange: Range<String.Index>,
enclosingRange: Range<String.Index>, stop: inout Bool)
in
expectNil(substring_)
let substring = s[substringRange]
substrings.append(String(substring))
expectEqual(substring, s[enclosingRange])
}
expectEqual(["\u{304b}\u{3099}", "お", "☺️", "😀"], substrings)
}
}
NSStringAPIs.test("fastestEncoding") {
let availableEncodings: [String.Encoding] = String.availableStringEncodings
expectTrue(availableEncodings.contains("abc".fastestEncoding))
}
NSStringAPIs.test("getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)") {
let s = "abc абв def где gh жз zzz"
let startIndex = s.index(s.startIndex, offsetBy: 8)
let endIndex = s.index(s.startIndex, offsetBy: 22)
do {
// 'maxLength' is limiting.
let bufferLength = 100
var expectedStr: [UInt8] = Array("def где ".utf8)
while (expectedStr.count != bufferLength) {
expectedStr.append(0xff)
}
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
let result = s.getBytes(&buffer, maxLength: 11, usedLength: &usedLength,
encoding: .utf8,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
expectEqual(11, usedLength)
expectEqual(remainingRange.lowerBound, s.index(startIndex, offsetBy: 8))
expectEqual(remainingRange.upperBound, endIndex)
}
do {
// 'bufferLength' is limiting. Note that the buffer is not filled
// completely, since doing that would break a UTF sequence.
let bufferLength = 5
var expectedStr: [UInt8] = Array("def ".utf8)
while (expectedStr.count != bufferLength) {
expectedStr.append(0xff)
}
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
let result = s.getBytes(&buffer, maxLength: 11, usedLength: &usedLength,
encoding: .utf8,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
expectEqual(4, usedLength)
expectEqual(remainingRange.lowerBound, s.index(startIndex, offsetBy: 4))
expectEqual(remainingRange.upperBound, endIndex)
}
do {
// 'range' is converted completely.
let bufferLength = 100
var expectedStr: [UInt8] = Array("def где gh жз ".utf8)
while (expectedStr.count != bufferLength) {
expectedStr.append(0xff)
}
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
let result = s.getBytes(&buffer, maxLength: bufferLength,
usedLength: &usedLength, encoding: .utf8,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
expectEqual(19, usedLength)
expectEqual(remainingRange.lowerBound, endIndex)
expectEqual(remainingRange.upperBound, endIndex)
}
do {
// Inappropriate encoding.
let bufferLength = 100
var expectedStr: [UInt8] = Array("def ".utf8)
while (expectedStr.count != bufferLength) {
expectedStr.append(0xff)
}
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
let result = s.getBytes(&buffer, maxLength: bufferLength,
usedLength: &usedLength, encoding: .ascii,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
expectEqual(4, usedLength)
expectEqual(remainingRange.lowerBound, s.index(startIndex, offsetBy: 4))
expectEqual(remainingRange.upperBound, endIndex)
}
}
NSStringAPIs.test("getCString(_:maxLength:encoding:)") {
let s = "abc あかさた"
do {
// The largest buffer that cannot accommodate the string plus null terminator.
let bufferLength = 16
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = s.getCString(&buffer, maxLength: 100,
encoding: .utf8)
expectFalse(result)
}
do {
// The smallest buffer where the result can fit.
let bufferLength = 17
var expectedStr = "abc あかさた\0".utf8.map { CChar(bitPattern: $0) }
while (expectedStr.count != bufferLength) {
expectedStr.append(CChar(bitPattern: 0xff))
}
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = s.getCString(&buffer, maxLength: 100,
encoding: .utf8)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
}
do {
// Limit buffer size with 'maxLength'.
let bufferLength = 100
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = s.getCString(&buffer, maxLength: 8,
encoding: .utf8)
expectFalse(result)
}
do {
// String with unpaired surrogates.
let illFormedUTF16 = NonContiguousNSString([ 0xd800 ]) as String
let bufferLength = 100
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = illFormedUTF16.getCString(&buffer, maxLength: 100,
encoding: .utf8)
expectFalse(result)
}
}
NSStringAPIs.test("getLineStart(_:end:contentsEnd:forRange:)") {
let s = "Глокая куздра\nштеко будланула\nбокра и кудрячит\nбокрёнка."
let r = s.index(s.startIndex, offsetBy: 16)..<s.index(s.startIndex, offsetBy: 35)
do {
var outStartIndex = s.startIndex
var outLineEndIndex = s.startIndex
var outContentsEndIndex = s.startIndex
s.getLineStart(&outStartIndex, end: &outLineEndIndex,
contentsEnd: &outContentsEndIndex, for: r)
expectEqual("штеко будланула\nбокра и кудрячит\n",
s[outStartIndex..<outLineEndIndex])
expectEqual("штеко будланула\nбокра и кудрячит",
s[outStartIndex..<outContentsEndIndex])
}
}
NSStringAPIs.test("getParagraphStart(_:end:contentsEnd:forRange:)") {
let s = "Глокая куздра\nштеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.\n Абв."
let r = s.index(s.startIndex, offsetBy: 16)..<s.index(s.startIndex, offsetBy: 35)
do {
var outStartIndex = s.startIndex
var outEndIndex = s.startIndex
var outContentsEndIndex = s.startIndex
s.getParagraphStart(&outStartIndex, end: &outEndIndex,
contentsEnd: &outContentsEndIndex, for: r)
expectEqual("штеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.\n",
s[outStartIndex..<outEndIndex])
expectEqual("штеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.",
s[outStartIndex..<outContentsEndIndex])
}
}
NSStringAPIs.test("hash") {
let s: String = "abc"
let nsstr: NSString = "abc"
expectEqual(nsstr.hash, s.hash)
}
NSStringAPIs.test("init(bytes:encoding:)") {
var s: String = "abc あかさた"
expectOptionalEqual(
s, String(bytes: s.utf8, encoding: .utf8))
/*
FIXME: Test disabled because the NSString documentation is unclear about
what should actually happen in this case.
expectNil(String(bytes: bytes, length: bytes.count,
encoding: .ascii))
*/
// FIXME: add a test where this function actually returns nil.
}
NSStringAPIs.test("init(bytesNoCopy:length:encoding:freeWhenDone:)") {
var s: String = "abc あかさた"
var bytes: [UInt8] = Array(s.utf8)
expectOptionalEqual(s, String(bytesNoCopy: &bytes,
length: bytes.count, encoding: .utf8,
freeWhenDone: false))
/*
FIXME: Test disabled because the NSString documentation is unclear about
what should actually happen in this case.
expectNil(String(bytesNoCopy: &bytes, length: bytes.count,
encoding: .ascii, freeWhenDone: false))
*/
// FIXME: add a test where this function actually returns nil.
}
NSStringAPIs.test("init(utf16CodeUnits:count:)") {
let expected = "abc абв \u{0001F60A}"
let chars: [unichar] = Array(expected.utf16)
expectEqual(expected, String(utf16CodeUnits: chars, count: chars.count))
}
NSStringAPIs.test("init(utf16CodeUnitsNoCopy:count:freeWhenDone:)") {
let expected = "abc абв \u{0001F60A}"
let chars: [unichar] = Array(expected.utf16)
expectEqual(expected, String(utf16CodeUnitsNoCopy: chars,
count: chars.count, freeWhenDone: false))
}
NSStringAPIs.test("init(format:_:...)") {
expectEqual("", String(format: ""))
expectEqual(
"abc абв \u{0001F60A}", String(format: "abc абв \u{0001F60A}"))
let world: NSString = "world"
expectEqual("Hello, world!%42",
String(format: "Hello, %@!%%%ld", world, 42))
// test for rdar://problem/18317906
expectEqual("3.12", String(format: "%.2f", 3.123456789))
expectEqual("3.12", NSString(format: "%.2f", 3.123456789))
}
NSStringAPIs.test("init(format:arguments:)") {
expectEqual("", String(format: "", arguments: []))
expectEqual(
"abc абв \u{0001F60A}",
String(format: "abc абв \u{0001F60A}", arguments: []))
let world: NSString = "world"
let args: [CVarArg] = [ world, 42 ]
expectEqual("Hello, world!%42",
String(format: "Hello, %@!%%%ld", arguments: args))
}
NSStringAPIs.test("init(format:locale:_:...)") {
let world: NSString = "world"
expectEqual("Hello, world!%42", String(format: "Hello, %@!%%%ld",
locale: nil, world, 42))
}
NSStringAPIs.test("init(format:locale:arguments:)") {
let world: NSString = "world"
let args: [CVarArg] = [ world, 42 ]
expectEqual("Hello, world!%42", String(format: "Hello, %@!%%%ld",
locale: nil, arguments: args))
}
NSStringAPIs.test("utf16Count") {
expectEqual(1, "a".utf16.count)
expectEqual(2, "\u{0001F60A}".utf16.count)
}
NSStringAPIs.test("lengthOfBytesUsingEncoding(_:)") {
expectEqual(1, "a".lengthOfBytes(using: .utf8))
expectEqual(2, "あ".lengthOfBytes(using: .shiftJIS))
}
NSStringAPIs.test("lineRangeFor(_:)") {
let s = "Глокая куздра\nштеко будланула\nбокра и кудрячит\nбокрёнка."
let r = s.index(s.startIndex, offsetBy: 16)..<s.index(s.startIndex, offsetBy: 35)
do {
let result = s.lineRange(for: r)
expectEqual("штеко будланула\nбокра и кудрячит\n", s[result])
}
}
NSStringAPIs.test("linguisticTagsIn(_:scheme:options:orthography:tokenRanges:)") {
let s: String = "Абв. Глокая куздра штеко будланула бокра и кудрячит бокрёнка. Абв."
let startIndex = s.index(s.startIndex, offsetBy: 5)
let endIndex = s.index(s.startIndex, offsetBy: 17)
var tokenRanges: [Range<String.Index>] = []
let scheme = NSLinguisticTagScheme.tokenType
let tags = s.linguisticTags(in: startIndex..<endIndex,
scheme: scheme.rawValue,
options: [],
orthography: nil, tokenRanges: &tokenRanges)
expectEqual([
NSLinguisticTag.word.rawValue,
NSLinguisticTag.whitespace.rawValue,
NSLinguisticTag.word.rawValue
], tags)
expectEqual(["Глокая", " ", "куздра"],
tokenRanges.map { String(s[$0]) } )
}
NSStringAPIs.test("localizedCaseInsensitiveCompare(_:)") {
expectEqual(ComparisonResult.orderedSame,
"abCD".localizedCaseInsensitiveCompare("AbCd"))
expectEqual(ComparisonResult.orderedAscending,
"abCD".localizedCaseInsensitiveCompare("AbCdE"))
expectEqual(ComparisonResult.orderedSame,
"абвг".localizedCaseInsensitiveCompare("АбВг"))
expectEqual(ComparisonResult.orderedAscending,
"абВГ".localizedCaseInsensitiveCompare("АбВгД"))
}
NSStringAPIs.test("localizedCompare(_:)") {
expectEqual(ComparisonResult.orderedAscending,
"abCD".localizedCompare("AbCd"))
expectEqual(ComparisonResult.orderedAscending,
"абвг".localizedCompare("АбВг"))
}
NSStringAPIs.test("localizedStandardCompare(_:)") {
expectEqual(ComparisonResult.orderedAscending,
"abCD".localizedStandardCompare("AbCd"))
expectEqual(ComparisonResult.orderedAscending,
"абвг".localizedStandardCompare("АбВг"))
}
NSStringAPIs.test("localizedLowercase") {
if #available(OSX 10.11, iOS 9.0, *) {
withOverriddenLocaleCurrentLocale("en") {
expectEqual("abcd", "abCD".localizedLowercase)
}
withOverriddenLocaleCurrentLocale("en") {
expectEqual("абвг", "абВГ".localizedLowercase)
}
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("абвг", "абВГ".localizedLowercase)
}
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("たちつてと", "たちつてと".localizedLowercase)
}
//
// Special casing.
//
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
withOverriddenLocaleCurrentLocale("en") {
expectEqual("\u{0069}\u{0307}", "\u{0130}".localizedLowercase)
}
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
withOverriddenLocaleCurrentLocale("tr") {
expectEqual("\u{0069}", "\u{0130}".localizedLowercase)
}
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
withOverriddenLocaleCurrentLocale("en") {
expectEqual(
"\u{0069}\u{0307}",
"\u{0049}\u{0307}".localizedLowercase)
}
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
withOverriddenLocaleCurrentLocale("tr") {
expectEqual("\u{0069}", "\u{0049}\u{0307}".localizedLowercase)
}
}
}
NSStringAPIs.test("lowercased(with:)") {
expectLocalizedEquality("abcd", { loc in "abCD".lowercased(with: loc) }, "en")
expectLocalizedEquality("абвг", { loc in "абВГ".lowercased(with: loc) }, "en")
expectLocalizedEquality("абвг", { loc in "абВГ".lowercased(with: loc) }, "ru")
expectLocalizedEquality("たちつてと", { loc in "たちつてと".lowercased(with: loc) }, "ru")
//
// Special casing.
//
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectLocalizedEquality("\u{0069}\u{0307}", { loc in "\u{0130}".lowercased(with: loc) }, "en")
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
expectLocalizedEquality("\u{0069}", { loc in "\u{0130}".lowercased(with: loc) }, "tr")
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectLocalizedEquality("\u{0069}\u{0307}", { loc in "\u{0049}\u{0307}".lowercased(with: loc) }, "en")
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
expectLocalizedEquality("\u{0069}", { loc in "\u{0049}\u{0307}".lowercased(with: loc) }, "tr")
}
NSStringAPIs.test("maximumLengthOfBytesUsingEncoding(_:)") {
do {
let s = "abc"
expectLE(s.utf8.count,
s.maximumLengthOfBytes(using: .utf8))
}
do {
let s = "abc абв"
expectLE(s.utf8.count,
s.maximumLengthOfBytes(using: .utf8))
}
do {
let s = "\u{1F60A}"
expectLE(s.utf8.count,
s.maximumLengthOfBytes(using: .utf8))
}
}
NSStringAPIs.test("paragraphRangeFor(_:)") {
let s = "Глокая куздра\nштеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.\n Абв."
let r = s.index(s.startIndex, offsetBy: 16)..<s.index(s.startIndex, offsetBy: 35)
do {
let result = s.paragraphRange(for: r)
expectEqual("штеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.\n", s[result])
}
}
NSStringAPIs.test("pathComponents") {
expectEqual([ "/", "foo", "bar" ] as [NSString], ("/foo/bar" as NSString).pathComponents as [NSString])
expectEqual([ "/", "абв", "где" ] as [NSString], ("/абв/где" as NSString).pathComponents as [NSString])
}
NSStringAPIs.test("precomposedStringWithCanonicalMapping") {
expectEqual("abc", "abc".precomposedStringWithCanonicalMapping)
expectEqual("だくてん",
"\u{305f}\u{3099}くてん".precomposedStringWithCanonicalMapping)
expectEqual("ダクテン",
"\u{ff80}\u{ff9e}クテン".precomposedStringWithCanonicalMapping)
expectEqual("\u{fb03}", "\u{fb03}".precomposedStringWithCanonicalMapping)
}
NSStringAPIs.test("precomposedStringWithCompatibilityMapping") {
expectEqual("abc", "abc".precomposedStringWithCompatibilityMapping)
/*
Test disabled because of:
<rdar://problem/17041347> NFKD normalization as implemented by
'precomposedStringWithCompatibilityMapping:' is not idempotent
expectEqual("\u{30c0}クテン",
"\u{ff80}\u{ff9e}クテン".precomposedStringWithCompatibilityMapping)
*/
expectEqual("ffi", "\u{fb03}".precomposedStringWithCompatibilityMapping)
}
NSStringAPIs.test("propertyList()") {
expectEqual(["foo", "bar"],
"(\"foo\", \"bar\")".propertyList() as! [String])
}
NSStringAPIs.test("propertyListFromStringsFileFormat()") {
expectEqual(["foo": "bar", "baz": "baz"],
"/* comment */\n\"foo\" = \"bar\";\n\"baz\";"
.propertyListFromStringsFileFormat() as Dictionary<String, String>)
}
NSStringAPIs.test("rangeOfCharacterFrom(_:options:range:)") {
do {
let charset = CharacterSet(charactersIn: "абв")
do {
let s = "Глокая куздра"
let r = s.rangeOfCharacter(from: charset)!
expectEqual(s.index(s.startIndex, offsetBy: 4), r.lowerBound)
expectEqual(s.index(s.startIndex, offsetBy: 5), r.upperBound)
}
do {
expectNil("клмн".rangeOfCharacter(from: charset))
}
do {
let s = "абвклмнабвклмн"
let r = s.rangeOfCharacter(from: charset,
options: .backwards)!
expectEqual(s.index(s.startIndex, offsetBy: 9), r.lowerBound)
expectEqual(s.index(s.startIndex, offsetBy: 10), r.upperBound)
}
do {
let s = "абвклмнабв"
let r = s.rangeOfCharacter(from: charset,
range: s.index(s.startIndex, offsetBy: 3)..<s.endIndex)!
expectEqual(s.index(s.startIndex, offsetBy: 7), r.lowerBound)
expectEqual(s.index(s.startIndex, offsetBy: 8), r.upperBound)
}
}
do {
let charset = CharacterSet(charactersIn: "\u{305f}\u{3099}")
expectNil("\u{3060}".rangeOfCharacter(from: charset))
}
do {
let charset = CharacterSet(charactersIn: "\u{3060}")
expectNil("\u{305f}\u{3099}".rangeOfCharacter(from: charset))
}
do {
let charset = CharacterSet(charactersIn: "\u{1F600}")
do {
let s = "abc\u{1F600}"
expectEqual("\u{1F600}",
s[s.rangeOfCharacter(from: charset)!])
}
do {
expectNil("abc\u{1F601}".rangeOfCharacter(from: charset))
}
}
}
NSStringAPIs.test("rangeOfComposedCharacterSequence(at:)") {
let s = "\u{1F601}abc \u{305f}\u{3099} def"
expectEqual("\u{1F601}", s[s.rangeOfComposedCharacterSequence(
at: s.startIndex)])
expectEqual("a", s[s.rangeOfComposedCharacterSequence(
at: s.index(s.startIndex, offsetBy: 1))])
expectEqual("\u{305f}\u{3099}", s[s.rangeOfComposedCharacterSequence(
at: s.index(s.startIndex, offsetBy: 5))])
expectEqual(" ", s[s.rangeOfComposedCharacterSequence(
at: s.index(s.startIndex, offsetBy: 6))])
}
NSStringAPIs.test("rangeOfComposedCharacterSequences(for:)") {
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual("\u{1F601}a", s[s.rangeOfComposedCharacterSequences(
for: s.startIndex..<s.index(s.startIndex, offsetBy: 2))])
expectEqual("せ\u{3099}そ\u{3099}", s[s.rangeOfComposedCharacterSequences(
for: s.index(s.startIndex, offsetBy: 8)..<s.index(s.startIndex, offsetBy: 10))])
}
func toIntRange<
S : StringProtocol
>(
_ string: S, _ maybeRange: Range<String.Index>?
) -> Range<Int>? where S.Index == String.Index {
guard let range = maybeRange else { return nil }
return
string.distance(from: string.startIndex, to: range.lowerBound) ..<
string.distance(from: string.startIndex, to: range.upperBound)
}
NSStringAPIs.test("range(of:options:range:locale:)") {
do {
let s = ""
expectNil(s.range(of: ""))
expectNil(s.range(of: "abc"))
}
do {
let s = "abc"
expectNil(s.range(of: ""))
expectNil(s.range(of: "def"))
expectOptionalEqual(0..<3, toIntRange(s, s.range(of: "abc")))
}
do {
let s = "さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectOptionalEqual(2..<3, toIntRange(s, s.range(of: "す\u{3099}")))
expectOptionalEqual(2..<3, toIntRange(s, s.range(of: "\u{305a}")))
expectNil(s.range(of: "\u{3099}す"))
expectNil(s.range(of: "す"))
// Note: here `rangeOf` API produces indexes that don't point between
// grapheme cluster boundaries -- these cannot be created with public
// String interface.
//
// FIXME: why does this search succeed and the above queries fail? There is
// no apparent pattern.
expectEqual("\u{3099}", s[s.range(of: "\u{3099}")!])
}
do {
let s = "а\u{0301}б\u{0301}в\u{0301}г\u{0301}"
expectOptionalEqual(0..<1, toIntRange(s, s.range(of: "а\u{0301}")))
expectOptionalEqual(1..<2, toIntRange(s, s.range(of: "б\u{0301}")))
expectNil(s.range(of: "б"))
expectNil(s.range(of: "\u{0301}б"))
// FIXME: Again, indexes that don't correspond to grapheme
// cluster boundaries.
expectEqual("\u{0301}", s[s.range(of: "\u{0301}")!])
}
}
NSStringAPIs.test("contains(_:)") {
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectFalse("".contains(""))
expectFalse("".contains("a"))
expectFalse("a".contains(""))
expectFalse("a".contains("b"))
expectTrue("a".contains("a"))
expectFalse("a".contains("A"))
expectFalse("A".contains("a"))
expectFalse("a".contains("a\u{0301}"))
expectTrue("a\u{0301}".contains("a\u{0301}"))
expectFalse("a\u{0301}".contains("a"))
expectTrue("a\u{0301}".contains("\u{0301}"))
expectFalse("a".contains("\u{0301}"))
expectFalse("i".contains("I"))
expectFalse("I".contains("i"))
expectFalse("\u{0130}".contains("i"))
expectFalse("i".contains("\u{0130}"))
return ()
}
withOverriddenLocaleCurrentLocale("tr") {
expectFalse("\u{0130}".contains("ı"))
}
}
NSStringAPIs.test("localizedCaseInsensitiveContains(_:)") {
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectFalse("".localizedCaseInsensitiveContains(""))
expectFalse("".localizedCaseInsensitiveContains("a"))
expectFalse("a".localizedCaseInsensitiveContains(""))
expectFalse("a".localizedCaseInsensitiveContains("b"))
expectTrue("a".localizedCaseInsensitiveContains("a"))
expectTrue("a".localizedCaseInsensitiveContains("A"))
expectTrue("A".localizedCaseInsensitiveContains("a"))
expectFalse("a".localizedCaseInsensitiveContains("a\u{0301}"))
expectTrue("a\u{0301}".localizedCaseInsensitiveContains("a\u{0301}"))
expectFalse("a\u{0301}".localizedCaseInsensitiveContains("a"))
expectTrue("a\u{0301}".localizedCaseInsensitiveContains("\u{0301}"))
expectFalse("a".localizedCaseInsensitiveContains("\u{0301}"))
expectTrue("i".localizedCaseInsensitiveContains("I"))
expectTrue("I".localizedCaseInsensitiveContains("i"))
expectFalse("\u{0130}".localizedCaseInsensitiveContains("i"))
expectFalse("i".localizedCaseInsensitiveContains("\u{0130}"))
return ()
}
withOverriddenLocaleCurrentLocale("tr") {
expectFalse("\u{0130}".localizedCaseInsensitiveContains("ı"))
}
}
NSStringAPIs.test("localizedStandardContains(_:)") {
if #available(OSX 10.11, iOS 9.0, *) {
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectFalse("".localizedStandardContains(""))
expectFalse("".localizedStandardContains("a"))
expectFalse("a".localizedStandardContains(""))
expectFalse("a".localizedStandardContains("b"))
expectTrue("a".localizedStandardContains("a"))
expectTrue("a".localizedStandardContains("A"))
expectTrue("A".localizedStandardContains("a"))
expectTrue("a".localizedStandardContains("a\u{0301}"))
expectTrue("a\u{0301}".localizedStandardContains("a\u{0301}"))
expectTrue("a\u{0301}".localizedStandardContains("a"))
expectTrue("a\u{0301}".localizedStandardContains("\u{0301}"))
expectFalse("a".localizedStandardContains("\u{0301}"))
expectTrue("i".localizedStandardContains("I"))
expectTrue("I".localizedStandardContains("i"))
expectTrue("\u{0130}".localizedStandardContains("i"))
expectTrue("i".localizedStandardContains("\u{0130}"))
return ()
}
withOverriddenLocaleCurrentLocale("tr") {
expectTrue("\u{0130}".localizedStandardContains("ı"))
}
}
}
NSStringAPIs.test("localizedStandardRange(of:)") {
if #available(OSX 10.11, iOS 9.0, *) {
func rangeOf(_ string: String, _ substring: String) -> Range<Int>? {
return toIntRange(
string, string.localizedStandardRange(of: substring))
}
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectNil(rangeOf("", ""))
expectNil(rangeOf("", "a"))
expectNil(rangeOf("a", ""))
expectNil(rangeOf("a", "b"))
expectEqual(0..<1, rangeOf("a", "a"))
expectEqual(0..<1, rangeOf("a", "A"))
expectEqual(0..<1, rangeOf("A", "a"))
expectEqual(0..<1, rangeOf("a", "a\u{0301}"))
expectEqual(0..<1, rangeOf("a\u{0301}", "a\u{0301}"))
expectEqual(0..<1, rangeOf("a\u{0301}", "a"))
do {
// FIXME: Indices that don't correspond to grapheme cluster boundaries.
let s = "a\u{0301}"
expectEqual(
"\u{0301}", s[s.localizedStandardRange(of: "\u{0301}")!])
}
expectNil(rangeOf("a", "\u{0301}"))
expectEqual(0..<1, rangeOf("i", "I"))
expectEqual(0..<1, rangeOf("I", "i"))
expectEqual(0..<1, rangeOf("\u{0130}", "i"))
expectEqual(0..<1, rangeOf("i", "\u{0130}"))
return ()
}
withOverriddenLocaleCurrentLocale("tr") {
expectEqual(0..<1, rangeOf("\u{0130}", "ı"))
}
}
}
NSStringAPIs.test("smallestEncoding") {
let availableEncodings: [String.Encoding] = String.availableStringEncodings
expectTrue(availableEncodings.contains("abc".smallestEncoding))
}
func getHomeDir() -> String {
#if os(macOS)
return String(cString: getpwuid(getuid()).pointee.pw_dir)
#elseif os(iOS) || os(tvOS) || os(watchOS)
// getpwuid() returns null in sandboxed apps under iOS simulator.
return NSHomeDirectory()
#else
preconditionFailed("implement")
#endif
}
NSStringAPIs.test("addingPercentEncoding(withAllowedCharacters:)") {
expectOptionalEqual(
"abcd1234",
"abcd1234".addingPercentEncoding(withAllowedCharacters: .alphanumerics))
expectOptionalEqual(
"abcd%20%D0%B0%D0%B1%D0%B2%D0%B3",
"abcd абвг".addingPercentEncoding(withAllowedCharacters: .alphanumerics))
}
NSStringAPIs.test("appendingFormat(_:_:...)") {
expectEqual("", "".appendingFormat(""))
expectEqual("a", "a".appendingFormat(""))
expectEqual(
"abc абв \u{0001F60A}",
"abc абв \u{0001F60A}".appendingFormat(""))
let formatArg: NSString = "привет мир \u{0001F60A}"
expectEqual(
"abc абв \u{0001F60A}def привет мир \u{0001F60A} 42",
"abc абв \u{0001F60A}"
.appendingFormat("def %@ %ld", formatArg, 42))
}
NSStringAPIs.test("appending(_:)") {
expectEqual("", "".appending(""))
expectEqual("a", "a".appending(""))
expectEqual("a", "".appending("a"))
expectEqual("さ\u{3099}", "さ".appending("\u{3099}"))
}
NSStringAPIs.test("folding(options:locale:)") {
func fwo(
_ s: String, _ options: String.CompareOptions
) -> (Locale?) -> String {
return { loc in s.folding(options: options, locale: loc) }
}
expectLocalizedEquality("abcd", fwo("abCD", .caseInsensitive), "en")
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectLocalizedEquality(
"\u{0069}\u{0307}", fwo("\u{0130}", .caseInsensitive), "en")
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
expectLocalizedEquality(
"\u{0069}", fwo("\u{0130}", .caseInsensitive), "tr")
expectLocalizedEquality(
"example123", fwo("example123", .widthInsensitive), "en")
}
NSStringAPIs.test("padding(toLength:withPad:startingAtIndex:)") {
expectEqual(
"abc абв \u{0001F60A}",
"abc абв \u{0001F60A}".padding(
toLength: 10, withPad: "XYZ", startingAt: 0))
expectEqual(
"abc абв \u{0001F60A}XYZXY",
"abc абв \u{0001F60A}".padding(
toLength: 15, withPad: "XYZ", startingAt: 0))
expectEqual(
"abc абв \u{0001F60A}YZXYZ",
"abc абв \u{0001F60A}".padding(
toLength: 15, withPad: "XYZ", startingAt: 1))
}
NSStringAPIs.test("replacingCharacters(in:with:)") {
do {
let empty = ""
expectEqual("", empty.replacingCharacters(
in: empty.startIndex..<empty.startIndex, with: ""))
}
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual(s, s.replacingCharacters(
in: s.startIndex..<s.startIndex, with: ""))
expectEqual(s, s.replacingCharacters(
in: s.endIndex..<s.endIndex, with: ""))
expectEqual("zzz" + s, s.replacingCharacters(
in: s.startIndex..<s.startIndex, with: "zzz"))
expectEqual(s + "zzz", s.replacingCharacters(
in: s.endIndex..<s.endIndex, with: "zzz"))
expectEqual(
"す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.startIndex..<s.index(s.startIndex, offsetBy: 7), with: ""))
expectEqual(
"zzzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.startIndex..<s.index(s.startIndex, offsetBy: 7), with: "zzz"))
expectEqual(
"\u{1F602}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.startIndex..<s.index(s.startIndex, offsetBy: 7), with: "\u{1F602}"))
expectEqual("\u{1F601}", s.replacingCharacters(
in: s.index(after: s.startIndex)..<s.endIndex, with: ""))
expectEqual("\u{1F601}zzz", s.replacingCharacters(
in: s.index(after: s.startIndex)..<s.endIndex, with: "zzz"))
expectEqual("\u{1F601}\u{1F602}", s.replacingCharacters(
in: s.index(after: s.startIndex)..<s.endIndex, with: "\u{1F602}"))
expectEqual(
"\u{1F601}aす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.index(s.startIndex, offsetBy: 2)..<s.index(s.startIndex, offsetBy: 7), with: ""))
expectEqual(
"\u{1F601}azzzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.index(s.startIndex, offsetBy: 2)..<s.index(s.startIndex, offsetBy: 7), with: "zzz"))
expectEqual(
"\u{1F601}a\u{1F602}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.index(s.startIndex, offsetBy: 2)..<s.index(s.startIndex, offsetBy: 7),
with: "\u{1F602}"))
}
NSStringAPIs.test("replacingOccurrences(of:with:options:range:)") {
do {
let empty = ""
expectEqual("", empty.replacingOccurrences(
of: "", with: ""))
expectEqual("", empty.replacingOccurrences(
of: "", with: "xyz"))
expectEqual("", empty.replacingOccurrences(
of: "abc", with: "xyz"))
}
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual(s, s.replacingOccurrences(of: "", with: "xyz"))
expectEqual(s, s.replacingOccurrences(of: "xyz", with: ""))
expectEqual("", s.replacingOccurrences(of: s, with: ""))
expectEqual(
"\u{1F601}xyzbc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(of: "a", with: "xyz"))
expectEqual(
"\u{1F602}\u{1F603}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "\u{1F601}", with: "\u{1F602}\u{1F603}"))
expectEqual(
"\u{1F601}abc さ\u{3099}xyzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "し\u{3099}", with: "xyz"))
expectEqual(
"\u{1F601}abc さ\u{3099}xyzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "し\u{3099}", with: "xyz"))
expectEqual(
"\u{1F601}abc さ\u{3099}xyzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "\u{3058}", with: "xyz"))
//
// Use non-default 'options:'
//
expectEqual(
"\u{1F602}\u{1F603}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "\u{1F601}", with: "\u{1F602}\u{1F603}",
options: String.CompareOptions.literal))
expectEqual(s, s.replacingOccurrences(
of: "\u{3058}", with: "xyz",
options: String.CompareOptions.literal))
//
// Use non-default 'range:'
//
expectEqual(
"\u{1F602}\u{1F603}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "\u{1F601}", with: "\u{1F602}\u{1F603}",
options: String.CompareOptions.literal,
range: s.startIndex..<s.index(s.startIndex, offsetBy: 1)))
expectEqual(s, s.replacingOccurrences(
of: "\u{1F601}", with: "\u{1F602}\u{1F603}",
options: String.CompareOptions.literal,
range: s.index(s.startIndex, offsetBy: 1)..<s.index(s.startIndex, offsetBy: 3)))
}
NSStringAPIs.test("removingPercentEncoding") {
expectOptionalEqual(
"abcd абвг",
"abcd абвг".removingPercentEncoding)
expectOptionalEqual(
"abcd абвг\u{0000}\u{0001}",
"abcd абвг%00%01".removingPercentEncoding)
expectOptionalEqual(
"abcd абвг",
"%61%62%63%64%20%D0%B0%D0%B1%D0%B2%D0%B3".removingPercentEncoding)
expectOptionalEqual(
"abcd абвг",
"ab%63d %D0%B0%D0%B1%D0%B2%D0%B3".removingPercentEncoding)
expectNil("%ED%B0".removingPercentEncoding)
expectNil("%zz".removingPercentEncoding)
expectNil("abcd%FF".removingPercentEncoding)
expectNil("%".removingPercentEncoding)
}
NSStringAPIs.test("removingPercentEncoding/OSX 10.9")
.xfail(.osxMinor(10, 9, reason: "looks like a bug in Foundation in OS X 10.9"))
.xfail(.iOSMajor(7, reason: "same bug in Foundation in iOS 7.*"))
.skip(.iOSSimulatorAny("same bug in Foundation in iOS Simulator 7.*"))
.code {
expectOptionalEqual("", "".removingPercentEncoding)
}
NSStringAPIs.test("trimmingCharacters(in:)") {
expectEqual("", "".trimmingCharacters(
in: CharacterSet.decimalDigits))
expectEqual("abc", "abc".trimmingCharacters(
in: CharacterSet.decimalDigits))
expectEqual("", "123".trimmingCharacters(
in: CharacterSet.decimalDigits))
expectEqual("abc", "123abc789".trimmingCharacters(
in: CharacterSet.decimalDigits))
// Performs Unicode scalar comparison.
expectEqual(
"し\u{3099}abc",
"し\u{3099}abc".trimmingCharacters(
in: CharacterSet(charactersIn: "\u{3058}")))
}
NSStringAPIs.test("NSString.stringsByAppendingPaths(_:)") {
expectEqual([] as [NSString], ("" as NSString).strings(byAppendingPaths: []) as [NSString])
expectEqual(
[ "/tmp/foo", "/tmp/bar" ] as [NSString],
("/tmp" as NSString).strings(byAppendingPaths: [ "foo", "bar" ]) as [NSString])
}
NSStringAPIs.test("substring(from:)") {
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual(s, s.substring(from: s.startIndex))
expectEqual("せ\u{3099}そ\u{3099}",
s.substring(from: s.index(s.startIndex, offsetBy: 8)))
expectEqual("", s.substring(from: s.index(s.startIndex, offsetBy: 10)))
}
NSStringAPIs.test("substring(to:)") {
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual("", s.substring(to: s.startIndex))
expectEqual("\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}",
s.substring(to: s.index(s.startIndex, offsetBy: 8)))
expectEqual(s, s.substring(to: s.index(s.startIndex, offsetBy: 10)))
}
NSStringAPIs.test("substring(with:)") {
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual("", s.substring(with: s.startIndex..<s.startIndex))
expectEqual(
"",
s.substring(with: s.index(s.startIndex, offsetBy: 1)..<s.index(s.startIndex, offsetBy: 1)))
expectEqual("", s.substring(with: s.endIndex..<s.endIndex))
expectEqual(s, s.substring(with: s.startIndex..<s.endIndex))
expectEqual(
"さ\u{3099}し\u{3099}す\u{3099}",
s.substring(with: s.index(s.startIndex, offsetBy: 5)..<s.index(s.startIndex, offsetBy: 8)))
}
NSStringAPIs.test("localizedUppercase") {
if #available(OSX 10.11, iOS 9.0, *) {
withOverriddenLocaleCurrentLocale("en") {
expectEqual("ABCD", "abCD".localizedUppercase)
}
withOverriddenLocaleCurrentLocale("en") {
expectEqual("АБВГ", "абВГ".localizedUppercase)
}
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("АБВГ", "абВГ".localizedUppercase)
}
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("たちつてと", "たちつてと".localizedUppercase)
}
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
withOverriddenLocaleCurrentLocale("en") {
expectEqual("\u{0049}", "\u{0069}".localizedUppercase)
}
// U+0069 LATIN SMALL LETTER I
// to upper case in Turkish locale:
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
withOverriddenLocaleCurrentLocale("tr") {
expectEqual("\u{0130}", "\u{0069}".localizedUppercase)
}
// U+00DF LATIN SMALL LETTER SHARP S
// to upper case:
// U+0053 LATIN CAPITAL LETTER S
// U+0073 LATIN SMALL LETTER S
// But because the whole string is converted to uppercase, we just get two
// U+0053.
withOverriddenLocaleCurrentLocale("en") {
expectEqual("\u{0053}\u{0053}", "\u{00df}".localizedUppercase)
}
// U+FB01 LATIN SMALL LIGATURE FI
// to upper case:
// U+0046 LATIN CAPITAL LETTER F
// U+0069 LATIN SMALL LETTER I
// But because the whole string is converted to uppercase, we get U+0049
// LATIN CAPITAL LETTER I.
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("\u{0046}\u{0049}", "\u{fb01}".localizedUppercase)
}
}
}
NSStringAPIs.test("uppercased(with:)") {
expectLocalizedEquality("ABCD", { loc in "abCD".uppercased(with: loc) }, "en")
expectLocalizedEquality("АБВГ", { loc in "абВГ".uppercased(with: loc) }, "en")
expectLocalizedEquality("АБВГ", { loc in "абВГ".uppercased(with: loc) }, "ru")
expectLocalizedEquality("たちつてと", { loc in "たちつてと".uppercased(with: loc) }, "ru")
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
expectLocalizedEquality("\u{0049}", { loc in "\u{0069}".uppercased(with: loc) }, "en")
// U+0069 LATIN SMALL LETTER I
// to upper case in Turkish locale:
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
expectLocalizedEquality("\u{0130}", { loc in "\u{0069}".uppercased(with: loc) }, "tr")
// U+00DF LATIN SMALL LETTER SHARP S
// to upper case:
// U+0053 LATIN CAPITAL LETTER S
// U+0073 LATIN SMALL LETTER S
// But because the whole string is converted to uppercase, we just get two
// U+0053.
expectLocalizedEquality("\u{0053}\u{0053}", { loc in "\u{00df}".uppercased(with: loc) }, "en")
// U+FB01 LATIN SMALL LIGATURE FI
// to upper case:
// U+0046 LATIN CAPITAL LETTER F
// U+0069 LATIN SMALL LETTER I
// But because the whole string is converted to uppercase, we get U+0049
// LATIN CAPITAL LETTER I.
expectLocalizedEquality("\u{0046}\u{0049}", { loc in "\u{fb01}".uppercased(with: loc) }, "ru")
}
NSStringAPIs.test("write(toFile:atomically:encoding:error:)") {
let (_, nonExistentPath) = createNSStringTemporaryFile()
do {
let s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
try s.write(
toFile: nonExistentPath, atomically: false, encoding: .ascii)
let content = try String(
contentsOfFile: nonExistentPath, encoding: .ascii)
expectEqual(s, content)
} catch {
expectUnreachableCatch(error)
}
}
NSStringAPIs.test("write(to:atomically:encoding:error:)") {
let (_, nonExistentPath) = createNSStringTemporaryFile()
let nonExistentURL = URL(string: "file://" + nonExistentPath)!
do {
let s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
try s.write(
to: nonExistentURL, atomically: false, encoding: .ascii)
let content = try String(
contentsOfFile: nonExistentPath, encoding: .ascii)
expectEqual(s, content)
} catch {
expectUnreachableCatch(error)
}
}
NSStringAPIs.test("applyingTransform(_:reverse:)") {
if #available(OSX 10.11, iOS 9.0, *) {
do {
let source = "tre\u{300}s k\u{fc}hl"
expectEqual(
"tres kuhl",
source.applyingTransform(.stripDiacritics, reverse: false))
}
do {
let source = "hiragana"
expectEqual(
"ひらがな",
source.applyingTransform(.latinToHiragana, reverse: false))
}
do {
let source = "ひらがな"
expectEqual(
"hiragana",
source.applyingTransform(.latinToHiragana, reverse: true))
}
}
}
NSStringAPIs.test("SameTypeComparisons") {
// U+0323 COMBINING DOT BELOW
// U+0307 COMBINING DOT ABOVE
// U+1E63 LATIN SMALL LETTER S WITH DOT BELOW
let xs = "\u{1e69}"
expectTrue(xs == "s\u{323}\u{307}")
expectFalse(xs != "s\u{323}\u{307}")
expectTrue("s\u{323}\u{307}" == xs)
expectFalse("s\u{323}\u{307}" != xs)
expectTrue("\u{1e69}" == "s\u{323}\u{307}")
expectFalse("\u{1e69}" != "s\u{323}\u{307}")
expectTrue(xs == xs)
expectFalse(xs != xs)
}
NSStringAPIs.test("MixedTypeComparisons") {
// U+0323 COMBINING DOT BELOW
// U+0307 COMBINING DOT ABOVE
// U+1E63 LATIN SMALL LETTER S WITH DOT BELOW
// NSString does not decompose characters, so the two strings will be (==) in
// swift but not in Foundation.
let xs = "\u{1e69}"
let ys: NSString = "s\u{323}\u{307}"
expectFalse(ys == "\u{1e69}")
expectTrue(ys != "\u{1e69}")
expectFalse("\u{1e69}" == ys)
expectTrue("\u{1e69}" != ys)
expectFalse(xs as NSString == ys)
expectTrue(xs as NSString != ys)
expectTrue(ys == ys)
expectFalse(ys != ys)
}
NSStringAPIs.test("CompareStringsWithUnpairedSurrogates")
.xfail(
.custom({ true },
reason: "<rdar://problem/18029104> Strings referring to underlying " +
"storage with unpaired surrogates compare unequal"))
.code {
let donor = "abcdef"
let acceptor = "\u{1f601}\u{1f602}\u{1f603}"
expectEqual("\u{fffd}\u{1f602}\u{fffd}",
acceptor[donor.index(donor.startIndex, offsetBy: 1)..<donor.index(donor.startIndex, offsetBy: 5)])
}
NSStringAPIs.test("copy construction") {
let expected = "abcd"
let x = NSString(string: expected as NSString)
expectEqual(expected, x as String)
let y = NSMutableString(string: expected as NSString)
expectEqual(expected, y as String)
}
runAllTests()
| apache-2.0 | 837e6e29c7bb2f52af65a553563eff71 | 31.269085 | 105 | 0.669905 | 3.885839 | false | true | false | false |
akane/Gaikan | Gaikan/Style/StyleRule+DirectAccess.swift | 1 | 3857 | //
// This file is part of Gaikan
//
// Created by JC on 17/06/16.
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code
//
import Foundation
public extension StyleRule {
public var background: BackgroundValue? {
get { return self[.background].map { return $0 as! BackgroundValue } }
set { self.attributes[.background] = newValue }
}
public var border: Border? {
get { return self[.border].map { return $0 as! Border } }
set { self.attributes[.border] = newValue }
}
public var clip: Bool {
get { return self[.clip].map { return $0 as! Bool } ?? false }
set { self.attributes[.clip] = newValue }
}
public var corners: Corners? {
get { return self[.cornerRadius].map { return $0 as! Corners } }
set { self.attributes[.cornerRadius] = newValue }
}
public var color: UIColor? {
get { return self[.color].map { return $0 as! UIColor } }
set { self.attributes[.color] = newValue }
}
public var font: UIFont? {
get { return self[.font].map { return $0 as! UIFont } }
set { self.attributes[.font] = newValue }
}
public var height: Constraint? {
get { return self[.height].map { $0 as! Constraint } }
set { self.attributes[.height] = newValue }
}
public var margin: UIEdgeInsets? {
get { return self[.margin].map { return $0 as! UIEdgeInsets } }
set { self.attributes[.margin] = newValue }
}
public var maxHeight: Constraint? {
get { return self[.maxHeight].map { $0 as! Constraint } }
set { self.attributes[.maxHeight] = newValue }
}
public var maxWidth: Constraint? {
get { return self[.maxWidth].map { $0 as! Constraint } }
set { self.attributes[.maxWidth] = newValue }
}
public var minHeight: Constraint? {
get { return self[.minHeight].map { $0 as! Constraint } }
set { self.attributes[.minHeight] = newValue }
}
public var minWidth: Constraint? {
get { return self[.minWidth].map { $0 as! Constraint } }
set { self.attributes[.minWidth] = newValue }
}
/// value must be between 0 and 100
/// default is 100
public var opacity: Double {
get { return self[.opacity].map { return $0 as! Double } ?? 100 }
set { self.attributes[.opacity] = newValue }
}
public var shadow: NSShadow? {
get { return self[.shadow].map { return $0 as! NSShadow } }
set { self.attributes[.shadow] = newValue }
}
public var textAlign: NSTextAlignment? {
get { return self[.textAlign].map { return $0 as! NSTextAlignment } }
set { self.attributes[.textAlign] = newValue }
}
public var textOverflow: NSLineBreakMode? {
get { return self[.textOverflow].map { return $0 as! NSLineBreakMode } }
set { self.attributes[.textOverflow] = newValue }
}
public var tintColor: UIColor? {
get { return self[.tintColor].map { return $0 as! UIColor } }
set { self.attributes[.tintColor] = newValue }
}
public var transform: CATransform3D {
get { return self[.transform].map { return $0 as! CATransform3D } ?? CATransform3DIdentity }
set { self.attributes[.transform] = newValue }
}
public var visible: Bool? {
get { return self[.visible].map { return $0 as! Bool } }
set { self.attributes[.visible] = newValue }
}
public var width: Constraint? {
get { return self[.width].map { $0 as! Constraint } }
set { self.attributes[.width] = newValue }
}
public var textShadow: NSShadow? {
get { return self[.textShadow].map { return $0 as! NSShadow } }
set { self.attributes[.textShadow] = newValue }
}
}
| mit | f4994a0910589599bf0a2a0875882f7a | 31.686441 | 100 | 0.599948 | 4.15625 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/General/UserDefaults + Helpers.swift | 1 | 19790 | //
// UserDefaults + Helpers.swift
// PennMobile
//
// Created by Josh Doman on 7/31/17.
// Copyright © 2017 PennLabs. All rights reserved.
//
import Foundation
import WebKit
// MARK: UserDefaultsKeys
extension UserDefaults {
enum UserDefaultsKeys: String, CaseIterable {
case account
case accountID
case deviceUUID
case controllerSettings
case sessionCount
case laundryPreferences
case isOnboarded
case appVersion
case cookies
case wharton
case coursePermission
case hasDiningPlan
case lastLogin
case unsentLogs
case lastTransactionRequest
case authedIntoShibboleth
case courses
case housing
case privacyPreferences
case notificationPreferences
case PCAPreferences
case gsrGroupsEnabled
case totpEnabledDate
case lastDiningHoursRequest
case lastMenuRequest
case diningTokenExpiration
case diningBalance
case nextAnalyticsStartDate
case firstDollarsBalance
case firstSwipesBalance
}
func clearAll() {
for key in UserDefaultsKeys.allCases {
removeObject(forKey: key.rawValue)
}
for option in PrivacyOption.allCases {
removeObject(forKey: option.didRequestKey)
removeObject(forKey: option.didShareKey)
}
}
}
// MARK: AccountID
extension UserDefaults {
func set(accountID: String) {
set(accountID, forKey: UserDefaultsKeys.accountID.rawValue)
synchronize()
}
func getAccountID() -> String? {
return string(forKey: UserDefaultsKeys.accountID.rawValue)
}
func clearAccountID() {
removeObject(forKey: UserDefaultsKeys.accountID.rawValue)
}
}
// MARK: Permanent DeviceUUID
extension UserDefaults {
func set(deviceUUID: String) {
set(deviceUUID, forKey: UserDefaultsKeys.deviceUUID.rawValue)
synchronize()
}
func getDeviceUUID() -> String? {
return string(forKey: UserDefaultsKeys.deviceUUID.rawValue)
}
func isFirstTimeUser() -> Bool {
return getDeviceUUID() == nil
}
}
// MARK: VC Controller Settings (order of VCs)
extension UserDefaults {
func set(vcDisplayNames: [String]) {
set(vcDisplayNames, forKey: UserDefaultsKeys.controllerSettings.rawValue)
synchronize()
}
func getVCDisplayNames() -> [String]? {
return array(forKey: UserDefaultsKeys.controllerSettings.rawValue) as? [String]
}
}
extension UserDefaults {
func set(sessionCount: Int) {
set(sessionCount, forKey: UserDefaultsKeys.sessionCount.rawValue)
synchronize()
}
func getSessionCount() -> Int? {
return integer(forKey: UserDefaultsKeys.sessionCount.rawValue)
}
func incrementSessionCount() {
if let count = getSessionCount() {
UserDefaults.standard.set(sessionCount: count + 1)
} else {
set(sessionCount: 0)
}
}
}
// MARK: Laundry Preferences
extension UserDefaults {
func setLaundryPreferences(to ids: [Int]) {
set(ids, forKey: UserDefaultsKeys.laundryPreferences.rawValue)
synchronize()
}
func getLaundryPreferences() -> [Int]? {
return array(forKey: UserDefaultsKeys.laundryPreferences.rawValue) as? [Int]
}
}
// MARK: Onboarding Status
extension UserDefaults {
func setIsOnboarded(value: Bool) {
set(value, forKey: UserDefaultsKeys.isOnboarded.rawValue)
synchronize()
}
func isOnboarded() -> Bool {
return bool(forKey: UserDefaultsKeys.isOnboarded.rawValue)
}
}
// MARK: Account
extension UserDefaults {
func saveAccount(_ account: Account) {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(account) {
UserDefaults.standard.set(encoded, forKey: UserDefaultsKeys.account.rawValue)
}
synchronize()
}
func getAccount() -> Account? {
let decoder = JSONDecoder()
if let decodedData = UserDefaults.standard.data(forKey: UserDefaultsKeys.account.rawValue) {
return try? decoder.decode(Account.self, from: decodedData)
}
return nil
}
func clearAccount() {
removeObject(forKey: UserDefaultsKeys.account.rawValue)
}
}
// MARK: - Courses
extension UserDefaults {
func clearCourses() {
removeObject(forKey: UserDefaultsKeys.courses.rawValue)
}
}
// MARK: - App Version
extension UserDefaults {
func isNewAppVersion() -> Bool {
let prevAppVersion = string(forKey: UserDefaultsKeys.appVersion.rawValue) ?? ""
let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
return prevAppVersion != version
}
func getAppVersion() -> String {
let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
return version
}
func setAppVersion() {
let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
set(version, forKey: UserDefaultsKeys.appVersion.rawValue)
synchronize()
}
}
// MARK: - Wharton Flag
extension UserDefaults {
func set(isInWharton: Bool) {
set(isInWharton, forKey: UserDefaultsKeys.wharton.rawValue)
synchronize()
}
func isInWharton() -> Bool {
return bool(forKey: UserDefaultsKeys.wharton.rawValue)
}
func clearWhartonFlag() {
removeObject(forKey: UserDefaultsKeys.wharton.rawValue)
}
}
// MARK: - Has Dining Plan
extension UserDefaults {
func set(hasDiningPlan: Bool) {
set(hasDiningPlan, forKey: UserDefaultsKeys.hasDiningPlan.rawValue)
synchronize()
}
func hasDiningPlan() -> Bool {
return bool(forKey: UserDefaultsKeys.hasDiningPlan.rawValue)
}
func clearHasDiningPlan() {
removeObject(forKey: UserDefaultsKeys.hasDiningPlan.rawValue)
}
}
// MARK: - Cookies
extension UserDefaults {
func storeCookies() {
guard let cookies = HTTPCookieStorage.shared.cookies else { return }
var cookieDict = [String: AnyObject]()
for cookie in cookies {
cookieDict[cookie.name + cookie.domain] = cookie.properties as AnyObject?
}
set(cookieDict, forKey: UserDefaultsKeys.cookies.rawValue)
}
func restoreCookies() {
let cookiesStorage = HTTPCookieStorage.shared
if let cookieDictionary = self.dictionary(forKey: UserDefaultsKeys.cookies.rawValue) {
for (_, cookieProperties) in cookieDictionary {
if let cookie = HTTPCookie(properties: cookieProperties as! [HTTPCookiePropertyKey: Any] ) {
cookiesStorage.setCookie(cookie)
}
}
}
}
func clearCookies() {
removeObject(forKey: UserDefaultsKeys.cookies.rawValue)
}
}
// MARK: - Course Permission
extension UserDefaults {
func setCoursePermission(_ granted: Bool) {
set(granted, forKey: UserDefaultsKeys.coursePermission.rawValue)
synchronize()
}
func coursePermissionGranted() -> Bool {
return bool(forKey: UserDefaultsKeys.coursePermission.rawValue)
}
}
// MARK: - Last Login
extension UserDefaults {
func setLastLogin() {
set(Date(), forKey: UserDefaultsKeys.lastLogin.rawValue)
synchronize()
}
func getLastLogin() -> Date? {
return object(forKey: UserDefaultsKeys.lastLogin.rawValue) as? Date
}
}
// MARK: - Unsent Event Logs
extension UserDefaults {
func saveEventLogs(events: Set<FeedAnalyticsEvent>) {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(events) {
UserDefaults.standard.set(encoded, forKey: UserDefaultsKeys.unsentLogs.rawValue)
}
synchronize()
}
func getUnsentEventLogs() -> Set<FeedAnalyticsEvent>? {
let decoder = JSONDecoder()
if let decodedData = UserDefaults.standard.data(forKey: UserDefaultsKeys.unsentLogs.rawValue) {
return try? decoder.decode( Set<FeedAnalyticsEvent>.self, from: decodedData)
}
return nil
}
func clearEventLogs() {
removeObject(forKey: UserDefaultsKeys.unsentLogs.rawValue)
}
}
// MARK: - Last Transaction Request
extension UserDefaults {
func setLastTransactionRequest() {
set(Date(), forKey: UserDefaultsKeys.lastTransactionRequest.rawValue)
synchronize()
}
func getLastTransactionRequest() -> Date? {
return object(forKey: UserDefaultsKeys.lastTransactionRequest.rawValue) as? Date
}
func clearLastTransactionRequest() {
removeObject(forKey: UserDefaultsKeys.lastTransactionRequest.rawValue)
}
}
// MARK: - Authed Into Shibboleth
extension UserDefaults {
func setShibbolethAuth(authedIn: Bool) {
set(authedIn, forKey: UserDefaultsKeys.authedIntoShibboleth.rawValue)
synchronize()
}
func isAuthedIn() -> Bool {
return bool(forKey: UserDefaultsKeys.authedIntoShibboleth.rawValue)
}
}
// MARK: - Housing
extension UserDefaults {
func saveHousingResult(_ result: HousingResult) {
let currentResults = getHousingResults() ?? [HousingResult]()
var newResults = currentResults.filter { $0.start != result.start }
newResults.append(result)
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(newResults) {
UserDefaults.standard.set(encoded, forKey: UserDefaultsKeys.housing.rawValue)
}
synchronize()
}
func getHousingResults() -> [HousingResult]? {
let decoder = JSONDecoder()
if let decodedData = UserDefaults.standard.data(forKey: UserDefaultsKeys.housing.rawValue) {
return try? decoder.decode(Array<HousingResult>.self, from: decodedData)
}
return nil
}
func isOnCampus() -> Bool? {
guard let results = getHousingResults() else {
return nil
}
let now = Date()
let start = now.month <= 5 ? now.year - 1 : now.year
let filteredResults = results.filter { $0.start == start }
if filteredResults.isEmpty {
return nil
} else {
return filteredResults.contains { !$0.offCampus }
}
}
}
// MARK: - Privacy Settings
extension UserDefaults {
// MARK: Get and Save Preferences
// Set values for each privacy option
func set(_ privacyOption: PrivacyOption, to newValue: Bool) {
var prefs = getAllPrivacyPreferences()
prefs[privacyOption.rawValue] = newValue
saveAll(privacyPreferences: prefs)
}
// Get values for each privacy option (default to false if no preference exists)
func getPreference(for option: PrivacyOption) -> Bool {
let prefs = getAllPrivacyPreferences()
return prefs[option.rawValue] ?? option.defaultValue
}
// Fetch preferences from disk
func getAllPrivacyPreferences() -> PrivacyPreferences {
let decoder = JSONDecoder()
if let decodedData = UserDefaults.standard.data(forKey: UserDefaultsKeys.privacyPreferences.rawValue) {
return (try? decoder.decode(PrivacyPreferences.self, from: decodedData)) ?? .init()
}
return .init()
}
// Save all privacy preferences to disk
func saveAll(privacyPreferences: PrivacyPreferences) {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(privacyPreferences) {
UserDefaults.standard.set(encoded, forKey: UserDefaultsKeys.privacyPreferences.rawValue)
}
}
private func clearPrivacyPreferences() {
removeObject(forKey: UserDefaultsKeys.privacyPreferences.rawValue)
}
// MARK: Last Permission Request Date
// Set values representing whether or not permission was requested for a given privacy option
// This is not synced to the server, so we ask a user again if they ever delete the app or get a new phone
func setLastDidAskPermission(for privacyOption: PrivacyOption) {
UserDefaults.standard.set(Date(), forKey: privacyOption.didRequestKey)
}
// Get the last date we asked for this option, or nil if we've never asked (on this installation)
func getLastDidAskPermission(for privacyOption: PrivacyOption) -> Date? {
UserDefaults.standard.value(forKey: privacyOption.didRequestKey) as? Date
}
// MARK: Last Data Sharing Date
// Set the last date we shared data corresponding to this option (ex: when did we last upload courses)
func setLastShareDate(for privacyOption: PrivacyOption) {
UserDefaults.standard.set(Date(), forKey: privacyOption.didShareKey)
}
// Get the last date we shared data for this option
func getLastShareDate(for privacyOption: PrivacyOption) -> Date? {
UserDefaults.standard.value(forKey: privacyOption.didShareKey) as? Date
}
// MARK: Privacy Option UUID
// Each privacy option has its own UUID, which is sent to the server along with any anonymous data to allow us to track that data over time, as well as delete it if requested by the user.
func getPrivacyUUID(for privacyOption: PrivacyOption) -> String? {
if let privateKey = privacyOption.privateIDKey {
if let uuid = UserDefaults.standard.string(forKey: privateKey) {
return uuid
} else {
let uuid = String.randomString(length: 32)
UserDefaults.standard.set(uuid, forKey: privateKey)
return uuid
}
}
return nil
}
}
// MARK: - Notification Settings
extension UserDefaults {
// Set values for each notification option
func set(_ notificationOption: NotificationOption, to newValue: Bool) {
var prefs = getAllNotificationPreferences()
prefs[notificationOption.rawValue] = newValue
saveAll(notificationPreferences: prefs)
}
// Get values for each notification option (default to true if no preference exists)
func getPreference(for option: NotificationOption) -> Bool {
let prefs = getAllNotificationPreferences()
return prefs[option.rawValue] ?? option.defaultValue
}
// Fetch preferences from disk
func getAllNotificationPreferences() -> NotificationPreferences {
let decoder = JSONDecoder()
if let decodedData = UserDefaults.standard.data(forKey: UserDefaultsKeys.notificationPreferences.rawValue) {
return (try? decoder.decode(NotificationPreferences.self, from: decodedData)) ?? .init()
}
return .init()
}
// Save all notification preferences to disk
func saveAll(notificationPreferences: NotificationPreferences) {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(notificationPreferences) {
UserDefaults.standard.set(encoded, forKey: UserDefaultsKeys.notificationPreferences.rawValue)
}
}
private func clearNotificationPreferences() {
removeObject(forKey: UserDefaultsKeys.notificationPreferences.rawValue)
}
}
// MARK: - GSR Groups Settings
extension UserDefaults {
// Sets whether or not GSR Groups are enabled
func set(gsrGroupsEnabled: Bool) {
set(gsrGroupsEnabled, forKey: UserDefaultsKeys.gsrGroupsEnabled.rawValue)
synchronize()
}
func gsrGroupsEnabled() -> Bool {
return bool(forKey: UserDefaultsKeys.gsrGroupsEnabled.rawValue)
}
}
// MARK: - Two Factor Enabled flag
extension UserDefaults {
func getTwoFactorEnabledDate() -> Date? {
return UserDefaults.standard.value(forKey: UserDefaultsKeys.totpEnabledDate.rawValue) as? Date
}
func setTwoFactorEnabledDate(_ date: Date?) {
UserDefaults.standard.set(date, forKey: UserDefaultsKeys.totpEnabledDate.rawValue)
}
}
// MARK: - DiningHours
extension UserDefaults {
func setLastDiningHoursRequest() {
UserDefaults.standard.set(Date(), forKey: UserDefaultsKeys.lastDiningHoursRequest.rawValue)
}
func getLastDiningHoursRequest() -> Date? {
return UserDefaults.standard.value(forKey: UserDefaultsKeys.lastDiningHoursRequest.rawValue) as? Date
}
}
// MARK: - MenuRequest
extension UserDefaults {
func setLastMenuRequest(id: Int) {
let dict: [Int: Date]? = UserDefaults.standard.value(forKey: UserDefaultsKeys.lastMenuRequest.rawValue) as? [Int: Date]
if var menuDateDict = dict {
menuDateDict[id] = Date()
UserDefaults.standard.set(menuDateDict, forKey: UserDefaultsKeys.lastMenuRequest.rawValue)
} else {
let menuDateDictInit = [id: Date()]
UserDefaults.standard.set(menuDateDictInit, forKey: UserDefaultsKeys.lastMenuRequest.rawValue)
}
}
func getLastMenuRequest(id: Int) -> Date? {
let dict = UserDefaults.standard.value(forKey: UserDefaultsKeys.lastMenuRequest.rawValue) as? [Int: Date]
return dict?[id]
}
}
// MARK: - Dining Token Expiration
extension UserDefaults {
func setDiningTokenExpiration(_ diningTokenExpiration: Date) {
UserDefaults.standard.set(diningTokenExpiration, forKey: UserDefaultsKeys.diningTokenExpiration.rawValue)
}
func getDiningTokenExpiration() -> Date? {
let result = UserDefaults.standard.value(forKey: UserDefaultsKeys.diningTokenExpiration.rawValue)
return result as? Date
}
func clearDiningTokenExpiration() {
removeObject(forKey: UserDefaultsKeys.diningTokenExpiration.rawValue)
}
}
// MARK: - Current Dining Balance Object
extension UserDefaults {
func setdiningBalance(_ diningBalance: DiningBalance) {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(diningBalance) {
UserDefaults.standard.set(encoded, forKey: UserDefaultsKeys.diningBalance.rawValue)
}
synchronize()
}
func getDiningBalance() -> DiningBalance? {
let decoder = JSONDecoder()
if let decodedData = UserDefaults.standard.data(forKey: UserDefaultsKeys.diningBalance.rawValue) {
return try? decoder.decode(DiningBalance.self, from: decodedData)
}
return nil
}
func clearDiningBalance() {
removeObject(forKey: UserDefaultsKeys.diningBalance.rawValue)
}
}
// MARK: - Last dining analytics end date called
extension UserDefaults {
func setNextAnalyticsStartDate(_ date: String) {
set(date, forKey: UserDefaultsKeys.nextAnalyticsStartDate.rawValue)
synchronize()
}
func getNextAnalyticsStartDate() -> String? {
return string(forKey: UserDefaultsKeys.nextAnalyticsStartDate.rawValue)
}
func clearNextAnalyticsStartDateDate() {
removeObject(forKey: UserDefaultsKeys.nextAnalyticsStartDate.rawValue)
}
}
extension UserDefaults {
func setFirstDollarsBalance(_ balance: Double) {
set(balance, forKey: UserDefaultsKeys.firstDollarsBalance.rawValue)
synchronize()
}
func getFirstDollarsBalance() -> Double? {
return double(forKey: UserDefaultsKeys.firstDollarsBalance.rawValue)
}
func clearFirstDollarsBalance() {
removeObject(forKey: UserDefaultsKeys.firstDollarsBalance.rawValue)
}
}
extension UserDefaults {
func setFirstSwipesBalance(_ balance: Double) {
set(balance, forKey: UserDefaultsKeys.firstSwipesBalance.rawValue)
synchronize()
}
func getFirstSwipesBalance() -> Double? {
return double(forKey: UserDefaultsKeys.firstSwipesBalance.rawValue)
}
func clearFirstSwipesBalance() {
removeObject(forKey: UserDefaultsKeys.firstSwipesBalance.rawValue)
}
}
| mit | 2f885aef3893133c4a42266d9b1b7bbd | 30.969305 | 191 | 0.674819 | 4.934913 | false | false | false | false |
eKasztany/4ania | ios/Queue/Queue/Models/Address.swift | 1 | 551 | //
// Created by Aleksander Grzyb on 24/09/16.
// Copyright © 2016 Aleksander Grzyb. All rights reserved.
//
import Foundation
struct Address {
let city: String
let code: String
let street: String
}
extension Address {
init?(dictionary: JSONDictionary) {
guard let city = dictionary["city"] as? String,
let code = dictionary["code"] as? String,
let street = dictionary["street"] as? String else { return nil }
self.city = city
self.code = code
self.street = street
}
}
| apache-2.0 | 63450029ccd7ccd6bccf89a2a5fc235e | 22.913043 | 76 | 0.618182 | 4.074074 | false | false | false | false |
onurersel/anim | src/Ease.swift | 1 | 5360 | //
// Ease.swift
// anim
//
// Created by Onur Ersel on 2017-02-16.
// Copyright (c) 2017 Onur Ersel. All rights reserved.
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
/// Easing value. Stores two points for cubic easing calculation.
public struct animEase {
/// Handle for beginning point of cubic bezier
internal let point1: CGPoint
/// Handle for ending point of cubic bezier
internal let point2: CGPoint
/// Creates a custom easing value for cubic easing calculation.
///
/// - Parameters:
/// - point1: First handle point.
/// - point2: Second handle point.
/// - Returns: Easing value.
public static func custom(point1: CGPoint, point2: CGPoint) -> animEase {
return animEase(point1: point1, point2: point2)
}
/// Converts ease value to media timing function for `ViewAnimator`.
internal var caMediaTimingFunction: CAMediaTimingFunction {
return CAMediaTimingFunction(controlPoints: Float(point1.x), Float(point1.y), Float(point2.x), Float(point2.y))
}
/// http://easings.net/#easeInSine
public static let easeInSine = animEase(point1: CGPoint(x: 0.47, y: 0), point2: CGPoint(x: 0.745, y: 0.715))
/// http://easings.net/#easeOutSine
public static let easeOutSine = animEase(point1: CGPoint(x: 0.39, y: 0.575), point2: CGPoint(x: 0.565, y: 1))
/// http://easings.net/#easeInOutSine
public static let easeInOutSine = animEase(point1: CGPoint(x: 0.445, y: 0.05), point2: CGPoint(x: 0.55, y: 0.95))
/// http://easings.net/#easeInQuad
public static let easeInQuad = animEase(point1: CGPoint(x: 0.55, y: 0.085), point2: CGPoint(x: 0.68, y: 0.53))
/// http://easings.net/#easeOutQuad
public static let easeOutQuad = animEase(point1: CGPoint(x: 0.25, y: 0.46), point2: CGPoint(x: 0.45, y: 0.94))
/// http://easings.net/#easeInOutQuad
public static let easeInOutQuad = animEase(point1: CGPoint(x: 0.455, y: 0.03), point2: CGPoint(x: 0.515, y: 0.955))
/// http://easings.net/#easeInCubic
public static let easeInCubic = animEase(point1: CGPoint(x: 0.55, y: 0.055), point2: CGPoint(x: 0.675, y: 0.19))
/// http://easings.net/#easeOutCubic
public static let easeOutCubic = animEase(point1: CGPoint(x: 0.215, y: 0.61), point2: CGPoint(x: 0.355, y: 1))
/// http://easings.net/#easeInOutCubic
public static let easeInOutCubic = animEase(point1: CGPoint(x: 0.645, y: 0.045), point2: CGPoint(x: 0.355, y: 1))
/// http://easings.net/#easeInQuart
public static let easeInQuart = animEase(point1: CGPoint(x: 0.895, y: 0.03), point2: CGPoint(x: 0.685, y: 0.22))
/// http://easings.net/#easeOutQuart
public static let easeOutQuart = animEase(point1: CGPoint(x: 0.165, y: 0.84), point2: CGPoint(x: 0.44, y: 1))
/// http://easings.net/#easeInOutQuart
public static let easeInOutQuart = animEase(point1: CGPoint(x: 0.77, y: 0), point2: CGPoint(x: 0.175, y: 1))
/// http://easings.net/#easeInQuint
public static let easeInQuint = animEase(point1: CGPoint(x: 0.755, y: 0.05), point2: CGPoint(x: 0.855, y: 0.06))
/// http://easings.net/#easeOutQuint
public static let easeOutQuint = animEase(point1: CGPoint(x: 0.23, y: 1), point2: CGPoint(x: 0.32, y: 1))
/// http://easings.net/#easeInOutQuint
public static let easeInOutQuint = animEase(point1: CGPoint(x: 0.86, y: 0), point2: CGPoint(x: 0.07, y: 1))
/// http://easings.net/#easeInExpo
public static let easeInExpo = animEase(point1: CGPoint(x: 0.95, y: 0.05), point2: CGPoint(x: 0.795, y: 0.035))
/// http://easings.net/#easeOutExpo
public static let easeOutExpo = animEase(point1: CGPoint(x: 0.19, y: 1), point2: CGPoint(x: 0.22, y: 1))
/// http://easings.net/#easeInOutExpo
public static let easeInOutExpo = animEase(point1: CGPoint(x: 1, y: 0), point2: CGPoint(x: 0, y: 1))
/// http://easings.net/#easeInCirc
public static let easeInCirc = animEase(point1: CGPoint(x: 0.6, y: 0.04), point2: CGPoint(x: 0.98, y: 0.335))
/// http://easings.net/#easeOutCirc
public static let easeOutCirc = animEase(point1: CGPoint(x: 0.075, y: 0.82), point2: CGPoint(x: 0.165, y: 1))
/// http://easings.net/#easeInOutCirc
public static let easeInOutCirc = animEase(point1: CGPoint(x: 0.785, y: 0.135), point2: CGPoint(x: 0.15, y: 0.86))
/// http://easings.net/#easeInBack
public static let easeInBack = animEase(point1: CGPoint(x: 0.6, y: -0.28), point2: CGPoint(x: 0.735, y: 0.045))
/// http://easings.net/#easeOutBack
public static let easeOutBack = animEase(point1: CGPoint(x: 0.175, y: 0.885), point2: CGPoint(x: 0.32, y: 1.275))
/// http://easings.net/#easeInOutBack
public static let easeInOutBack = animEase(point1: CGPoint(x: 0.68, y: -0.55), point2: CGPoint(x: 0.265, y: 1.55))
}
extension animEase: Equatable {
/// Checks equality between easing types.
///
/// - Parameters:
/// - lhs: First easing value.
/// - rhs: Second easing value.
/// - Returns: Return if two easing values are equal or not.
public static func == (lhs: animEase, rhs: animEase) -> Bool {
return lhs.point1 == rhs.point1 && lhs.point2 == rhs.point2
}
}
| mit | ba90e9a4ee488712dd61d330ec9b7b38 | 49.566038 | 123 | 0.641231 | 3.274282 | false | false | false | false |
WestlakeAPC/game-off-2016 | external/Fiber2D/Fiber2D/Scheduling.swift | 1 | 1747 | //
// Scheduling.swift
// Fiber2D
//
// Created by Andrey Volodin on 28.08.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
public typealias Time = Float
extension Timer {
func forEach(block: (Timer) -> Void) {
var timer: Timer? = self
while timer != nil {
block(timer!)
timer = timer!.next
}
}
func removeRecursive(skip: Timer) -> Timer? {
if self === skip {
return self.next
} else {
self.next = self.next?.removeRecursive(skip: skip)
return self
}
}
}
// Targets are things that can have update: and fixedUpdate: methods called by the scheduler.
// Scheduled blocks (Timers) can be associated with a target to inherit their priority and paused state.
internal final class ScheduledTarget {
weak var target: Node?
var timers: Timer?
var actions = [ActionContainer]()
var empty: Bool {
return timers == nil && !enableUpdates
}
var hasActions: Bool {
return !actions.isEmpty
}
var paused = false {
didSet {
if paused != oldValue {
let pause = self.paused
timers?.forEach { $0.paused = pause }
}
}
}
var enableUpdates = false
func invalidateTimers() {
timers?.forEach { $0.invalidate() }
}
func add(action: ActionContainer) {
actions.append(action)
}
func removeAction(by tag: Int) {
actions = actions.filter {
$0.tag != tag
}
}
func remove(timer: Timer) {
timers = timers?.removeRecursive(skip: timer)
}
init(target: Node) {
self.target = target
}
}
| apache-2.0 | 68bf531f465ce96f87fd69af53a5de52 | 22.917808 | 104 | 0.553265 | 4.248175 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/BuySellKit/Core/Client/Model/Network/QuoteResponse.swift | 1 | 8340 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BigInt
import MoneyKit
import ToolKit
@available(*, deprecated, message: "This should not be used when new quote model becomes stable")
struct OldQuoteResponse: Decodable {
let time: String
let rate: String
let rateWithoutFee: String
let fee: String
}
struct QuoteResponse: Decodable {
struct FeeDetails: Decodable {
enum FeeFlag: String, Decodable {
case newUserWaiver = "NEW_USER_WAIVER"
}
let feeWithoutPromo: String
let fee: String
let feeFlags: [FeeFlag]
}
struct SettlementDetails: Decodable {
enum AvailabilityType: String, Decodable {
case instant = "INSTANT"
case regular = "REGULAR"
case unavailable = "UNAVAILABLE"
}
let availability: AvailabilityType
}
let quoteId: String
let quoteMarginPercent: Double
let quoteCreatedAt: String
let quoteExpiresAt: String
/// The price is in destination currency specified by the `brokerage/quote` request
let price: String
let networkFee: String?
let staticFee: String?
let feeDetails: FeeDetails
let settlementDetails: SettlementDetails
let sampleDepositAddress: String?
}
public struct Quote {
// MARK: - Types
enum SetupError: Error {
case dateFormatting
case feeParsing
case priceParsing
case wrongCurrenciesPair
}
// MARK: - Properties
public let quoteId: String?
public let quoteCreatedAt: Date
public let quoteExpiresAt: Date
public let fee: MoneyValue
public let rate: MoneyValue
public let estimatedDestinationAmount: MoneyValue
public let estimatedSourceAmount: MoneyValue
private let dateFormatter = DateFormatter.sessionDateFormat
// MARK: - Setup
@available(*, deprecated, message: "This should not be used when new quote model becomes stable")
init(
sourceCurrency: Currency,
destinationCurrency: Currency,
value: MoneyValue,
response: OldQuoteResponse
) throws {
guard let quoteCreated = dateFormatter.date(from: response.time) else {
throw SetupError.dateFormatting
}
guard let rate = BigInt(response.rate) else {
throw SetupError.priceParsing
}
guard let feeRateMinor = Decimal(string: response.fee) else {
throw SetupError.feeParsing
}
guard let source = sourceCurrency as? FiatCurrency,
let destination = destinationCurrency as? CryptoCurrency
else {
throw SetupError.wrongCurrenciesPair
}
let majorEstimatedAmount: Decimal = value.amount.decimalDivision(by: rate)
// Decimal string interpolation always uses '.' (full stop) as decimal separator, because of that we will use US locale.
let estimatedCryptoAmount = CryptoValue.create(major: majorEstimatedAmount, currency: destination)
estimatedDestinationAmount = estimatedCryptoAmount.moneyValue
let feeAmountMinor = feeRateMinor * estimatedDestinationAmount.displayMajorValue
// Decimal string interpolation always uses '.' (full stop) as decimal separator, because of that we will use US locale.
fee = FiatValue.create(minor: feeAmountMinor, currency: source).moneyValue
quoteCreatedAt = quoteCreated
let fiatRate = FiatValue.create(minor: rate, currency: source)
self.rate = fiatRate.moneyValue
estimatedSourceAmount = estimatedCryptoAmount.convert(using: fiatRate).moneyValue
// Unused
quoteId = nil
quoteExpiresAt = quoteCreatedAt
}
init(
sourceCurrency: Currency,
destinationCurrency: Currency,
value: MoneyValue,
response: QuoteResponse
) throws {
quoteId = response.quoteId
// formatting dates
guard let quoteCreatedDate = dateFormatter.date(from: response.quoteCreatedAt),
let quoteExpiresDate = dateFormatter.date(from: response.quoteExpiresAt)
else {
throw SetupError.dateFormatting
}
quoteCreatedAt = quoteCreatedDate
quoteExpiresAt = quoteExpiresDate
// parsing fee (source currency)
guard let feeMinor = Decimal(string: response.feeDetails.fee) else {
throw SetupError.feeParsing
}
// parsing price (destination currency)
guard let priceMinorBigInt = BigInt(response.price) else {
throw SetupError.priceParsing
}
switch (sourceCurrency, destinationCurrency) {
// buy flow
case (let source as FiatCurrency, let destination as CryptoCurrency):
guard let fiatAmount = value.fiatValue else {
fatalError("Amount must be in fiat for a buy quote")
}
let estimatedFiatAmount = FiatValue.create(minor: fiatAmount.amount, currency: source)
let cryptoPriceValue = CryptoValue.create(minor: priceMinorBigInt, currency: destination)
let cryptoPriceDisplayString = cryptoPriceValue.toDisplayString(includeSymbol: false, locale: Locale.US)
guard let cryptoMajorAmount = Decimal(string: cryptoPriceDisplayString) else {
throw SetupError.priceParsing
}
let fiatRate = FiatValue.create(major: 1 / cryptoMajorAmount, currency: source)
let estimatedCryptoAmount = CryptoValue.create(
major: estimatedFiatAmount.amount.decimalDivision(by: fiatRate.amount),
currency: destination
)
estimatedSourceAmount = estimatedFiatAmount.moneyValue
estimatedDestinationAmount = estimatedCryptoAmount.moneyValue
rate = fiatRate.moneyValue
fee = MoneyValue.create(minor: feeMinor, currency: .fiat(source))
// sell flow
case (let source as CryptoCurrency, let destination as FiatCurrency):
guard let cryptoAmount = value.cryptoValue else {
fatalError("Amount must be in crypto for a sell quote")
}
let estimatedCryptoAmount = CryptoValue.create(minor: cryptoAmount.amount, currency: source)
let fiatPriceValue = FiatValue.create(minor: priceMinorBigInt, currency: destination)
guard let fiatMajorAmount = Decimal(string: fiatPriceValue.displayString) else {
throw SetupError.priceParsing
}
let cryptoRate = CryptoValue.create(major: 1 / fiatMajorAmount, currency: source)
let estimatedFiatAmount = FiatValue.create(
major: estimatedCryptoAmount.amount.decimalDivision(by: cryptoRate.amount),
currency: destination
)
estimatedSourceAmount = estimatedCryptoAmount.moneyValue
estimatedDestinationAmount = estimatedFiatAmount.moneyValue
rate = cryptoRate.moneyValue
fee = MoneyValue.create(minor: feeMinor, currency: .crypto(source))
// swap flow
case (let source as CryptoCurrency, let destination as CryptoCurrency):
guard let cryptoAmount = value.cryptoValue else {
fatalError("Amount must be in crypto for a sell quote")
}
let fromTokenAmount = CryptoValue.create(minor: cryptoAmount.amount, currency: source)
let toTokenPriceValue = CryptoValue.create(minor: priceMinorBigInt, currency: destination)
guard let toTokenMajorAmount = Decimal(string: toTokenPriceValue.displayString) else {
throw SetupError.priceParsing
}
let fromTokenRate = CryptoValue.create(major: 1 / toTokenMajorAmount, currency: source)
let toTokenAmount = CryptoValue.create(
major: fromTokenAmount.amount.decimalDivision(by: fromTokenRate.amount),
currency: destination
)
estimatedSourceAmount = fromTokenAmount.moneyValue
estimatedDestinationAmount = toTokenAmount.moneyValue
rate = fromTokenRate.moneyValue
fee = MoneyValue.create(minor: feeMinor, currency: .crypto(source))
default:
fatalError("Unsupported source and destination currency pair")
}
}
}
| lgpl-3.0 | cc17b22cbdcfd326335f65a4a740ea25 | 39.480583 | 128 | 0.664828 | 5.453891 | false | false | false | false |
AlesTsurko/DNMKit | DNM_iOS/DNM_iOS/BGStratum.swift | 1 | 12807 | //
// BGStratum.swift
// denm_view
//
// Created by James Bean on 8/23/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
import DNMModel
// clean up, add documentation
public class BGStratum: ViewNode, BuildPattern {
public override var description: String { get { return getDescription() } }
private func getDescription() -> String {
var description: String = "BGStratum"
description += ": StemDirection: \(stemDirection)"
return description
}
// this is temporary!!
public var id: String? {
get { if iIDsByPID.count == 1 { return iIDsByPID.first!.0 }; return nil }
}
public var system: SystemLayer? // temp
public var g: CGFloat = 12
public var s: CGFloat = 1
public var gS: CGFloat { get { return g * s } }
public var stemDirection: StemDirection = .Down
public var beatWidth: CGFloat = 0
public var isMetrical: Bool?
public var isNumerical: Bool?
public var beamEndY: CGFloat { get { return getBeamEndY() } }
public var hasBeenBuilt: Bool = false
public var beamGroups: [BeamGroup] = []
public var bgEvents: [BGEvent] { get { return getBGEvents() } }
public var deNode: DENode?
public var saNodeByType: [ArticulationType : SANode] = [:]
public var beamsLayerGroup: BeamsLayerGroup?
public var tbGroupAtDepth: [Int : TBGroup] = [:]
public var tbLigaturesAtDepth: [Int : [TBLigature]] = [:]
public var augmentationDots: [AugmentationDot] = []
public var instrumentIDsByPerformerID: [String: [String]] { return getIIDsByPID() }
// deprecate
// make verbose title at some point: instrumentsIDsByPerformerID
public var iIDsByPID: [String: [String]] { get { return getIIDsByPID() } }
public init(stemDirection: StemDirection = .Down, g: CGFloat = 12, s: CGFloat = 1) {
super.init()
self.stemDirection = stemDirection
self.g = g
self.s = s
layoutAccumulation_vertical = stemDirection == .Down ? .Top : .Bottom
}
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
public override init(layer: AnyObject) { super.init(layer: layer) }
public func showTBGroupAtDepth(depth: Int) {
// something
}
public func hideTBGRoupAtDepth(depth: Int) {
}
public func commitDENode() {
if deNode != nil {
addNode(deNode!)
deNode!.layout()
}
}
private func createSANodes() {
}
private func ensureDENode() {
if deNode == nil {
deNode = DENode(left: 0, top: 0, height: 0.5 * beamGroups.first!.g)
deNode!.pad_bottom = 0.5 * g
deNode!.pad_top = 0.5 * g
}
}
private func addAugmentationDotsToDENode() {
guard let deNode = deNode else { return }
let augDotPad = g
// set amount of of augmentation dots... (2 for 7, 3 and so on)
for bgEvent in bgEvents {
if bgEvent.hasAugmentationDot {
let x = bgEvent.x_objective!
bgEvent.augmentationDot = deNode.addAugmentationDotAtX(x + augDotPad)
}
}
}
private func addDurationalExtensionsToDENode() {
guard let deNode = deNode else { return }
let pad = 0.618 * g
for e in 0..<bgEvents.count {
let curEvent = bgEvents[e]
// first event
if e == 0 {
if curEvent.stopsExtension {
let start: CGFloat = -2 * pad
let stop = curEvent.x_objective! - pad
deNode.addDurationalExtensionFromLeft(start, toRight: stop)
}
}
else {
let prevEvent = bgEvents[e - 1]
if curEvent.stopsExtension {
let x = prevEvent.augmentationDot?.frame.maxX ?? prevEvent.x_objective!
let start = x + pad
let stop = curEvent.x_objective! - pad // refine
deNode.addDurationalExtensionFromLeft(start, toRight: stop)
}
// last event
if e == bgEvents.count - 1 {
if curEvent.startsExtension {
let start_x = curEvent.augmentationDot?.frame.maxX ?? curEvent.x_objective!
let start = start_x + pad
let stop_x = system?.frame.width ?? UIScreen.mainScreen().bounds.width
let stop = stop_x + 2 * pad
deNode.addDurationalExtensionFromLeft(start, toRight: stop)
}
}
}
}
}
private func createDENode() {
ensureDENode()
addAugmentationDotsToDENode()
addDurationalExtensionsToDENode()
commitDENode()
layout()
}
public override func layout() {
super.layout()
// manage LIGATURES
/*
for (level, tbLigatures) in tbLigaturesAtDepth {
let beamEndY = stemDirection == .Down
? beamsLayerGroup!.frame.minY
: beamsLayerGroup!.frame.maxY
let bracketEndY = tbGroupAtDepth[level]!.position.y
for tbLigature in tbLigatures {
addSublayer(tbLigature)
tbLigature.setBeamEndY(beamEndY, andBracketEndY: bracketEndY)
}
}
*/
//uiView?.setFrame()
}
public func addBeamGroupWithDurationNode(durationNode: DurationNode, atX x: CGFloat) {
let beamGroup = BeamGroup(durationNode: durationNode, left: x)
beamGroup.beatWidth = beatWidth
beamGroups.append(beamGroup)
}
// make private
public func buildBeamGroups() {
for beamGroup in beamGroups {
beamGroup.g = g
beamGroup.s = s
beamGroup.stemDirection = stemDirection
if !beamGroup.hasBeenBuilt { beamGroup.build() }
}
}
// make private
public func commitBeamGroups() {
buildBeamGroups()
handOffBeamGroups()
}
private func handOffBeamGroups() {
for beamGroup in beamGroups { handOffBeamGroup(beamGroup) }
}
public func handOffTupletBracketGroupsFromBeamGroup(beamGroup: BeamGroup) {
for (depth, tbGroup) in beamGroup.tbGroupAtDepth {
addTBGroup(tbGroup, atDepth: depth)
}
}
public func handOffBeamGroup(beamGroup: BeamGroup) {
guard beamGroup.hasBeenBuilt else { return }
handOffTupletBracketGroupsFromBeamGroup(beamGroup)
ensureBeamsLayerGroup()
beamGroup.beamsLayerGroup!.layout()
beamGroup.bgStratum = self
beamsLayerGroup!.addNode(beamGroup.beamsLayerGroup!)
}
// THIS IS BEING REFACTORED OUT
/*
private func addMGNode(mgNode: MGNode, atDepth depth: Int) {
ensuremgNodeAtDepth(depth)
mgNodeAtDepth[depth]?.addNode(mgNode)
}
*/
private func ensureBeamsLayerGroup() {
if beamsLayerGroup == nil {
beamsLayerGroup = BeamsLayerGroup(stemDirection: stemDirection)
beamsLayerGroup!.pad_bottom = 6 // hack
beamsLayerGroup!.pad_top = 6 // hack
}
}
private func commitTBGroups() {
let tbGroupsSorted: [TBGroup] = makeSortedTBGroups()
for tbGroup in tbGroupsSorted { addNode(tbGroup) }
}
private func commitBeamsLayerGroup() {
addNode(beamsLayerGroup!)
}
public func build() {
buildBeamGroups()
commitBeamGroups()
commitTBGroups()
commitBeamsLayerGroup()
createDENode()
createSANodes()
layout()
hasBeenBuilt = true
}
// THESE ARE BEING REFACTORED OUT ------------------------------------------------------->
/*
private func makeSortedMGNodes() -> [MGNode] {
var mggs: [MGNode] = []
var mggsByDepth: [(Int, MGNode)] = []
for (depth, mgg) in mgNodeAtDepth {
mggsByDepth.append((depth, mgg))
}
mggsByDepth.sortInPlace { $0.0 < $1.0 }
for mgg in mggsByDepth { mggs.append(mgg.1) }
return mggs
}
*/
/*
public func addTestStems() {
for event in bgEvents {
let x = event.x + event.bgContainer!.left + event.bgContainer!.beamGroup!.left
let stem = Stem(x: x, beamEndY: beamsLayerGroup!.frame.minY, infoEndY: 100) // hack
stem.lineWidth = 0.0618 * beamGroups.first!.g // hack
let hue = HueByTupletDepth[event.bgContainer!.depth]
stem.strokeColor = UIColor.colorWithHue(hue, andDepthOfField: .Foreground).CGColor
addSublayer(stem)
}
}
*/
private func makeSortedTBGroups() -> [TBGroup] {
var tbgs: [TBGroup] = []
var tbgsByDepth: [(Int, TBGroup)] = []
for (depth, tbg) in tbGroupAtDepth { tbgsByDepth.append((depth, tbg)) }
tbgsByDepth.sortInPlace { $0.0 < $1.0 }
for tbg in tbgsByDepth { tbgs.append(tbg.1) }
return tbgs
}
private func addTBGroup(tbGroup: TBGroup, atDepth depth: Int ) {
ensureTupletBracketGroupAtDepth(depth)
tbGroupAtDepth[depth]?.addNode(tbGroup)
}
// THIS IS BEING REFACTORED OUT --------------------------------------------------------->
/*
private func ensuremgNodeAtDepth(depth: Int) {
if mgNodeAtDepth[depth] == nil {
mgNodeAtDepth[depth] = MGNode()
mgNodeAtDepth[depth]!.depth = depth
// TO-DO: PAD
//mgNodeAtDepth[depth]!.pad.bottom = 5
}
}
*/
private func ensureTupletBracketGroupAtDepth(depth: Int) {
if tbGroupAtDepth[depth] == nil {
tbGroupAtDepth[depth] = TBGroup()
tbGroupAtDepth[depth]!.pad_bottom = 3 // hack
tbGroupAtDepth[depth]!.pad_top = 3 // hack
tbGroupAtDepth[depth]!.depth = depth
tbGroupAtDepth[depth]!.bgStratum = self
}
}
private func getBGEvents() -> [BGEvent] {
var bgEvents: [BGEvent] = []
for beamGroup in beamGroups {
bgEvents.appendContentsOf(beamGroup.bgEvents)
}
for bgEvent in bgEvents { bgEvent.bgStratum = self }
bgEvents.sortInPlace { $0.x_inBGStratum! < $1.x_inBGStratum! }
return bgEvents
}
private func getPad_below() -> CGFloat {
// refine
return stemDirection == .Down ? 0.0618 * frame.height : 0.0618 * frame.height
}
private func getPad_above() -> CGFloat {
// refine
return stemDirection == .Down ? 0.0618 * frame.height : 0.0618 * frame.height
}
private func getBeamEndY() -> CGFloat {
if beamsLayerGroup != nil {
return stemDirection == .Up ? beamsLayerGroup!.frame.height : 0
}
else { return 0 }
}
private func getIIDsByPID() -> [String : [String]] {
var iIDsByPID: [String : [String]] = [:]
for beamGroup in beamGroups {
if let durationNode = beamGroup.durationNode {
let bg_iIDsByPID = durationNode.instrumentIDsByPerformerID
for (pid, iids) in bg_iIDsByPID {
if iIDsByPID[pid] == nil {
iIDsByPID[pid] = iids
}
else {
iIDsByPID[pid]!.appendContentsOf(iids)
iIDsByPID[pid] = iIDsByPID[pid]!.unique()
}
}
}
}
return iIDsByPID
}
// THESE ARE BEING REFACTORED OUT ------------------------------------------------------->
/*
public func switchMGNodeAtDepth(depth: Int) {
if !hasNode(mgNodeAtDepth[depth]!) { showMGNodeAtDepth(depth) }
else { hideMGNodeAtDepth(depth) }
}
*/
/*
public func showMGNodeAtDepth(depth: Int) {
let mgNode = mgNodeAtDepth[depth]
if mgNode == nil { return }
let tbGroup = tbGroupAtDepth[depth]
if tbGroup == nil { return }
if !hasNode(mgNode!) { insertNode(mgNode!, afterNode: tbGroup!) }
//layout()
//container?.layout()
print("showMGNodeAtDepth")
print("bgStratum.container: \(container)")
}
public func hideMGNodeAtDepth(depth: Int) {
let mgNode = mgNodeAtDepth[depth]
if mgNode == nil { return }
removeNode(mgNode!)
//layout()
//container?.layout()
}
*/
// <--------------------------------------------------------------------------------------
}
| gpl-2.0 | 3f80799753b593451e24886d5ec73c12 | 31.175879 | 99 | 0.555677 | 4.690842 | false | false | false | false |
tensorflow/swift-apis | Sources/TensorFlow/Epochs/Sampling.swift | 1 | 3069 | // Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// A lazy selection of elements, in a given order, from some base collection.
public struct Sampling<Base: Collection, Selection: Collection>
where Selection.Element == Base.Index {
/// The order that base elements appear in `self`.
private let selection: Selection
/// The base collection.
private let base: Base
/// Creates an instance from `base` and `selection`.
public init(base: Base, selection: Selection) {
self.selection = selection
self.base = base
}
}
extension Sampling: Collection {
public typealias Element = Base.Element
/// A type whose instances represent positions in `self`.
public typealias Index = Selection.Index
/// The position of the first element.
public var startIndex: Index { selection.startIndex }
/// The position one past the last element.
public var endIndex: Index { selection.endIndex }
/// Returns the element at `i`.
public subscript(i: Index) -> Element { base[selection[i]] }
/// Returns the position after `i`.
public func index(after i: Index) -> Index { selection.index(after: i) }
/// Returns the number of forward steps required to convert `start` into `end`.
///
/// A negative result indicates that `end < start`.
public func distance(from start: Index, to end: Index) -> Int {
selection.distance(from: start, to: end)
}
/// Returns the position `n` places from `i`.
public func index(_ i: Index, offsetBy n: Int) -> Index {
selection.index(i, offsetBy: n)
}
/// Returns `i` offset by `distance` unless that requires passing `limit`, in
/// which case `nil` is returned.
public func index(
_ i: Index, offsetBy distance: Int, limitedBy limit: Index
) -> Index? {
selection.index(i, offsetBy: distance, limitedBy: limit)
}
}
extension Sampling: BidirectionalCollection
where Selection: BidirectionalCollection
{
/// Returns the position before `i`.
public func index(before i: Index) -> Index {
selection.index(before: i)
}
}
extension Sampling: RandomAccessCollection
where Selection: RandomAccessCollection {}
extension Collection {
/// Returns a collection of elements of `self` at the positions and in the order
/// specified by `selection` without reading the elements of either collection.
///
/// - Complexity: O(1)
public func sampled<Selection: Collection>(at selection: Selection)
-> Sampling<Self, Selection>
{
.init(base: self, selection: selection)
}
}
| apache-2.0 | 09e5bb6b0e41c95b54de377f1bf01fc8 | 32.725275 | 82 | 0.707722 | 4.250693 | false | false | false | false |
dannys42/DTSImage | Sources/DTSImageRGBA8.swift | 1 | 6194 | //
// DTSImageRGBA8.swift
// Pods
//
// Created by Danny Sung on 12/01/2016.
//
//
import Foundation
import Accelerate
/// A Container to manage an image as raw 8-bit RGBA values
public struct DTSImageRGBA8: DTSImage {
// MARK: DTSImage conformance
public private(set) var width: Int
public private(set) var height: Int
public init(width: Int, height: Int, fill: DTSImageFillMethod) {
let numBytes = width * height * DTSImageRGBA8.numberOfComponentsPerPixel
let pixels: [UInt8]
switch fill {
case .black:
pixels = [UInt8].init(repeating: UInt8.min, count: numBytes)
case .white:
pixels = [UInt8].init(repeating: UInt8.max, count: numBytes)
case .value(let val):
pixels = [UInt8].init(repeating: UInt8(val), count: numBytes)
}
self.init(width: width, height: height, pixels: pixels)!
}
public func getPixel(x: Int, y:Int) throws -> DTSPixelRGBA8 {
guard self.coordinateIsValid(x: x, y: y) else { throw DTSImageError.outOfRange }
let offset = (y * self.width + x) * DTSPixelRGBA8.numberOfComponentsPerPixel
let pixel = DTSPixelRGBA8(red: self.pixels[offset+0],
green: self.pixels[offset+1],
blue: self.pixels[offset+2],
alpha: self.pixels[offset+3])
return pixel
}
public mutating func setPixel(x: Int, y:Int, pixel: DTSPixelRGBA8) {
guard self.coordinateIsValid(x: x, y: y) else { return }
let offset = (y * self.width + x) * DTSPixelRGBA8.numberOfComponentsPerPixel
self.pixels[offset+0] = pixel.red
self.pixels[offset+1] = pixel.green
self.pixels[offset+2] = pixel.blue
self.pixels[offset+3] = pixel.alpha
}
public init?(image: UIImage, scaleFactor: Float) {
guard let cgImage = image.cgImage else { return nil }
let outSize = CGSize(width: image.size.width * CGFloat(scaleFactor),
height: image.size.height * CGFloat(scaleFactor))
let width = Int(outSize.width)
let height = Int(outSize.height)
let numPixels = width * height
let numComponentsPerPixel = DTSImageRGBA8.numberOfComponentsPerPixel
let totalNumberOfComponents = numPixels * numComponentsPerPixel
self.width = width
self.height = height
let numBytesPerRow = width * DTSImageRGBA8.numberOfBytesPerPixel
let colorSpace = CGColorSpaceCreateDeviceRGB()
var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue
bitmapInfo |= CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
let black = UInt8(0)
var pixels = [UInt8](repeating: black, count: totalNumberOfComponents)
let buffer = UnsafeMutableBufferPointer(start: &pixels, count: numPixels).baseAddress!
guard let imageContext = CGContext(data: buffer,
width: width,
height: height,
bitsPerComponent: DTSImageRGBA8.numberOfBitsPerComponent,
bytesPerRow: numBytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo)
else { return nil }
imageContext.draw(cgImage, in: CGRect(origin: CGPoint.zero, size: outSize))
self.pixels = pixels
}
public func toUIImage() -> UIImage? {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let destBytesPerRow = self.width * DTSPixelRGBA8.bytesPerPixel
let destBitsPerComponent = 8
var bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue
bitmapInfo |= CGImageAlphaInfo.premultipliedLast.rawValue & CGBitmapInfo.alphaInfoMask.rawValue
guard let imageContext = CGContext(data: nil,
width: width,
height: height,
bitsPerComponent: destBitsPerComponent,
bytesPerRow: destBytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo,
releaseCallback: nil,
releaseInfo: nil)
else { return nil }
guard let buffer = imageContext.data else { return nil }
let pixels = buffer.bindMemory(to: DTSPixelRGBA8.self, capacity: self.numPixels)
let totalNumberOfComponents = Int(self.numPixels * 4)
memcpy(pixels, self.pixels, totalNumberOfComponents)
guard let cgImage = imageContext.makeImage() else { return nil }
let image = UIImage(cgImage: cgImage)
return image
}
// MARK: DTSImageComponentArray conformance
static public var numberOfComponentsPerPixel: Int = 4
public var pixels: [UInt8]
public init?(width: Int, height: Int, pixels: [UInt8]) {
guard pixels.count >= width * height * DTSImageRGBA8.numberOfComponentsPerPixel else { return nil }
self.width = width
self.height = height
self.pixels = pixels
}
// MARK: Custom methods
static public let numberOfBytesPerComponent = 1
static public var numberOfBitsPerComponent: Int = 8*numberOfBytesPerComponent
static public var numberOfBytesPerPixel: Int = DTSImageRGBA8.numberOfBytesPerComponent * DTSImageRGBA8.numberOfComponentsPerPixel
public var numberOfComponentsPerRow: Int {
get {
return DTSImageRGBA8.numberOfComponentsPerPixel * self.width
}
}
public var numberOfBytesPerRow: Int {
get {
return self.numberOfComponentsPerRow * DTSImageRGBA8.numberOfBytesPerComponent
}
}
// MARK: Protocol Conformance
// MARK: Private methods
}
| mit | 9c46854b7ec4929d1e16713f5a894b62 | 40.57047 | 133 | 0.590572 | 5.303082 | false | false | false | false |
nikHowlett/Attend-O | attendo1/Class.swift | 1 | 14395 | //
// Class.swift
// T-Squared for Georgia Tech
//
// Created by Cal on 8/27/15.
// Copyright © 2015 Cal Stephens. All rights reserved.
//
import Foundation
import UIKit
import Kanna
let TSClassOpenCountKey = "edu.gatech.cal.classOpenCount"
let TSSpecificSubjectNamesKey = "edu.gatech.cal.specificSubjectNamesDict"
func == (lhs: Class, rhs: Class) -> Bool {
return lhs.permanentID == rhs.permanentID
}
class Class : CustomStringConvertible, Equatable {
let permanentID: String
let fullName: String
let subjectID: String?
var subjectName: String?
let subjectIcon: String
var name: String
let link: String
var isActive: Bool = false
var classPage: HTMLDocument? {
didSet {
pullSpecificSubjectNameIfNotCached()
}
}
var announcements: [Announcement] = []
var rootResource: ResourceFolder?
var assignments: [Assignment]?
var grades: GradeGroup?
var description: String {
return name
}
var displayCell: UITableViewCell?
//MARK: - Set up the class and decide how it should be displayed
convenience init(fromElement element: XMLElement) {
let fullName = element.text!.cleansed()
let link = element["href"]!.stringByReplacingOccurrencesOfString("site", withString: "pda")
self.init(withFullName: fullName, link: link)
}
init(withFullName fullName: String, link: String, displayName: String? = nil) {
self.fullName = fullName
self.link = link
self.permanentID = link.componentsSeparatedByString("/").last ?? fullName
//create user-facing name
let nameParts = fullName.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "- "))
if nameParts.count >= 2 {
if let displayName = displayName {
self.name = displayName
} else {
self.name = nameParts[0] + " " + nameParts[1]
}
if nameParts[0].containsString("/") || nameParts[0].containsString("\\") {
self.subjectID = nameParts[0].componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "/\\"))[0]
} else {
self.subjectID = nameParts[0]
}
let subjectInfo = GTSubjects[self.subjectID!]
self.subjectName = subjectInfo?.description
self.subjectIcon = subjectInfo != nil ? "class-" + subjectInfo!.image : "class-language"
}
else {
self.name = displayName ?? fullName
let nsname = name as NSString
//attempt to find the subject name from the first few characters
for i in 1...min(5,nsname.length) {
let substring = nsname.substringToIndex(i)
if let subjectInfo = GTSubjects[substring] {
self.subjectID = substring
self.subjectName = subjectInfo.description
self.subjectIcon = "class-" + subjectInfo.image
return
}
}
self.subjectID = nil
self.subjectName = nil
self.subjectIcon = "class-language"
}
verifySingleSubjectName()
offsetOpenCount(0)
useSpecificSubjectNameIfCached()
}
func verifySingleSubjectName() {
//not really sure what this function is supposed to do, in retrospect
//something about classes where there are two names
if let subjectID = subjectID where (fullName as NSString).countOccurancesOfString(subjectID) > 1 {
var subs: [String] = []
let subNames = fullName.componentsSeparatedByString(" ")
for sub in subNames {
let nameParts = sub.componentsSeparatedByString("-")
if nameParts.count >= 2 {
let new = nameParts[0] + " " + nameParts[1]
if !subs.contains(new) {
subs.append(new)
}
}
}
if subs.count > 0 {
var newName = ""
for i in 0 ..< subs.count {
newName += subs[i]
newName += (i != (subs.count - 1) ? " / " : "")
}
self.name = newName
}
}
}
func useFullName() {
self.name = (fullName as NSString).stringByReplacingOccurrencesOfString("-", withString: " ")
offsetOpenCount(0)
}
func getClassPage() -> HTMLDocument? {
if let classPage = self.classPage { return classPage }
classPage = HttpClient.contentsOfPage(self.link)
return classPage
}
func useSpecificSubjectNameIfCached() {
//check if it's cached
let data = NSUserDefaults.standardUserDefaults()
let dict = data.dictionaryForKey(TSSpecificSubjectNamesKey) as? [String : String] ?? [:]
if let specificSubjectName = dict[self.permanentID] where specificSubjectName != "TSSubjectNameUnavailable" {
self.subjectName = specificSubjectName
return
}
}
static var cachedSpecificSubjectNames: [String : String]? = nil
func pullSpecificSubjectNameIfNotCached() {
//check if it's cached
Class.cachedSpecificSubjectNames = NSUserDefaults.standardUserDefaults().dictionaryForKey(TSSpecificSubjectNamesKey) as? [String : String] ?? [:]
if Class.cachedSpecificSubjectNames?[self.permanentID] != nil {
return
}
//not cached
let specificSubjectName = TSAuthenticatedReader.getSpecificSubjectNameForClass(self) ?? "TSSubjectNameUnavailable"
//reload the dictionary since things are happening asynchronously
if Class.cachedSpecificSubjectNames == nil {
Class.cachedSpecificSubjectNames = NSUserDefaults.standardUserDefaults().dictionaryForKey(TSSpecificSubjectNamesKey) as? [String : String] ?? [:]
}
Class.cachedSpecificSubjectNames?.updateValue(specificSubjectName, forKey: self.permanentID)
if let cachedSpecificSubjectNames = Class.cachedSpecificSubjectNames {
NSUserDefaults.standardUserDefaults().setValue(cachedSpecificSubjectNames, forKey: TSSpecificSubjectNamesKey)
}
if specificSubjectName != "TSSubjectNameUnavailable" {
self.subjectName = specificSubjectName
/*if let displayCell = displayCell {
if displayCell.nameLabel.text == self.name {
sync { displayCell.subjectLabel.text = specificSubjectName }
}
}*/
}
}
//MARK: - Tracking for 3D Touch Shortcut items
func markClassOpened() {
offsetOpenCount(1)
}
private static var ignoreOpenCountOffsets = false
private func offsetOpenCount(offset: Int) {
if Class.ignoreOpenCountOffsets { return }
//update open count on disk
let data = NSUserDefaults.standardUserDefaults()
var dict: [String : Int] = data.dictionaryForKey(TSClassOpenCountKey) as? [String : Int] ?? [:]
let key = "\(self.fullName)~~\(self.subjectIcon)~~\(self.name)~~\(self.link)"
var previousCount = dict[key] ?? 0
for otherKey in dict.keys {
//remove any duplicates from a name change out of my control
if otherKey.containsString(self.link) && otherKey != key {
let otherCount = dict[otherKey]!
previousCount += otherCount
dict.removeValueForKey(otherKey)
}
}
dict.updateValue(previousCount + offset, forKey: key)
data.setValue(dict, forKey: TSClassOpenCountKey)
//prevent this method from being called again while inside updateShortcutItems()
//because otherwise we get a recursive overflow
Class.ignoreOpenCountOffsets = true
Class.updateShortcutItems()
Class.ignoreOpenCountOffsets = false
}
static func updateShotcutItemsForActiveClasses(classes: [Class]) {
let activeClassLinks: [String] = classes.map({ return $0.link })
let data = NSUserDefaults.standardUserDefaults()
var dict: [String : Int] = data.dictionaryForKey(TSClassOpenCountKey) as? [String : Int] ?? [:]
for (key, _) in dict {
let link = key.componentsSeparatedByString("~~")[3]
if !activeClassLinks.contains(link) {
dict.removeValueForKey(key)
}
}
data.setValue(dict, forKey: TSClassOpenCountKey)
updateShortcutItems()
}
static func updateShortcutItems() {
//update Shortcut Items list
if #available(iOS 9.0, *) {
let data = NSUserDefaults.standardUserDefaults()
let dict: [String : Int] = data.dictionaryForKey(TSClassOpenCountKey) as? [String : Int] ?? [:]
let sorted = dict.sort{ $0.1 > $1.1 }
var shortcuts: [UIApplicationShortcutItem] = []
for i in 0 ..< min(4, sorted.count) {
let (key, _) = sorted[i]
let splits = key.componentsSeparatedByString("~~")
if splits.count != 4 { continue }
let fullName = splits[0]
let icon = splits[1]
let name = splits[2]
let link = splits[3]
//grab the subject display name through the logic in the Class constructor
let subjectName = Class(withFullName: fullName, link: link).subjectName
let shortcutIcon = UIApplicationShortcutIcon(templateImageName: icon)
let info = ["URL" : link, "FULL_NAME" : fullName, "DISPLAY_NAME" : name]
let shortcut = UIApplicationShortcutItem(type: "openClass", localizedTitle: name, localizedSubtitle: subjectName, icon: shortcutIcon, userInfo: info)
shortcuts.append(shortcut)
}
UIApplication.sharedApplication().shortcutItems = shortcuts
}
}
}
let GTSubjects: [String : (description: String, image: String)] = [
"ACCT" : ("Accounting", "accounting"),
"AE" : ("Aerospace Engineering", "space"),
"AS" : ("Air Force Aerospace Studies", "space"),
"APPH" : ("Applied Physiology", "science"),
"ASE" : ("Applied Systems Engineering", "engineering"),
"ARBC" : ("Arabic", "language"),
"ARCH" : ("Architecture", "architecture"),
"BIOL" : ("Biology", "science"),
"BMEJ" : ("Biomed Engineering/Joint Emory PKU", "science"),
"BMED" : ("Biomedical Engineering", "science"),
"BMEM" : ("Biomedical Engineering/Joint Emory", "science"),
"BC" : ("Building Construction", "architecture"),
"CETL" : ("Center Enhancement Teach/Learn", "world"),
"CHBE" : ("Chemical & Biomolecular Engr", "science"),
"CHEM" : ("Chemistry", "science"),
"CHIN" : ("Chinese", "language"),
"CP" : ("City Planning", "architecture"),
"CEE" : ("Civil and Environmental Engineering", "architecture"),
"COA" : ("College of Architecture", "architecture"),
"COE" : ("College of Engineering", "engineering"),
"CX" : ("Computational Mod, Sim, & Data", "computer"),
"CSE" : ("Computational Science & Engineering", "computer"),
"CS" : ("Computer Science", "computer"),
"COOP" : ("Cooperative Work Assignment", "world"),
"UCGA" : ("Cross Enrollment", "world"),
"EAS" : ("Earth and Atmospheric Sciences", "world"),
"ECON" : ("Economics", "econ"),
"ECEP" : ("Electrical & Computer Engineering Professional", "engineering"),
"ECE" : ("Electrical & Computer Engineering", "engineering"),
"ENGL" : ("English", "language"),
"FS" : ("Foreign Studies", "world"),
"FREN" : ("French", "language"),
"GT" : ("Georgia Tech", "gt"),
"GTL" : ("Georgia Tech Lorraine", "world"),
"GRMN" : ("German", "language"),
"HS" : ("Health Systems", "science"),
"HIST" : ("History", "world"),
"HTS" : ("History of Technology & Society", "world"),
"ISYE" : ("Industrial & Systems Engineering", "engineering"),
"ID" : ("Industrial Design", "engineering"),
"IPCO" : ("International Plan Co-op Abroad", "world"),
"IPIN" : ("International Plan Intern Abroad", "world"),
"IPFS" : ("International Plan-Exchange Program", "world"),
"IPSA" : ("International Plan-Study Abroad", "world"),
"INTA" : ("International Affairs", "world"),
"IL" : ("International Logistics", "world"),
"INTN" : ("Internship", "world"),
"IMBA" : ("International Executive MBA", "world"),
"JAPN" : ("Japanese", "language"),
"KOR" : ("Korean", "language"),
"LS" : ("Learning Support", "humanities"),
"LING" : ("Linguistics", "language"),
"LMC" : ("Literature", "language"),
"MGT" : ("Management", "humanities"),
"MOT" : ("Management of Technology", "humanities"),
"MSE" : ("Materials Science & Engineering", "engineering"),
"MATH" : ("Mathematics", "math"),
"ME" : ("Mechanical Engineering", "engineering"),
"MP" : ("Medical Physics", "science"),
"MSL" : ("Military Science & Leadership", "science"),
"MUSI" : ("Music", "music"),
"NS" : ("Naval Science", "science"),
"NRE" : ("Nuclear & Radiological Engineering", "science"),
"PERS" : ("Persian", "language"),
"PHIL" : ("Philosophy", "humanities"),
"PHYS" : ("Physics", "science"),
"POL" : ("Political Science", "humanities"),
"PTFE" : ("Polymer, Textile and Fiber Engineering", "engineering"),
"DOPP" : ("Professional Practice", "world"),
"PSYC" : ("Psychology", "science"),
"PUBP" : ("Public Policy", "humanities"),
"PUBJ" : ("Public Policy/Joint GSU PhD", "humanities"),
"RUSS" : ("Russian", "language"),
"SOC" : ("Sociology", "humanities"),
"SPAN" : ("Spanish", "language"),
]
| mit | 97b19e3c3a6fa20eab80e1d26ef4a497 | 38.872576 | 165 | 0.575795 | 4.635749 | false | false | false | false |
tjw/swift | stdlib/public/core/SentinelCollection.swift | 1 | 4697 | //===--- SentinelCollection.swift -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public // @testable
protocol _Function {
associatedtype Input
associatedtype Output
func apply(_: Input) -> Output
}
protocol _Predicate : _Function where Output == Bool { }
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
internal struct _SentinelIterator<
Base: IteratorProtocol,
IsSentinel : _Predicate
> : IteratorProtocol, Sequence
where IsSentinel.Input == Base.Element {
@usableFromInline // FIXME(sil-serialize-all)
internal var _base: Base
@usableFromInline // FIXME(sil-serialize-all)
internal var _isSentinel: IsSentinel
@usableFromInline // FIXME(sil-serialize-all)
internal var _expired: Bool = false
@inlinable // FIXME(sil-serialize-all)
internal init(_ base: Base, until condition: IsSentinel) {
_base = base
_isSentinel = condition
}
@inlinable // FIXME(sil-serialize-all)
internal mutating func next() -> Base.Element? {
guard _fastPath(!_expired) else { return nil }
let x = _base.next()
// We don't need this check if it's a precondition that the sentinel will be
// found
// guard _fastPath(x != nil), let y = x else { return x }
guard _fastPath(!_isSentinel.apply(x!)) else { _expired = true; return nil }
return x
}
}
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
internal struct _SentinelCollection<
Base: Collection,
IsSentinel : _Predicate
> : Collection
where IsSentinel.Input == Base.Iterator.Element {
@usableFromInline // FIXME(sil-serialize-all)
internal let _isSentinel: IsSentinel
@usableFromInline // FIXME(sil-serialize-all)
internal var _base : Base
@inlinable // FIXME(sil-serialize-all)
internal func makeIterator() -> _SentinelIterator<Base.Iterator, IsSentinel> {
return _SentinelIterator(_base.makeIterator(), until: _isSentinel)
}
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
internal struct Index : Comparable {
@inlinable // FIXME(sil-serialize-all)
internal init(
_impl: (position: Base.Index, element: Base.Iterator.Element)?
) {
self._impl = _impl
}
@usableFromInline // FIXME(sil-serialize-all)
internal var _impl: (position: Base.Index, element: Base.Iterator.Element)?
@inlinable // FIXME(sil-serialize-all)
internal static func == (lhs: Index, rhs: Index) -> Bool {
if rhs._impl == nil { return lhs._impl == nil }
return lhs._impl != nil && rhs._impl!.position == lhs._impl!.position
}
@inlinable // FIXME(sil-serialize-all)
internal static func < (lhs: Index, rhs: Index) -> Bool {
if rhs._impl == nil { return lhs._impl != nil }
return lhs._impl != nil && rhs._impl!.position < lhs._impl!.position
}
}
@inlinable // FIXME(sil-serialize-all)
internal var startIndex : Index {
return _index(at: _base.startIndex)
}
@inlinable // FIXME(sil-serialize-all)
internal var endIndex : Index {
return Index(_impl: nil)
}
@inlinable // FIXME(sil-serialize-all)
internal subscript(i: Index) -> Base.Iterator.Element {
return i._impl!.element
}
@inlinable // FIXME(sil-serialize-all)
internal func index(after i: Index) -> Index {
return _index(at: _base.index(after: i._impl!.position))
}
@inlinable // FIXME(sil-serialize-all)
internal func _index(at i: Base.Index) -> Index {
// We don't need this check if it's a precondition that the sentinel will be
// found
// guard _fastPath(i != _base.endIndex) else { return endIndex }
let e = _base[i]
guard _fastPath(!_isSentinel.apply(e)) else { return endIndex }
return Index(_impl: (position: i, element: e))
}
@inlinable // FIXME(sil-serialize-all)
internal init(_ base: Base, until condition: IsSentinel) {
_base = base
_isSentinel = condition
}
}
@_fixed_layout // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
internal struct _IsZero<T : BinaryInteger> : _Predicate {
@inlinable // FIXME(sil-serialize-all)
internal init() {}
@inlinable // FIXME(sil-serialize-all)
internal func apply(_ x: T) -> Bool {
return x == 0
}
}
| apache-2.0 | a13bda99d5df87cb9a9039ec85cbde7a | 31.846154 | 80 | 0.65808 | 3.970414 | false | false | false | false |
turingcorp/gattaca | gattaca/Model/Home/Abstract/MHomeRequest.swift | 1 | 3390 | import Foundation
extension MHome
{
private static let kLimit:Int = 3
private static let kStatusCodeSuccess:Int = 200
//MARK: private
private func requestError()
{
let message:String = String.localizedModel(
key:"MHome_requestError")
view?.loadError(message:message)
}
private func requestGifsResponse(data:Data?) -> Any?
{
guard
let data:Data = data
else
{
return nil
}
let json:Any
do
{
try json = JSONSerialization.jsonObject(
with:data,
options:
JSONSerialization.ReadingOptions.allowFragments)
}
catch
{
return nil
}
return json
}
//MARK: internal
func requestGifs()
{
guard
let request:URLRequest = MGiphy.factoryTrendingRequest(
offset:requestOffset,
limit:MHome.kLimit)
else
{
return
}
print(request.url!)
let sessionTask:URLSessionDataTask = urlSession.dataTask(with:request)
{ [weak self] (data:Data?, urlResponse:URLResponse?, error:Error?) in
guard
let items:[MGiphyItem] = self?.requestGifsResponse(
data:data,
urlResponse:urlResponse,
error:error)
else
{
self?.requestError()
return
}
self?.requestGifsSuccess(items:items)
}
sessionTask.resume()
}
func requestGifsResponse(
data:Data?,
urlResponse:URLResponse?,
error:Error?) -> [MGiphyItem]?
{
if let _:Error = error
{
return nil
}
guard
let statusCode:Int = urlResponse?.httpStatusCode
else
{
return nil
}
if statusCode == MHome.kStatusCodeSuccess
{
guard
let json:Any = requestGifsResponse(
data:data),
let items:[MGiphyItem] = MGiphy.factoryItems(
json:json)
else
{
return nil
}
return items
}
return nil
}
func requestGifsSuccess(items:[MGiphyItem])
{
requestOffset += MHome.kLimit
let purged:[MGiphyItem] = gif.purgeItems(items:items)
let countPurged:Int = purged.count
if countPurged > 0
{
guard
let coreData:Database = self.coreData
else
{
return
}
gif.storeItems(
coreData:coreData,
items:purged)
{ [weak self] in
self?.gif.strategy?.download()
}
}
else
{
requestGifs()
}
}
}
| mit | 2b3cb619fe5ce0766563c07c07abd460 | 20.730769 | 78 | 0.418289 | 6 | false | false | false | false |
hooman/swift | stdlib/public/Concurrency/CheckedContinuation.swift | 3 | 10671 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 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
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_continuation_logFailedCheck")
internal func logFailedCheck(_ message: UnsafeRawPointer)
/// Implementation class that holds the `UnsafeContinuation` instance for
/// a `CheckedContinuation`.
@available(SwiftStdlib 5.5, *)
internal final class CheckedContinuationCanary {
// The instance state is stored in tail-allocated raw memory, so that
// we can atomically check the continuation state.
private init() { fatalError("must use create") }
private static func _create(continuation: UnsafeRawPointer, function: String)
-> Self {
let instance = Builtin.allocWithTailElems_1(self,
1._builtinWordValue,
(UnsafeRawPointer?, String).self)
instance._continuationPtr.initialize(to: continuation)
instance._functionPtr.initialize(to: function)
return instance
}
private var _continuationPtr: UnsafeMutablePointer<UnsafeRawPointer?> {
return UnsafeMutablePointer<UnsafeRawPointer?>(
Builtin.projectTailElems(self, (UnsafeRawPointer?, String).self))
}
private var _functionPtr: UnsafeMutablePointer<String> {
let tailPtr = UnsafeMutableRawPointer(
Builtin.projectTailElems(self, (UnsafeRawPointer?, String).self))
let functionPtr = tailPtr
+ MemoryLayout<(UnsafeRawPointer?, String)>.offset(of: \(UnsafeRawPointer?, String).1)!
return functionPtr.assumingMemoryBound(to: String.self)
}
internal static func create<T, E>(continuation: UnsafeContinuation<T, E>,
function: String) -> Self {
return _create(
continuation: unsafeBitCast(continuation, to: UnsafeRawPointer.self),
function: function)
}
internal var function: String {
return _functionPtr.pointee
}
// Take the continuation away from the container, or return nil if it's
// already been taken.
internal func takeContinuation<T, E>() -> UnsafeContinuation<T, E>? {
// Atomically exchange the current continuation value with a null pointer.
let rawContinuationPtr = unsafeBitCast(_continuationPtr,
to: Builtin.RawPointer.self)
let rawOld = Builtin.atomicrmw_xchg_seqcst_Word(rawContinuationPtr,
0._builtinWordValue)
return unsafeBitCast(rawOld, to: UnsafeContinuation<T, E>?.self)
}
deinit {
_functionPtr.deinitialize(count: 1)
// Log if the continuation was never consumed before the instance was
// destructed.
if _continuationPtr.pointee != nil {
logFailedCheck("SWIFT TASK CONTINUATION MISUSE: \(function) leaked its continuation!\n")
}
}
}
/// A wrapper class for `UnsafeContinuation` that logs misuses of the
/// continuation, logging a message if the continuation is resumed
/// multiple times, or if an object is destroyed without its continuation
/// ever being resumed.
///
/// Raw `UnsafeContinuation`, like other unsafe constructs, requires the
/// user to apply it correctly in order to maintain invariants. The key
/// invariant is that the continuation must be resumed exactly once,
/// and bad things happen if this invariant is not upheld--if a continuation
/// is abandoned without resuming the task, then the task will be stuck in
/// the suspended state forever, and conversely, if the same continuation is
/// resumed multiple times, it will put the task in an undefined state.
///
/// `UnsafeContinuation` avoids enforcing these invariants at runtime because
/// it aims to be a low-overhead mechanism for interfacing Swift tasks with
/// event loops, delegate methods, callbacks, and other non-`async` scheduling
/// mechanisms. However, during development, being able to verify that the
/// invariants are being upheld in testing is important.
///
/// `CheckedContinuation` is designed to be a drop-in API replacement for
/// `UnsafeContinuation` that can be used for testing purposes, at the cost of
/// an extra allocation and indirection for the wrapper object. Changing a call
/// of `withUnsafeContinuation` or `withUnsafeThrowingContinuation` into a call
/// of `withCheckedContinuation` or `withCheckedThrowingContinuation` should be
/// enough to obtain the extra checking without further source modification in
/// most circumstances.
@available(SwiftStdlib 5.5, *)
public struct CheckedContinuation<T, E: Error> {
private let canary: CheckedContinuationCanary
/// Initialize a `CheckedContinuation` wrapper around an
/// `UnsafeContinuation`.
///
/// In most cases, you should use `withCheckedContinuation` or
/// `withCheckedThrowingContinuation` instead. You only need to initialize
/// your own `CheckedContinuation<T, E>` if you already have an
/// `UnsafeContinuation` you want to impose checking on.
///
/// - Parameters:
/// - continuation: a fresh `UnsafeContinuation` that has not yet
/// been resumed. The `UnsafeContinuation` must not be used outside of
/// this object once it's been given to the new object.
/// - function: a string identifying the declaration that is the notional
/// source for the continuation, used to identify the continuation in
/// runtime diagnostics related to misuse of this continuation.
public init(continuation: UnsafeContinuation<T, E>, function: String = #function) {
canary = CheckedContinuationCanary.create(
continuation: continuation,
function: function)
}
/// Resume the task awaiting the continuation by having it return normally
/// from its suspension point.
///
/// - Parameter value: The value to return from the continuation.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation again will trap.
///
/// After `resume` enqueues the task, control is immediately returned to
/// the caller. The task will continue executing when its executor is
/// able to reschedule it.
public func resume(returning value: __owned T) {
if let c: UnsafeContinuation<T, E> = canary.takeContinuation() {
c.resume(returning: value)
} else {
fatalError("SWIFT TASK CONTINUATION MISUSE: \(canary.function) tried to resume its continuation more than once, returning \(value)!\n")
}
}
/// Resume the task awaiting the continuation by having it throw an error
/// from its suspension point.
///
/// - Parameter error: The error to throw from the continuation.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation again will trap.
///
/// After `resume` enqueues the task, control is immediately returned to
/// the caller. The task will continue executing when its executor is
/// able to reschedule it.
public func resume(throwing error: __owned E) {
if let c: UnsafeContinuation<T, E> = canary.takeContinuation() {
c.resume(throwing: error)
} else {
fatalError("SWIFT TASK CONTINUATION MISUSE: \(canary.function) tried to resume its continuation more than once, throwing \(error)!\n")
}
}
}
@available(SwiftStdlib 5.5, *)
extension CheckedContinuation {
/// Resume the task awaiting the continuation by having it either
/// return normally or throw an error based on the state of the given
/// `Result` value.
///
/// - Parameter result: A value to either return or throw from the
/// continuation.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation again will trap.
///
/// After `resume` enqueues the task, control is immediately returned to
/// the caller. The task will continue executing when its executor is
/// able to reschedule it.
@_alwaysEmitIntoClient
public func resume<Er: Error>(with result: Result<T, Er>) where E == Error {
switch result {
case .success(let val):
self.resume(returning: val)
case .failure(let err):
self.resume(throwing: err)
}
}
/// Resume the task awaiting the continuation by having it either
/// return normally or throw an error based on the state of the given
/// `Result` value.
///
/// - Parameter result: A value to either return or throw from the
/// continuation.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation again will trap.
///
/// After `resume` enqueues the task, control is immediately returned to
/// the caller. The task will continue executing when its executor is
/// able to reschedule it.
@_alwaysEmitIntoClient
public func resume(with result: Result<T, E>) {
switch result {
case .success(let val):
self.resume(returning: val)
case .failure(let err):
self.resume(throwing: err)
}
}
/// Resume the task awaiting the continuation by having it return normally
/// from its suspension point.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation again will trap.
///
/// After `resume` enqueues the task, control is immediately returned to
/// the caller. The task will continue executing when its executor is
/// able to reschedule it.
@_alwaysEmitIntoClient
public func resume() where T == Void {
self.resume(returning: ())
}
}
@available(SwiftStdlib 5.5, *)
public func withCheckedContinuation<T>(
function: String = #function,
_ body: (CheckedContinuation<T, Never>) -> Void
) async -> T {
return await withUnsafeContinuation {
body(CheckedContinuation(continuation: $0, function: function))
}
}
@available(SwiftStdlib 5.5, *)
public func withCheckedThrowingContinuation<T>(
function: String = #function,
_ body: (CheckedContinuation<T, Error>) -> Void
) async throws -> T {
return try await withUnsafeThrowingContinuation {
body(CheckedContinuation(continuation: $0, function: function))
}
}
| apache-2.0 | cf5901c52bb31efb0d08c1d1d0aeecb1 | 39.574144 | 141 | 0.704526 | 4.774497 | false | false | false | false |
testpress/ios-app | ios-app/UI/BaseQuestionsSlidingViewController.swift | 1 | 3830 | //
// BaseQuestionsSlidingViewController.swift
// ios-app
//
// Copyright © 2017 Testpress. All rights reserved.
//
// 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 SlideMenuControllerSwift
protocol SlidingMenuDelegate {
func dismissViewController()
}
protocol QuestionsSlidingMenuDelegate {
func displayQuestions(currentQuestionIndex: Int)
func updateQuestions(_ attemptItems: [AttemptItem])
}
class BaseQuestionsSlidingViewController: SlideMenuController {
@IBOutlet weak var navigationBarItem: UINavigationItem!
var exam: Exam!
var attempt: Attempt!
var courseContent: Content!
var contentAttempt: ContentAttempt!
var slidingMenuDelegate: SlidingMenuDelegate!
var questionsSlidingMenuDelegate: QuestionsSlidingMenuDelegate!
var panelOpened: Bool = false
override func awakeFromNib() {
let mainViewController = self.mainViewController as! BaseQuestionsPageViewController
let leftViewController = self.leftViewController as! BaseQuestionsListViewController
leftViewController.delegate = mainViewController
questionsSlidingMenuDelegate = leftViewController
delegate = self
SlideMenuOptions.contentViewScale = 1.0
SlideMenuOptions.hideStatusBar = false
SlideMenuOptions.panGesturesEnabled = false
SlideMenuOptions.leftViewWidth = self.view.frame.size.width
super.awakeFromNib()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let questionsPageViewController = mainViewController as! BaseQuestionsPageViewController
questionsPageViewController.attempt = attempt
questionsPageViewController.exam = exam
questionsPageViewController.courseContent = courseContent
questionsPageViewController.contentAttempt = contentAttempt
questionsPageViewController.parentviewController = self
}
@IBAction func onPressBackButton() {
if panelOpened {
slideMenuController()?.closeLeft()
} else {
slidingMenuDelegate.dismissViewController()
}
}
func showQuestionList() {
panelOpened = true
let questionsPageViewController = mainViewController as! BaseQuestionsPageViewController
questionsSlidingMenuDelegate.displayQuestions(
currentQuestionIndex: questionsPageViewController.getCurrentIndex())
}
}
extension BaseQuestionsSlidingViewController: SlideMenuControllerDelegate {
func leftWillOpen() {
showQuestionList()
}
func leftDidOpen() {
if !panelOpened {
showQuestionList()
}
}
func leftDidClose() {
panelOpened = false
}
}
| mit | 1ebd4f2ac1464eceaaf085eb795bab1d | 35.122642 | 96 | 0.726822 | 5.672593 | false | false | false | false |
wosheesh/uchatclient | uchat/Controller/ChannelsViewController.swift | 1 | 8801 | //
// ChannelsViewController.swift
// uchat
//
// Created by Wojtek Materka on 21/02/2016.
// Copyright © 2016 Wojtek Materka. All rights reserved.
//
//TODO: crash if logout is pressed too soon
import UIKit
import CoreData
class ChannelsViewController: UITableViewController, ManagedObjectContextSettable, SegueHandlerType, ProgressViewPresenter {
// MARK: - 🎛 Properties
var managedObjectContext: NSManagedObjectContext!
@IBOutlet weak var refreshButton: UIBarButtonItem!
@IBOutlet weak var logoutButton: UIBarButtonItem!
@IBOutlet var channelsTable: UITableView!
// SegueHandlerType
enum SegueIdentifier: String {
case EnterChannel = "EnterChannel"
case Logout = "Logout"
}
// ProgressViewPresenter
var progressView = UIView()
//MARK: - 🔄 Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
UIApplication.sharedApplication().statusBarStyle = .LightContent
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
setUIEnabled(true)
refreshCatalogue(self)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
hideProgressView()
}
@IBAction func logoutButtonTouchUp(sender: AnyObject) {
setUIEnabled(false)
showProgressView("Leaving...")
UdacityUser.logout() { result in
switch result {
case .Success(_):
// if current user has logged out, set the current NSManagedContext to nil
self.managedObjectContext = nil
self.removeUserKeychain()
self.performSegue(SegueIdentifier.Logout)
case .Failure(let error):
self.hideProgressView()
switch error {
case .ConnectionError:
simpleAlert(self, message: "Couldn't log-out. There was an issue with your connection. Please try again")
default:
simpleAlert(self, message: "Something went wrong while trying to logout... maybe try again?")
}
}
}
}
// MARK: - 🐵 Helpers
@IBAction func refreshCatalogue(sender: AnyObject) {
UClient.sharedInstance().updateUdacityCourseCatalogue() { result in
switch result {
case .Success(_):
print("Setting up Table Data Source for Channels")
self.setupTableView()
print("Updating the channels list with catalogue...")
self.updateChannels()
case .Failure(let error):
switch error {
case .ConnectionError:
simpleAlert(self, message: "There was an issue with your connection. Please try again")
case .JSONParseError:
simpleAlert(self, message: "I couldn't parse the data from Udacity server...")
case .NoDataReceived:
simpleAlert(self, message: "I didn't receive any data from Udacity server... maybe try again?")
default:
simpleAlert(self, message: "Something went wrong while trying to access Udacity server... maybe try again?")
}
}
}
}
func updateChannels() {
// Add or fetch the General Channel
managedObjectContext.performChanges {
Channel.findOrCreateChannel("000", name: "General Channel", tagline: "Conversations about everything", picturePath: nil, inContext: self.managedObjectContext)
}
// Check if the user has any course enrollments
guard let coursesEnrolled = UdacityUser.enrolledCourses else {
print("User has no courses enrolled. Only General channel available")
return
}
// Check if the catalogue is available
guard let courseCatalogue = NSArray(contentsOfFile: UClient.sharedInstance().courseCatalogueFilePath) as? [[String : AnyObject]] else {
print("No catalogue found - allowing conversation on general channel only")
return
}
// Match user's courses with the catalogue.
let coursesMatching = courseCatalogue.filter { course in
coursesEnrolled.contains(course[UClient.JSONResponseKeys.CourseKeyCatalogue] as! String)
}
print("Found \(coursesMatching.count) matching courses in the catalogue.")
//Update the channels in coredata
for course in coursesMatching {
let channelCode = course[UClient.JSONResponseKeys.CourseKeyCatalogue] as! String
let channelName = course[UClient.JSONResponseKeys.CourseTitle] as! String
let channelTagline = course[UClient.JSONResponseKeys.CourseSubtitle] as! String
var imagePathOnline = course[UClient.JSONResponseKeys.CourseImage] as! String?
if imagePathOnline == "" { imagePathOnline = nil } // force unwrapping AnyObject as String cannot yield nil?
managedObjectContext.performChanges {
// create or fetch channel object
let channel = Channel.findOrCreateChannel(channelCode, name: channelName, tagline: channelTagline, picturePath: imagePathOnline, inContext: self.managedObjectContext)
// Download a picture for the channel if we haven't one and there's a url available from the catalogue
if channel.localPictureName == nil,
let pictureUrl = channel.picturePath {
PictureCache().downloadPicture(pictureUrl) { result in
switch result {
case .Success(let picture):
channel.updatePicture(picture as? UIImage, inContext: self.managedObjectContext)
case .Failure(_): break
}
}
}
}
}
}
/// remove keys for logout
func removeUserKeychain() {
let removeEmailOK: Bool = KeychainWrapper.removeObjectForKey("email")
let removePasswdOK: Bool = KeychainWrapper.removeObjectForKey("password")
guard (removeEmailOK && removePasswdOK) else {
fatalError("Couldn't remove user's keychain information")
}
}
func setUIEnabled(enabled: Bool) {
refreshButton.enabled = enabled
logoutButton.enabled = enabled
channelsTable.userInteractionEnabled = enabled
}
// MARK: - ➡️ Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segueIdentifierForSegue(segue) {
case .EnterChannel:
guard let vc = segue.destinationViewController as? ChatViewController else { fatalError("Wrong view controller type") }
guard let channel = dataSource.selectedObject else { fatalError("Showing ChatViewController, but no selected row?") }
print("Opening channel : \(channel)")
vc.managedObjectContext = managedObjectContext
vc.channel = channel
case .Logout:
guard let _ = segue.destinationViewController as? LoginViewController else { fatalError("Wrong view controller type") }
}
}
// MARK: Private
private typealias Data = FetchedResultsDataProvider<ChannelsViewController>
private var dataSource: TableViewDataSource<ChannelsViewController, Data, ChannelTableCell>!
private func setupTableView() {
let request = Channel.sortedFetchRequest
request.returnsObjectsAsFaults = false
print("running fetch request on Channels")
let frc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
print("configuring dataProvider for channelsTable")
let dataProvider = FetchedResultsDataProvider(fetchedResultsController: frc, delegate: self)
print("configuring dataSource for channelsTable")
dataSource = TableViewDataSource(tableView: channelsTable, dataProvider: dataProvider, delegate: self)
}
}
// MARK: - 🎩 DataProviderDelegate & DataSourceDelegate
extension ChannelsViewController: DataProviderDelegate {
func dataProviderDidUpdate(updates: [DataProviderUpdate<Channel>]?) {
dataSource.processUpdates(updates)
}
}
extension ChannelsViewController: DataSourceDelegate {
func cellIdentifierForObject(object: Channel) -> String {
return "ChannelCell"
}
}
| mit | d0d7a03c98b886bf2e4e22c48a77207f | 39.109589 | 182 | 0.629326 | 5.821074 | false | false | false | false |
Coderian/SwiftedKML | SwiftedKML/Elements/North.swift | 1 | 1341 | //
// North.swift
// SwiftedKML
//
// Created by 佐々木 均 on 2016/02/02.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// KML North
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <element name="north" type="kml:angle180Type" default="180.0"/>
public class North:SPXMLElement,HasXMLElementValue,HasXMLElementSimpleValue {
public static var elementName: String = "north"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as LatLonAltBox: v.value.north = self
case let v as LatLonBox: v.value.north = self
default: break
}
}
}
}
public var value:Double = 0.0 { // angle180Type
willSet {
if(newValue < -180 && 180 < newValue ){
// TODO: Error
return
}
}
}
public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{
self.value = Double(contents)!
self.parent = parent
return parent
}
}
| mit | 2ca52b5af76fc8a6d580851580a61490 | 28.181818 | 83 | 0.563084 | 3.93865 | false | false | false | false |
kperryua/swift | test/IRGen/struct_resilience.swift | 1 | 10027 | // RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-ir -enable-resilience %s | %FileCheck %s
// RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-ir -enable-resilience -O %s
import resilient_struct
import resilient_enum
// CHECK: %Si = type <{ [[INT:i32|i64]] }>
// CHECK-LABEL: @_TMfV17struct_resilience26StructWithResilientStorage = internal global
// Resilient structs from outside our resilience domain are manipulated via
// value witnesses
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience26functionWithResilientTypesFTV16resilient_struct4Size1fFS1_S1__S1_(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i8*, %swift.refcounted*)
public func functionWithResilientTypes(_ s: Size, f: (Size) -> Size) -> Size {
// CHECK: [[RESULT:%.*]] = alloca [[BUFFER_TYPE:\[.* x i8\]]]
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV16resilient_struct4Size()
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 5
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[initializeBufferWithCopy:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[BUFFER:%.*]] = call %swift.opaque* [[initializeBufferWithCopy]]([[BUFFER_TYPE]]* [[RESULT]], %swift.opaque* %1, %swift.type* [[METADATA]])
// CHECK: [[FN:%.*]] = bitcast i8* %2 to void (%swift.opaque*, %swift.opaque*, %swift.refcounted*)*
// CHECK: call void [[FN]](%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture [[BUFFER]], %swift.refcounted* %3)
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 3
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[deallocateBuffer:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: call void [[deallocateBuffer]]([[BUFFER_TYPE]]* [[RESULT]], %swift.type* [[METADATA]])
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[destroy:%.*]] = bitcast i8* [[WITNESS]] to void (%swift.opaque*, %swift.type*)*
// CHECK: call void [[destroy]](%swift.opaque* %1, %swift.type* [[METADATA]])
// CHECK: ret void
return f(s)
}
// CHECK-LABEL: declare %swift.type* @_TMaV16resilient_struct4Size()
// Rectangle has fixed layout inside its resilience domain, and dynamic
// layout on the outside.
//
// Make sure we use a type metadata accessor function, and load indirect
// field offsets from it.
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience26functionWithResilientTypesFV16resilient_struct9RectangleT_(%V16resilient_struct9Rectangle* noalias nocapture)
public func functionWithResilientTypes(_ r: Rectangle) {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV16resilient_struct9Rectangle()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], i32 3
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %V16resilient_struct9Rectangle* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Si*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %Si, %Si* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
_ = r.color
// CHECK: ret void
}
// Resilient structs from inside our resilience domain are manipulated
// directly.
public struct MySize {
public let w: Int
public let h: Int
}
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience28functionWithMyResilientTypesFTVS_6MySize1fFS0_S0__S0_(%V17struct_resilience6MySize* {{.*}}, %V17struct_resilience6MySize* {{.*}}, i8*, %swift.refcounted*)
public func functionWithMyResilientTypes(_ s: MySize, f: (MySize) -> MySize) -> MySize {
// CHECK: [[TEMP:%.*]] = alloca %V17struct_resilience6MySize
// CHECK: bitcast
// CHECK: llvm.lifetime.start
// CHECK: [[COPY:%.*]] = bitcast %V17struct_resilience6MySize* %4 to i8*
// CHECK: [[ARG:%.*]] = bitcast %V17struct_resilience6MySize* %1 to i8*
// CHECK: call void @llvm.memcpy{{.*}}(i8* [[COPY]], i8* [[ARG]], {{i32 8|i64 16}}, i32 {{.*}}, i1 false)
// CHECK: [[FN:%.*]] = bitcast i8* %2
// CHECK: call void [[FN]](%V17struct_resilience6MySize* {{.*}} %0, {{.*}} [[TEMP]], %swift.refcounted* %3)
// CHECK: ret void
return f(s)
}
// Structs with resilient storage from a different resilience domain require
// runtime metadata instantiation, just like generics.
public struct StructWithResilientStorage {
public let s: Size
public let ss: (Size, Size)
public let n: Int
public let i: ResilientInt
}
// Make sure we call a function to access metadata of structs with
// resilient layout, and go through the field offset vector in the
// metadata when accessing stored properties.
// CHECK-LABEL: define{{( protected)?}} {{i32|i64}} @_TFV17struct_resilience26StructWithResilientStorageg1nSi(%V17struct_resilience26StructWithResilientStorage* {{.*}})
// CHECK: [[METADATA:%.*]] = call %swift.type* @_TMaV17struct_resilience26StructWithResilientStorage()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], i32 3
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %V17struct_resilience26StructWithResilientStorage* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Si*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %Si, %Si* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Indirect enums with resilient payloads are still fixed-size.
public struct StructWithIndirectResilientEnum {
public let s: FunnyShape
public let n: Int
}
// CHECK-LABEL: define{{( protected)?}} {{i32|i64}} @_TFV17struct_resilience31StructWithIndirectResilientEnumg1nSi(%V17struct_resilience31StructWithIndirectResilientEnum* {{.*}})
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %V17struct_resilience31StructWithIndirectResilientEnum, %V17struct_resilience31StructWithIndirectResilientEnum* %0, i32 0, i32 1
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %Si, %Si* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Partial application of methods on resilient value types
public struct ResilientStructWithMethod {
public func method() {}
}
// Corner case -- type is address-only in SIL, but empty in IRGen
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience29partialApplyOfResilientMethodFT1rVS_25ResilientStructWithMethod_T_(%V17struct_resilience25ResilientStructWithMethod* noalias nocapture)
public func partialApplyOfResilientMethod(r: ResilientStructWithMethod) {
_ = r.method
}
// Type is address-only in SIL, and resilient in IRGen
// CHECK-LABEL: define{{( protected)?}} void @_TF17struct_resilience29partialApplyOfResilientMethodFT1sV16resilient_struct4Size_T_(%swift.opaque* noalias nocapture)
public func partialApplyOfResilientMethod(s: Size) {
_ = s.method
}
// Public metadata accessor for our resilient struct
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_TMaV17struct_resilience6MySize()
// CHECK: ret %swift.type* bitcast ([[INT]]* getelementptr inbounds {{.*}} @_TMfV17struct_resilience6MySize, i32 0, i32 1) to %swift.type*)
// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_StructWithResilientStorage(i8*)
// CHECK: [[FIELDS:%.*]] = alloca [4 x i8**]
// CHECK: [[VWT:%.*]] = load i8**, i8*** getelementptr inbounds ({{.*}} @_TMfV17struct_resilience26StructWithResilientStorage{{.*}}, [[INT]] -1)
// CHECK: [[FIELDS_ADDR:%.*]] = getelementptr inbounds [4 x i8**], [4 x i8**]* [[FIELDS]], i32 0, i32 0
// public let s: Size
// CHECK: [[FIELD_1:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 0
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_1]]
// public let ss: (Size, Size)
// CHECK: [[FIELD_2:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 1
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_2]]
// Fixed-layout aggregate -- we can reference a static value witness table
// public let n: Int
// CHECK: [[FIELD_3:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 2
// CHECK: store i8** getelementptr inbounds (i8*, i8** @_TWVBi{{32|64}}_, i32 {{.*}}), i8*** [[FIELD_3]]
// Resilient aggregate with one field -- make sure we don't look inside it
// public let i: ResilientInt
// CHECK: [[FIELD_4:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 3
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_4]]
// CHECK: call void @swift_initStructMetadata_UniversalStrategy([[INT]] 4, i8*** [[FIELDS_ADDR]], [[INT]]* {{.*}}, i8** [[VWT]])
// CHECK: store atomic %swift.type* {{.*}} @_TMfV17struct_resilience26StructWithResilientStorage{{.*}}, %swift.type** @_TMLV17struct_resilience26StructWithResilientStorage release,
// CHECK: ret void
| apache-2.0 | 2542e377374fa9ae87b0ee5d546424dd | 49.641414 | 233 | 0.671288 | 3.621163 | false | false | false | false |
FRA7/FJWeibo | FJWeibo/Classes/Home/HomeTableViewController.swift | 1 | 10576 | //
// HomeTableViewController.swift
// FJWeibo
//
// Created by Francis on 16/2/26.
// Copyright © 2016年 FRAJ. All rights reserved.
//
import UIKit
import SDWebImage
import MJRefresh
class HomeTableViewController: BaseTableViewController {
// MARK:- 懒加载属性
private lazy var titleBtn : TitleButton = TitleButton(type: .Custom)
private lazy var popoverAnimator : PopoverAnimator = PopoverAnimator() // 动画管理的对象
private lazy var statusViewModels : [StatusViewModel] = [StatusViewModel]()
private lazy var cellHeightCache : [String : CGFloat] = [String : CGFloat]()
private lazy var tipLabel: UILabel = UILabel()
//记录菜单是否展开
var isPresent :Bool = false
// MARK:- 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
// 1.判断用户是否登录
if !isLogin {
visitorView.addRotationAnimate()
return
}
// 2.初始化导航栏
setupNavigationBar()
//4.注册通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.change), name: FJPopoverAnimatorWillShow, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeTableViewController.change), name: FJPopoverAnimatorWillDismiss, object: nil)
//提示微博数量的label
setupTipLabel()
// 3.请求数据
setupHeaderFooterView()
}
deinit {
//移除通知
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/**
设置标题按钮状态
*/
func change(){
let titleB = navigationItem.titleView as! TitleButton
titleB.selected = !titleB.selected
}
}
// MARK:- 设置UI的内容
extension HomeTableViewController {
///设置导航栏的内容
private func setupNavigationBar() {
// 1.设置左侧的Item
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(HomeTableViewController.leftItemClick))
// 2.设置右侧的Item
navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(HomeTableViewController.rightItemClick))
// 3.设置标题按钮
let name = UserAccountViewModel.shareInstance.account?.screen_name
titleBtn.setTitle(name, forState: .Normal)
titleBtn.addTarget(self, action: #selector(HomeTableViewController.titleBtnClick(_:)), forControlEvents: .TouchUpInside)
navigationItem.titleView = titleBtn
}
///添加headerView
private func setupHeaderFooterView(){
//1.创建headerView
let headerView = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeTableViewController.loadNewData))
headerView.setTitle("下拉刷新", forState: .Idle)
headerView.setTitle("释放更新", forState: .Pulling)
headerView.setTitle("加载中", forState: .Refreshing)
tableView.mj_header = headerView
//2.进入刷新状态
headerView.beginRefreshing()
// //3.创建footerView
// let footerView = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: "loadMoreData")
// tableView.mj_footer = footerView
// //2.进入刷新状态
// footerView.beginRefreshing()
}
private func setupTipLabel(){
//1.给label添加父控件
navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
//2.设置frame
tipLabel.frame = CGRect(x: 0, y: 12, width: UIScreen.mainScreen().bounds.width, height: 32)
//3.设置属性
tipLabel.backgroundColor = UIColor.orangeColor()
tipLabel.textColor = UIColor.whiteColor()
tipLabel.font = UIFont.systemFontOfSize(14)
tipLabel.textAlignment = .Center
tipLabel.hidden = true
}
}
// MARK:- 事件监听函数
extension HomeTableViewController {
@objc private func leftItemClick() {
FJLog("leftItemClick")
}
@objc private func rightItemClick() {
// FJLog("rightItemClick")
let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil)
let vc = sb.instantiateInitialViewController()
presentViewController(vc!, animated: true, completion: nil)
}
@objc private func titleBtnClick(titleBtn : TitleButton) {
//1.弹出菜单
let sb = UIStoryboard(name: "PopoverViewController", bundle: nil)
let vc = sb.instantiateInitialViewController()
//2.1设置转场代理
popoverAnimator.presentFrame = CGRect(x: (UIScreen.mainScreen().bounds.width - 200)*0.5, y: 56, width: 200, height: 300)
vc?.transitioningDelegate = popoverAnimator
//2.2设置转场样式
vc?.modalPresentationStyle = UIModalPresentationStyle.Custom
presentViewController(vc!, animated: true, completion: nil) }
}
// MARK:- tableView的数据源方法和代理方法
extension HomeTableViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return statusViewModels.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// 1.创建cell
let cell = tableView.dequeueReusableCellWithIdentifier("HomeCell") as! HomeViewCell
// 2.给cell设置数据
cell.statusViewModel = statusViewModels[indexPath.row]
//3.判断是否是最后一个cell
if indexPath.row == statusViewModels.count - 1{
loadMoreData()
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// 0.取出模型对象
let statusViewModel = statusViewModels[indexPath.row]
// 1.先从缓存池中取出高度
var cellHeight : CGFloat? = cellHeightCache["\(statusViewModel.status!.id)"]
if cellHeight != nil {
return cellHeight!
}
// 2.取出indexPath对应的cell
let cell = tableView.dequeueReusableCellWithIdentifier("HomeCell") as! HomeViewCell
// 3.获取cell的高度
cellHeight = cell.cellHeight(statusViewModel)
// 4.缓存高度
cellHeightCache["\(statusViewModel.status!.id)"] = cellHeight!
return cellHeight!
}
}
// MARK:- 网络请求
extension HomeTableViewController {
@objc private func loadNewData(){
loadStatuses(true)
}
@objc private func loadMoreData(){
loadStatuses(false)
}
/// 请求首页数据
private func loadStatuses(isNewData: Bool) {
var since_id: Int = 0
var max_id:Int = 0
if isNewData{
since_id = statusViewModels.first?.status?.id ?? 0
}else{
max_id = statusViewModels.first?.status?.id ?? 0
max_id = max_id == 0 ? 0 : max_id - 1
}
NetWorkTool.shareInstance.loadStatuses(since_id,max_id: max_id) { (result, error) -> () in
// 1.错误校验
if error != nil {
self.tableView.mj_header.endRefreshing()
return
}
// 2.判断数组是否有值
guard let resultArray = result else {
self.tableView.mj_header.endRefreshing()
return
}
// 3.遍历数组,将数组中的字典转成模型对象
var models = [StatusViewModel]()
for resultDict in resultArray {
let status = Status(dict: resultDict)
let statusViewModel = StatusViewModel(status: status)
models.append(statusViewModel)
}
if isNewData{
self.statusViewModels = models + self.statusViewModels
}else{
self.statusViewModels += models
}
// 4.缓存图片
self.cacheImages(models)
}
}
/// 缓存图片
private func cacheImages(models: [StatusViewModel]) {
//0.创建group
let group = dispatch_group_create()
// 1.缓存图片
// 1.1.遍历所有的微博
for status in statusViewModels {
// 1.2.遍历所有的微博中url
for url in status.picURLs {
// 1.3.将一部请求加载group中
dispatch_group_enter(group)
// 1.4.缓存图片
SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
FJLog("下载了一张图片")
// 1.5.将异步处理从group中移除掉
dispatch_group_leave(group)
})
}
}
// 2.刷新表格
dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
// FJLog("刷新表格")
//1.刷新表格
self.tableView.reloadData()
//2.header、footer停止刷新
self.tableView.mj_header.endRefreshing()
// self.tableView.mj_footer.endRefreshing()
//3.显示tipLabel
self.showTipLabelAni(models.count)
}
}
private func showTipLabelAni(count: Int){
//1.设置label属性
tipLabel.hidden = false
tipLabel.text = count == 0 ? "没有新微薄" : "\(count)条新微博"
//2.执行动画
UIView.animateWithDuration(1.0, animations: { () -> Void in
self.tipLabel.frame.origin.y = 44
}) { (_) -> Void in
UIView.animateWithDuration(1.0, delay: 1.0, options: [], animations: { () -> Void in
self.tipLabel.frame.origin.y = 12
}, completion: { (_) -> Void in
self.tipLabel.hidden = true
})
}
}
}
| mit | 4f05c3b54be389253bc4add32e41b1d4 | 30.650641 | 174 | 0.580152 | 5.11658 | false | false | false | false |
slightair/syu | Syu/RxCocoaExtension/NSTableView+Rx.swift | 1 | 2127 | import Foundation
import Cocoa
import RxSwift
import RxCocoa
public typealias WillDisplayCellEvent = (cell: Any, tableColumn: NSTableColumn?, row: Int)
extension Reactive where Base: NSTableView {
func items<S: Sequence, O: ObservableType>
(_ source: O)
-> Disposable
where O.E == S {
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S>()
return self.items(dataSource: dataSource)(source)
}
func items<
DataSource: RxTableViewDataSourceType & NSTableViewDataSource,
O: ObservableType>
(dataSource: DataSource)
-> (_ source: O)
-> Disposable
where DataSource.Element == O.E {
return { source in
return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource, retainDataSource: true) { [weak tableView = self.base] (_: RxTableViewDataSourceProxy, event) -> Void in
guard let tableView = tableView else {
return
}
dataSource.tableView(tableView, observedEvent: event)
}
}
}
}
extension NSTableView {
func createRxDataSourceProxy() -> RxTableViewDataSourceProxy {
return RxTableViewDataSourceProxy(parentObject: self)
}
func createRxDelegateProxy() -> RxTableViewDelegateProxy {
return RxTableViewDelegateProxy(parentObject: self)
}
}
extension Reactive where Base: NSTableView {
var dataSource: DelegateProxy {
return RxTableViewDataSourceProxy.proxyForObject(base)
}
func setDataSource(_ dataSource: NSTableViewDataSource) -> Disposable {
return RxTableViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base)
}
var delegate: DelegateProxy {
return RxTableViewDelegateProxy.proxyForObject(base)
}
func setDelegate(_ delegate: NSTableViewDelegate) -> Disposable {
return RxTableViewDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base)
}
}
| mit | 0306ee89031d0d9cee289b1693bd12e4 | 33.868852 | 204 | 0.673249 | 5.991549 | false | false | false | false |
DanisFabric/Infinity | Infinity/PullToRefresher.swift | 1 | 7335 | //
// PullToRefresher.swift
// InfinitySample
//
// Created by Danis on 15/12/21.
// Copyright © 2015年 danis. All rights reserved.
//
import UIKit
public protocol CustomPullToRefreshAnimator {
func animateState(_ state: PullToRefreshState)
}
public enum PullToRefreshState: Equatable, CustomStringConvertible {
case none
case releasing(progress:CGFloat)
case loading
public var description: String {
switch self {
case .none: return "None"
case .releasing(let progress): return "Releasing: \(progress)"
case .loading: return "Loading"
}
}
}
public func == (left: PullToRefreshState, right: PullToRefreshState) -> Bool {
switch (left, right) {
case (.none, .none): return true
case (.releasing, .releasing): return true
case (.loading, .loading): return true
default:
return false
}
}
class PullToRefresher: NSObject {
weak var scrollView: UIScrollView? {
willSet {
removeScrollViewObserving(scrollView)
self.containerView.removeFromSuperview()
}
didSet {
addScrollViewObserving(scrollView)
if let scrollView = scrollView {
defaultContentInset = scrollView.contentInset
containerView.scrollView = scrollView
scrollView.addSubview(containerView)
containerView.frame = CGRect(x: 0 + animatorOffset.horizontal, y: -defaultHeightToTrigger + animatorOffset.vertical, width: scrollView.frame.width, height: defaultHeightToTrigger)
}
}
}
var animator: CustomPullToRefreshAnimator
var containerView: HeaderContainerView
var action:(()->Void)?
var enable = true
var animatorOffset: UIOffset = UIOffset() {
didSet {
if let scrollView = scrollView {
containerView.frame = CGRect(x: 0 + animatorOffset.horizontal, y: -defaultHeightToTrigger + animatorOffset.vertical, width: scrollView.frame.width, height: defaultHeightToTrigger)
if Infinity.debugModeEnabled {
print(containerView.frame)
}
}
}
}
// Values
var defaultContentInset: UIEdgeInsets = UIEdgeInsets()
var defaultHeightToTrigger: CGFloat = 0
var scrollbackImmediately = true
init(height: CGFloat, animator: CustomPullToRefreshAnimator) {
self.defaultHeightToTrigger = height
self.animator = animator
self.containerView = HeaderContainerView()
}
// MARK: - Observe Scroll View
var KVOContext = "PullToRefreshKVOContext"
func addScrollViewObserving(_ scrollView: UIScrollView?) {
scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .new, context: &KVOContext)
scrollView?.addObserver(self, forKeyPath: "contentInset", options: .new, context: &KVOContext)
}
func removeScrollViewObserving(_ scrollView: UIScrollView?) {
scrollView?.removeObserver(self, forKeyPath: "contentOffset", context: &KVOContext)
scrollView?.removeObserver(self, forKeyPath: "contentInset", context: &KVOContext)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &KVOContext {
if keyPath == "contentOffset" {
guard !updatingState && enable else {
return
}
let point = (change![.newKey]! as AnyObject).cgPointValue!
let offsetY = point.y + defaultContentInset.top
switch offsetY {
case 0 where state != .loading:
state = .none
case -defaultHeightToTrigger...0 where state != .loading:
state = .releasing(progress: min(-offsetY / defaultHeightToTrigger, 1.0))
case (-CGFloat.greatestFiniteMagnitude)...(-defaultHeightToTrigger) where state == .releasing(progress:1):
if scrollView!.isDragging {
state = .releasing(progress: 1.0)
}else {
state = .loading
}
default:
break
}
}
else if keyPath == "contentInset" {
guard !self.scrollView!.lockInset else {
return
}
self.defaultContentInset = (change![.newKey]! as AnyObject).uiEdgeInsetsValue!
}
}else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
var updatingState = false
var state: PullToRefreshState = .none {
didSet {
self.animator.animateState(state)
switch self.state {
case .none where oldValue == .loading:
if !self.scrollbackImmediately {
self.updatingState = true
if self.scrollView is UICollectionView {
self.scrollView?.setContentInset(self.defaultContentInset, completion: { [unowned self] (finished) -> Void in
self.updatingState = false
})
} else {
self.scrollView?.setContentInset(self.defaultContentInset, completion: { [unowned self] (finished) -> Void in
self.updatingState = false
})
}
}
case .loading where oldValue != .loading:
if !self.scrollbackImmediately {
self.updatingState = true
var inset = self.defaultContentInset
inset.top += self.defaultHeightToTrigger
self.scrollView?.setContentInset(inset, completion: { [unowned self] (finished) -> Void in
self.updatingState = false
})
}
self.action?()
default:
break
}
}
}
// MARK: - Refresh
func beginRefreshing() {
self.scrollView?.setContentOffset(CGPoint(x: 0, y: -(defaultHeightToTrigger + defaultContentInset.top + 1)), animated: true)
}
func endRefreshing() {
self.state = .none
}
}
class HeaderContainerView: UIView {
var scrollView: UIScrollView?
override func layoutSubviews() {
super.layoutSubviews()
for view in subviews {
view.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
}
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
self.firstResponderViewController()?.automaticallyAdjustsScrollViewInsets = false
}
}
extension UIView {
func firstResponderViewController() -> UIViewController? {
var responder: UIResponder? = self as UIResponder
while responder != nil {
if responder!.isKind(of: UIViewController.self) {
return responder as? UIViewController
}
responder = responder?.next
}
return nil
}
}
| mit | 9cd207d4a90391c1e87398cf15393ef1 | 35.477612 | 195 | 0.576514 | 5.674923 | false | false | false | false |
yossan4343434/TK_15 | src/app/Visy/Visy/VSMovieListViewController.swift | 1 | 2296 | //
// VSMovieListViewController.swift
// Visy
//
// Created by Yoshiyuki Kuga on 2015/11/28.
// Copyright © 2015年 TK_15. All rights reserved.
//
import UIKit
class VSMovieListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let youtubeIds: [String] = ["NIXcEWrGtsM", "eGljbxH9jXI", "XxpzKJxye1s"]
var selectedId = String()
@IBOutlet weak var movieListTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let nib: UINib = UINib(nibName: "VSMovieListCell", bundle: nil)
movieListTableView.registerNib(nib, forCellReuseIdentifier: "movieListCell")
movieListTableView.delegate = self
movieListTableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return youtubeIds.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: VSMovieListCell = tableView.dequeueReusableCellWithIdentifier("movieListCell", forIndexPath: indexPath) as! VSMovieListCell
var movie = VSMovie(youtubeId: youtubeIds[indexPath.row])
cell.movieTitleLabel.text = movie.title
cell.movieImageView.image = movie.thumbnail
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return VSMovieListCell.cellHeight()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedId = youtubeIds[indexPath.row]
performSegueWithIdentifier("toMoviePlayer", sender: nil)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "toMoviePlayer") {
var moviePlayerViewController = VSMoviePlayerViewController()
moviePlayerViewController = segue.destinationViewController as! VSMoviePlayerViewController
moviePlayerViewController.youtubeId = selectedId
}
}
}
| mit | 28710afe48689e1cf81f9ace0d3130df | 34.828125 | 141 | 0.718273 | 5.187783 | false | false | false | false |
cpageler93/ConsulSwift | Sources/ConsulSwift/ConsulKeyValuePair.swift | 1 | 927 | //
// ConsulKeyValuePair.swift
// ConsulSwift
//
// Created by Christoph Pageler on 19.06.17.
//
import Foundation
import Quack
public extension Consul {
public class KeyValuePair: Quack.Model {
public var key: String
public var value: String
public required init?(json: JSON) {
guard let jsonArray = json.array,
let firstJsonEntry = jsonArray.first,
let key = firstJsonEntry["Key"].string,
let value = firstJsonEntry["Value"].string
else {
return nil
}
self.key = key
self.value = value
}
public func decodedValue() -> String? {
guard let decodedData = Data(base64Encoded: value) else { return nil }
return String(data: decodedData, encoding: .utf8)
}
}
}
| mit | 84a9592bf44dc281771988fa17cd72e7 | 22.175 | 82 | 0.527508 | 4.753846 | false | false | false | false |
jeffreykuiken/npo-appletv | Releases/1.1/npo-appletv/AppDelegate.swift | 1 | 2945 | //
// AppDelegate.swift
// npo-appletv
//
// Copyright (c) 2016 Jeffrey Kuiken. All rights reserved.
//
import UIKit
import TVMLKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate {
var window: UIWindow?
var appController: TVApplicationController?
static let tvBaseURL = "http://52.213.130.58/npo-appletv"
static let tvBootURL = "\(AppDelegate.tvBaseURL)/application.js"
// MARK: Javascript Execution Helper
func executeRemoteMethod(_ methodName: String, completion: @escaping (Bool) -> Void) {
appController?.evaluate(inJavaScriptContext: { (context: JSContext) in
let appObject : JSValue = context.objectForKeyedSubscript("App")
if appObject.hasProperty(methodName) {
appObject.invokeMethod(methodName, withArguments: [])
}
}, completion: completion)
}
// MARK: UIApplicationDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let appControllerContext = TVApplicationControllerContext()
if let javaScriptURL = URL(string: AppDelegate.tvBootURL) {
appControllerContext.javaScriptApplicationURL = javaScriptURL
}
appControllerContext.launchOptions["BASEURL"] = AppDelegate.tvBaseURL as NSString
appControllerContext.launchOptions["APPVERSION"] = 1.1 as Double
appControllerContext.launchOptions["APIBASE"] = "http://52.213.130.58/api/v1" as NSString
if let launchOptions = launchOptions {
for (kind, value) in launchOptions {
appControllerContext.launchOptions[kind.rawValue] = value
}
}
appController = TVApplicationController(context: appControllerContext, window: window, delegate: self)
return true
}
// MARK: TVApplicationControllerDelegate
func appController(_ appController: TVApplicationController, didFinishLaunching options: [String: Any]?) {
print("\(#function) invoked with options: \(options)")
}
func appController(_ appController: TVApplicationController, didFail error: Error) {
print("\(#function) invoked with error: \(error)")
let title = "Error Launching Application"
let message = error.localizedDescription
let alertController = UIAlertController(title: title, message: message, preferredStyle:.alert )
self.appController?.navigationController.present(alertController, animated: true)
}
func appController(_ appController: TVApplicationController, didStop options: [String: Any]?) {
print("\(#function) invoked with options: \(options)")
}
}
| mit | f2eb171639393d6abb2ab871059edf61 | 36.278481 | 144 | 0.667912 | 5.641762 | false | false | false | false |
garvankeeley/firefox-ios | Client/Frontend/Browser/OpenSearch.swift | 7 | 11486 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Fuzi
private let TypeSearch = "text/html"
private let TypeSuggest = "application/x-suggestions+json"
class OpenSearchEngine: NSObject, NSCoding {
static let PreferredIconSize = 30
let shortName: String
let engineID: String?
let image: UIImage
let isCustomEngine: Bool
let searchTemplate: String
fileprivate let suggestTemplate: String?
fileprivate let SearchTermComponent = "{searchTerms}"
fileprivate let LocaleTermComponent = "{moz:locale}"
fileprivate lazy var searchQueryComponentKey: String? = self.getQueryArgFromTemplate()
init(engineID: String?, shortName: String, image: UIImage, searchTemplate: String, suggestTemplate: String?, isCustomEngine: Bool) {
self.shortName = shortName
self.image = image
self.searchTemplate = searchTemplate
self.suggestTemplate = suggestTemplate
self.isCustomEngine = isCustomEngine
self.engineID = engineID
}
required init?(coder aDecoder: NSCoder) {
// this catches the cases where bool encoded in Swift 2 needs to be decoded with decodeObject, but a Bool encoded in swift 3 needs
// to be decoded using decodeBool. This catches the upgrade case to ensure that we are always able to fetch a keyed valye for isCustomEngine
// http://stackoverflow.com/a/40034694
let isCustomEngine = aDecoder.decodeAsBool(forKey: "isCustomEngine")
guard let searchTemplate = aDecoder.decodeObject(forKey: "searchTemplate") as? String,
let shortName = aDecoder.decodeObject(forKey: "shortName") as? String,
let image = aDecoder.decodeObject(forKey: "image") as? UIImage else {
assertionFailure()
return nil
}
self.searchTemplate = searchTemplate
self.shortName = shortName
self.isCustomEngine = isCustomEngine
self.image = image
self.engineID = aDecoder.decodeObject(forKey: "engineID") as? String
self.suggestTemplate = nil
}
func encode(with aCoder: NSCoder) {
aCoder.encode(searchTemplate, forKey: "searchTemplate")
aCoder.encode(shortName, forKey: "shortName")
aCoder.encode(isCustomEngine, forKey: "isCustomEngine")
aCoder.encode(image, forKey: "image")
aCoder.encode(engineID, forKey: "engineID")
}
/**
* Returns the search URL for the given query.
*/
func searchURLForQuery(_ query: String) -> URL? {
return getURLFromTemplate(searchTemplate, query: query)
}
/**
* Return the arg that we use for searching for this engine
* Problem: the search terms may not be a query arg, they may be part of the URL - how to deal with this?
**/
fileprivate func getQueryArgFromTemplate() -> String? {
// we have the replace the templates SearchTermComponent in order to make the template
// a valid URL, otherwise we cannot do the conversion to NSURLComponents
// and have to do flaky pattern matching instead.
let placeholder = "PLACEHOLDER"
let template = searchTemplate.replacingOccurrences(of: SearchTermComponent, with: placeholder)
var components = URLComponents(string: template)
if let retVal = extractQueryArg(in: components?.queryItems, for: placeholder) {
return retVal
} else {
// Query arg may be exist inside fragment
components = URLComponents()
components?.query = URL(string: template)?.fragment
return extractQueryArg(in: components?.queryItems, for: placeholder)
}
}
fileprivate func extractQueryArg(in queryItems: [URLQueryItem]?, for placeholder: String) -> String? {
let searchTerm = queryItems?.filter { item in
return item.value == placeholder
}
return searchTerm?.first?.name
}
/**
* check that the URL host contains the name of the search engine somewhere inside it
**/
fileprivate func isSearchURLForEngine(_ url: URL?) -> Bool {
guard let urlHost = url?.shortDisplayString,
let queryEndIndex = searchTemplate.range(of: "?")?.lowerBound,
let templateURL = URL(string: String(searchTemplate[..<queryEndIndex])) else { return false }
return urlHost == templateURL.shortDisplayString
}
/**
* Returns the query that was used to construct a given search URL
**/
func queryForSearchURL(_ url: URL?) -> String? {
guard isSearchURLForEngine(url), let key = searchQueryComponentKey else { return nil }
if let value = url?.getQuery()[key] {
return value.replacingOccurrences(of: "+", with: " ").removingPercentEncoding
} else {
// If search term could not found in query, it may be exist inside fragment
var components = URLComponents()
components.query = url?.fragment?.removingPercentEncoding
guard let value = components.url?.getQuery()[key] else { return nil }
return value.replacingOccurrences(of: "+", with: " ").removingPercentEncoding
}
}
/**
* Returns the search suggestion URL for the given query.
*/
func suggestURLForQuery(_ query: String) -> URL? {
if let suggestTemplate = suggestTemplate {
return getURLFromTemplate(suggestTemplate, query: query)
}
return nil
}
fileprivate func getURLFromTemplate(_ searchTemplate: String, query: String) -> URL? {
if let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: .SearchTermsAllowed) {
// Escape the search template as well in case it contains not-safe characters like symbols
let templateAllowedSet = NSMutableCharacterSet()
templateAllowedSet.formUnion(with: .URLAllowed)
// Allow brackets since we use them in our template as our insertion point
templateAllowedSet.formUnion(with: CharacterSet(charactersIn: "{}"))
if let encodedSearchTemplate = searchTemplate.addingPercentEncoding(withAllowedCharacters: templateAllowedSet as CharacterSet) {
let localeString = Locale.current.identifier
let urlString = encodedSearchTemplate
.replacingOccurrences(of: SearchTermComponent, with: escapedQuery, options: .literal, range: nil)
.replacingOccurrences(of: LocaleTermComponent, with: localeString, options: .literal, range: nil)
return URL(string: urlString)
}
}
return nil
}
}
/**
* OpenSearch XML parser.
*
* This parser accepts standards-compliant OpenSearch 1.1 XML documents in addition to
* the Firefox-specific search plugin format.
*
* OpenSearch spec: http://www.opensearch.org/Specifications/OpenSearch/1.1
*/
class OpenSearchParser {
fileprivate let pluginMode: Bool
init(pluginMode: Bool) {
self.pluginMode = pluginMode
}
func parse(_ file: String, engineID: String) -> OpenSearchEngine? {
guard let data = try? Data(contentsOf: URL(fileURLWithPath: file)) else {
print("Invalid search file")
return nil
}
guard let indexer = try? XMLDocument(data: data),
let docIndexer = indexer.root else {
print("Invalid XML document")
return nil
}
let shortNameIndexer = docIndexer.children(tag: "ShortName")
if shortNameIndexer.count != 1 {
print("ShortName must appear exactly once")
return nil
}
let shortName = shortNameIndexer[0].stringValue
if shortName == "" {
print("ShortName must contain text")
return nil
}
let urlIndexers = docIndexer.children(tag: "Url")
if urlIndexers.isEmpty {
print("Url must appear at least once")
return nil
}
var searchTemplate: String!
var suggestTemplate: String?
for urlIndexer in urlIndexers {
let type = urlIndexer.attributes["type"]
if type == nil {
print("Url element requires a type attribute", terminator: "\n")
return nil
}
if type != TypeSearch && type != TypeSuggest {
// Not a supported search type.
continue
}
var template = urlIndexer.attributes["template"]
if template == nil {
print("Url element requires a template attribute", terminator: "\n")
return nil
}
if pluginMode {
let paramIndexers = urlIndexer.children(tag: "Param")
if !paramIndexers.isEmpty {
template! += "?"
var firstAdded = false
for paramIndexer in paramIndexers {
if firstAdded {
template! += "&"
} else {
firstAdded = true
}
let name = paramIndexer.attributes["name"]
let value = paramIndexer.attributes["value"]
if name == nil || value == nil {
print("Param element must have name and value attributes", terminator: "\n")
return nil
}
template! += name! + "=" + value!
}
}
}
if type == TypeSearch {
searchTemplate = template
} else {
suggestTemplate = template
}
}
if searchTemplate == nil {
print("Search engine must have a text/html type")
return nil
}
let imageIndexers = docIndexer.children(tag: "Image")
var largestImage = 0
var largestImageElement: XMLElement?
// TODO: For now, just use the largest icon.
for imageIndexer in imageIndexers {
let imageWidth = Int(imageIndexer.attributes["width"] ?? "")
let imageHeight = Int(imageIndexer.attributes["height"] ?? "")
// Only accept square images.
if imageWidth != imageHeight {
continue
}
if let imageWidth = imageWidth {
if imageWidth > largestImage {
largestImage = imageWidth
largestImageElement = imageIndexer
}
}
}
let uiImage: UIImage
if let imageElement = largestImageElement,
let imageURL = URL(string: imageElement.stringValue),
let imageData = try? Data(contentsOf: imageURL),
let image = UIImage.imageFromDataThreadSafe(imageData) {
uiImage = image
} else {
print("Error: Invalid search image data")
return nil
}
return OpenSearchEngine(engineID: engineID, shortName: shortName, image: uiImage, searchTemplate: searchTemplate, suggestTemplate: suggestTemplate, isCustomEngine: false)
}
}
| mpl-2.0 | a78a6b667d2bd836409e3cfc1dad9871 | 37.804054 | 178 | 0.605433 | 5.428166 | false | false | false | false |
airspeedswift/swift | stdlib/public/core/ContiguousArrayBuffer.swift | 4 | 35258 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
#if INTERNAL_CHECKS_ENABLED
@available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
@_silgen_name("swift_COWSanityChecksEnabled")
public func _COWSanityChecksEnabled() -> Bool
@_alwaysEmitIntoClient
internal func doCOWSanityChecks() -> Bool {
if #available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *) {
return _COWSanityChecksEnabled()
}
return false
}
#endif
/// Class used whose sole instance is used as storage for empty
/// arrays. The instance is defined in the runtime and statically
/// initialized. See stdlib/runtime/GlobalObjects.cpp for details.
/// Because it's statically referenced, it requires non-lazy realization
/// by the Objective-C runtime.
///
/// NOTE: older runtimes called this _EmptyArrayStorage. The two must
/// coexist, so it was renamed. The old name must not be used in the new
/// runtime.
@_fixed_layout
@usableFromInline
@_objc_non_lazy_realization
internal final class __EmptyArrayStorage
: __ContiguousArrayStorageBase {
@inlinable
@nonobjc
internal init(_doNotCallMe: ()) {
_internalInvariantFailure("creating instance of __EmptyArrayStorage")
}
#if _runtime(_ObjC)
override internal func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
return try body(UnsafeBufferPointer(start: nil, count: 0))
}
override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer {
return _BridgingBuffer(0)
}
#endif
@inlinable
override internal func canStoreElements(ofDynamicType _: Any.Type) -> Bool {
return false
}
/// A type that every element in the array is.
@inlinable
override internal var staticElementType: Any.Type {
return Void.self
}
}
/// The empty array prototype. We use the same object for all empty
/// `[Native]Array<Element>`s.
@inlinable
internal var _emptyArrayStorage: __EmptyArrayStorage {
return Builtin.bridgeFromRawPointer(
Builtin.addressof(&_swiftEmptyArrayStorage))
}
// The class that implements the storage for a ContiguousArray<Element>
@_fixed_layout
@usableFromInline
internal final class _ContiguousArrayStorage<
Element
>: __ContiguousArrayStorageBase {
@inlinable
deinit {
_elementPointer.deinitialize(count: countAndCapacity.count)
_fixLifetime(self)
}
#if _runtime(_ObjC)
internal final override func withUnsafeBufferOfObjects<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R {
_internalInvariant(_isBridgedVerbatimToObjectiveC(Element.self))
let count = countAndCapacity.count
let elements = UnsafeRawPointer(_elementPointer)
.assumingMemoryBound(to: AnyObject.self)
defer { _fixLifetime(self) }
return try body(UnsafeBufferPointer(start: elements, count: count))
}
@objc(countByEnumeratingWithState:objects:count:)
@_effects(releasenone)
internal final override func countByEnumerating(
with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>,
objects: UnsafeMutablePointer<AnyObject>?, count: Int
) -> Int {
var enumerationState = state.pointee
if enumerationState.state != 0 {
return 0
}
return withUnsafeBufferOfObjects {
objects in
enumerationState.mutationsPtr = _fastEnumerationStorageMutationsPtr
enumerationState.itemsPtr =
AutoreleasingUnsafeMutablePointer(objects.baseAddress)
enumerationState.state = 1
state.pointee = enumerationState
return objects.count
}
}
@inline(__always)
@_effects(readonly)
@nonobjc private func _objectAt(_ index: Int) -> Unmanaged<AnyObject> {
return withUnsafeBufferOfObjects {
objects in
_precondition(
_isValidArraySubscript(index, count: objects.count),
"Array index out of range")
return Unmanaged.passUnretained(objects[index])
}
}
@objc(objectAtIndexedSubscript:)
@_effects(readonly)
final override internal func objectAtSubscript(_ index: Int) -> Unmanaged<AnyObject> {
return _objectAt(index)
}
@objc(objectAtIndex:)
@_effects(readonly)
final override internal func objectAt(_ index: Int) -> Unmanaged<AnyObject> {
return _objectAt(index)
}
@objc internal override final var count: Int {
@_effects(readonly) get {
return withUnsafeBufferOfObjects { $0.count }
}
}
@_effects(releasenone)
@objc internal override final func getObjects(
_ aBuffer: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange
) {
return withUnsafeBufferOfObjects {
objects in
_precondition(
_isValidArrayIndex(range.location, count: objects.count),
"Array index out of range")
_precondition(
_isValidArrayIndex(
range.location + range.length, count: objects.count),
"Array index out of range")
if objects.isEmpty { return }
// These objects are "returned" at +0, so treat them as pointer values to
// avoid retains. Copy bytes via a raw pointer to circumvent reference
// counting while correctly aliasing with all other pointer types.
UnsafeMutableRawPointer(aBuffer).copyMemory(
from: objects.baseAddress! + range.location,
byteCount: range.length * MemoryLayout<AnyObject>.stride)
}
}
/// If the `Element` is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements and return the result.
/// Otherwise, return `nil`.
internal final override func _withVerbatimBridgedUnsafeBuffer<R>(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> R
) rethrows -> R? {
var result: R?
try self._withVerbatimBridgedUnsafeBufferImpl {
result = try body($0)
}
return result
}
/// If `Element` is bridged verbatim, invoke `body` on an
/// `UnsafeBufferPointer` to the elements.
internal final func _withVerbatimBridgedUnsafeBufferImpl(
_ body: (UnsafeBufferPointer<AnyObject>) throws -> Void
) rethrows {
if _isBridgedVerbatimToObjectiveC(Element.self) {
let count = countAndCapacity.count
let elements = UnsafeRawPointer(_elementPointer)
.assumingMemoryBound(to: AnyObject.self)
defer { _fixLifetime(self) }
try body(UnsafeBufferPointer(start: elements, count: count))
}
}
/// Bridge array elements and return a new buffer that owns them.
///
/// - Precondition: `Element` is bridged non-verbatim.
override internal func _getNonVerbatimBridgingBuffer() -> _BridgingBuffer {
_internalInvariant(
!_isBridgedVerbatimToObjectiveC(Element.self),
"Verbatim bridging should be handled separately")
let count = countAndCapacity.count
let result = _BridgingBuffer(count)
let resultPtr = result.baseAddress
let p = _elementPointer
for i in 0..<count {
(resultPtr + i).initialize(to: _bridgeAnythingToObjectiveC(p[i]))
}
_fixLifetime(self)
return result
}
#endif
/// Returns `true` if the `proposedElementType` is `Element` or a subclass of
/// `Element`. We can't store anything else without violating type
/// safety; for example, the destructor has static knowledge that
/// all of the elements can be destroyed as `Element`.
@inlinable
internal override func canStoreElements(
ofDynamicType proposedElementType: Any.Type
) -> Bool {
#if _runtime(_ObjC)
return proposedElementType is Element.Type
#else
// FIXME: Dynamic casts don't currently work without objc.
// rdar://problem/18801510
return false
#endif
}
/// A type that every element in the array is.
@inlinable
internal override var staticElementType: Any.Type {
return Element.self
}
@inlinable
internal final var _elementPointer: UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self))
}
}
@usableFromInline
@frozen
internal struct _ContiguousArrayBuffer<Element>: _ArrayBufferProtocol {
/// Make a buffer with uninitialized elements. After using this
/// method, you must either initialize the `count` elements at the
/// result's `.firstElementAddress` or set the result's `.count`
/// to zero.
@inlinable
internal init(
_uninitializedCount uninitializedCount: Int,
minimumCapacity: Int
) {
let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity)
if realMinimumCapacity == 0 {
self = _ContiguousArrayBuffer<Element>()
}
else {
_storage = Builtin.allocWithTailElems_1(
_ContiguousArrayStorage<Element>.self,
realMinimumCapacity._builtinWordValue, Element.self)
let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_storage))
if let allocSize = _mallocSize(ofAllocation: storageAddr) {
let endAddr = storageAddr + allocSize
let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress
_initStorageHeader(
count: uninitializedCount, capacity: realCapacity)
} else {
_initStorageHeader(
count: uninitializedCount, capacity: realMinimumCapacity)
}
}
}
/// Initialize using the given uninitialized `storage`.
/// The storage is assumed to be uninitialized. The returned buffer has the
/// body part of the storage initialized, but not the elements.
///
/// - Warning: The result has uninitialized elements.
///
/// - Warning: storage may have been stack-allocated, so it's
/// crucial not to call, e.g., `malloc_size` on it.
@inlinable
internal init(count: Int, storage: _ContiguousArrayStorage<Element>) {
_storage = storage
_initStorageHeader(count: count, capacity: count)
}
@inlinable
internal init(_ storage: __ContiguousArrayStorageBase) {
_storage = storage
}
/// Initialize the body part of our storage.
///
/// - Warning: does not initialize elements
@inlinable
internal func _initStorageHeader(count: Int, capacity: Int) {
#if _runtime(_ObjC)
let verbatim = _isBridgedVerbatimToObjectiveC(Element.self)
#else
let verbatim = false
#endif
// We can initialize by assignment because _ArrayBody is a trivial type,
// i.e. contains no references.
_storage.countAndCapacity = _ArrayBody(
count: count,
capacity: capacity,
elementTypeIsBridgedVerbatim: verbatim)
}
/// True, if the array is native and does not need a deferred type check.
@inlinable
internal var arrayPropertyIsNativeTypeChecked: Bool {
return true
}
/// A pointer to the first element.
@inlinable
internal var firstElementAddress: UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(Builtin.projectTailElems(_storage,
Element.self))
}
/// A mutable pointer to the first element.
///
/// - Precondition: The buffer must be mutable.
@_alwaysEmitIntoClient
internal var mutableFirstElementAddress: UnsafeMutablePointer<Element> {
return UnsafeMutablePointer(Builtin.projectTailElems(mutableOrEmptyStorage,
Element.self))
}
@inlinable
internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? {
return firstElementAddress
}
/// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the
/// underlying contiguous storage.
@inlinable
internal func withUnsafeBufferPointer<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R {
defer { _fixLifetime(self) }
return try body(UnsafeBufferPointer(start: firstElementAddress,
count: count))
}
/// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer`
/// over the underlying contiguous storage.
@inlinable
internal mutating func withUnsafeMutableBufferPointer<R>(
_ body: (UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R {
defer { _fixLifetime(self) }
return try body(
UnsafeMutableBufferPointer(start: firstElementAddress, count: count))
}
//===--- _ArrayBufferProtocol conformance -----------------------------------===//
/// Create an empty buffer.
@inlinable
internal init() {
_storage = _emptyArrayStorage
}
@inlinable
internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) {
_internalInvariant(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0")
self = buffer
}
@inlinable
internal mutating func requestUniqueMutableBackingBuffer(
minimumCapacity: Int
) -> _ContiguousArrayBuffer<Element>? {
if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) {
return self
}
return nil
}
@inlinable
internal mutating func isMutableAndUniquelyReferenced() -> Bool {
return isUniquelyReferenced()
}
/// If this buffer is backed by a `_ContiguousArrayBuffer`
/// containing the same number of elements as `self`, return it.
/// Otherwise, return `nil`.
@inlinable
internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? {
return self
}
@inlinable
@inline(__always)
internal func getElement(_ i: Int) -> Element {
_internalInvariant(i >= 0 && i < count, "Array index out of range")
let addr = UnsafePointer<Element>(
Builtin.projectTailElems(immutableStorage, Element.self))
return addr[i]
}
/// The storage of an immutable buffer.
///
/// - Precondition: The buffer must be immutable.
@_alwaysEmitIntoClient
@inline(__always)
internal var immutableStorage : __ContiguousArrayStorageBase {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(isImmutable, "Array storage is not immutable")
#endif
return Builtin.COWBufferForReading(_storage)
}
/// The storage of a mutable buffer.
///
/// - Precondition: The buffer must be mutable.
@_alwaysEmitIntoClient
@inline(__always)
internal var mutableStorage : __ContiguousArrayStorageBase {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(isMutable, "Array storage is immutable")
#endif
return _storage
}
/// The storage of a mutable or empty buffer.
///
/// - Precondition: The buffer must be mutable or the empty array singleton.
@_alwaysEmitIntoClient
@inline(__always)
internal var mutableOrEmptyStorage : __ContiguousArrayStorageBase {
#if INTERNAL_CHECKS_ENABLED
_internalInvariant(isMutable || _storage.countAndCapacity.capacity == 0,
"Array storage is immutable and not empty")
#endif
return _storage
}
#if INTERNAL_CHECKS_ENABLED
@_alwaysEmitIntoClient
internal var isImmutable: Bool {
get {
if doCOWSanityChecks() {
return capacity == 0 || _swift_isImmutableCOWBuffer(_storage)
}
return true
}
nonmutating set {
if doCOWSanityChecks() {
if newValue {
if capacity > 0 {
let wasImmutable = _swift_setImmutableCOWBuffer(_storage, true)
_internalInvariant(!wasImmutable,
"re-setting immutable array buffer to immutable")
}
} else {
_internalInvariant(capacity > 0,
"setting empty array buffer to mutable")
let wasImmutable = _swift_setImmutableCOWBuffer(_storage, false)
_internalInvariant(wasImmutable,
"re-setting mutable array buffer to mutable")
}
}
}
}
@_alwaysEmitIntoClient
internal var isMutable: Bool {
if doCOWSanityChecks() {
return !_swift_isImmutableCOWBuffer(_storage)
}
return true
}
#endif
/// Get or set the value of the ith element.
@inlinable
internal subscript(i: Int) -> Element {
@inline(__always)
get {
return getElement(i)
}
@inline(__always)
nonmutating set {
_internalInvariant(i >= 0 && i < count, "Array index out of range")
// FIXME: Manually swap because it makes the ARC optimizer happy. See
// <rdar://problem/16831852> check retain/release order
// firstElementAddress[i] = newValue
var nv = newValue
let tmp = nv
nv = firstElementAddress[i]
firstElementAddress[i] = tmp
}
}
/// The number of elements the buffer stores.
///
/// This property is obsolete. It's only used for the ArrayBufferProtocol and
/// to keep backward compatibility.
/// Use `immutableCount` or `mutableCount` instead.
@inlinable
internal var count: Int {
get {
return _storage.countAndCapacity.count
}
nonmutating set {
_internalInvariant(newValue >= 0)
_internalInvariant(
newValue <= mutableCapacity,
"Can't grow an array buffer past its capacity")
mutableStorage.countAndCapacity.count = newValue
}
}
/// The number of elements of the buffer.
///
/// - Precondition: The buffer must be immutable.
@_alwaysEmitIntoClient
@inline(__always)
internal var immutableCount: Int {
return immutableStorage.countAndCapacity.count
}
/// The number of elements of the buffer.
///
/// - Precondition: The buffer must be mutable.
@_alwaysEmitIntoClient
internal var mutableCount: Int {
@inline(__always)
get {
return mutableOrEmptyStorage.countAndCapacity.count
}
@inline(__always)
nonmutating set {
_internalInvariant(newValue >= 0)
_internalInvariant(
newValue <= mutableCapacity,
"Can't grow an array buffer past its capacity")
mutableStorage.countAndCapacity.count = newValue
}
}
/// Traps unless the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
///
/// - Precondition: The buffer must be immutable.
@inlinable
@inline(__always)
internal func _checkValidSubscript(_ index: Int) {
_precondition(
(index >= 0) && (index < immutableCount),
"Index out of range"
)
}
/// Traps unless the given `index` is valid for subscripting, i.e.
/// `0 ≤ index < count`.
///
/// - Precondition: The buffer must be mutable.
@_alwaysEmitIntoClient
@inline(__always)
internal func _checkValidSubscriptMutating(_ index: Int) {
_precondition(
(index >= 0) && (index < mutableCount),
"Index out of range"
)
}
/// The number of elements the buffer can store without reallocation.
///
/// This property is obsolete. It's only used for the ArrayBufferProtocol and
/// to keep backward compatibility.
/// Use `immutableCapacity` or `mutableCapacity` instead.
@inlinable
internal var capacity: Int {
return _storage.countAndCapacity.capacity
}
/// The number of elements the buffer can store without reallocation.
///
/// - Precondition: The buffer must be immutable.
@_alwaysEmitIntoClient
@inline(__always)
internal var immutableCapacity: Int {
return immutableStorage.countAndCapacity.capacity
}
/// The number of elements the buffer can store without reallocation.
///
/// - Precondition: The buffer must be mutable.
@_alwaysEmitIntoClient
@inline(__always)
internal var mutableCapacity: Int {
return mutableOrEmptyStorage.countAndCapacity.capacity
}
/// Copy the elements in `bounds` from this buffer into uninitialized
/// memory starting at `target`. Return a pointer "past the end" of the
/// just-initialized memory.
@inlinable
@discardableResult
internal __consuming func _copyContents(
subRange bounds: Range<Int>,
initializing target: UnsafeMutablePointer<Element>
) -> UnsafeMutablePointer<Element> {
_internalInvariant(bounds.lowerBound >= 0)
_internalInvariant(bounds.upperBound >= bounds.lowerBound)
_internalInvariant(bounds.upperBound <= count)
let initializedCount = bounds.upperBound - bounds.lowerBound
target.initialize(
from: firstElementAddress + bounds.lowerBound, count: initializedCount)
_fixLifetime(owner)
return target + initializedCount
}
public __consuming func _copyContents(
initializing buffer: UnsafeMutableBufferPointer<Element>
) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) {
// This customization point is not implemented for internal types.
// Accidentally calling it would be a catastrophic performance bug.
fatalError("unsupported")
}
/// Returns a `_SliceBuffer` containing the given `bounds` of values
/// from this buffer.
@inlinable
internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> {
get {
return _SliceBuffer(
owner: _storage,
subscriptBaseAddress: firstElementAddress,
indices: bounds,
hasNativeBuffer: true)
}
set {
fatalError("not implemented")
}
}
/// Returns `true` iff this buffer's storage is uniquely-referenced.
///
/// This function should only be used for internal sanity checks.
/// To guard a buffer mutation, use `beginCOWMutation`.
@inlinable
internal mutating func isUniquelyReferenced() -> Bool {
return _isUnique(&_storage)
}
/// Returns `true` and puts the buffer in a mutable state iff the buffer's
/// storage is uniquely-referenced.
///
/// - Precondition: The buffer must be immutable.
///
/// - Warning: It's a requirement to call `beginCOWMutation` before the buffer
/// is mutated.
@_alwaysEmitIntoClient
internal mutating func beginCOWMutation() -> Bool {
if Bool(Builtin.beginCOWMutation(&_storage)) {
#if INTERNAL_CHECKS_ENABLED
isImmutable = false
#endif
return true
}
return false;
}
/// Puts the buffer in an immutable state.
///
/// - Precondition: The buffer must be mutable.
///
/// - Warning: After a call to `endCOWMutation` the buffer must not be mutated
/// until the next call of `beginCOWMutation`.
@_alwaysEmitIntoClient
@inline(__always)
internal mutating func endCOWMutation() {
#if INTERNAL_CHECKS_ENABLED
isImmutable = true
#endif
Builtin.endCOWMutation(&_storage)
}
/// Creates and returns a new uniquely referenced buffer which is a copy of
/// this buffer.
///
/// This buffer is consumed, i.e. it's released.
@_alwaysEmitIntoClient
@inline(never)
@_semantics("optimize.sil.specialize.owned2guarantee.never")
internal __consuming func _consumeAndCreateNew() -> _ContiguousArrayBuffer {
return _consumeAndCreateNew(bufferIsUnique: false,
minimumCapacity: count,
growForAppend: false)
}
/// Creates and returns a new uniquely referenced buffer which is a copy of
/// this buffer.
///
/// If `bufferIsUnique` is true, the buffer is assumed to be uniquely
/// referenced and the elements are moved - instead of copied - to the new
/// buffer.
/// The `minimumCapacity` is the lower bound for the new capacity.
/// If `growForAppend` is true, the new capacity is calculated using
/// `_growArrayCapacity`, but at least kept at `minimumCapacity`.
///
/// This buffer is consumed, i.e. it's released.
@_alwaysEmitIntoClient
@inline(never)
@_semantics("optimize.sil.specialize.owned2guarantee.never")
internal __consuming func _consumeAndCreateNew(
bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool
) -> _ContiguousArrayBuffer {
let newCapacity = _growArrayCapacity(oldCapacity: capacity,
minimumCapacity: minimumCapacity,
growForAppend: growForAppend)
let c = count
_internalInvariant(newCapacity >= c)
let newBuffer = _ContiguousArrayBuffer<Element>(
_uninitializedCount: c, minimumCapacity: newCapacity)
if bufferIsUnique {
// As an optimization, if the original buffer is unique, we can just move
// the elements instead of copying.
let dest = newBuffer.mutableFirstElementAddress
dest.moveInitialize(from: firstElementAddress,
count: c)
mutableCount = 0
} else {
_copyContents(
subRange: 0..<c,
initializing: newBuffer.mutableFirstElementAddress)
}
return newBuffer
}
#if _runtime(_ObjC)
/// Convert to an NSArray.
///
/// - Precondition: `Element` is bridged to Objective-C.
///
/// - Complexity: O(1).
@usableFromInline
internal __consuming func _asCocoaArray() -> AnyObject {
// _asCocoaArray was @inlinable in Swift 5.0 and 5.1, which means that there
// are existing apps out there that effectively have the old implementation
// Be careful with future changes to this function. Here be dragons!
// The old implementation was
// if count == 0 {
// return _emptyArrayStorage
// }
// if _isBridgedVerbatimToObjectiveC(Element.self) {
// return _storage
// }
// return __SwiftDeferredNSArray(_nativeStorage: _storage)
_connectOrphanedFoundationSubclassesIfNeeded()
if count == 0 {
return _emptyArrayStorage
}
if _isBridgedVerbatimToObjectiveC(Element.self) {
return _storage
}
return __SwiftDeferredNSArray(_nativeStorage: _storage)
}
#endif
/// An object that keeps the elements stored in this buffer alive.
@inlinable
internal var owner: AnyObject {
return _storage
}
/// An object that keeps the elements stored in this buffer alive.
@inlinable
internal var nativeOwner: AnyObject {
return _storage
}
/// A value that identifies the storage used by the buffer.
///
/// Two buffers address the same elements when they have the same
/// identity and count.
@inlinable
internal var identity: UnsafeRawPointer {
return UnsafeRawPointer(firstElementAddress)
}
/// Returns `true` iff we have storage for elements of the given
/// `proposedElementType`. If not, we'll be treated as immutable.
@inlinable
func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool {
return _storage.canStoreElements(ofDynamicType: proposedElementType)
}
/// Returns `true` if the buffer stores only elements of type `U`.
///
/// - Precondition: `U` is a class or `@objc` existential.
///
/// - Complexity: O(*n*)
@inlinable
internal func storesOnlyElementsOfType<U>(
_: U.Type
) -> Bool {
_internalInvariant(_isClassOrObjCExistential(U.self))
if _fastPath(_storage.staticElementType is U.Type) {
// Done in O(1)
return true
}
// Check the elements
for x in self {
if !(x is U) {
return false
}
}
return true
}
@usableFromInline
internal var _storage: __ContiguousArrayStorageBase
}
/// Append the elements of `rhs` to `lhs`.
@inlinable
internal func += <Element, C: Collection>(
lhs: inout _ContiguousArrayBuffer<Element>, rhs: __owned C
) where C.Element == Element {
let oldCount = lhs.count
let newCount = oldCount + rhs.count
let buf: UnsafeMutableBufferPointer<Element>
if _fastPath(newCount <= lhs.capacity) {
buf = UnsafeMutableBufferPointer(
start: lhs.firstElementAddress + oldCount,
count: rhs.count)
lhs.mutableCount = newCount
}
else {
var newLHS = _ContiguousArrayBuffer<Element>(
_uninitializedCount: newCount,
minimumCapacity: _growArrayCapacity(lhs.capacity))
newLHS.firstElementAddress.moveInitialize(
from: lhs.firstElementAddress, count: oldCount)
lhs.mutableCount = 0
(lhs, newLHS) = (newLHS, lhs)
buf = UnsafeMutableBufferPointer(
start: lhs.firstElementAddress + oldCount,
count: rhs.count)
}
var (remainders,writtenUpTo) = buf.initialize(from: rhs)
// ensure that exactly rhs.count elements were written
_precondition(remainders.next() == nil, "rhs underreported its count")
_precondition(writtenUpTo == buf.endIndex, "rhs overreported its count")
}
extension _ContiguousArrayBuffer: RandomAccessCollection {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
@inlinable
internal var startIndex: Int {
return 0
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `index(after:)`.
@inlinable
internal var endIndex: Int {
return count
}
@usableFromInline
internal typealias Indices = Range<Int>
}
extension Sequence {
@inlinable
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
return _copySequenceToContiguousArray(self)
}
}
@inlinable
internal func _copySequenceToContiguousArray<
S: Sequence
>(_ source: S) -> ContiguousArray<S.Element> {
let initialCapacity = source.underestimatedCount
var builder =
_UnsafePartiallyInitializedContiguousArrayBuffer<S.Element>(
initialCapacity: initialCapacity)
var iterator = source.makeIterator()
// FIXME(performance): use _copyContents(initializing:).
// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
builder.addWithExistingCapacity(iterator.next()!)
}
// Add remaining elements, if any.
while let element = iterator.next() {
builder.add(element)
}
return builder.finish()
}
extension Collection {
@inlinable
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
return _copyCollectionToContiguousArray(self)
}
}
extension _ContiguousArrayBuffer {
@inlinable
internal __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
return ContiguousArray(_buffer: self)
}
}
/// This is a fast implementation of _copyToContiguousArray() for collections.
///
/// It avoids the extra retain, release overhead from storing the
/// ContiguousArrayBuffer into
/// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support
/// ARC loops, the extra retain, release overhead cannot be eliminated which
/// makes assigning ranges very slow. Once this has been implemented, this code
/// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer.
@inlinable
internal func _copyCollectionToContiguousArray<
C: Collection
>(_ source: C) -> ContiguousArray<C.Element>
{
let count = source.count
if count == 0 {
return ContiguousArray()
}
var result = _ContiguousArrayBuffer<C.Element>(
_uninitializedCount: count,
minimumCapacity: 0)
let p = UnsafeMutableBufferPointer(
start: result.firstElementAddress,
count: count)
var (itr, end) = source._copyContents(initializing: p)
_debugPrecondition(itr.next() == nil,
"invalid Collection: more than 'count' elements in collection")
// We also have to check the evil shrink case in release builds, because
// it can result in uninitialized array elements and therefore undefined
// behavior.
_precondition(end == p.endIndex,
"invalid Collection: less than 'count' elements in collection")
result.endCOWMutation()
return ContiguousArray(_buffer: result)
}
/// A "builder" interface for initializing array buffers.
///
/// This presents a "builder" interface for initializing an array buffer
/// element-by-element. The type is unsafe because it cannot be deinitialized
/// until the buffer has been finalized by a call to `finish`.
@usableFromInline
@frozen
internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> {
@usableFromInline
internal var result: _ContiguousArrayBuffer<Element>
@usableFromInline
internal var p: UnsafeMutablePointer<Element>
@usableFromInline
internal var remainingCapacity: Int
/// Initialize the buffer with an initial size of `initialCapacity`
/// elements.
@inlinable
@inline(__always) // For performance reasons.
internal init(initialCapacity: Int) {
if initialCapacity == 0 {
result = _ContiguousArrayBuffer()
} else {
result = _ContiguousArrayBuffer(
_uninitializedCount: initialCapacity,
minimumCapacity: 0)
}
p = result.firstElementAddress
remainingCapacity = result.capacity
}
/// Add an element to the buffer, reallocating if necessary.
@inlinable
@inline(__always) // For performance reasons.
internal mutating func add(_ element: Element) {
if remainingCapacity == 0 {
// Reallocate.
let newCapacity = max(_growArrayCapacity(result.capacity), 1)
var newResult = _ContiguousArrayBuffer<Element>(
_uninitializedCount: newCapacity, minimumCapacity: 0)
p = newResult.firstElementAddress + result.capacity
remainingCapacity = newResult.capacity - result.capacity
if !result.isEmpty {
// This check prevents a data race writing to _swiftEmptyArrayStorage
// Since count is always 0 there, this code does nothing anyway
newResult.firstElementAddress.moveInitialize(
from: result.firstElementAddress, count: result.capacity)
result.mutableCount = 0
}
(result, newResult) = (newResult, result)
}
addWithExistingCapacity(element)
}
/// Add an element to the buffer, which must have remaining capacity.
@inlinable
@inline(__always) // For performance reasons.
internal mutating func addWithExistingCapacity(_ element: Element) {
_internalInvariant(remainingCapacity > 0,
"_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity")
remainingCapacity -= 1
p.initialize(to: element)
p += 1
}
/// Finish initializing the buffer, adjusting its count to the final
/// number of elements.
///
/// Returns the fully-initialized buffer. `self` is reset to contain an
/// empty buffer and cannot be used afterward.
@inlinable
@inline(__always) // For performance reasons.
internal mutating func finish() -> ContiguousArray<Element> {
// Adjust the initialized count of the buffer.
if (result.capacity != 0) {
result.mutableCount = result.capacity - remainingCapacity
} else {
_internalInvariant(remainingCapacity == 0)
_internalInvariant(result.count == 0)
}
return finishWithOriginalCount()
}
/// Finish initializing the buffer, assuming that the number of elements
/// exactly matches the `initialCount` for which the initialization was
/// started.
///
/// Returns the fully-initialized buffer. `self` is reset to contain an
/// empty buffer and cannot be used afterward.
@inlinable
@inline(__always) // For performance reasons.
internal mutating func finishWithOriginalCount() -> ContiguousArray<Element> {
_internalInvariant(remainingCapacity == result.capacity - result.count,
"_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count")
var finalResult = _ContiguousArrayBuffer<Element>()
(finalResult, result) = (result, finalResult)
remainingCapacity = 0
finalResult.endCOWMutation()
return ContiguousArray(_buffer: finalResult)
}
}
| apache-2.0 | 6ed7f47dc2a0f0ba296f5e110d0a1311 | 30.81769 | 94 | 0.690276 | 4.853249 | false | false | false | false |
jtbandes/swift | test/Reflection/typeref_lowering.swift | 2 | 70163 | // REQUIRES: no_asan
// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift %S/Inputs/TypeLowering.swift -parse-as-library -emit-module -emit-library -module-name TypeLowering -o %t/libTypesToReflect.%target-dylib-extension
// RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect.%target-dylib-extension -binary-filename %platform-module-dir/libswiftCore.%target-dylib-extension -dump-type-lowering < %s | %FileCheck %s --check-prefix=CHECK-%target-ptrsize
12TypeLowering11BasicStructV
// CHECK-64: (struct TypeLowering.BasicStruct)
// CHECK-64-NEXT: (struct size=16 alignment=4 stride=16 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=i1 offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=i2 offset=2
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=i3 offset=4
// CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=bi1 offset=8
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=bi2 offset=10
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=bi3 offset=12
// CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))))
// CHECK-32: (struct TypeLowering.BasicStruct)
// CHECK-32-NEXT: (struct size=16 alignment=4 stride=16 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=i1 offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=i2 offset=2
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=i3 offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field name=bi1 offset=8
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=bi2 offset=10
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=bi3 offset=12
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))))
12TypeLowering05AssocA6StructV
// CHECK-64: (struct TypeLowering.AssocTypeStruct)
// CHECK-64-NEXT: (struct size=36 alignment=2 stride=36 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=t1 offset=0
// CHECK-64-NEXT: (struct size=7 alignment=2 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=a offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=b offset=2
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=c offset=4
// CHECK-64-NEXT: (tuple size=3 alignment=2 stride=4 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field offset=2
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))))))
// CHECK-64-NEXT: (field name=t2 offset=8
// CHECK-64-NEXT: (struct size=7 alignment=2 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=a offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=b offset=2
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=c offset=4
// CHECK-64-NEXT: (tuple size=3 alignment=2 stride=4 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field offset=2
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))))))
// CHECK-64-NEXT: (field name=t3 offset=16
// CHECK-64-NEXT: (struct size=8 alignment=2 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=a offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=b offset=2
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=c offset=4
// CHECK-64-NEXT: (tuple size=4 alignment=2 stride=4 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field offset=2
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))))))
// CHECK-64-NEXT: (field name=t4 offset=24
// CHECK-64-NEXT: (struct size=8 alignment=2 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=a offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=b offset=2
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=c offset=4
// CHECK-64-NEXT: (tuple size=4 alignment=2 stride=4 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field offset=2
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))))))
// CHECK-64-NEXT: (field name=t5 offset=32
// CHECK-64-NEXT: (struct size=4 alignment=1 stride=4 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=a offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=b offset=1
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=c offset=2
// CHECK-64-NEXT: (tuple size=2 alignment=1 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field offset=1
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0)))))))))))
// CHECK-32: (struct TypeLowering.AssocTypeStruct)
// CHECK-32-NEXT: (struct size=36 alignment=2 stride=36 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=t1 offset=0
// CHECK-32-NEXT: (struct size=7 alignment=2 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=a offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=b offset=2
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=c offset=4
// CHECK-32-NEXT: (tuple size=3 alignment=2 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field offset=2
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))))))
// CHECK-32-NEXT: (field name=t2 offset=8
// CHECK-32-NEXT: (struct size=7 alignment=2 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=a offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=b offset=2
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=c offset=4
// CHECK-32-NEXT: (tuple size=3 alignment=2 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field offset=2
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))))))
// CHECK-32-NEXT: (field name=t3 offset=16
// CHECK-32-NEXT: (struct size=8 alignment=2 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=a offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=b offset=2
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=c offset=4
// CHECK-32-NEXT: (tuple size=4 alignment=2 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field offset=2
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))))))
// CHECK-32-NEXT: (field name=t4 offset=24
// CHECK-32-NEXT: (struct size=8 alignment=2 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=a offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=b offset=2
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=c offset=4
// CHECK-32-NEXT: (tuple size=4 alignment=2 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field offset=2
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))))))
// CHECK-32-NEXT: (field name=t5 offset=32
// CHECK-32-NEXT: (struct size=4 alignment=1 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=a offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=b offset=1
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field name=c offset=2
// CHECK-32-NEXT: (tuple size=2 alignment=1 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field offset=1
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0)))))))))))
12TypeLowering3BoxVys5Int16VG_s5Int32Vt
// CHECK-64-NEXT: (tuple
// CHECK-64-NEXT: (bound_generic_struct TypeLowering.Box
// CHECK-64-NEXT: (struct Swift.Int16))
// CHECK-64-NEXT: (struct Swift.Int32))
// CHECK-32-NEXT: (tuple
// CHECK-32-NEXT: (bound_generic_struct TypeLowering.Box
// CHECK-32-NEXT: (struct Swift.Int16))
// CHECK-32-NEXT: (struct Swift.Int32))
// CHECK-64-NEXT: (tuple size=8 alignment=4 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field offset=4
// CHECK-64-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
// CHECK-32-NEXT: (tuple size=8 alignment=4 stride=8 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-32-NEXT: (field offset=4
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
12TypeLowering15ReferenceStructV
// CHECK-64: (struct TypeLowering.ReferenceStruct)
// CHECK-64-NEXT: (struct size=72 alignment=8 stride=72 num_extra_inhabitants=[[PTR_XI:2048|4096|2147483647]]
// CHECK-64-NEXT: (field name=strongRef offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field name=optionalStrongRef offset=8
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1:2047|4095|2147483646]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))))
// CHECK-64-NEXT: (field name=strongRefTuple offset=16
// CHECK-64-NEXT: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field offset=8
// CHECK-64-NEXT: (reference kind=strong refcounting=native))))
// CHECK-64-NEXT: (field name=optionalStrongRefTuple offset=32
// CHECK-64-NEXT: (single_payload_enum size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (tuple size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field offset=8
// CHECK-64-NEXT: (reference kind=strong refcounting=native))))))
// CHECK-64-NEXT: (field name=unownedRef offset=48
// CHECK-64-NEXT: (reference kind=unowned refcounting=native))
// CHECK-64-NEXT: (field name=weakRef offset=56
// CHECK-64-NEXT: (reference kind=weak refcounting=native))
// CHECK-64-NEXT: (field name=unmanagedRef offset=64
// CHECK-64-NEXT: (reference kind=unmanaged refcounting=native)))
// CHECK-32: (struct TypeLowering.ReferenceStruct)
// CHECK-32-NEXT: (struct size=36 alignment=4 stride=36 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=strongRef offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=native))
// CHECK-32-NEXT: (field name=optionalStrongRef offset=4
// CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=native))))
// CHECK-32-NEXT: (field name=strongRefTuple offset=8
// CHECK-32-NEXT: (tuple size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=native))
// CHECK-32-NEXT: (field offset=4
// CHECK-32-NEXT: (reference kind=strong refcounting=native))))
// CHECK-32-NEXT: (field name=optionalStrongRefTuple offset=16
// CHECK-32-NEXT: (single_payload_enum size=8 alignment=4 stride=8 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (tuple size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=native))
// CHECK-32-NEXT: (field offset=4
// CHECK-32-NEXT: (reference kind=strong refcounting=native))))))
// CHECK-32-NEXT: (field name=unownedRef offset=24
// CHECK-32-NEXT: (reference kind=unowned refcounting=native))
// CHECK-32-NEXT: (field name=weakRef offset=28
// CHECK-32-NEXT: (reference kind=weak refcounting=native))
// CHECK-32-NEXT: (field name=unmanagedRef offset=32
// CHECK-32-NEXT: (reference kind=unmanaged refcounting=native)))
12TypeLowering14FunctionStructV
// CHECK-64: (struct TypeLowering.FunctionStruct)
// CHECK-64-NEXT: (struct size=64 alignment=8 stride=64 num_extra_inhabitants=[[PTR_XI_2:4096|2147483647]]
// CHECK-64-NEXT: (field name=thickFunction offset=0
// CHECK-64-NEXT: (thick_function size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_2]]
// CHECK-64-NEXT: (field name=function offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2]]))
// CHECK-64-NEXT: (field name=context offset=8
// CHECK-64-NEXT: (reference kind=strong refcounting=native))))
// CHECK-64-NEXT: (field name=optionalThickFunction offset=16
// CHECK-64-NEXT: (single_payload_enum size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_2_SUB_1:4095|2147483646]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (thick_function size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_2]]
// CHECK-64-NEXT: (field name=function offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2]]))
// CHECK-64-NEXT: (field name=context offset=8
// CHECK-64-NEXT: (reference kind=strong refcounting=native))))))
// CHECK-64-NEXT: (field name=thinFunction offset=32
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2]]))
// CHECK-64-NEXT: (field name=optionalThinFunction offset=40
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2]]))))
// CHECK-64-NEXT: (field name=cFunction offset=48
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2]]))
// CHECK-64-NEXT: (field name=optionalCFunction offset=56
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_2]])))))
// CHECK-32: (struct TypeLowering.FunctionStruct)
// CHECK-32-NEXT: (struct size=32 alignment=4 stride=32 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=thickFunction offset=0
// CHECK-32-NEXT: (thick_function size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=function offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=context offset=4
// CHECK-32-NEXT: (reference kind=strong refcounting=native))))
// CHECK-32-NEXT: (field name=optionalThickFunction offset=8
// CHECK-32-NEXT: (single_payload_enum size=8 alignment=4 stride=8 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (thick_function size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=function offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=context offset=4
// CHECK-32-NEXT: (reference kind=strong refcounting=native))))))
// CHECK-32-NEXT: (field name=thinFunction offset=16
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=optionalThinFunction offset=20
// CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))))
// CHECK-32-NEXT: (field name=cFunction offset=24
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=optionalCFunction offset=28
// CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096)))))
12TypeLowering17ExistentialStructV
// CHECK-64: (struct TypeLowering.ExistentialStruct)
// CHECK-64-NEXT: (struct size=464 alignment=8 stride=464 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=any offset=0
// CHECK-64-NEXT: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))))
// CHECK-64-NEXT: (field name=optionalAny offset=32
// CHECK-64-NEXT: (single_payload_enum size=33 alignment=8 stride=40 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (opaque_existential size=32 alignment=8 stride=32 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))))))
// CHECK-64-NEXT: (field name=anyObject offset=72
// CHECK-64-NEXT: (class_existential size=8 alignment=8 stride=8
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))))
// CHECK-64-NEXT: (field name=optionalAnyObject offset=80
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (class_existential size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))))))
// CHECK-64-NEXT: (field name=anyProto offset=88
// CHECK-64-NEXT: (opaque_existential size=40 alignment=8 stride=40 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))
// CHECK-64-NEXT: (field name=wtable offset=32
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=optionalAnyProto offset=128
// CHECK-64-NEXT: (single_payload_enum size=41 alignment=8 stride=48 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (opaque_existential size=40 alignment=8 stride=40 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))
// CHECK-64-NEXT: (field name=wtable offset=32
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))))
// CHECK-64-NEXT: (field name=anyProtoComposition offset=176
// CHECK-64-NEXT: (opaque_existential size=48 alignment=8 stride=48 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))
// CHECK-64-NEXT: (field name=wtable offset=32
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))
// CHECK-64-NEXT: (field name=wtable offset=40
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=optionalAnyProtoComposition offset=224
// CHECK-64-NEXT: (single_payload_enum size=49 alignment=8 stride=56 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (opaque_existential size=48 alignment=8 stride=48 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=metadata offset=24
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))
// CHECK-64-NEXT: (field name=wtable offset=32
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))
// CHECK-64-NEXT: (field name=wtable offset=40
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))))
// CHECK-64-NEXT: (field name=anyClassBoundProto1 offset=280
// CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=optionalAnyClassBoundProto1 offset=296
// CHECK-64-NEXT: (single_payload_enum size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))))
// CHECK-64-NEXT: (field name=anyClassBoundProto2 offset=312
// CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=optionalAnyClassBoundProto2 offset=328
// CHECK-64-NEXT: (single_payload_enum size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))))
// CHECK-64-NEXT: (field name=anyClassBoundProtoComposition1 offset=344
// CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=optionalAnyClassBoundProtoComposition1 offset=360
// CHECK-64-NEXT: (single_payload_enum size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))))
// CHECK-64-NEXT: (field name=anyClassBoundProtoComposition2 offset=376
// CHECK-64-NEXT: (class_existential size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))
// CHECK-64-NEXT: (field name=wtable offset=16
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=optionalAnyClassBoundProtoComposition2 offset=400
// CHECK-64-NEXT: (single_payload_enum size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (class_existential size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))
// CHECK-64-NEXT: (field name=wtable offset=16
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))))
// CHECK-64-NEXT: (field name=weakAnyObject offset=424
// CHECK-64-NEXT: (class_existential size=8 alignment=8 stride=8
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=weak refcounting=unknown))))
// CHECK-64-NEXT: (field name=weakAnyClassBoundProto offset=432
// CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=weak refcounting=unknown))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=classConstrainedP1 offset=448
// CHECK-64-NEXT: (class_existential size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=object offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1)))))
// CHECK-32: (struct TypeLowering.ExistentialStruct)
// CHECK-32-NEXT: (struct size=232 alignment=4 stride=232 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=any offset=0
// CHECK-32-NEXT: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))))
// CHECK-32-NEXT: (field name=optionalAny offset=16
// CHECK-32-NEXT: (single_payload_enum size=17 alignment=4 stride=20 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (opaque_existential size=16 alignment=4 stride=16 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))))))
// CHECK-32-NEXT: (field name=anyObject offset=36
// CHECK-32-NEXT: (class_existential size=4 alignment=4 stride=4 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))))
// CHECK-32-NEXT: (field name=optionalAnyObject offset=40
// CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (class_existential size=4 alignment=4 stride=4 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))))))
// CHECK-32-NEXT: (field name=anyProto offset=44
// CHECK-32-NEXT: (opaque_existential size=20 alignment=4 stride=20 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=16
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=optionalAnyProto offset=64
// CHECK-32-NEXT: (single_payload_enum size=21 alignment=4 stride=24 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (opaque_existential size=20 alignment=4 stride=20 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=16
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))))
// CHECK-32-NEXT: (field name=anyProtoComposition offset=88
// CHECK-32-NEXT: (opaque_existential size=24 alignment=4 stride=24 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=16
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))
// CHECK-32-NEXT: (field name=wtable offset=20
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=optionalAnyProtoComposition offset=112
// CHECK-32-NEXT: (single_payload_enum size=25 alignment=4 stride=28 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (opaque_existential size=24 alignment=4 stride=24 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=metadata offset=12
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=16
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))
// CHECK-32-NEXT: (field name=wtable offset=20
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))))
// CHECK-32-NEXT: (field name=anyClassBoundProto1 offset=140
// CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=optionalAnyClassBoundProto1 offset=148
// CHECK-32-NEXT: (single_payload_enum size=8 alignment=4 stride=8 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))))
// CHECK-32-NEXT: (field name=anyClassBoundProto2 offset=156
// CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=optionalAnyClassBoundProto2 offset=164
// CHECK-32-NEXT: (single_payload_enum size=8 alignment=4 stride=8 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))))
// CHECK-32-NEXT: (field name=anyClassBoundProtoComposition1 offset=172
// CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=optionalAnyClassBoundProtoComposition1 offset=180
// CHECK-32-NEXT: (single_payload_enum size=8 alignment=4 stride=8 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))))
// CHECK-32-NEXT: (field name=anyClassBoundProtoComposition2 offset=188
// CHECK-32-NEXT: (class_existential size=12 alignment=4 stride=12 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))
// CHECK-32-NEXT: (field name=wtable offset=8
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=optionalAnyClassBoundProtoComposition2 offset=200
// CHECK-32-NEXT: (single_payload_enum size=12 alignment=4 stride=12 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (class_existential size=12 alignment=4 stride=12 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))
// CHECK-32-NEXT: (field name=wtable offset=8
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))))
// CHECK-32-NEXT: (field name=weakAnyObject offset=212
// CHECK-32-NEXT: (class_existential size=4 alignment=4 stride=4 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=weak refcounting=unknown))))
// CHECK-32-NEXT: (field name=weakAnyClassBoundProto offset=216
// CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=weak refcounting=unknown))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=classConstrainedP1 offset=224
// CHECK-32-NEXT: (class_existential size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=object offset=0
// CHECK-32-NEXT: (reference kind=strong refcounting=native))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1)))))
12TypeLowering14MetatypeStructV
// CHECK-64: (struct TypeLowering.MetatypeStruct)
// CHECK-64-NEXT: (struct size=152 alignment=8 stride=152 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=any offset=0
// CHECK-64-NEXT: (existential_metatype size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=metadata offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))))
// CHECK-64-NEXT: (field name=optionalAny offset=8
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (existential_metatype size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=metadata offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))))))
// CHECK-64-NEXT: (field name=anyObject offset=16
// CHECK-64-NEXT: (existential_metatype size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=metadata offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))))
// CHECK-64-NEXT: (field name=optionalAnyObject offset=24
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (existential_metatype size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=metadata offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))))))
// CHECK-64-NEXT: (field name=anyProto offset=32
// CHECK-64-NEXT: (existential_metatype size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=metadata offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=optionalAnyProto offset=48
// CHECK-64-NEXT: (single_payload_enum size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (existential_metatype size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=metadata offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))))
// CHECK-64-NEXT: (field name=anyProtoComposition offset=64
// CHECK-64-NEXT: (existential_metatype size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=metadata offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))
// CHECK-64-NEXT: (field name=wtable offset=16
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))
// CHECK-64-NEXT: (field name=optionalAnyProtoComposition offset=88
// CHECK-64-NEXT: (single_payload_enum size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (existential_metatype size=24 alignment=8 stride=24 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=metadata offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))
// CHECK-64-NEXT: (field name=wtable offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))
// CHECK-64-NEXT: (field name=wtable offset=16
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1))))))
// CHECK-64-NEXT: (field name=structMetatype offset=112
// CHECK-64-NEXT: (builtin size=0 alignment=1 stride=1 num_extra_inhabitants=0))
// CHECK-64-NEXT: (field name=optionalStructMetatype offset=112
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))))
// CHECK-64-NEXT: (field name=classMetatype offset=120
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))
// CHECK-64-NEXT: (field name=optionalClassMetatype offset=128
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))))
// CHECK-64-NEXT: (field name=abstractMetatype offset=136
// CHECK-64-NEXT: (struct size=16 alignment=8 stride=16 num_extra_inhabitants=[[PTR_XI]]
// CHECK-64-NEXT: (field name=t offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]]))
// CHECK-64-NEXT: (field name=u offset=8
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI]])))))
// CHECK-32: (struct TypeLowering.MetatypeStruct)
// CHECK-32-NEXT: (struct size=76 alignment=4 stride=76 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=any offset=0
// CHECK-32-NEXT: (existential_metatype size=4 alignment=4 stride=4 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=metadata offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))))
// CHECK-32-NEXT: (field name=optionalAny offset=4
// CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (existential_metatype size=4 alignment=4 stride=4 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=metadata offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))))))
// CHECK-32-NEXT: (field name=anyObject offset=8
// CHECK-32-NEXT: (existential_metatype size=4 alignment=4 stride=4 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=metadata offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))))
// CHECK-32-NEXT: (field name=optionalAnyObject offset=12
// CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (existential_metatype size=4 alignment=4 stride=4 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=metadata offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))))))
// CHECK-32-NEXT: (field name=anyProto offset=16
// CHECK-32-NEXT: (existential_metatype size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=metadata offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=optionalAnyProto offset=24
// CHECK-32-NEXT: (single_payload_enum size=8 alignment=4 stride=8 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (existential_metatype size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=metadata offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))))
// CHECK-32-NEXT: (field name=anyProtoComposition offset=32
// CHECK-32-NEXT: (existential_metatype size=12 alignment=4 stride=12 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=metadata offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))
// CHECK-32-NEXT: (field name=wtable offset=8
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))
// CHECK-32-NEXT: (field name=optionalAnyProtoComposition offset=44
// CHECK-32-NEXT: (single_payload_enum size=12 alignment=4 stride=12 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (existential_metatype size=12 alignment=4 stride=12 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=metadata offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=wtable offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))
// CHECK-32-NEXT: (field name=wtable offset=8
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=1))))))
// CHECK-32-NEXT: (field name=structMetatype offset=56
// CHECK-32-NEXT: (builtin size=0 alignment=1 stride=1 num_extra_inhabitants=0))
// CHECK-32-NEXT: (field name=optionalStructMetatype offset=56
// CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))))
// CHECK-32-NEXT: (field name=classMetatype offset=60
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=optionalClassMetatype offset=64
// CHECK-32-NEXT: (single_payload_enum size=4 alignment=4 stride=4 num_extra_inhabitants=4095
// CHECK-32-NEXT: (field name=some offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))))
// CHECK-32-NEXT: (field name=abstractMetatype offset=68
// CHECK-32-NEXT: (struct size=8 alignment=4 stride=8 num_extra_inhabitants=4096
// CHECK-32-NEXT: (field name=t offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096))
// CHECK-32-NEXT: (field name=u offset=4
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=4096)))))
12TypeLowering10EnumStructV
// CHECK-64: (struct TypeLowering.EnumStruct)
// CHECK-64-NEXT: (struct size=81 alignment=8 stride=88 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=empty offset=0
// CHECK-64-NEXT: (no_payload_enum size=0 alignment=1 stride=1 num_extra_inhabitants=0))
// CHECK-64-NEXT: (field name=noPayload offset=0
// CHECK-64-NEXT: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=0))
// CHECK-64-NEXT: (field name=sillyNoPayload offset=1
// CHECK-64-NEXT: (no_payload_enum size=1 alignment=1 stride=1 num_extra_inhabitants=0))
// CHECK-64-NEXT: (field name=singleton offset=8
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field name=singlePayload offset=16
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=Indirect offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))))
// CHECK-64-NEXT: (field name=multiPayloadConcrete offset=24
// CHECK-64-NEXT: (multi_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=Left offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field name=Right offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))))
// CHECK-64-NEXT: (field name=multiPayloadGenericFixed offset=32
// CHECK-64-NEXT: (multi_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=Left offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))
// CHECK-64-NEXT: (field name=Right offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))))
// CHECK-64-NEXT: (field name=multiPayloadGenericDynamic offset=48
// CHECK-64-NEXT: (multi_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=Left offset=0
// CHECK-64-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field name=Right offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))))
// CHECK-64-NEXT: (field name=optionalOptionalRef offset=64
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_2:2147483645|2046|4094]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=[[PTR_XI_SUB_1]]
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (reference kind=strong refcounting=native))))))
// CHECK-64-NEXT: (field name=optionalOptionalPtr offset=72
// CHECK-64-NEXT: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (single_payload_enum size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=some offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=1
// CHECK-64-NEXT: (field name=_rawValue offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=1)))))))))
Bo
// CHECK-64: (builtin Builtin.NativeObject)
// CHECK-64-NEXT: (reference kind=strong refcounting=native)
// CHECK-32: (builtin Builtin.NativeObject)
// CHECK-32-NEXT: (reference kind=strong refcounting=native)
BO
// CHECK-64: (builtin Builtin.UnknownObject)
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown)
// CHECK-32: (builtin Builtin.UnknownObject)
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown)
| apache-2.0 | 8695f90ff667467ee373fd806356ad51 | 69.943377 | 252 | 0.659878 | 3.288788 | false | false | false | false |
firebase/firebase-ios-sdk | FirebaseStorage/Sources/Internal/StorageDeleteTask.swift | 1 | 2532 | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
#if COCOAPODS
import GTMSessionFetcher
#else
import GTMSessionFetcherCore
#endif
/**
* Task which provides the ability to delete an object in Firebase Storage.
*/
internal class StorageDeleteTask: StorageTask, StorageTaskManagement {
private var fetcher: GTMSessionFetcher?
private var fetcherCompletion: ((Data?, NSError?) -> Void)?
private var taskCompletion: ((_ error: Error?) -> Void)?
internal init(reference: StorageReference,
fetcherService: GTMSessionFetcherService,
queue: DispatchQueue,
completion: ((_: Error?) -> Void)?) {
super.init(reference: reference, service: fetcherService, queue: queue)
taskCompletion = completion
}
deinit {
self.fetcher?.stopFetching()
}
/**
* Prepares a task and begins execution.
*/
internal func enqueue() {
weak var weakSelf = self
dispatchQueue.async {
guard let strongSelf = weakSelf else { return }
strongSelf.state = .queueing
var request = strongSelf.baseRequest
request.httpMethod = "DELETE"
request.timeoutInterval = strongSelf.reference.storage.maxOperationRetryTime
let callback = strongSelf.taskCompletion
strongSelf.taskCompletion = nil
let fetcher = strongSelf.fetcherService.fetcher(with: request)
fetcher.comment = "DeleteTask"
strongSelf.fetcher = fetcher
strongSelf.fetcherCompletion = { (data: Data?, error: NSError?) in
if let error = error, self.error == nil {
self.error = StorageErrorCode.error(withServerError: error, ref: strongSelf.reference)
}
callback?(self.error)
self.fetcherCompletion = nil
}
strongSelf.fetcher?.beginFetch { data, error in
let strongSelf = weakSelf
if let fetcherCompletion = strongSelf?.fetcherCompletion {
fetcherCompletion(data, error as? NSError)
}
}
}
}
}
| apache-2.0 | 9dce22b7ce7235ccfa3fa031d7e122da | 31.461538 | 96 | 0.689573 | 4.750469 | false | false | false | false |
danielsaidi/KeyboardKit | Tests/KeyboardKitTests/Extensions/String+DelimitersTests.swift | 1 | 1248 | //
// String+DelimitersTests.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-01-18.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import Quick
import Nimble
import KeyboardKit
class String_DelimitersTests: QuickSpec {
override func spec() {
describe("string") {
it("can identify a sentence delimiter") {
let result = String.sentenceDelimiters.map { $0.isSentenceDelimiter }
expect(result.allSatisfy { $0 == true }).to(beTrue())
expect("a".isSentenceDelimiter).to(beFalse())
}
it("can identify a word delimiter") {
let result = String.wordDelimiters.map { $0.isWordDelimiter }
expect(result.allSatisfy { $0 == true }).to(beTrue())
expect("a".isWordDelimiter).to(beFalse())
}
it("provides sentence delimiters") {
expect(String.sentenceDelimiters).to(equal(["!", ".", "?", "\n"]))
}
it("provides word delimiters") {
expect(String.wordDelimiters).to(equal(["!", ".", "?", "\n", ",", ";", ":", " "]))
}
}
}
}
| mit | 469377f17205f791d57132b148f5fa38 | 30.175 | 98 | 0.509222 | 4.759542 | false | false | false | false |
loudnate/LoopKit | LoopKitUI/View Controllers/CommandResponseViewController.swift | 2 | 3456 | //
// CommandResponseViewController.swift
// LoopKit
//
// Created by Nate Racklyeft on 8/26/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
import os.log
public class CommandResponseViewController: UIViewController {
public typealias Command = (_ completionHandler: @escaping (_ responseText: String) -> Void) -> String
public init(command: @escaping Command) {
self.command = command
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public var fileName: String?
private let uuid = UUID()
private let command: Command
fileprivate lazy var textView = UITextView()
public override func loadView() {
self.view = textView
}
public override func viewDidLoad() {
super.viewDidLoad()
textView.contentInsetAdjustmentBehavior = .always
let font = UIFont(name: "Menlo-Regular", size: 14)
if let font = font {
let metrics = UIFontMetrics(forTextStyle: .body)
textView.font = metrics.scaledFont(for: font)
} else {
textView.font = font
}
textView.text = command { [weak self] (responseText) -> Void in
var newText = self?.textView.text ?? ""
newText += "\n\n"
newText += responseText
self?.textView.text = newText
}
textView.isEditable = false
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareText(_:)))
}
@objc func shareText(_: Any?) {
let title = fileName ?? "\(self.title ?? uuid.uuidString).txt"
guard let item = SharedResponse(text: textView.text, title: title) else {
return
}
let activityVC = UIActivityViewController(activityItems: [item], applicationActivities: nil)
present(activityVC, animated: true, completion: nil)
}
}
private class SharedResponse: NSObject, UIActivityItemSource {
let title: String
let fileURL: URL
init?(text: String, title: String) {
self.title = title
var url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
url.appendPathComponent(title, isDirectory: false)
do {
try text.write(to: url, atomically: true, encoding: .utf8)
} catch let error {
os_log("Failed to write to file %{public}@: %{public}@", log: .default, type: .error, title, String(describing: error))
return nil
}
fileURL = url
super.init()
}
public func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return fileURL
}
public func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
return fileURL
}
public func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
return title
}
public func activityViewController(_ activityViewController: UIActivityViewController, dataTypeIdentifierForActivityType activityType: UIActivity.ActivityType?) -> String {
return "public.utf8-plain-text"
}
}
| mit | febfcb56ff700896ff70009cd673170e | 29.307018 | 176 | 0.655572 | 5.126113 | false | false | false | false |
lennet/proNotes | app/proNotesUITests/AddLayerUITests.swift | 1 | 3437 | //
// AddLayerUITests.swift
// proNotes
//
// Created by Leo Thomas on 07/07/16.
// Copyright © 2016 leonardthomas. All rights reserved.
//
import XCTest
class AddLayerUITests: XCTestCase {
override func setUp() {
super.setUp()
continueAfterFailure = false
let app = XCUIApplication()
app.launchArguments = ["UITEST"]
app.launch()
XCUIDevice.shared().orientation = .landscapeLeft
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testCreateTextLayer() {
let app = XCUIApplication()
let documentName = createAndOpenDocument()
let layerTableView = app.scrollViews.otherElements.tables
XCTAssertEqual(layerTableView.cells.matching(identifier: "LayerTableViewCell").count, 0)
addTextField()
pressLayerButton()
XCTAssertTrue(layerTableView.staticTexts["text"].exists, "Textlayer doesn't exists")
XCTAssertEqual(layerTableView.cells.matching(identifier: "LayerTableViewCell").count, 1)
closeDocument()
deleteDocument(name: documentName)
}
func testCreateImageLayer() {
let app = XCUIApplication()
let documentName = createAndOpenDocument()
let layerTableView = app.scrollViews.otherElements.tables
XCTAssertEqual(layerTableView.cells.matching(identifier: "LayerTableViewCell").count, 0)
addImage()
pressLayerButton()
XCTAssertTrue(layerTableView.staticTexts["image"].exists, "Textlayer doesn't exists")
XCTAssertEqual(layerTableView.cells.matching(identifier: "LayerTableViewCell").count, 1)
closeDocument()
deleteDocument(name: documentName)
}
func testCreateSketchCanvas() {
let app = XCUIApplication()
let documentName = createAndOpenDocument()
let layerTableView = app.scrollViews.otherElements.tables
XCTAssertEqual(layerTableView.cells.matching(identifier: "LayerTableViewCell").count, 0)
addSketchLayer()
pressLayerButton()
XCTAssertTrue(layerTableView.staticTexts["sketch"].exists, "Textlayer doesn't exists")
XCTAssertEqual(layerTableView.cells.matching(identifier: "LayerTableViewCell").count, 1)
closeDocument()
deleteDocument(name: documentName)
}
func testCreatePage() {
let app = XCUIApplication()
let documentName = createAndOpenDocument()
let layerTableView = app.scrollViews.otherElements.tables
XCTAssertEqual(layerTableView.cells.matching(identifier: "LayerTableViewCell").count, 0)
let tablesQuery = app.tables.matching(identifier: "PagesOverViewTableView")
XCTAssertEqual(tablesQuery.cells.count, 1)
XCTAssertTrue(app.scrollViews.otherElements.staticTexts["Page 1"].exists, "First Page doesnt exist")
addEmptyPage()
tablesQuery.cells.containing(.staticText, identifier:"2").children(matching: .button).element.tap()
XCTAssertTrue(app.scrollViews.otherElements.staticTexts["Page 2"].exists, "Second Page doesnt exist")
XCTAssertEqual(layerTableView.cells.matching(identifier: "LayerTableViewCell").count, 0)
XCTAssertEqual(tablesQuery.cells.count, 2)
closeDocument()
deleteDocument(name: documentName)
}
}
| mit | c7686d9eb403d8e1f6d3abbd09f831e2 | 40.39759 | 111 | 0.690629 | 5.253823 | false | true | false | false |
MaddTheSane/Simple-Comic | Classes/Progress Bar/TSSTInfoWindow.swift | 1 | 1719 | //
// TSSTInfoWindow.swift
// SimpleComic
//
// Created by C.W. Betts on 1/17/16.
// Copyright © 2016 Dancing Tortoise Software. All rights reserved.
//
import Cocoa
/// This panel subclass is used by both the loupe,
/// and the speech bubble styled page preview.
class TSSTInfoWindow: NSPanel {
override init(contentRect: NSRect, styleMask aStyle: NSWindow.StyleMask, backing bufferingType: NSWindow.BackingStoreType, defer flag: Bool) {
super.init(contentRect: contentRect, styleMask: .borderless, backing: bufferingType, defer: flag)
isOpaque = false
ignoresMouseEvents = true
backgroundColor = NSColor.clear
}
@objc(caretAtPoint:size:withLimitLeft:right:)
func caret(at point: NSPoint, size: NSSize, limitLeft left: CGFloat, limitRight right: CGFloat) {
let limitWidth = right - left
let relativePosition = (point.x - left) / limitWidth
let offset = size.width * relativePosition
let frameRect = NSRect(x: point.x - offset - 10, y: point.y, width: size.width + 20, height: size.height + 25)
(contentView as? TSSTInfoView)?.caretPosition = offset + 10
setFrame(frameRect, display: true, animate: false)
invalidateShadow()
}
@objc(centerAtPoint:)
func center(at center: NSPoint) {
let frame = self.frame
let fo = NSPoint(x: center.x - frame.width / 2, y: center.y - frame.height / 2)
setFrameOrigin(fo)
invalidateShadow()
}
@objc(resizeToDiameter:)
func resize(toDiameter diameter: CGFloat) {
let frame = self.frame
let center = NSPoint(x: frame.minX + frame.width / 2, y: frame.minY + frame.height / 2)
setFrame(NSRect(x: center.x - diameter / 2, y: center.y - diameter / 2, width: diameter, height: diameter),
display: true,
animate: false)
}
}
| mit | 8f8e07a5bea75d9ec40241a9bda39c66 | 34.791667 | 143 | 0.715367 | 3.484787 | false | false | false | false |
BareFeetWare/BFWControls | BFWControls/Modules/NibReplaceable/View/UIStackView+Joined.swift | 1 | 2424 | //
// UIStackView+Joined.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 22/7/18.
// Copyright © 2018 BareFeetWare. All rights reserved.
// Free to use and modify, without warranty.
//
import UIKit
@available(iOS 9.0, *)
public extension UIStackView {
/// Returns a string containing the stack view's labels' text, using the specified separators.
func textJoinedFromSubviews(columnSeparator: String = ":",
rowSeparator: String = ",") -> String?
{
return subviews
.map {
($0.subviews as! [UILabel])
.map { $0.text }
.compactMap { $0 }
.joined(separator: columnSeparator)
}
.joined(separator: rowSeparator)
}
/// Updates the stack view's subviews so each label contains a component when the string is separated using the specified separators.
func updateSubviews(fromString string: String,
columnSeparator: String = ":",
rowSeparator: String = ",")
{
let rowStrings = string.components(separatedBy: rowSeparator)
let oldRowCount = subviews.count
let addingRowCount = rowStrings.count - oldRowCount
if addingRowCount < 0 {
subviews.dropFirst(-addingRowCount)
.forEach {
removeArrangedSubview($0)
$0.removeFromSuperview()
}
} else if addingRowCount > 0 {
for _ in 1 ... addingRowCount {
let sourceView = subviews.first!
let duplicatedRowView = sourceView.copied(withSubviews: sourceView.subviews,
includeConstraints: false)
if let stackRowView = duplicatedRowView as? UIStackView {
stackRowView.subviews.forEach { stackRowView.addArrangedSubview($0) }
}
addArrangedSubview(duplicatedRowView)
}
}
for (index, rowString) in rowStrings.enumerated() {
let labels = arrangedSubviews[index].subviews as! [UILabel]
let strings = rowString.components(separatedBy: columnSeparator)
labels.first!.text = strings.first!
labels[1].text = strings.dropFirst().joined(separator: columnSeparator)
}
}
}
| mit | d042cbc4c4ff56d450423e5a78f859a5 | 38.080645 | 137 | 0.567066 | 5.267391 | false | false | false | false |
dydyistc/DYWeibo | DYWeibo/Classes/Home(首页)/HomeViewController.swift | 1 | 9218 | //
// HomeViewController.swift
// DYWeibo
//
// Created by Yi Deng on 05/04/2017.
// Copyright © 2017 TD. All rights reserved.
//
import UIKit
import Alamofire
import Kingfisher
import MJRefresh
class HomeViewController: BaseViewController {
fileprivate lazy var titleButton : TitleButton = TitleButton()
// 注意:在闭包中如果使用当前对象的属性或者调用方法,也需要加self
// 两个地方需要使用self : 1> 如果在一个函数中出现歧义 2> 在闭包中使用当前对象的属性和方法也需要加self
fileprivate lazy var popoverAnimator : PopoverAnimator = PopoverAnimator {[weak self] (presented) -> () in
self?.titleButton.isSelected = presented
}
fileprivate lazy var viewModels = [StatusViewModel]()
fileprivate lazy var tipLabel : UILabel = UILabel()
fileprivate lazy var photoBrowserAnimator : PhotoBrowserAnimator = PhotoBrowserAnimator()
override func viewDidLoad() {
super.viewDidLoad()
// 没有登录时设置的内容
visitorView.addRotationAnimation()
if !isLogin {
return
}
setupNavigationBar()
tableView.estimatedRowHeight = 200
setupHeaderView()
setupFooterView()
setupTipLabel()
setupNatifications()
}
}
// MARK: - setup UI
extension HomeViewController {
fileprivate func setupNavigationBar() {
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention")
navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
titleButton.setTitle("德艺双馨萌妹纸", for: .normal)
titleButton.addTarget(self, action: #selector(titleBtnClick(_:)), for: .touchUpInside)
navigationItem.titleView = titleButton
}
fileprivate func setupHeaderView() {
// 1.创建headerView
let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadNewStatuses))
// 2.设置header的属性
header?.setTitle("下拉刷新", for: .idle)
header?.setTitle("释放更新", for: .pulling)
header?.setTitle("加载中...", for: .refreshing)
// 3.设置tableView的header
tableView.mj_header = header
// 4.进入刷新状态
tableView.mj_header.beginRefreshing()
}
fileprivate func setupFooterView() {
tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction:#selector(loadMoreStatuses))
}
fileprivate func setupTipLabel() {
navigationController?.navigationBar.insertSubview(tipLabel, at: 0)
tipLabel.frame = CGRect(x: 0, y: 10, width: UIScreen.main.bounds.width, height: 32)
tipLabel.backgroundColor = UIColor.orange
tipLabel.textColor = UIColor.white
tipLabel.font = UIFont.systemFont(ofSize: 14)
tipLabel.textAlignment = .center
tipLabel.isHidden = true
}
fileprivate func setupNatifications() {
NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.showPhotoBrowser(_:)), name: NSNotification.Name(rawValue: ShowPhotoBrowserNote), object: nil)
}
}
// MARK: - listening events
extension HomeViewController {
@objc fileprivate func titleBtnClick(_ titleBtn : TitleButton) {
let popoverViewController = PopoverViewController()
popoverViewController.modalPresentationStyle = .custom
popoverViewController.transitioningDelegate = popoverAnimator
popoverAnimator.presentedFrame = CGRect(x: 100, y: 100, width: 180, height: 250)
present(popoverViewController, animated: true, completion: nil)
}
@objc fileprivate func showPhotoBrowser(_ note : Notification) {
// 0.取出数据
let indexPath = note.userInfo![ShowPhotoBrowserIndexKey] as! IndexPath
let picURLs = note.userInfo![ShowPhotoBrowserUrlsKey] as! [URL]
let object = note.object as! PicCollectionView
// 1.创建控制器
let photoBrowserVc = PhotoBrowserController(indexPath: indexPath, picURLs: picURLs)
// 2.设置modal样式
photoBrowserVc.modalPresentationStyle = .custom
// 3.设置转场的代理
photoBrowserVc.transitioningDelegate = photoBrowserAnimator
// 4.设置动画的代理
photoBrowserAnimator.presentedDelegate = object
photoBrowserAnimator.indexPath = indexPath
photoBrowserAnimator.dismissDelegate = photoBrowserVc
// 以modal的形式弹出控制器
present(photoBrowserVc, animated: true, completion: nil)
}
}
// MARK: - request data
extension HomeViewController {
@objc fileprivate func loadNewStatuses() {
loadStatuses(true)
}
@objc fileprivate func loadMoreStatuses() {
loadStatuses(false)
}
fileprivate func loadStatuses(_ isNewData : Bool) {
// 0.获取since_id/max_id
var since_id = 0
var max_id = 0
if isNewData {
since_id = viewModels.first?.status?.mid ?? 0
} else {
max_id = viewModels.last?.status?.mid ?? 0
max_id = max_id == 0 ? 0 : (max_id - 1)
}
// 1.获取请求的URLString
let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
// 2.获取请求的参数
let parameters = ["access_token" : (UserAccountViewModel.sharedIntance.account?.access_token)!, "since_id" : "\(since_id)", "max_id" : "\(max_id)"]
Alamofire.request(urlString, method: .get, parameters: parameters).responseJSON { (response) in
if response.result.isSuccess {
let result = response.result.value as! [String : AnyObject]
guard let resultArray = result["statuses"] as? [[String : AnyObject]] else {
return
}
// 3.遍历微博对应的字典
var tempViewModel = [StatusViewModel]()
for statusDict in resultArray {
let status = Status(dict: statusDict)
let viewModel = StatusViewModel(status: status)
tempViewModel.append(viewModel)
}
// 4.将数据放入到成员变量的数组中
if isNewData {
self.viewModels = tempViewModel + self.viewModels
} else {
self.viewModels += tempViewModel
}
// 5.缓存图片
self.cacheImages(tempViewModel)
}
}
}
fileprivate func cacheImages(_ viewModels : [StatusViewModel]) {
DispatchQueue.global(qos: .userInitiated).async {
for viewmodel in viewModels {
for picURL in viewmodel.picURLs {
KingfisherManager.shared.downloader.downloadImage(with: picURL, options: [], progressBlock: nil, completionHandler: { (_, _, _, _) in
})
}
}
// 主线程刷新
DispatchQueue.main.async {
print("刷新表格")
self.tableView.reloadData()
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
self.showTipLabel(viewModels.count)
}
}
}
fileprivate func showTipLabel(_ count : Int) {
tipLabel.isHidden = false
tipLabel.text = count == 0 ? "没有新数据" : "\(count) 条新微博"
// execute animation
UIView.animate(withDuration: 1.0, animations: { () -> Void in
self.tipLabel.frame.origin.y = 44
}, completion: { (_) -> Void in
UIView.animate(withDuration: 1.0, delay: 1.5, options: [], animations: { () -> Void in
self.tipLabel.frame.origin.y = 10
}, completion: { (_) -> Void in
self.tipLabel.isHidden = true
})
})
}
}
// MARK:- tableView's data source
extension HomeViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModels.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 1.创建cell
let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as! HomeViewCell
// 2.给cell设置数据
cell.viewModel = viewModels[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let viewModel = viewModels[indexPath.row]
return viewModel.cellHeight
}
}
| apache-2.0 | 00747e0f2f9f11b6462446710176f6f0 | 32.811538 | 186 | 0.594472 | 5.337583 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.