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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
barbrobmich/linkbase | LinkBase/LinkBase/AddNewTableViewController.swift | 1 | 3560 | //
// AddNewTableViewController.swift
// LinkBase
//
// Created by Barbara Ristau on 4/2/17.
// Copyright © 2017 barbrobmich. All rights reserved.
//
import UIKit
class AddNewTableViewController: UITableViewController {
@IBOutlet weak var nameTextField: UITextField!
var affiliation: Affiliation!
override func viewDidLoad() {
super.viewDidLoad()
affiliation = Affiliation()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 4
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 2
}
@IBAction func onSave(_ sender: UIButton) {
print("Saving")
affiliation.name = nameTextField.text
affiliation.user = User.current()
Affiliation.postAffiliationToParse(affiliation: affiliation) { (success: Bool, error: Error?) -> Void in
if success {
print("Successful Post to Parse")
// segue to next section
}
else {
print("Can't post to parse")
}
}
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
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
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 311c4f2251ba030d749bbaafb602af7f | 29.161017 | 136 | 0.636134 | 5.368024 | false | false | false | false |
royratcliffe/Snippets | Sources/JSONTransformer.swift | 1 | 2978 | // Snippets JSONTransformer.swift
//
// Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom
//
// 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, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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
/// Value transformer using JSON. Forward transforms from any object to data,
/// where any object includes dictionaries, arrays, strings, integers, floats,
/// booleans and nulls.
///
/// Pretty-prints the JSON by default. Allows solo JSON primitives by
/// default. Adjust the reading and writing options if defaults require an
/// alternative configuration.
public class JSONTransformer: ValueTransformer {
public var readingOptions: JSONSerialization.ReadingOptions = .allowFragments
public var writingOptions: JSONSerialization.WritingOptions = .prettyPrinted
public override class func allowsReverseTransformation() -> Bool {
return true
}
public override class func transformedValueClass() -> AnyClass {
// swiftlint:disable:next force_cast
return Data.self as! AnyClass
}
public override func transformedValue(_ value: Any?) -> Any? {
guard let value = value else {
return nil
}
return try? JSONSerialization.data(withJSONObject: value, options: writingOptions)
}
public override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let value = value as? Data else {
return nil
}
return try? JSONSerialization.jsonObject(with: value, options: readingOptions)
}
/// Initialises the class before it receives its first message. Use the
/// identity operator on the class and the receiver in order to avoid multiple
/// initialisations when sub-classes exist.
public override class func initialize() {
guard self === JSONTransformer.self else { return }
setValueTransformer(JSONTransformer(), forName: NSValueTransformerName(rawValue: NSStringFromClass(self)))
}
}
| mit | 65d579fbbee8995bf859062aa31ba1d0 | 41.414286 | 110 | 0.731223 | 5.032203 | false | false | false | false |
jeromexiong/DouYuZB | DouYu/DouYu/Classes/Main/Model/AnchorModel.swift | 1 | 1125 | //
// AnchorModel.swift
// DouYu
//
// Created by JeromeXiong on 2017/7/6.
// Copyright © 2017年 JeromeXiong. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
//房间ID
var room_id: String = ""
//房间图片对应的url
var room_src: String = ""
//判断是手机直播还是电脑直播(0:电脑直播,1:手机直播)
var isVertical: Int = 0
//房间名称
var room_name: String = ""
//主播昵称
var nickname: String = ""
//观看人数
var online: Int = 0
//所在城市
var anchor_city: String = ""
//封面
var vertical_src: String = ""
init(dics: [String: NSObject]){
super.init()
//将字典中的键值对根据 模型中的Key值进行对应赋值,如果模型中的属性少于字典中的属性,需要复写setValue:forUndefinedKey方法
//** 如若要正确赋值,则要把属性名完全一样 **//
setValuesForKeys(dics)
}
//因为可能要传空值,会报错,所以重写方法
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| mit | b85e449bb7995c0c04c95c4d88d88404 | 21.526316 | 83 | 0.608645 | 3.19403 | false | false | false | false |
weizhangCoder/DYZB_ZW | DYZB_ZW/DYZB_ZW/Classes/Tool/NetworkTools.swift | 1 | 1051 | //
// NetworkTools.swift
// DYZB_ZW
//
// Created by zhangwei on 17/8/25.
// Copyright © 2017年 jyall. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType{
case get
case post
}
class NetworkTools {
//逃逸闭包几秒后才执行 所以 这样就需要显示的声明@escaping才能编译通过。 如果这个闭包是在函数执行完后才被调用,调用的地方超过了这函数的范围,所以叫逃逸闭包。
class func requestData(_ type : MethodType ,URLString : String ,parameters : [String : Any]? = nil , finishedCallback :@escaping (_ result : Any)->()){
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
// 2.发送网络请求
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
guard let result = response.result.value else{
print(response.result.error ?? "")
return
}
finishedCallback(result)
}
}
}
| mit | e29a10597c4ea37503aba98d5fc28214 | 23.162162 | 155 | 0.61745 | 3.853448 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Models/Search/Hit/Hit.swift | 1 | 2413 | //
// Hit.swift
//
//
// Created by Vladislav Fitc on 13.03.2020.
//
import Foundation
/// Wraps a generic hit object with its meta information
public struct Hit<T: Codable> {
public let objectID: ObjectID
public let object: T
/// Snippeted attributes. Only returned when `attributesToSnippet` is non-empty.
public let snippetResult: TreeModel<SnippetResult>?
/// Highlighted attributes. Only returned when `attributesToHighlight` is non-empty.
public let highlightResult: TreeModel<HighlightResult>?
/// Ranking information. Only returned when `getRankingInfo` is true.
public let rankingInfo: RankingInfo?
public let geolocation: SingleOrList<Point>?
/// Answer information
public let answer: Answer?
}
extension Hit: Equatable where T: Equatable {}
extension Hit: Codable {
enum CodingKeys: String, CodingKey {
case objectID
case snippetResult = "_snippetResult"
case highlightResult = "_highlightResult"
case rankingInfo = "_rankingInfo"
case geolocation = "_geoloc"
case answer = "_answer"
}
public init(from decoder: Decoder) throws {
self.object = try T(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.objectID = try container.decode(ObjectID.self, forKey: .objectID)
self.snippetResult = try container.decodeIfPresent(TreeModel<SnippetResult>.self, forKey: .snippetResult)
self.highlightResult = try container.decodeIfPresent(TreeModel<HighlightResult>.self, forKey: .highlightResult)
self.rankingInfo = try container.decodeIfPresent(RankingInfo.self, forKey: .rankingInfo)
self.geolocation = try? container.decodeIfPresent(SingleOrList<Point>.self, forKey: .geolocation)
self.answer = try container.decodeIfPresent(forKey: .answer)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(objectID, forKey: .objectID)
try container.encodeIfPresent(objectID, forKey: .objectID)
try container.encodeIfPresent(snippetResult, forKey: .snippetResult)
try container.encodeIfPresent(highlightResult, forKey: .highlightResult)
try container.encodeIfPresent(rankingInfo, forKey: .rankingInfo)
try container.encodeIfPresent(geolocation, forKey: .geolocation)
try container.encodeIfPresent(answer, forKey: .answer)
try object.encode(to: encoder)
}
}
| mit | 315248539bbf99d4eb2300d168aeda4e | 34.485294 | 115 | 0.750518 | 4.339928 | false | false | false | false |
spitzgoby/Tunits | Example/Tests/DateExtensionsSubunitsTests.swift | 1 | 15888 | //
// DateExtensionSubunitsTests.swift
// Tunits
//
// Created by Tom on 12/27/15.
// Copyright © 2015 CocoaPods. 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 Tunits
import XCTest
class DateExtensionSubunitsTests: XCTestCase {
private var dateFormatter : NSDateFormatter = NSDateFormatter();
private let utilities : TimeUnitTestsUtilities = TimeUnitTestsUtilities()
override func setUp() {
self.dateFormatter = NSDateFormatter();
self.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
}
// MARK: - Creating Subunits
// MARK: minutesOfHours
func testCalculatingMinutesOfAnHour() {
let minutesIn7AM_September5_2015 = [
self.dateFormatter.dateFromString("2015-09-05 7:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:01:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:02:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:03:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:04:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:05:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:06:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:07:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:08:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:09:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:10:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:11:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:12:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:13:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:14:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:15:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:16:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:17:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:18:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:19:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:20:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:21:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:22:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:23:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:24:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:25:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:26:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:27:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:28:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:29:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:30:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:31:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:32:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:33:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:34:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:35:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:36:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:37:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:38:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:39:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:40:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:41:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:42:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:43:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:44:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:45:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:46:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:47:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:48:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:49:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:50:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:51:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:52:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:53:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:54:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:55:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:56:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:57:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:58:00")!,
self.dateFormatter.dateFromString("2015-09-05 7:59:00")!,
]
let minuteIn7AM_September5_2015 = self.dateFormatter.dateFromString("2015-09-05 7:32:12")!
XCTAssertEqual(minutesIn7AM_September5_2015, minuteIn7AM_September5_2015.minutesOfHour())
}
// MARK: hoursOfDay
func testCalculatingHoursOfDay() {
let hoursInSeptember5_2015 = [
self.dateFormatter.dateFromString("2015-09-05 00:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 01:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 02:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 03:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 04:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 05:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 06:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 07:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 08:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 09:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 10:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 11:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 12:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 13:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 14:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 15:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 16:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 17:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 18:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 19:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 20:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 21:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 22:00:00")!,
self.dateFormatter.dateFromString("2015-09-05 23:00:00")!,
]
let dateInSeptember5_2015 = self.dateFormatter.dateFromString("2015-09-05 17:23:37")!
XCTAssertEqual(hoursInSeptember5_2015, dateInSeptember5_2015.hoursOfDay())
}
// MARK: daysOfWeek
func testCalculatingDaysOfWeekWithSundayAsFirstDayOfWeek() {
let daysOfWeekOctober7_2015 = [
self.dateFormatter.dateFromString("2015-10-04 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-05 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-06 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-07 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-08 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-09 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-10 00:00:00")!,
]
let dateInWeekOfOctober7_2015 = self.dateFormatter.dateFromString("2015-10-07 20:26:32")!
TimeUnit.setStaticCalendar(self.utilities.calendarWithSundayAsFirstWeekday())
XCTAssertEqual(daysOfWeekOctober7_2015, dateInWeekOfOctober7_2015.daysOfWeek())
}
func testCalculatingDaysOfWeekWithMondayAsFirstDayOfWeek() {
let daysOfWeekOctober10_2015 = [
self.dateFormatter.dateFromString("2015-10-05 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-06 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-07 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-08 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-09 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-10 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-11 00:00:00")!,
]
let dateInWeekOfOctober10_2015 = self.dateFormatter.dateFromString("2015-10-10 17:16:12")!
TimeUnit.setStaticCalendar(self.utilities.calendarWithMondayAsFirstWeekday())
XCTAssertEqual(daysOfWeekOctober10_2015, dateInWeekOfOctober10_2015.daysOfWeek())
}
// MARK: daysOfMonth
func testCalculatingDaysOfMonth() {
let daysInFebruary_2015 = [
self.dateFormatter.dateFromString("2015-02-01 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-02 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-03 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-04 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-05 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-06 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-07 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-08 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-09 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-10 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-11 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-12 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-13 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-14 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-15 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-16 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-17 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-18 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-19 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-20 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-21 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-22 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-23 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-24 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-25 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-26 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-27 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-28 00:00:00")!,
]
let dateInFebruary = self.dateFormatter.dateFromString("2015-02-03 11:24:57")!
XCTAssertEqual(daysInFebruary_2015, dateInFebruary.daysOfMonth())
}
func testCalculatingDaysOfLeapMonth() {
let daysInFebruary_2012 = [
self.dateFormatter.dateFromString("2012-02-01 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-02 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-03 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-04 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-05 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-06 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-07 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-08 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-09 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-10 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-11 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-12 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-13 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-14 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-15 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-16 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-17 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-18 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-19 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-20 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-21 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-22 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-23 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-24 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-25 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-26 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-27 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-28 00:00:00")!,
self.dateFormatter.dateFromString("2012-02-29 00:00:00")!,
]
let dateInFebruary = self.dateFormatter.dateFromString("2012-02-27 09:17:03")!
XCTAssertEqual(daysInFebruary_2012, TimeUnit().daysOfMonth(dateInFebruary))
XCTAssertEqual(daysInFebruary_2012, TimeUnit.daysOfMonth(dateInFebruary))
}
// MARK: monthsOfYear
func testCalculatingMonthsOfYear() {
let monthsIn_2015 = [
self.dateFormatter.dateFromString("2015-01-01 00:00:00")!,
self.dateFormatter.dateFromString("2015-02-01 00:00:00")!,
self.dateFormatter.dateFromString("2015-03-01 00:00:00")!,
self.dateFormatter.dateFromString("2015-04-01 00:00:00")!,
self.dateFormatter.dateFromString("2015-05-01 00:00:00")!,
self.dateFormatter.dateFromString("2015-06-01 00:00:00")!,
self.dateFormatter.dateFromString("2015-07-01 00:00:00")!,
self.dateFormatter.dateFromString("2015-08-01 00:00:00")!,
self.dateFormatter.dateFromString("2015-09-01 00:00:00")!,
self.dateFormatter.dateFromString("2015-10-01 00:00:00")!,
self.dateFormatter.dateFromString("2015-11-01 00:00:00")!,
self.dateFormatter.dateFromString("2015-12-01 00:00:00")!,
]
let dateIn_2015 = self.dateFormatter.dateFromString("2015-09-05 13:29:18")!
XCTAssertEqual(monthsIn_2015, dateIn_2015.monthsOfYear())
}
}
| mit | 099c578e2ac60928d7c636c28242fa41 | 57.194139 | 98 | 0.648392 | 4.056946 | false | false | false | false |
hughbe/swift | test/decl/func/static_func.swift | 16 | 6434 | // RUN: %target-typecheck-verify-swift
static func gf1() {} // expected-error {{static methods may only be declared on a type}}{{1-8=}}
class func gf2() {} // expected-error {{class methods may only be declared on a type}}{{1-7=}}
override static func gf3() {} // expected-error {{static methods may only be declared on a type}}{{10-17=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
override class func gf4() {} // expected-error {{class methods may only be declared on a type}}{{10-16=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}}
static override func gf5() {} // expected-error {{static methods may only be declared on a type}}{{1-8=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}}
class override func gf6() {} // expected-error {{class methods may only be declared on a type}}{{1-7=}}
// expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}}
static gf7() {} // expected-error {{expected declaration}} expected-error {{closure expression is unused}} expected-error{{begin with a closure}} expected-note{{did you mean to use a 'do' statement?}} {{14-14=do }}
class gf8() {} // expected-error {{expected '{' in class}} expected-error {{closure expression is unused}} expected-error{{begin with a closure}} expected-note{{did you mean to use a 'do' statement?}} {{13-13=do }}
func inGlobalFunc() {
static func gf1() {} // expected-error {{static methods may only be declared on a type}}{{3-10=}}
class func gf2() {} // expected-error {{class methods may only be declared on a type}}{{3-9=}}
}
struct InMemberFunc {
func member() {
static func gf1() {} // expected-error {{static methods may only be declared on a type}}{{5-12=}}
class func gf2() {} // expected-error {{class methods may only be declared on a type}}{{5-11=}}
}
}
struct DuplicateStatic {
static static func f1() {} // expected-error{{'static' specified twice}}{{10-17=}}
static class func f2() {} // expected-error{{'class' specified twice}}{{10-16=}}
class static func f3() {} // expected-error{{'static' specified twice}}{{9-16=}} expected-error{{class methods are only allowed within classes; use 'static' to declare a static method}}{{3-8=static}}
class class func f4() {} // expected-error{{'class' specified twice}}{{9-15=}} expected-error{{class methods are only allowed within classes; use 'static' to declare a static method}}{{3-8=static}}
override static static func f5() {} // expected-error{{'static' specified twice}}{{19-26=}} expected-error{{'override' can only be specified on class members}} {{3-12=}}
static override static func f6() {} // expected-error{{'static' specified twice}}{{19-26=}} expected-error{{'override' can only be specified on class members}} {{10-19=}}
static static override func f7() {} // expected-error{{'static' specified twice}}{{10-17=}} expected-error{{'override' can only be specified on class members}} {{17-26=}}
static final func f8() {} // expected-error {{only classes and class members may be marked with 'final'}}
}
struct S { // expected-note {{extended type declared here}}
static func f1() {}
class func f2() {} // expected-error {{class methods are only allowed within classes; use 'static' to declare a static method}} {{3-8=static}}
}
extension S {
static func ef1() {}
class func ef2() {} // expected-error {{class methods are only allowed within classes; use 'static' to declare a static method}} {{3-8=static}}
}
enum E { // expected-note {{extended type declared here}}
static func f1() {}
class func f2() {} // expected-error {{class methods are only allowed within classes; use 'static' to declare a static method}} {{3-8=static}}
static final func f3() {} // expected-error {{only classes and class members may be marked with 'final'}}
}
extension E {
static func f4() {}
class func f5() {} // expected-error {{class methods are only allowed within classes; use 'static' to declare a static method}} {{3-8=static}}
}
class C {
static func f1() {} // expected-note 3{{overridden declaration is here}}
class func f2() {}
class func f3() {}
class func f4() {} // expected-note {{overridden declaration is here}}
class func f5() {} // expected-note {{overridden declaration is here}}
static final func f6() {} // expected-error {{static declarations are already final}} {{10-16=}}
final class func f7() {} // expected-note 3{{overridden declaration is here}}
}
extension C {
static func ef1() {}
class func ef2() {} // expected-note {{overridden declaration is here}}
class func ef3() {} // expected-note {{overridden declaration is here}}
class func ef4() {} // expected-note {{overridden declaration is here}}
class func ef5() {} // expected-note {{overridden declaration is here}}
}
class C_Derived : C {
override static func f1() {} // expected-error {{cannot override static method}}
override class func f2() {}
class override func f3() {}
override class func ef2() {} // expected-error {{declarations from extensions cannot be overridden yet}}
class override func ef3() {} // expected-error {{declarations from extensions cannot be overridden yet}}
override static func f7() {} // expected-error {{static method overrides a 'final' class method}}
}
class C_Derived2 : C {
override final class func f1() {} // expected-error {{cannot override static method}}
override final class func f7() {} // expected-error {{class method overrides a 'final' class method}}
}
class C_Derived3 : C {
override class func f1() {} // expected-error {{cannot override static method}}
override class func f7() {} // expected-error {{class method overrides a 'final' class method}}
}
extension C_Derived {
override class func f4() {} // expected-error {{declarations in extensions cannot override yet}}
class override func f5() {} // expected-error {{declarations in extensions cannot override yet}}
override class func ef4() {} // expected-error {{declarations in extensions cannot override yet}}
class override func ef5() {} // expected-error {{declarations in extensions cannot override yet}}
}
protocol P {
static func f1()
static func f2()
static func f3() {} // expected-error {{protocol methods may not have bodies}}
static final func f4() // expected-error {{only classes and class members may be marked with 'final'}}
}
| apache-2.0 | 7bc2d4edc62c6c00471457f7760dc140 | 55.438596 | 214 | 0.685887 | 3.969155 | false | false | false | false |
a7ex/SwiftDTO | SwiftDTO/Models/ProtocolDeclaration.swift | 1 | 2276 | //
// ProtocolDeclaration.swift
// SwiftDTO
//
// Created by Alex da Franca on 09/10/2016.
// Copyright © 2016 farbflash. All rights reserved.
//
import Foundation
class ProtocolDeclaration {
let name: String
let parentName: String
let restProperties: [RESTProperty]
var consumers = Set<String>()
// wsdl XML uses this
init(name: String,
restProperties: [RESTProperty] = [RESTProperty](),
withParentRelations parentRelations: Set<ParentRelation>) {
self.name = name
self.restProperties = restProperties
parentName = parentRelations.first(where: { $0.subclass == name })?.parentClass ?? ""
}
// coreData XML uses this
init?(xmlElement: XMLElement,
isEnum: Bool,
withEnumNames enums: Set<String>,
withProtocolNames protocolNames: Set<String>,
withProtocols protocols: [ProtocolDeclaration]?,
withPrimitiveProxyNames primitiveProxyNames: Set<String>) {
guard let name = xmlElement.attribute(forName: "name")?.stringValue else {
return nil
}
guard let properties = xmlElement.children as? [XMLElement] else { return nil }
let restProps = properties.flatMap { RESTProperty(xmlElement: $0,
enumParentName: nil,
withEnumNames: enums,
withProtocolNames: protocolNames,
withProtocols: protocols,
withPrimitiveProxyNames: primitiveProxyNames,
embedParseSDKSupport: false) }
guard !restProps.isEmpty else { return nil }
parentName = ""
self.name = name
self.restProperties = restProps
}
var declarationString: String {
var declareString = ""
for property in restProperties {
declareString += "\(property.protocolDeclarationString)\n"
}
return declareString
}
func addConsumer(structName: String) {
consumers.insert(structName)
}
}
| apache-2.0 | 0443af74a348db25065484a7a4832fb5 | 33.469697 | 105 | 0.555165 | 5.390995 | false | false | false | false |
kafejo/timezoner-backend | Sources/App/main.swift | 1 | 8708 | import Vapor
import VaporPostgreSQL
import Auth
import Turnstile
import HTTP
import Foundation
let drop = Droplet()
let host = drop.config["postgresql", "host"]?.string ?? "localhost"
let port = drop.config["postgresql", "port"]?.int ?? 5432
let dbname = drop.config["postgresql", "database"]?.string ?? "timezoner"
let password = drop.config["postgresql", "password"]?.string ?? "kofejn"
let user = drop.config["postgresql", "user"]?.string ?? "admin"
try drop.addProvider(VaporPostgreSQL.Provider(host: host, port: port, dbname: dbname, user: user, password: password))
drop.preparations = [User.self, Timezone.self]
let auth = AuthMiddleware(user: User.self)
drop.middleware.append(auth)
drop.group("users") { users in
users.post("signup") { request in
guard let username = request.data["username"]?.string, let password = request.data["password"]?.string else {
throw Abort.custom(status: .badRequest, message: "Missing credentials")
}
let credentials = UsernamePassword(username: username, password: password)
let authuser = try User.register(credentials: credentials)
try request.auth.login(credentials)
guard var user = authuser as? User else {
throw Abort.serverError
}
try user.save()
return user
}
users.post("signin") { request in
guard let username = request.data["username"]?.string, let password = request.data["password"]?.string else {
throw Abort.custom(status: .badRequest, message: "Missing credentials")
}
let credentials = UsernamePassword(username: username, password: password)
try request.auth.login(credentials)
guard let user = try request.auth.user() as? User else {
throw Abort.serverError
}
return user
}
}
let protectMiddleware = ProtectMiddleware(error: Abort.custom(status: .unauthorized, message: "Unauthorized"))
drop.grouped(BearerAuthenticationMiddleware(), protectMiddleware).group("me") { me in
me.get() { request in
return try request.user()
}
me.patch() { request in
var user = try request.user()
if let roleValue = request.data["role"]?.string, let role = User.Role(rawValue: roleValue) {
user.role = role
try user.save()
}
return user
}
me.group("timezones") { timezones in
timezones.get() { request in
let timezones = try request.user().timezones()
return try JSON(node: timezones.all())
}
timezones.post() { request in
guard let name = request.data["name"]?.string, let identifier = request.data["identifier"]?.string else {
throw Abort.badRequest
}
if !TimeZone.knownTimeZoneIdentifiers.contains(identifier) {
throw Abort.custom(status: .badRequest, message: "Invalid timezone identifier")
}
let user = try request.user()
var timezone = try Timezone(name: name, identifier: identifier, user: user)
try timezone.save()
return timezone
}
timezones.put(":id") { request in
let user = try request.user()
guard let timezone_id = request.parameters["id"]?.int else {
throw Abort.badRequest
}
let filtered = try user.timezones().all().filter { $0.id == Node.number(Node.Number(timezone_id)) }
guard var timezone = filtered.first else {
throw Abort.custom(status: .notFound, message: "Timezone wasn't found")
}
guard let name = request.data["name"]?.string, let identifier = request.data["identifier"]?.string else {
throw Abort.badRequest
}
if !TimeZone.knownTimeZoneIdentifiers.contains(identifier) {
throw Abort.custom(status: .badRequest, message: "Invalid timezone identifier")
}
timezone.identifier = identifier
timezone.name = name
try timezone.save()
return timezone
}
timezones.delete(":id") { (request) in
let user = try request.user()
guard let timezone_id = request.parameters["id"]?.int else {
throw Abort.badRequest
}
let filtered = try user.timezones().all().filter { $0.id == Node.number(Node.Number(timezone_id)) }
if let timezone = filtered.first {
try timezone.delete()
return try Response(status: .ok, json: JSON(node: [:]))
} else {
throw Abort.custom(status: .notFound, message: "Timezone wasn't found")
}
}
}
}
let managerMiddleware = RoleMiddleware(accessibleRoles: [.manager, .admin])
let adminMiddleware = RoleMiddleware(accessibleRoles: [.admin])
drop.grouped(BearerAuthenticationMiddleware(), protectMiddleware, managerMiddleware).group("users") { users in
users.get() { request in
return try JSON(node: User.all())
}
users.delete(User.self) { request, user in
try user.delete()
return try Response(status: .ok, json: JSON(node: [:]))
}
users.grouped(adminMiddleware).get(":id", "timezones") { (request) -> ResponseRepresentable in
guard let id = request.parameters["id"]?.int, let user = try User.query().filter("id", id).first() else {
throw Abort.badRequest
}
return try JSON(node: user.timezones().all())
}
users.grouped(adminMiddleware).post(User.self, "timezones") { (request, user) -> ResponseRepresentable in
guard let name = request.data["name"]?.string, let identifier = request.data["identifier"]?.string else {
throw Abort.badRequest
}
if !TimeZone.knownTimeZoneIdentifiers.contains(identifier) {
throw Abort.custom(status: .badRequest, message: "Invalid timezone identifier")
}
var timezone = try Timezone(name: name, identifier: identifier, user: user)
try timezone.save()
return timezone
}
users.grouped(adminMiddleware).get(":id", "timezones", ":timezone_id") { (request) -> ResponseRepresentable in
guard let id = request.parameters["id"]?.int, let user = try User.query().filter("id", id).first() else {
throw Abort.badRequest
}
guard let timezone_id = request.parameters["timezone_id"]?.int else {
throw Abort.badRequest
}
let filteredTimezones = try user.timezones().all().filter { $0.id == Node.number(Node.Number(timezone_id)) }
if let first = filteredTimezones.first {
return first
} else {
throw Abort.notFound
}
}
users.grouped(adminMiddleware).patch(":id", "timezones", ":timezone_id") { (request) -> ResponseRepresentable in
guard let id = request.parameters["id"]?.int else {
throw Abort.custom(status: .badRequest, message: "User not found")
}
guard let user = try User.query().filter("id", id).first() else {
throw Abort.custom(status: .badRequest, message: "User not found!")
}
guard let timezone_id = request.parameters["timezone_id"]?.int else {
throw Abort.custom(status: .badRequest, message: "Timezone id missing")
}
let filteredTimezones = try user.timezones().all().filter { $0.id == Node.number(Node.Number(timezone_id)) }
if let first = filteredTimezones.first {
try first.delete()
return try Response(status: .ok, json: JSON(node: [:]))
} else {
throw Abort.notFound
}
}
users.grouped(adminMiddleware).put(":id", "timezones", ":timezone_id") { (request) -> ResponseRepresentable in
guard let id = request.parameters["id"]?.int, let user = try User.query().filter("id", id).first() else {
throw Abort.badRequest
}
guard let timezone_id = request.parameters["timezone_id"]?.int else {
throw Abort.badRequest
}
guard let name = request.data["name"]?.string, let identifier = request.data["identifier"]?.string else {
throw Abort.badRequest
}
let filteredTimezones = try user.timezones().all().filter { $0.id == Node.number(Node.Number(timezone_id)) }
if var first = filteredTimezones.first {
first.identifier = identifier
first.name = name
try first.save()
return first
} else {
throw Abort.notFound
}
}
}
drop.run()
| mit | c049a8b29f251083c8a197d3308ec8fa | 34.112903 | 118 | 0.60542 | 4.533056 | false | false | false | false |
mactive/rw-courses-note | DesignCode/layoutandstack/layoutandstack/ContentView.swift | 1 | 6599 | //
// ContentView.swift
// layoutandstack
//
// Created by Qian Meng on 2020/2/2.
// Copyright © 2020 meng. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State var show = false
@State var viewState = CGSize.zero
@State var showCard = false
@State var bottomState = CGSize.zero
@State var showFull = false
var body: some View {
ZStack {
TitleView()
.blur(radius: show ? 20 : 0)
.opacity(showCard ? 0.4 : 1)
.offset(y: showCard ? -200 : 0)
.animation(
Animation
.default
.delay(0.1)
// .speed(2)
// .repeatForever(autoreverses: true)
)
BackCardView()
.frame(width: showCard ? 300 : 340, height: 220)
.background(show ? Color("card3") : Color("card4"))
.cornerRadius(20)
.shadow(radius: 20)
.offset(x: 0, y: show ? -400 : -40)
.offset(x: viewState.width, y: viewState.height)
.offset(y: showCard ? -180 : 0)
.scaleEffect(showCard ? 1 : 0.9)
.rotationEffect(.degrees(show ? 0 : 10))
.rotationEffect(Angle(degrees: showCard ? -10 : 0))
.rotation3DEffect(Angle(degrees: showCard ? 0 : 10), axis: (x: 10.0, y: 0, z: 0))
.blendMode(.hardLight)
.animation(.easeInOut(duration: 0.5))
BackCardView()
.frame(width: 340, height: 220)
.background(show ? Color("card4") : Color("card3"))
.cornerRadius(20)
.shadow(radius: 20)
.offset(x: 0, y: show ? -200 : -20)
.offset(x: viewState.width, y: viewState.height)
.offset(y: showCard ? -140 : 0)
.scaleEffect(showCard ? 1 : 0.95)
.rotationEffect(Angle.degrees(show ? 0 : 5))
.rotationEffect(Angle(degrees: showCard ? -5 : 0))
.rotation3DEffect(Angle(degrees: showCard ? 0 : 5), axis: (x: 10.0, y: 0, z: 0))
.blendMode(.hardLight)
.animation(.easeInOut(duration: 0.3))
CardView()
.frame(width: showCard ? 375 : 340.0, height: 220.0)
.background(Color.black)
// .cornerRadius(20)
.clipShape(RoundedRectangle(cornerRadius: showCard ? 30 : 20, style: .continuous))
.shadow(radius: 20)
.offset(x: viewState.width, y: viewState.height)
.offset(y: showCard ? -100 : 0)
.blendMode(.hardLight)
.animation(.spring(response: 0.3, dampingFraction: 0.6, blendDuration: 0))
.onTapGesture {
self.showCard.toggle()
}
.gesture(
DragGesture().onChanged { value in
self.viewState = value.translation
self.show = true
}
.onEnded { value in
self.viewState = .zero
self.show = false
}
)
Text("\(bottomState.height)").offset(y: -300)
BottomCardView()
.offset(x: 0, y: showCard ? 360 : 1000)
.offset(y: bottomState.height)
.blur(radius: show ? 20 : 0)
.animation(.timingCurve(0.2, 0.8, 0.2, 1, duration: 0.8))
.gesture(
DragGesture().onChanged { value in
self.bottomState = value.translation
if self.showFull {
self.bottomState.height += -300
}
if self.bottomState.height < -300 {
self.bottomState.height = -300
}
}
.onEnded { value in
if self.bottomState.height > 50 {
self.showCard = false
}
if (self.bottomState.height < -100 && !self.showFull) || (self.bottomState.height < -250 && self.showFull) {
self.bottomState.height = -300
self.showFull = true
} else {
self.bottomState = .zero
self.showFull = false
}
}
)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct CardView: View {
var body: some View {
VStack {
HStack {
VStack(alignment: .leading) {
Text("UI Design")
.font(.title)
.fontWeight(.semibold)
.foregroundColor(.white)
Text("Certificate")
.foregroundColor(Color("accent"))
}
Spacer()
Image("Logo1")
}
.padding(.horizontal, 20)
.padding(.top, 20)
Spacer()
Image("Card1")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 300, height: 110, alignment: .top)
}
}
}
struct TitleView: View {
var body: some View {
VStack {
HStack {
Text("Certificates")
.font(.largeTitle)
.fontWeight(.bold)
Spacer()
}
.padding()
Image("Background1")
Spacer()
}
}
}
struct BottomCardView: View {
var body: some View {
VStack{
Rectangle()
.background(Color.black)
.frame(width: 40, height: 6)
.cornerRadius(3)
.opacity(0.1)
.padding(.bottom, 20)
Text("This certificates is proof that Meng To has achived the UI Design course with approval from a Design+Code instructor")
.font(.subheadline)
.multilineTextAlignment(.center)
.lineSpacing(4)
Spacer()
}
.padding(.top, 10)
.padding(.horizontal, 20)
.frame(maxWidth:.infinity )
.background(Color.white)
.cornerRadius(30)
.shadow(radius: 20)
}
}
| mit | 2e1b06da4fbb927b0ff6f3c503a1c896 | 33.544503 | 136 | 0.446651 | 4.753602 | false | false | false | false |
piscoTech/GymTracker | Gym Tracker watchOS Extension/Table View Cells.swift | 1 | 1976 | //
// Table View Cells.swift
// Gym Tracker
//
// Created by Marco Boschi on 21/03/2017.
// Copyright © 2017 Marco Boschi. All rights reserved.
//
import WatchKit
import GymTrackerCore
class AccessoryCell: NSObject {
@IBOutlet weak var titleLabel: WKInterfaceLabel!
@IBOutlet weak var detailLabel: WKInterfaceLabel!
@IBOutlet private weak var accessory: WKInterfaceImage!
@IBOutlet private weak var mainContent: WKInterfaceObject!
var accessoryWidth: CGFloat = 0
func setAccessory(_ image: UIImage?) {
accessory.setImage(image)
}
func showAccessory(_ visible: Bool) {
if visible {
accessory.setHidden(false)
mainContent.setRelativeWidth(1, withAdjustment: -accessoryWidth - 1)
} else {
accessory.setHidden(true)
mainContent.setRelativeWidth(1, withAdjustment: 0)
}
}
}
class ExerciseCell: AccessoryCell {
@IBOutlet private weak var collectionImage: WKInterfaceImage!
@IBOutlet private weak var collectionLabel: WKInterfaceLabel!
static private let font = UIFont.systemFont(ofSize: 16)
static private let italicFont = UIFont.italicSystemFont(ofSize: 16)
private var isChoice = false
func set(title: String) {
titleLabel.setAttributedText(NSAttributedString(string: title, attributes: [.font: Self.font]))
}
func setCircuit(number: Int, total: Int) {
collectionImage.setImageNamed(isChoice ? "IsChoiceCircuit" : "IsCircuit")
collectionLabel.setText("\(number)/\(total)")
showAccessory(true)
}
func setChoice(title: String, total: Int) {
isChoice = true
titleLabel.setAttributedText(NSAttributedString(string: title, attributes: [.font: Self.italicFont]))
collectionImage.setImageNamed("IsChoice")
collectionLabel.setText(total.description)
showAccessory(true)
}
}
class RestCell: NSObject {
@IBOutlet weak var restLabel: WKInterfaceLabel!
func set(rest r: TimeInterval) {
restLabel.setText(String(format: GTLocalizedString("%@_REST", comment: "rest"), r.formattedDuration))
}
}
| mit | 52a91895b6fc0b68a7b12f0d6bf4caad | 25.333333 | 103 | 0.748861 | 3.827519 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS | Aztec/Classes/NSAttributedString/Conversions/AttachmentToElementConverter/ImageAttachmentToElementConverter.swift | 2 | 3878 | import Foundation
import UIKit
class ImageAttachmentToElementConverter: AttachmentToElementConverter {
func convert(_ attachment: ImageAttachment, attributes: [NSAttributedString.Key : Any]) -> [Node] {
let imageElement: ElementNode
if let representation = attributes[.imageHtmlRepresentation] as? HTMLRepresentation,
case let .element(representationElement) = representation.kind {
imageElement = representationElement.toElementNode()
} else {
imageElement = ElementNode(type: .img)
}
if let attribute = imageSourceAttribute(from: attachment) {
imageElement.updateAttribute(named: attribute.name, value: attribute.value)
}
if let attribute = imageClassAttribute(from: attachment) {
imageElement.updateAttribute(named: attribute.name, value: attribute.value)
}
for attribute in imageSizeAttributes(from: attachment) {
imageElement.updateAttribute(named: attribute.name, value: attribute.value)
}
for attribute in attachment.extraAttributes {
let key = attribute.name
guard let value = attribute.value.toString() else {
continue
}
var finalValue = value
if key == "class",
let baseValue = imageElement.stringValueForAttribute(named: "class") {
// Apple, we really need a Swift-native ordered set. Thank you!
let baseComponents = NSMutableOrderedSet(array: baseValue.components(separatedBy: " "))
let extraComponents = NSOrderedSet(array: value.components(separatedBy: " "))
baseComponents.union(extraComponents)
finalValue = (baseComponents.array as! [String]).joined(separator: " ")
}
imageElement.updateAttribute(named: key, value: .string(finalValue))
}
return [imageElement]
}
/// Extracts the class attribute from an ImageAttachment Instance.
///
private func imageClassAttribute(from attachment: ImageAttachment) -> Attribute? {
var style = String()
if let alignment = attachment.alignment {
style += alignment.htmlString()
}
if attachment.size != .none {
style += style.isEmpty ? String() : String(.space)
style += attachment.size.htmlString()
}
guard !style.isEmpty else {
return nil
}
return Attribute(type: .class, value: .string(style))
}
/// Extracts the Image's Width and Height attributes, whenever the Attachment's Size is set to (anything) but .none.
///
private func imageSizeAttributes(from attachment: ImageAttachment) -> [Attribute] {
guard let imageSize = attachment.image?.size, attachment.size.shouldResizeAsset else {
return []
}
let calculatedHeight = floor(attachment.size.width * imageSize.height / imageSize.width)
let heightValue = String(describing: Int(calculatedHeight))
let widthValue = String(describing: Int(attachment.size.width))
return [
Attribute(name: "width", value: .string(widthValue)),
Attribute(name: "height", value: .string(heightValue))
]
}
/// Extracts the src attribute from an ImageAttachment Instance.
///
private func imageSourceAttribute(from attachment: ImageAttachment) -> Attribute? {
guard let source = attachment.url?.absoluteString else {
return nil
}
return Attribute(type: .src, value: .string(source))
}
}
| mpl-2.0 | aec051a46c4f9f2e2d8af469974e7274 | 37.019608 | 120 | 0.596441 | 5.524217 | false | false | false | false |
m0rb1u5/iOS_10_1 | iOS_15_1 Extension/TipoQuesoWKController.swift | 1 | 1271 | //
// TipoQuesoWKController.swift
// iOS_10_1
//
// Created by Juan Carlos Carbajal Ipenza on 18/04/16.
// Copyright © 2016 Juan Carlos Carbajal Ipenza. All rights reserved.
//
import WatchKit
import Foundation
class TipoQuesoWKController: WKInterfaceController {
let mozarela: String = "Mozarela"
let cheddar: String = "Cheddar"
let parmesano: String = "Parmesano"
let sinQueso: String = "Sin queso"
var valorContexto: Valor = Valor()
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
self.setTitle("Tipo de Queso")
valorContexto = context as! Valor
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
@IBAction func guardarMozarela() {
setContexto(mozarela)
}
@IBAction func guardarCheddar() {
setContexto(cheddar)
}
@IBAction func guardarParmesano() {
setContexto(parmesano)
}
@IBAction func guardarSinQueso() {
setContexto(sinQueso)
}
func setContexto(opcion: String) {
valorContexto.queso = opcion
pushControllerWithName("idIngredientes", context: valorContexto)
print(opcion)
}
}
| gpl-3.0 | ba29d544b5d80baa518c5de89492827a | 25.458333 | 72 | 0.659843 | 3.919753 | false | false | false | false |
huonw/swift | test/Interpreter/SDK/archive_attributes.swift | 10 | 4597 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -module-name=test -DENCODE -o %t/encode
// RUN: %target-build-swift %s -module-name=test -o %t/decode
// RUN: %target-build-swift %s -module-name=test -Xfrontend -disable-llvm-optzns -emit-ir | %FileCheck -check-prefix=CHECK-IR %s
// RUN: %target-run %t/encode %t/test.arc
// RUN: plutil -p %t/test.arc | %FileCheck -check-prefix=CHECK-ARCHIVE %s
// RUN: %target-run %t/decode %t/test.arc | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// REQUIRES: CPU=i386 || CPU=x86_64
// UNSUPPORTED: OS=tvos
// UNSUPPORTED: OS=watchos
import Foundation
struct ABC {
// CHECK-ARCHIVE-DAG: "$classname" => "nested_class_coding"
@objc(nested_class_coding)
class NestedClass : NSObject, NSCoding {
var i : Int
init(_ ii: Int) {
i = ii
}
required init(coder aDecoder: NSCoder) {
i = aDecoder.decodeInteger(forKey: "i")
}
func encode(with aCoder: NSCoder) {
aCoder.encode(i, forKey: "i")
}
}
}
// CHECK-ARCHIVE-DAG: "$classname" => "private_class_coding"
@objc(private_class_coding)
private class PrivateClass : NSObject, NSCoding {
var pi : Int
init(_ ii: Int) {
pi = ii
}
required init(coder aDecoder: NSCoder) {
pi = aDecoder.decodeInteger(forKey: "pi")
}
func encode(with aCoder: NSCoder) {
aCoder.encode(pi, forKey: "pi")
}
}
class GenericClass<T> : NSObject, NSCoding {
var gi : T? = nil
override init() {
}
required init(coder aDecoder: NSCoder) {
}
func encode(with aCoder: NSCoder) {
}
}
// CHECK-ARCHIVE-DAG: "$classname" => "test.IntClass"
class IntClass : GenericClass<Int> {
init(ii: Int) {
super.init()
gi = ii
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
gi = aDecoder.decodeInteger(forKey: "gi")
}
override func encode(with aCoder: NSCoder) {
aCoder.encode(gi!, forKey: "gi")
}
}
// CHECK-ARCHIVE-DAG: "$classname" => "double_class_coding"
@objc(double_class_coding)
class DoubleClass : GenericClass<Double> {
init(dd: Double) {
super.init()
gi = dd
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
gi = aDecoder.decodeDouble(forKey: "gi")
}
override func encode(with aCoder: NSCoder) {
aCoder.encode(gi!, forKey: "gi")
}
}
// CHECK-ARCHIVE-DAG: "$classname" => "top_level_coding"
@objc(top_level_coding)
class TopLevel : NSObject, NSCoding {
var tli : Int
var nested: ABC.NestedClass?
fileprivate var priv: PrivateClass?
var intc : IntClass?
var doublec : DoubleClass?
init(_ ii: Int) {
tli = ii
}
required init(coder aDecoder: NSCoder) {
tli = aDecoder.decodeInteger(forKey: "tli")
nested = aDecoder.decodeObject(forKey: "nested") as? ABC.NestedClass
priv = aDecoder.decodeObject(forKey: "priv") as? PrivateClass
intc = aDecoder.decodeObject(forKey: "int") as? IntClass
doublec = aDecoder.decodeObject(forKey: "double") as? DoubleClass
}
func encode(with aCoder: NSCoder) {
aCoder.encode(tli, forKey: "tli")
aCoder.encode(nested, forKey: "nested")
aCoder.encode(priv, forKey: "priv")
aCoder.encode(intc, forKey: "int")
aCoder.encode(doublec, forKey: "double")
}
}
func main() {
let args = CommandLine.arguments
#if ENCODE
let c = TopLevel(27)
c.nested = ABC.NestedClass(28)
c.priv = PrivateClass(29)
c.intc = IntClass(ii: 42)
c.doublec = DoubleClass(dd: 3.14)
NSKeyedArchiver.archiveRootObject(c, toFile: args[1])
#else
if let u = NSKeyedUnarchiver.unarchiveObject(withFile: args[1]) {
if let x = u as? TopLevel {
// CHECK: top-level: 27
print("top-level: \(x.tli)")
if let n = x.nested {
// CHECK: nested: 28
print("nested: \(n.i)")
}
if let p = x.priv {
// CHECK: private: 29
print("private: \(p.pi)")
}
if let g = x.intc {
// CHECK: int: 42
print("int: \(g.gi!)")
}
if let d = x.doublec {
// CHECK: double: 3.14
print("double: \(d.gi!)")
}
} else {
print(u)
}
} else {
print("nil")
}
#endif
}
main()
// Check that we eagerly create metadata of generic classes, but not for nested classes.
// CHECK-IR-LABEL: define {{.*}} @_swift_eager_class_initialization
// CHECK-IR-NEXT: entry:
// CHECK-IR-NEXT: call {{.*}}IntClassCMa
// CHECK-IR-NEXT: extractvalue
// CHECK-IR-NEXT: call void asm
// CHECK-IR-NEXT: call {{.*}}DoubleClassCMa
// CHECK-IR-NEXT: extractvalue
// CHECK-IR-NEXT: call void asm
// CHECK-IR-NEXT: ret
| apache-2.0 | b93dbcaabd26eb8c585c23307d841292 | 23.068063 | 128 | 0.629106 | 3.290623 | false | false | false | false |
Yalantis/Segmentio | Example/Segmentio/ViewControllers/ContentViewController.swift | 1 | 2435 | //
// ContentViewController.swift
// Segmentio
//
// Created by Dmitriy Demchenko
// Copyright © 2016 Yalantis Mobile. All rights reserved.
//
import UIKit
private func yal_isPhone6() -> Bool {
let size = UIScreen.main.bounds.size
let minSide = min(size.height, size.width)
let maxSide = max(size.height, size.width)
return (abs(minSide - 375.0) < 0.01) && (abs(maxSide - 667.0) < 0.01)
}
class ExampleTableViewCell: UITableViewCell {
@IBOutlet fileprivate weak var hintLabel: UILabel!
}
class ContentViewController: UIViewController {
@IBOutlet fileprivate weak var cardNameLabel: UILabel!
@IBOutlet fileprivate weak var hintTableView: UITableView!
@IBOutlet fileprivate weak var bottomCardConstraint: NSLayoutConstraint!
@IBOutlet fileprivate weak var heightConstraint: NSLayoutConstraint!
var disaster: Disaster?
fileprivate var hints: [String]?
class func create() -> ContentViewController {
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
return mainStoryboard.instantiateViewController(withIdentifier: String(describing: self)) as! ContentViewController
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
hintTableView.rowHeight = UITableView.automaticDimension
hintTableView.estimatedRowHeight = 100
if yal_isPhone6() {
bottomCardConstraint.priority = UILayoutPriority(rawValue: 900)
heightConstraint.priority = UILayoutPriority(rawValue: 1000)
heightConstraint.constant = 430
} else {
bottomCardConstraint.priority = UILayoutPriority(rawValue: 1000)
heightConstraint.priority = UILayoutPriority(rawValue: 900)
}
if let disaster = disaster {
cardNameLabel.text = disaster.cardName
hints = disaster.hints
}
}
}
extension ContentViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return hints?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ExampleTableViewCell
cell.hintLabel?.text = hints?[indexPath.row]
return cell
}
}
| mit | aca1339507eadf1669a9ab60507796d0 | 32.342466 | 123 | 0.680772 | 5.113445 | false | false | false | false |
jjjjaren/jCode | jCode/Classes/Utilities/CoreDataAccessUtility.swift | 1 | 5316 | //
// CoreDataAccessUtility.swift
// ResearchKit-Demo-1
//
// Created by Jaren Hamblin on 8/16/16.
// Copyright © 2016 Jaren Hamblin. All rights reserved.
//
import Foundation
import CoreData
open class CoreDataAccessUtility: CoreDataAccessProtocol {
open let sqliteFileName: String
open let sqliteFileDirectory: String?
open let managedObjectModelName: String
open var persistentStoreCoordinator: NSPersistentStoreCoordinator!
open lazy var managedObjectContext: NSManagedObjectContext! = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
public init(sqliteFileName: String, sqliteFileDirectory: String?, managedObjectModelName: String) {
self.sqliteFileName = sqliteFileName
self.sqliteFileDirectory = sqliteFileDirectory
self.managedObjectModelName = managedObjectModelName
// MARK: - Core Data Stack
let applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.Jaren Hamblinhealthcare.mCareNext" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
let managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: managedObjectModelName, withExtension: "momd")!
let objectModel: NSManagedObjectModel! = NSManagedObjectModel(contentsOf: modelURL)
return objectModel
}()
self.persistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
let url = applicationDocumentsDirectory.appendingPathComponent("\(sqliteFileName).sqlite")
let failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: [NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true])
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
}
// MARK: - DataAccessProtocol
open func fetchFirst<T : NSManagedObject>(_ context: NSManagedObjectContext, predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?) -> T? {
return fetch(context, predicate: predicate, sortDescriptors: sortDescriptors, limit: 0).first
}
open func fetch<T : NSManagedObject>(_ context: NSManagedObjectContext, predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?, limit: Int?) -> [T] {
// Build request
let request: NSFetchRequest<T> = NSFetchRequest(entityName: T.entityName)
request.predicate = predicate
request.sortDescriptors = sortDescriptors
if let limit = limit , limit > 0 {
request.fetchLimit = limit
}
// Execute request
var results = [T]()
do {
results = try context.fetch(request)
} catch let e as NSError {
print(e)
}
return results
}
open func save() throws {
guard managedObjectContext.hasChanges else { return }
try managedObjectContext.save()
}
}
| mit | 5c6a0c87c951e3e35fc5b847300831ed | 50.105769 | 294 | 0.693697 | 5.866446 | false | false | false | false |
ArslanBilal/Swift-TableView-Example | TableView/TableView/RecipesTableViewController.swift | 1 | 2011 | //
// RecipesTableViewController.swift
// Swift-TableView-Example
//
// Created by Bilal Arslan on 28/02/16.
// Copyright © 2016 Bilal ARSLAN. All rights reserved.
//
import UIKit
class RecipesTableViewController: UITableViewController {
var recipes = Recipe.createRecipes()
let identifier: String = "tableCell"
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
// MARK: Segue Method
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "recipeDetail",
let indexPath = tableView?.indexPathForSelectedRow,
let destinationViewController: DetailViewController = segue.destination as? DetailViewController {
destinationViewController.recipe = recipes[indexPath.row]
}
}
}
extension RecipesTableViewController {
func setupUI() {
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .done, target: self, action: nil)
navigationItem.title = "Recipes"
tableView.reloadData()
}
}
// MARK: - UITableView DataSource
extension RecipesTableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? TableCell {
cell.configurateTheCell(recipes[indexPath.row])
return cell
}
return UITableViewCell()
}
}
// MARK: - UITableView Delegate
extension RecipesTableViewController {
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
recipes.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .bottom)
}
}
}
| mit | 044c171483d21ed80c207d086e1cdd17 | 27.309859 | 137 | 0.683582 | 5.101523 | false | false | false | false |
justindhill/Facets | Facets/View Controllers/Form Builder/OZLButtonFormField.swift | 1 | 3385 | //
// OZLButtonFormField.swift
// Facets
//
// Created by Justin Hill on 3/17/16.
// Copyright © 2016 Justin Hill. All rights reserved.
//
class OZLButtonFormField: OZLFormField {
var title: String
weak var target: AnyObject?
var action: Selector
var titleColor: UIColor?
var accessoryType: UITableViewCellAccessoryType
init(keyPath: String, title: String, titleColor: UIColor? = nil, highlightBackgroundColor: UIColor? = nil,
accessoryType: UITableViewCellAccessoryType = .none, target: AnyObject, action: Selector) {
self.title = title
self.titleColor = titleColor
self.target = target
self.action = action
self.accessoryType = accessoryType
super.init(keyPath: keyPath, placeholder: title)
self.fieldHeight = 44.0
self.cellClass = OZLButtonFormFieldCell.self
}
}
class OZLButtonFormFieldCell: OZLFormFieldCell {
let buttonControl = UIButton()
var currentValue = false
var useTintColor = true
var highlightBackgroundColor: UIColor?
var buttonTarget: AnyObject?
var buttonAction: Selector?
required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
func setup() {
self.buttonControl.addTarget(self, action: #selector(buttonActionInternal(_:)), for: .touchUpInside)
}
@objc func buttonActionInternal(_ sender: UIButton?) {
if let target = self.buttonTarget as? NSObject, let action = self.buttonAction {
target.perform(action, with: self.keyPath)
}
}
override func applyFormField(_ field: OZLFormField) {
super.applyFormField(field)
guard let field = field as? OZLButtonFormField else {
assertionFailure("Somehow received the wrong type of field")
return
}
if let titleColor = field.titleColor {
self.useTintColor = false
self.setTitleColor(titleColor)
} else {
self.useTintColor = true
self.setTitleColor(self.tintColor)
}
self.buttonTarget = field.target
self.buttonAction = field.action
self.accessoryType = field.accessoryType
self.buttonControl.titleLabel?.font = UIFont.systemFont(ofSize: 17.0)
self.buttonControl.contentHorizontalAlignment = .left
self.buttonControl.setTitle(field.title, for: .normal)
}
override func layoutSubviews() {
super.layoutSubviews()
if self.buttonControl.superview == nil {
self.contentView.addSubview(self.buttonControl)
}
self.buttonControl.frame = self.contentView.bounds
self.buttonControl.titleEdgeInsets = UIEdgeInsetsMake(0, self.layoutMargins.left, 0, self.layoutMargins.right)
}
fileprivate func setTitleColor(_ titleColor: UIColor) {
self.buttonControl.setTitleColor(titleColor, for: .normal)
self.buttonControl.setTitleColor(titleColor.withAlphaComponent(0.75), for: .highlighted)
}
override func tintColorDidChange() {
super.tintColorDidChange()
if self.useTintColor {
self.setTitleColor(self.tintColor)
}
}
}
| mit | 443c8427a57a3dc8deaf48f87862fab7 | 29.763636 | 118 | 0.664598 | 4.862069 | false | false | false | false |
Sweefties/FutureKit | FutureKit/FoundationExtensions/NSOperation+FutureKit.swift | 3 | 3491 | //
// NSData-Ext.swift
// FutureKit
//
// Created by Michael Gray on 4/21/15.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
class FutureOperation<T> : _FutureAnyOperation {
class func OperationWithBlock(block b: () -> Future<T>) -> FutureOperation<T> {
return FutureOperation<T>(block:b)
}
var future : Future<T> {
return self.promise.future.As()
}
init(block b: () -> Future<T>) {
super.init(block: { () -> FutureProtocol in
return b()
})
}
}
class _FutureAnyOperation : NSOperation, FutureProtocol {
private var getSubFuture : () -> FutureProtocol
var subFuture : Future<Any>?
var cancelToken : CancellationToken?
var promise = Promise<Any>()
override var asynchronous : Bool {
return true
}
private var _is_executing : Bool {
willSet {
self.willChangeValueForKey("isExecuting")
}
didSet {
self.didChangeValueForKey("isExecuting")
}
}
private var _is_finished : Bool {
willSet {
self.willChangeValueForKey("isFinished")
}
didSet {
self.didChangeValueForKey("isFinished")
}
}
override var executing : Bool {
return _is_executing
}
override var finished : Bool {
return _is_finished
}
init(block : () -> FutureProtocol) {
self.getSubFuture = block
self._is_executing = false
self._is_finished = false
super.init()
}
override func main() {
if self.cancelled {
self._is_executing = false
self._is_finished = true
self.promise.completeWithCancel()
return
}
self._is_executing = true
let f : Future<Any> = self.getSubFuture().As()
self.subFuture = f
self.cancelToken = f.getCancelToken()
f.onComplete { completion in
self._is_executing = false
self._is_finished = true
self.promise.complete(completion)
}
}
override func cancel() {
super.cancel()
self.cancelToken?.cancel()
}
func As<S>() -> Future<S> {
return self.promise.future.As()
}
func convertOptional<S>() -> Future<S?> {
return self.promise.future.convertOptional()
}
}
| mit | 8d508492fbfa1c0ef340e63445be71ac | 26.928 | 83 | 0.610713 | 4.587385 | false | false | false | false |
mspvirajpatel/SwiftyBase | SwiftyBase/Classes/Extensions/DictionaryExtension.swift | 1 | 10111 | //
// DictionaryExtension.swift
// Pods
//
// Created by MacMini-2 on 04/09/17.
//
//
import Foundation
/// This extension adds some useful functions to NSDictionary
public extension Dictionary {
// MARK: - Instance functions -
internal var query: String {
var parts = [String]()
for (key, value) in self {
parts.append("\(key)=\(value)")
}
return parts.joined(separator: "&")
}
internal func urlEncodedQuery(using encoding: String.Encoding) -> String {
var parts = [String]()
for case let (key as String, value as String) in self {
parts.append("\(key.urlEncoded)=\(value.urlEncoded)")
}
return parts.joined(separator: "&")
}
internal func urlEncodedAndSortedQuery(using encoding: String.Encoding) -> String {
var parts = [String]()
for case let (key as String, value as String) in self {
parts.append("\(key.urlEncoded)=\(value.urlEncoded)")
}
return parts.sorted().joined(separator: "&")
}
/**
Convert self to JSON as String
- returns: Returns the JSON as String or nil if error while parsing
*/
func dictionaryToJSON() throws -> String {
return try Dictionary.dictionaryToJSON(dictionary: self as AnyObject)
}
// MARK: - Class functions -
/**
Convert the given dictionary to JSON as String
- parameter dictionary: The dictionary to be converted
- returns: Returns the JSON as String or nil if error while parsing
*/
static func dictionaryToJSON(dictionary: AnyObject) throws -> String {
var json: NSString
let jsonData: NSData = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted) as NSData
json = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue)!
return json as String
}
/// EZSE: Returns a random element inside Dictionary
func random() -> Value {
let index: Int = Int(arc4random_uniform(UInt32(self.count)))
return Array(self.values)[index]
}
/// EZSE: Union of self and the input dictionaries.
func union(_ dictionaries: Dictionary...) -> Dictionary {
var result = self
dictionaries.forEach { (dictionary) -> Void in
dictionary.forEach { (key, value) -> Void in
_ = result.updateValue(value, forKey: key)
}
}
return result
}
/// EZSE: Checks if a key exists in the dictionary.
func has(_ key: Key) -> Bool {
return index(forKey: key) != nil
}
/// EZSE: Creates an Array with values generated by running
/// each [key: value] of self through the mapFunction.
func toArray<V>(_ map: (Key, Value) -> V) -> [V] {
var mapped: [V] = []
forEach {
mapped.append(map($0, $1))
}
return mapped
}
/// EZSE: Creates a Dictionary with the same keys as self and values generated by running
/// each [key: value] of self through the mapFunction.
func mapValues<V>(_ map: (Key, Value) -> V) -> [Key: V] {
var mapped: [Key: V] = [:]
forEach {
mapped[$0] = map($0, $1)
}
return mapped
}
/// EZSE: Creates a Dictionary with the same keys as self and values generated by running
/// each [key: value] of self through the mapFunction discarding nil return values.
func mapFilterValues<V>(_ map: (Key, Value) -> V?) -> [Key: V] {
var mapped: [Key: V] = [:]
forEach {
if let value = map($0, $1) {
mapped[$0] = value
}
}
return mapped
}
/// EZSE: Creates a Dictionary with keys and values generated by running
/// each [key: value] of self through the mapFunction discarding nil return values.
func mapFilter<K, V>(_ map: (Key, Value) -> (K, V)?) -> [K: V] {
var mapped: [K: V] = [:]
forEach {
if let value = map($0, $1) {
mapped[value.0] = value.1
}
}
return mapped
}
/// EZSE: Creates a Dictionary with keys and values generated by running
/// each [key: value] of self through the mapFunction.
func map<K, V>(_ map: (Key, Value) -> (K, V)) -> [K: V] {
var mapped: [K: V] = [:]
forEach {
let (_key, _value) = map($0, $1)
mapped[_key] = _value
}
return mapped
}
/// EZSE: Constructs a dictionary containing every [key: value] pair from self
/// for which testFunction evaluates to true.
func filter(_ test: (Key, Value) -> Bool) -> Dictionary {
var result = Dictionary()
for (key, value) in self {
if test(key, value) {
result[key] = value
}
}
return result
}
/// EZSE: Checks if test evaluates true for all the elements in self.
func testAll(_ test: (Key, Value) -> (Bool)) -> Bool {
for (key, value) in self {
if !test(key, value) {
return false
}
}
return true
}
}
extension Dictionary where Value: Equatable {
/// EZSE: Difference of self and the input dictionaries.
/// Two dictionaries are considered equal if they contain the same [key: value] pairs.
public func difference(_ dictionaries: [Key: Value]...) -> [Key: Value] {
var result = self
for dictionary in dictionaries {
for (key, value) in dictionary {
if result.has(key) && result[key] == value {
result.removeValue(forKey: key)
}
}
}
return result
}
}
/// EZSE: Combines the first dictionary with the second and returns single dictionary
public func += <KeyType, ValueType> (left: inout Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
/// EZSE: Difference operator
public func - <K, V: Equatable> (first: [K: V], second: [K: V]) -> [K: V] {
return first.difference(second)
}
public extension Dictionary where Key: ExpressibleByStringLiteral {
/// Merge the keys/values of two dictionaries.
///
/// let dict : [String : String] = ["key1" : "value1"]
/// let dict2 : [String : String] = ["key2" : "value2"]
/// let result = dict + dict2
/// result["key1"] -> "value1"
/// result["key2"] -> "value2"
///
/// - Parameters:
/// - lhs: dictionary
/// - rhs: dictionary
/// - Returns: An dictionary with keys and values from both.
static func +(lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
var result = lhs
rhs.forEach{ result[$0] = $1 }
return result
}
// MARK: - Operators
/// Append the keys and values from the second dictionary into the first one.
///
/// var dict : [String : String] = ["key1" : "value1"]
/// let dict2 : [String : String] = ["key2" : "value2"]
/// dict += dict2
/// dict["key1"] -> "value1"
/// dict["key2"] -> "value2"
///
/// - Parameters:
/// - lhs: dictionary
/// - rhs: dictionary
static func +=(lhs: inout [Key: Value], rhs: [Key: Value]) {
rhs.forEach({ lhs[$0] = $1})
}
/// Remove contained in the array from the dictionary
///
/// let dict : [String : String] = ["key1" : "value1", "key2" : "value2", "key3" : "value3"]
/// let result = dict-["key1", "key2"]
/// result.keys.contains("key3") -> true
/// result.keys.contains("key1") -> false
/// result.keys.contains("key2") -> false
///
/// - Parameters:
/// - lhs: dictionary
/// - rhs: array with the keys to be removed.
/// - Returns: a new dictionary with keys removed.
static func -(lhs: [Key: Value], keys: [Key]) -> [Key: Value]{
var result = lhs
result.removeAll(keys: keys)
return result
}
/// Remove contained in the array from the dictionary
///
/// var dict : [String : String] = ["key1" : "value1", "key2" : "value2", "key3" : "value3"]
/// dict-=["key1", "key2"]
/// dict.keys.contains("key3") -> true
/// dict.keys.contains("key1") -> false
/// dict.keys.contains("key2") -> false
///
/// - Parameters:
/// - lhs: dictionary
/// - rhs: array with the keys to be removed.
static func -=(lhs: inout [Key: Value], keys: [Key]) {
lhs.removeAll(keys: keys)
}
/// Lowercase all keys in dictionary.
///
/// var dict = ["tEstKeY": "value"]
/// dict.lowercaseAllKeys()
/// print(dict) // prints "["testkey": "value"]"
mutating func lowercaseAllKeys() {
for key in keys {
if let lowercaseKey = String(describing: key).lowercased() as? Key {
self[lowercaseKey] = removeValue(forKey: key)
}
}
}
/// Check if key exists in dictionary.
///
/// let dict: [String : Any] = ["testKey": "testValue", "testArrayKey": [1, 2, 3, 4, 5]]
/// dict.has(key: "testKey") -> true
/// dict.has(key: "anotherKey") -> false
///
/// - Parameter key: key to search for
/// - Returns: true if key exists in dictionary.
func has(key: Key) -> Bool {
return index(forKey: key) != nil
}
/// Remove all keys of the dictionary.
///
/// var dict : [String : String] = ["key1" : "value1", "key2" : "value2", "key3" : "value3"]
/// dict.removeAll(keys: ["key1", "key2"])
/// dict.keys.contains("key3") -> true
/// dict.keys.contains("key1") -> false
/// dict.keys.contains("key2") -> false
///
/// - Parameter keys: keys to be removed
mutating func removeAll(keys: [Key]) {
keys.forEach({ removeValue(forKey: $0)})
}
}
| mit | 7d12321ecd50ebd08a215ba73830c0c6 | 31.098413 | 121 | 0.543863 | 3.991709 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Seller/views/SLV_UserReviewCell.swift | 1 | 2986 | //
// SLV_UserReviewCell.swift
// selluv-ios
//
// Created by 조백근 on 2017. 2. 11..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import UIKit
class SLV_UserReviewCell: UICollectionViewCell {
@IBOutlet weak var photosView: UICollectionView!
@IBOutlet weak var textView: UITextView!
var type: ProductPhotoType = .sellerItem
var photos: [String] = []
var text: String?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func awakeFromNib() {
super.awakeFromNib()
self.setupCollectionView()
}
override func layoutSubviews() {
super.layoutSubviews()
}
func setupCollectionView() {
self.photosView.register(UINib(nibName: "SLVProductPhoteHorizontalCell", bundle: nil), forCellWithReuseIdentifier: "SLVProductPhoteHorizontalCell")
self.photosView.delegate = self
self.photosView.dataSource = self
}
func setupData(photos: [String]?, text: String?) {
if let list = photos {
self.photos = list
self.photosView.reloadData()
}
if let text = text {
self.textView.text = text
}
}
func imageDomain() -> String {
var domain = dnProduct
switch self.type {
case .style :
domain = dnStyle
break
case .damage :
domain = dnDamage
break
case .accessory :
domain = dnAccessory
break
default:
break
}
return domain
}
}
extension SLV_UserReviewCell: UICollectionViewDataSource, UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// log.debug("PhotoType : \(self.type) - count : \( self.photos!.count)")
return self.photos.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SLVProductPhoteHorizontalCell", for: indexPath) as! SLVProductPhoteHorizontalCell
cell.isViewer = true
if self.photos.count >= indexPath.row + 1 {
let name = self.photos[indexPath.row] as! String
if name != "" {
let domain = self.imageDomain()
let from = URL(string: "\(domain)\(name)")
let dnModel = SLVDnImageModel.shared
DispatchQueue.global(qos: .default).async {
dnModel.setupImageView(view: (cell.thumnail)!, from: from!)
}
}
}
return cell
}
}
| mit | c280783188b60e1c5e6773d598f4a839 | 29.070707 | 157 | 0.599261 | 4.994966 | false | false | false | false |
osorioabel/checklist-app | checklist-app/checklist-app/AppDelegate.swift | 1 | 4047 | //
// AppDelegate.swift
// checklist-app
//
// Created by Abel Osorio on 2/16/16.
// Copyright © 2016 Abel Osorio. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let dataModel = DataModel()
// MARK: - Life Cycle
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
customAppApperence()
let navigationController = window?.rootViewController as! UINavigationController
let controller = navigationController.viewControllers[0] as! AllListViewController
controller.dataModel = dataModel
let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings( notificationSettings)
simulateNotification()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
saveData()
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
saveData()
}
// MARK: - Notification
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
print("didReceiveLocalNotification \(notification)")
}
func simulateNotification (){
let date = NSDate(timeIntervalSinceNow: 10)
let localNotification = UILocalNotification()
localNotification.fireDate = date
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.alertBody = "I am a local notification!"
localNotification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification( localNotification)
}
// MARK: - Persistence
func saveData() {
dataModel.saveChecklists()
}
// MARK: - Customization
func customAppApperence(){
UINavigationBar.appearance().barTintColor = UIColor(red: 49/255.0, green: 130/255.0, blue: 217/255.0, alpha: 1)
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
}
}
| mit | d8a76aa66bba5dd84f309ef74d63cb93 | 39.46 | 285 | 0.708354 | 6.065967 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/DiffController.swift | 1 | 10516 | import Foundation
enum DiffError: Error {
case generateUrlFailure
case missingDiffResponseFailure
case missingUrlResponseFailure
case fetchRevisionConstructTitleFailure
case unrecognizedHardcodedIdsForIntermediateCounts
case failureToPopulateModelsFromDeepLink
case failureToVerifyRevisionIDs
var localizedDescription: String {
return CommonStrings.genericErrorDescription
}
}
class DiffController {
enum RevisionDirection {
case next
case previous
}
let diffFetcher: DiffFetcher
let pageHistoryFetcher: PageHistoryFetcher?
let globalUserInfoFetcher: GlobalUserInfoFetcher
let siteURL: URL
let type: DiffContainerViewModel.DiffType
private weak var revisionRetrievingDelegate: DiffRevisionRetrieving?
let transformer: DiffTransformer
init(siteURL: URL, diffFetcher: DiffFetcher = DiffFetcher(), pageHistoryFetcher: PageHistoryFetcher?, revisionRetrievingDelegate: DiffRevisionRetrieving?, type: DiffContainerViewModel.DiffType) {
self.diffFetcher = diffFetcher
self.pageHistoryFetcher = pageHistoryFetcher
self.globalUserInfoFetcher = GlobalUserInfoFetcher()
self.siteURL = siteURL
self.revisionRetrievingDelegate = revisionRetrievingDelegate
self.type = type
self.transformer = DiffTransformer(type: type, siteURL: siteURL)
}
func fetchEditCount(guiUser: String, completion: @escaping ((Result<Int, Error>) -> Void)) {
globalUserInfoFetcher.fetchEditCount(guiUser: guiUser, siteURL: siteURL, completion: completion)
}
func fetchIntermediateCounts(for pageTitle: String, pageURL: URL, from fromRevisionID: Int , to toRevisionID: Int, completion: @escaping (Result<EditCountsGroupedByType, Error>) -> Void) {
pageHistoryFetcher?.fetchEditCounts(.edits, .editors, for: pageTitle, pageURL: pageURL, from: fromRevisionID, to: toRevisionID, completion: completion)
}
func fetchFirstRevisionModel(articleTitle: String, completion: @escaping ((Result<WMFPageHistoryRevision, Error>) -> Void)) {
guard let articleTitle = articleTitle.normalizedPageTitle else {
completion(.failure(DiffError.fetchRevisionConstructTitleFailure))
return
}
diffFetcher.fetchFirstRevisionModel(siteURL: siteURL, articleTitle: articleTitle, completion: completion)
}
struct DeepLinkModelsResponse {
let from: WMFPageHistoryRevision?
let to: WMFPageHistoryRevision?
let first: WMFPageHistoryRevision
let articleTitle: String
}
func populateModelsFromDeepLink(fromRevisionID: Int?, toRevisionID: Int?, articleTitle: String?, completion: @escaping ((Result<DeepLinkModelsResponse, Error>) -> Void)) {
if let articleTitle = articleTitle {
populateModelsFromDeepLink(fromRevisionID: fromRevisionID, toRevisionID: toRevisionID, articleTitle: articleTitle, completion: completion)
return
}
let maybeRevisionID = toRevisionID ?? fromRevisionID
guard let revisionID = maybeRevisionID else {
completion(.failure(DiffError.failureToVerifyRevisionIDs))
return
}
diffFetcher.fetchArticleTitle(siteURL: siteURL, revisionID: revisionID) { (result) in
switch result {
case .success(let title):
self.populateModelsFromDeepLink(fromRevisionID: fromRevisionID, toRevisionID: toRevisionID, articleTitle: title, completion: completion)
case .failure(let error):
completion(.failure(error))
}
}
}
private func populateModelsFromDeepLink(fromRevisionID: Int?, toRevisionID: Int?, articleTitle: String, completion: @escaping ((Result<DeepLinkModelsResponse, Error>) -> Void)) {
guard let articleTitle = articleTitle.normalizedPageTitle else {
completion(.failure(DiffError.fetchRevisionConstructTitleFailure))
return
}
var fromResponse: WMFPageHistoryRevision?
var toResponse: WMFPageHistoryRevision?
var firstResponse: WMFPageHistoryRevision?
let group = DispatchGroup()
if let fromRevisionID = fromRevisionID {
group.enter()
let fromRequest = DiffFetcher.FetchRevisionModelRequest.populateModel(revisionID: fromRevisionID)
diffFetcher.fetchRevisionModel(siteURL, articleTitle: articleTitle, request: fromRequest) { (result) in
switch result {
case .success(let fetchResponse):
fromResponse = fetchResponse
case .failure:
break
}
group.leave()
}
}
if let toRevisionID = toRevisionID {
group.enter()
let toRequest = DiffFetcher.FetchRevisionModelRequest.populateModel(revisionID: toRevisionID)
diffFetcher.fetchRevisionModel(siteURL, articleTitle: articleTitle, request: toRequest) { (result) in
switch result {
case .success(let fetchResponse):
toResponse = fetchResponse
case .failure:
break
}
group.leave()
}
}
group.enter()
diffFetcher.fetchFirstRevisionModel(siteURL: siteURL, articleTitle: articleTitle) { (result) in
switch result {
case .success(let fetchResponse):
firstResponse = fetchResponse
case .failure:
break
}
group.leave()
}
group.notify(queue: DispatchQueue.global(qos: .userInitiated)) {
guard let firstResponse = firstResponse,
(fromResponse != nil || toResponse != nil) else {
completion(.failure(DiffError.failureToPopulateModelsFromDeepLink))
return
}
let response = DeepLinkModelsResponse(from: fromResponse, to: toResponse, first: firstResponse, articleTitle: articleTitle)
completion(.success(response))
}
}
func fetchAdjacentRevisionModel(sourceRevision: WMFPageHistoryRevision, direction: RevisionDirection, articleTitle: String, completion: @escaping ((Result<WMFPageHistoryRevision, Error>) -> Void)) {
if let revisionRetrievingDelegate = revisionRetrievingDelegate {
// optimization - first try to grab a revision we might already have in memory from the revisionRetrievingDelegate
switch direction {
case .next:
if let nextRevision = revisionRetrievingDelegate.retrieveNextRevision(with: sourceRevision) {
completion(.success(nextRevision))
return
}
case .previous:
if let previousRevision = revisionRetrievingDelegate.retrievePreviousRevision(with: sourceRevision) {
completion(.success(previousRevision))
return
}
}
}
let direction: DiffFetcher.FetchRevisionModelRequestDirection = direction == .previous ? .older : .newer
let request = DiffFetcher.FetchRevisionModelRequest.adjacent(sourceRevision: sourceRevision, direction: direction)
diffFetcher.fetchRevisionModel(siteURL, articleTitle: articleTitle, request: request) { (result) in
switch result {
case .success(let response):
completion(.success(response))
case .failure(let error):
completion(.failure(error))
}
}
}
func fetchFirstRevisionDiff(revisionId: Int, siteURL: URL, theme: Theme, traitCollection: UITraitCollection, completion: @escaping ((Result<[DiffListGroupViewModel], Error>) -> Void)) {
diffFetcher.fetchWikitext(siteURL: siteURL, revisionId: revisionId) { (result) in
switch result {
case .success(let wikitext):
do {
let viewModels = try self.transformer.firstRevisionViewModels(from: wikitext, theme: theme, traitCollection: traitCollection)
completion(.success(viewModels))
} catch let error {
completion(.failure(error))
}
case .failure(let error):
completion(.failure(error))
}
}
}
func fetchDiff(fromRevisionId: Int, toRevisionId: Int, theme: Theme, traitCollection: UITraitCollection, completion: @escaping ((Result<[DiffListGroupViewModel], Error>) -> Void)) {
// let queue = DispatchQueue.global(qos: .userInitiated)
//
// queue.async { [weak self] in
//
// guard let self = self else { return }
//
// do {
//
// let url = Bundle.main.url(forResource: "DiffResponse", withExtension: "json")!
// let data = try Data(contentsOf: url)
// let diffResponse = try JSONDecoder().decode(DiffResponse.self, from: data)
//
//
// do {
// let viewModels = try self.transformer.viewModels(from: diffResponse, theme: theme, traitCollection: traitCollection)
//
// completion(.success(viewModels))
// } catch (let error) {
// completion(.failure(error))
// }
//
//
// } catch (let error) {
// completion(.failure(error))
// }
// }
diffFetcher.fetchDiff(fromRevisionId: fromRevisionId, toRevisionId: toRevisionId, siteURL: siteURL) { [weak self] (result) in
guard let self = self else { return }
switch result {
case .success(let diffResponse):
do {
let viewModels = try self.transformer.viewModels(from: diffResponse, theme: theme, traitCollection: traitCollection)
completion(.success(viewModels))
} catch let error {
completion(.failure(error))
}
case .failure(let error):
completion(.failure(error))
}
}
}
}
| mit | 88fddf3d099353e028388f9cf05853d8 | 39.291188 | 202 | 0.615824 | 6.009143 | false | false | false | false |
ello/ello-ios | Sources/Controllers/Categories/CategoryScreen.swift | 1 | 12834 | ////
/// CategoryScreen.swift
//
import SnapKit
class CategoryScreen: HomeSubviewScreen, CategoryScreenProtocol {
struct Size {
static let navigationBarHeight: CGFloat = 43
static let buttonWidth: CGFloat = 40
static let buttonMargin: CGFloat = 5
static let gradientMidpoint: Float = 0.4
static var categoryCardListInset: CGFloat { return CategoryCardListView.Size.spacing }
}
enum NavBarItems {
case onlyGridToggle
case all
case none
}
enum Selection {
case all
case subscribed
case category(Int)
}
typealias Usage = CategoryViewController.Usage
weak var delegate: CategoryScreenDelegate?
var topInsetView: UIView {
if usage == .detail {
return navigationBar
}
else {
return categoryCardList
}
}
var showSubscribed: Bool = false
var showEditButton: Bool = false { didSet { updateEditButton() } }
var isGridView = false {
didSet {
gridListButton.setImage(
isGridView ? .listView : .gridView,
imageStyle: .normal,
for: .normal
)
}
}
var categoriesLoaded: Bool = false { didSet { updateEditButton() } }
private let usage: Usage
init(usage: Usage) {
self.usage = usage
super.init(frame: .default)
}
required init(frame: CGRect) {
fatalError("init(frame:) has not been implemented")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private let categoryCardList = CategoryCardListView()
private let iPhoneBlackBar = UIView()
private let searchField = SearchNavBarField()
private let searchFieldButton = UIButton()
private let backButton = UIButton()
private let editCategoriesButton = StyledButton(style: .clearWhite)
private let editCategoriesGradient = CategoryScreen.generateGradientLayer()
private let gridListButton = UIButton()
private let shareButton = UIButton()
private let navigationContainer = Container()
private var categoryCardTopConstraint: Constraint!
private var iPhoneBlackBarTopConstraint: Constraint!
private var backVisibleConstraint: Constraint!
private var backHiddenConstraint: Constraint!
private var navBarVisible = true
private var categoryCardListTop: CGFloat {
if navBarVisible && usage == .largeNav {
return ElloNavigationBar.Size.discoverLargeHeight - 1
}
else if navBarVisible {
return ElloNavigationBar.Size.height - 1
}
else if Globals.isIphoneX {
return Globals.statusBarHeight
}
else {
return 0
}
}
override func layoutSubviews() {
super.layoutSubviews()
editCategoriesGradient.frame = editCategoriesButton.bounds
}
override func setup() {
editCategoriesButton.isHidden = true
categoryCardList.isHidden = usage == .detail
}
override func style() {
styleHomeScreenNavBar(navigationBar: navigationBar)
iPhoneBlackBar.backgroundColor = .black
backButton.setImages(.backChevron)
shareButton.setImage(.share, imageStyle: .normal, for: .normal)
editCategoriesButton.contentEdgeInsets = UIEdgeInsets(
top: 0,
left: 30,
bottom: 0,
right: 10
)
}
override func setText() {
navigationBar.title = ""
editCategoriesButton.title = InterfaceString.Edit
}
override func bindActions() {
categoryCardList.delegate = self
searchFieldButton.addTarget(
self,
action: #selector(searchFieldButtonTapped),
for: .touchUpInside
)
backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
gridListButton.addTarget(self, action: #selector(gridListToggled), for: .touchUpInside)
shareButton.addTarget(self, action: #selector(shareTapped), for: .touchUpInside)
editCategoriesButton.addTarget(
self,
action: #selector(editCategoriesTapped),
for: .touchUpInside
)
}
override func arrange() {
super.arrange()
addSubview(categoryCardList)
editCategoriesButton.layer.insertSublayer(editCategoriesGradient, at: 0)
addSubview(editCategoriesButton)
addSubview(navigationBar)
navigationContainer.addSubview(searchField)
navigationContainer.addSubview(searchFieldButton)
navigationBar.addSubview(backButton)
navigationBar.addSubview(navigationContainer)
navigationBar.addSubview(gridListButton)
navigationBar.addSubview(shareButton)
if usage == .largeNav {
navigationBar.sizeClass = .discoverLarge
arrangeHomeScreenNavBar(type: .discover, navigationBar: navigationBar)
}
if Globals.isIphoneX {
addSubview(iPhoneBlackBar)
iPhoneBlackBar.snp.makeConstraints { make in
iPhoneBlackBarTopConstraint = make.top.equalTo(self).constraint
make.leading.trailing.equalTo(self)
make.height.equalTo(Globals.statusBarHeight + Size.navigationBarHeight)
}
iPhoneBlackBar.alpha = 0
}
categoryCardList.snp.makeConstraints { make in
categoryCardTopConstraint =
make.top.equalTo(self).offset(categoryCardListTop).constraint
make.leading.trailing.equalTo(self)
make.height.equalTo(CategoryCardListView.Size.height)
}
editCategoriesButton.snp.makeConstraints { make in
make.top.bottom.equalTo(categoryCardList).inset(Size.categoryCardListInset)
make.trailing.equalTo(self)
}
backButton.snp.makeConstraints { make in
make.leading.bottom.equalTo(navigationBar)
make.height.equalTo(Size.navigationBarHeight)
make.width.equalTo(36.5)
}
searchField.snp.makeConstraints { make in
var insets: UIEdgeInsets
if usage == .largeNav {
insets = SearchNavBarField.Size.largeNavSearchInsets
}
else {
insets = SearchNavBarField.Size.searchInsets
}
insets.top -= StatusBar.Size.height
insets.bottom -= 1
make.bottom.equalTo(navigationBar).inset(insets)
make.height.equalTo(Size.navigationBarHeight - insets.tops)
backHiddenConstraint = make.leading.equalTo(navigationBar).inset(insets).constraint
backVisibleConstraint =
make.leading.equalTo(backButton.snp.trailing).offset(insets.left).constraint
make.trailing.equalTo(shareButton.snp.leading).offset(-Size.buttonMargin)
}
navigationContainer.snp.makeConstraints { make in
make.leading.equalTo(searchField).offset(-SearchNavBarField.Size.searchInsets.left)
make.bottom.equalTo(navigationBar)
make.height.equalTo(Size.navigationBarHeight)
make.trailing.equalTo(gridListButton.snp.leading)
}
searchFieldButton.snp.makeConstraints { make in
make.edges.equalTo(navigationContainer)
}
gridListButton.snp.makeConstraints { make in
make.height.equalTo(Size.navigationBarHeight)
make.bottom.equalTo(navigationBar)
make.trailing.equalTo(navigationBar).offset(-Size.buttonMargin)
make.width.equalTo(Size.buttonWidth)
}
shareButton.snp.makeConstraints { make in
make.top.bottom.width.equalTo(gridListButton)
make.trailing.equalTo(gridListButton.snp.leading)
}
navigationBar.snp.makeConstraints { make in
let intrinsicHeight = navigationBar.sizeClass.height
make.height.equalTo(intrinsicHeight - 1).priority(Priority.required)
}
}
func set(
categoriesInfo newValue: [CategoryCardListView.CategoryInfo],
completion: @escaping Block
) {
categoryCardList.categoriesInfo = newValue
if navBarVisible {
completion()
return
}
let editCategoriesButtonY = categoryCardListTop + Size.categoryCardListInset
let originalY = categoryCardList.frame.origin.y
categoryCardList.frame.origin.y = originalY - categoryCardList.frame.size.height
editCategoriesButton.frame.origin.y = editCategoriesButtonY
- editCategoriesButton.frame.height
elloAnimate {
self.editCategoriesButton.frame.origin.y = editCategoriesButtonY
self.categoryCardList.frame.origin.y = originalY
}.done(completion)
}
private func updateEditButton() {
let actuallyShowEditButton = showEditButton && categoriesLoaded
editCategoriesButton.isVisible = actuallyShowEditButton
let rightInset = actuallyShowEditButton
? editCategoriesButton.frame.width * CGFloat(1 - Size.gradientMidpoint) : 0
categoryCardList.rightInset = rightInset
}
func toggleCategoriesList(navBarVisible: Bool, animated: Bool) {
self.navBarVisible = navBarVisible
elloAnimate(animated: animated) {
self.categoryCardTopConstraint.update(offset: self.categoryCardListTop)
self.categoryCardList.frame.origin.y = self.categoryCardListTop
self.editCategoriesButton.frame.origin.y = self.categoryCardListTop
+ Size.categoryCardListInset
if Globals.isIphoneX {
let iPhoneBlackBarTop = self.categoryCardList.frame.minY
- self.iPhoneBlackBar.frame.height
self.iPhoneBlackBarTopConstraint.update(offset: iPhoneBlackBarTop)
self.iPhoneBlackBar.frame.origin.y = iPhoneBlackBarTop
self.iPhoneBlackBar.alpha = navBarVisible ? 0 : 1
}
}
}
func scrollToCategory(_ selection: Selection) {
switch selection {
case .all:
self.categoryCardList.scrollToIndex(0, animated: true)
case .subscribed:
self.categoryCardList.scrollToIndex(1, animated: true)
case let .category(index):
let offset = showSubscribed ? 2 : 1
self.categoryCardList.scrollToIndex(index + offset, animated: true)
}
}
func selectCategory(_ selection: Selection) {
switch selection {
case .all:
self.categoryCardList.selectCategory(index: 0)
case .subscribed:
self.categoryCardList.selectCategory(index: 1)
case let .category(index):
let offset = showSubscribed ? 2 : 1
self.categoryCardList.selectCategory(index: index + offset)
}
}
@objc
func searchFieldButtonTapped() {
delegate?.searchButtonTapped()
}
@objc
func backButtonTapped() {
delegate?.backButtonTapped()
}
@objc
func gridListToggled() {
delegate?.gridListToggled(sender: gridListButton)
}
@objc
func shareTapped() {
delegate?.shareTapped(sender: shareButton)
}
func setupNavBar(back backVisible: Bool, animated: Bool) {
backButton.isVisible = backVisible
backVisibleConstraint.set(isActivated: backVisible)
backHiddenConstraint.set(isActivated: !backVisible)
elloAnimate(animated: animated) {
self.navigationBar.layoutIfNeeded()
}
}
}
extension CategoryScreen: CategoryCardListDelegate {
@objc
func allCategoriesTapped() {
delegate?.allCategoriesTapped()
}
@objc
func editCategoriesTapped() {
delegate?.editCategoriesTapped()
}
@objc
func subscribedCategoryTapped() {
delegate?.subscribedCategoryTapped()
}
@objc
func categoryCardSelected(_ index: Int) {
delegate?.categorySelected(index: index)
}
}
extension CategoryScreen: HomeScreenNavBar {
@objc
func homeScreenScrollToTop() {
delegate?.scrollToTop()
}
}
extension CategoryScreen {
private static func generateGradientLayer() -> CAGradientLayer {
let layer = CAGradientLayer()
layer.locations = [0, NSNumber(value: CategoryScreen.Size.gradientMidpoint), 1]
layer.colors = [
UIColor(hex: 0x000000, alpha: 0).cgColor,
UIColor(hex: 0x000000, alpha: 1).cgColor,
UIColor(hex: 0x000000, alpha: 1).cgColor,
]
layer.startPoint = CGPoint(x: 0, y: 0.5)
layer.endPoint = CGPoint(x: 1, y: 0.5)
return layer
}
}
| mit | 4fa1bb15a9872f31ec7629f0763442e9 | 32.335065 | 95 | 0.64259 | 5.29019 | false | false | false | false |
orkoden/congestion | Congestion/Congestion/ParticleEmitter.swift | 1 | 7362 | //
// ParticleEmitter.swift
// Congestion
//
// Created by Robert Atkins on 20/05/2015.
// Copyright (c) 2015 Congestion. All rights reserved.
//
import MultipeerConnectivity
protocol ParticleEmitterDelegate {
func particleEmitter(particleEmitter: ParticleEmitter, didReceiveParticleSet particleSet: ParticleSet)
}
class ParticleEmitter: NSObject, MCNearbyServiceAdvertiserDelegate, MCNearbyServiceBrowserDelegate, MCSessionDelegate {
static let ParticleEmitterErrorNotification = "ParticleEmitterErrorNotification"
static let ParticleEmitterInfoNotification = "ParticleEmitterInfoNotification"
static let ParticleEmitterNotificationMessageKey = "ParticleEmitterNotificationMessageKey"
static let CongestionServiceType = "congestion"
let particleRepository: ParticleRepository
let delegate: ParticleEmitterDelegate
let localPeerId: MCPeerID
let serviceAdvertiser: MCNearbyServiceAdvertiser
let serviceBrowser: MCNearbyServiceBrowser
var session: MCSession
// joerg: C7470831-0122-4B9D-AD31-B6362CBBB49F
// ratkins: D890E9D6-BDE6-4496-A6F8-F7D81B62CB79
init(particleRepository: ParticleRepository, delegate: ParticleEmitterDelegate) {
self.particleRepository = particleRepository
localPeerId = MCPeerID(displayName: UIDevice.currentDevice().identifierForVendor.UUIDString)
self.session = MCSession(peer: localPeerId, securityIdentity: nil, encryptionPreference: .None)
serviceAdvertiser = MCNearbyServiceAdvertiser(peer: localPeerId, discoveryInfo: nil, serviceType: ParticleEmitter.CongestionServiceType)
serviceBrowser = MCNearbyServiceBrowser(peer: localPeerId, serviceType: ParticleEmitter.CongestionServiceType)
self.delegate = delegate
super.init()
self.session.delegate = self
if UIDevice.currentDevice().identifierForVendor.UUIDString == "C7470831-0122-4B9D-AD31-B6362CBBB49F" {
// Joerg advertises
serviceAdvertiser.delegate = self
serviceAdvertiser.startAdvertisingPeer()
} else {
// Robert browses
serviceBrowser.delegate = self
serviceBrowser.startBrowsingForPeers()
}
}
func upload(session: MCSession!, peerID: MCPeerID) {
let propertyListSerialisationError = NSErrorPointer()
let data = NSPropertyListSerialization.dataWithPropertyList(particleRepository.particleSets, format: NSPropertyListFormat.BinaryFormat_v1_0, options: 0, error: propertyListSerialisationError)
let sendDataError = NSErrorPointer()
let success = session.sendData(data, toPeers: [peerID], withMode: MCSessionSendDataMode.Reliable, error: sendDataError)
if !success {
NSNotificationCenter.defaultCenter().postNotificationName(ParticleEmitter.ParticleEmitterErrorNotification,
object: [ParticleEmitter.ParticleEmitterNotificationMessageKey: "Sending data failed"])
}
}
// MARK: - Advertiser delegate
func advertiser(advertiser: MCNearbyServiceAdvertiser!, didNotStartAdvertisingPeer error: NSError!) {
println("\(__FUNCTION__)")
NSNotificationCenter.defaultCenter().postNotificationName(ParticleEmitter.ParticleEmitterErrorNotification,
object: [ParticleEmitter.ParticleEmitterNotificationMessageKey: "Advertising failed, retrying..."])
serviceAdvertiser.startAdvertisingPeer()
}
func advertiser(advertiser: MCNearbyServiceAdvertiser!, didReceiveInvitationFromPeer peerID: MCPeerID!, withContext context: NSData!, invitationHandler: ((Bool, MCSession!) -> Void)!) {
println("\(__FUNCTION__)")
NSNotificationCenter.defaultCenter().postNotificationName(ParticleEmitter.ParticleEmitterInfoNotification,
object: [ParticleEmitter.ParticleEmitterNotificationMessageKey: "Found peer, sending..."])
invitationHandler(true, session)
}
// MARK: - Browser delegate
func browser(browser: MCNearbyServiceBrowser!, didNotStartBrowsingForPeers error: NSError!) {
println("\(__FUNCTION__)")
NSNotificationCenter.defaultCenter().postNotificationName(ParticleEmitter.ParticleEmitterErrorNotification,
object: [ParticleEmitter.ParticleEmitterNotificationMessageKey: "Browsing failed, retrying..."])
serviceBrowser.startBrowsingForPeers()
}
func browser(browser: MCNearbyServiceBrowser!, foundPeer peerID: MCPeerID!, withDiscoveryInfo info: [NSObject : AnyObject]!) {
println("\(__FUNCTION__)")
NSNotificationCenter.defaultCenter().postNotificationName(ParticleEmitter.ParticleEmitterInfoNotification,
object: [ParticleEmitter.ParticleEmitterNotificationMessageKey: "Found peer, receiving..."])
session.nearbyConnectionDataForPeer(peerID) { data, error in
if data != nil {
self.session.connectPeer(peerID, withNearbyConnectionData: data)
}
}
}
func browser(browser: MCNearbyServiceBrowser!, lostPeer peerID: MCPeerID!) {
println("\(__FUNCTION__)")
NSNotificationCenter.defaultCenter().postNotificationName(ParticleEmitter.ParticleEmitterErrorNotification,
object: [ParticleEmitter.ParticleEmitterNotificationMessageKey: "Lost peer"])
}
// MARK: - Session delegate
func session(session: MCSession!, didReceiveData data: NSData!, fromPeer peerID: MCPeerID!) {
println("\(__FUNCTION__)")
let readError = NSErrorPointer()
let propertyList: AnyObject? = NSPropertyListSerialization.propertyListWithData(data, options: Int(NSPropertyListMutabilityOptions.Immutable.rawValue), format: nil, error: readError)
if let particleSet = propertyList as? Array<ParticleSet> {
for particleSet in particleSet {
delegate.particleEmitter(self, didReceiveParticleSet: particleSet)
}
}
}
func session(session: MCSession!, didReceiveStream stream: NSInputStream!, withName streamName: String!, fromPeer peerID: MCPeerID!) {
println("\(__FUNCTION__)")
}
func session(session: MCSession!, didStartReceivingResourceWithName resourceName: String!, fromPeer peerID: MCPeerID!, withProgress progress: NSProgress!) {
println("\(__FUNCTION__)")
}
func session(session: MCSession!, didFinishReceivingResourceWithName resourceName: String!, fromPeer peerID: MCPeerID!, atURL localURL: NSURL!, withError error: NSError!) {
println("\(__FUNCTION__)")
}
func session(session: MCSession!, peer peerID: MCPeerID!, didChangeState state: MCSessionState) {
let str: String
switch state {
case .NotConnected:
str = "NotConnected"
case .Connecting:
str = "Connecting"
case .Connected:
str = "Connected"
upload(session, peerID: peerID)
}
println("\(__FUNCTION__) \(peerID.description) did change state to \(str)")
}
func session(session: MCSession!, didReceiveCertificate certificate: [AnyObject]!, fromPeer peerID: MCPeerID!, certificateHandler: ((Bool) -> Void)!) {
println("\(__FUNCTION__)")
certificateHandler(true)
}
} | mit | 7b967a084f0879e48b845a34218a1b5b | 44.171779 | 199 | 0.705379 | 5.980504 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/TXTReader/Reader/View/ZSFontViewController.swift | 1 | 4529 | //
// ZSFontViewController.swift
// zhuishushenqi
//
// Created by caony on 2018/9/13.
// Copyright © 2018年 QS. All rights reserved.
//
import UIKit
typealias ZSClickHandler = ()->Void
class ZSFontViewController: ZSBaseTableViewController {
var viewModel = ZSFontViewModel()
override func viewDidLoad() {
super.viewDidLoad()
viewModel.copyFont()
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.01
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.fonts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.qs_dequeueReusableCell(ZSFontViewCell.self)
let image = viewModel.fonts[indexPath.row]["image"] ?? ""
if image == "" {
cell?.textLabel?.text = viewModel.fonts[indexPath.row]["name"]
} else {
cell?.imageView?.image = UIImage(named: image)
}
let exist = viewModel.fileExist(indexPath: indexPath)
if exist {
cell?.setDownloadType(type: .finished)
} else {
cell?.setDownloadType(type: .notdown)
}
if indexPath == viewModel.selectedIndexPath {
cell?.setDownloadType(type: .inuse)
}
cell?.downloadHandler = {
if cell?.type == .notdown {
self.viewModel.fetchFont(indexPath: indexPath, handler: { (finished) in
if finished! {
cell?.setDownloadType(type: .finished)
}
})
} else if cell?.type == .finished {
self.viewModel.selectedIndexPath = indexPath
cell?.setDownloadType(type: .inuse)
self.tableView.reloadData()
}
}
return cell!
}
override func registerCellClasses() -> Array<AnyClass> {
return [ZSFontViewCell.self]
}
}
class ZSFontViewCell: UITableViewCell {
enum ZSDownloadType {
case notdown
case finished
case inuse
}
var download:UIButton = UIButton(type: .custom)
var downloadHandler:ZSClickHandler?
var type:ZSDownloadType = .notdown
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setDownloadType(type: .notdown)
download.titleLabel?.font = UIFont.systemFont(ofSize: 11)
download.setTitleColor(UIColor.red, for: .normal)
download.layer.borderColor = UIColor.red.cgColor
download.layer.borderWidth = 0.5
download.frame = CGRect(x: 0, y: 0, width: 60, height: 30)
download.addTarget(self, action: #selector(downloadAction(sender:)), for: .touchUpInside)
self.accessoryView = download
self.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0)
self.selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc
private func downloadAction(sender:UIButton) {
downloadHandler?()
}
func setDownloadType(type:ZSDownloadType) {
self.type = type
if type == .finished {
self.download.setTitle("启用", for: .normal)
self.download.setTitleColor(UIColor.white, for: .normal)
self.download.backgroundColor = UIColor.red
self.download.isEnabled = true
self.download.layer.borderColor = UIColor.red.cgColor
} else if type == .inuse {
self.download.setTitle("使用中", for: .normal)
self.download.isEnabled = false
self.download.setTitleColor(UIColor.black, for: .normal)
self.download.backgroundColor = UIColor.white
self.download.layer.borderColor = UIColor.clear.cgColor
} else if type == .notdown {
self.download.setTitle("下载", for: .normal)
self.download.isEnabled = true
self.download.setTitleColor(UIColor.red, for: .normal)
self.download.backgroundColor = UIColor.white
self.download.layer.borderColor = UIColor.red.cgColor
}
}
override func prepareForReuse() {
self.setDownloadType(type: .notdown)
}
}
| mit | 3c9a559b1810580bfda58016c622e6a4 | 33.442748 | 109 | 0.611259 | 4.76452 | false | false | false | false |
danielmartin/swift | stdlib/public/core/Dictionary.swift | 1 | 74182 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Implementation notes
// ====================
//
// `Dictionary` uses two storage schemes: native storage and Cocoa storage.
//
// Native storage is a hash table with open addressing and linear probing. The
// bucket array forms a logical ring (e.g., a chain can wrap around the end of
// buckets array to the beginning of it).
//
// The logical bucket array is implemented as three arrays: Key, Value, and a
// bitmap that marks valid entries. An unoccupied entry marks the end of a
// chain. There is always at least one unoccupied entry among the
// buckets. `Dictionary` does not use tombstones.
//
// In addition to the native storage, `Dictionary` can also wrap an
// `NSDictionary` in order to allow bridging `NSDictionary` to `Dictionary` in
// `O(1)`.
//
// Native dictionary storage uses a data structure like this::
//
// struct Dictionary<K,V>
// +------------------------------------------------+
// | enum Dictionary<K,V>._Variant |
// | +--------------------------------------------+ |
// | | [struct _NativeDictionary<K,V> | |
// | +---|----------------------------------------+ |
// +----/-------------------------------------------+
// /
// |
// V
// class _RawDictionaryStorage
// +-----------------------------------------------------------+
// | <isa> |
// | <refcount> |
// | _count |
// | _capacity |
// | _scale |
// | _age |
// | _seed |
// | _rawKeys |
// | _rawValue |
// | [inline bitset of occupied entries] |
// | [inline array of keys] |
// | [inline array of values] |
// +-----------------------------------------------------------+
//
// Cocoa storage uses a data structure like this:
//
// struct Dictionary<K,V>
// +----------------------------------------------+
// | enum Dictionary<K,V>._Variant |
// | +----------------------------------------+ |
// | | [ struct _CocoaDictionary | |
// | +---|------------------------------------+ |
// +----/-----------------------------------------+
// /
// |
// V
// class NSDictionary
// +--------------+
// | [refcount#1] |
// | etc. |
// +--------------+
// ^
// |
// \ struct _CocoaDictionary.Index
// +--|------------------------------------+
// | * base: _CocoaDictionary |
// | allKeys: array of all keys |
// | currentKeyIndex: index into allKeys |
// +---------------------------------------+
//
//
// The Native Kinds of Storage
// ---------------------------
//
// The native backing store is represented by three different classes:
// * `_RawDictionaryStorage`
// * `_EmptyDictionarySingleton` (extends Raw)
// * `_DictionaryStorage<K: Hashable, V>` (extends Raw)
//
// (Hereafter `Raw`, `Empty`, and `Storage`, respectively)
//
// In a less optimized implementation, `Raw` and `Empty` could be eliminated, as
// they exist only to provide special-case behaviors.
//
// `Empty` is the a type-punned empty singleton storage. Its single instance is
// created by the runtime during process startup. Because we use the same
// instance for all empty dictionaries, it cannot declare type parameters.
//
// `Storage` provides backing storage for regular native dictionaries. All
// non-empty native dictionaries use an instance of `Storage` to store their
// elements. `Storage` is a generic class with a nontrivial deinit.
//
// `Raw` is the base class for both `Empty` and `Storage`. It defines a full set
// of ivars to access dictionary contents. Like `Empty`, `Raw` is also
// non-generic; the base addresses it stores are represented by untyped raw
// pointers. The only reason `Raw` exists is to allow `_NativeDictionary` to
// treat `Empty` and `Storage` in a unified way.
//
// Storage classes don't contain much logic; `Raw` in particular is just a
// collection of ivars. `Storage` provides allocation/deinitialization logic,
// while `Empty`/`Storage` implement NSDictionary methods. All other operations
// are actually implemented by the `_NativeDictionary` and `_HashTable` structs.
//
// The `_HashTable` struct provides low-level hash table metadata operations.
// (Lookups, iteration, insertion, removal.) It owns and maintains the
// tail-allocated bitmap.
//
// `_NativeDictionary` implements the actual Dictionary operations. It
// consists of a reference to a `Raw` instance, to allow for the possibility of
// the empty singleton.
//
//
// Index Invalidation
// ------------------
//
// FIXME: decide if this guarantee is worth making, as it restricts
// collision resolution to first-come-first-serve. The most obvious alternative
// would be robin hood hashing. The Rust code base is the best
// resource on a *practical* implementation of robin hood hashing I know of:
// https://github.com/rust-lang/rust/blob/ac919fcd9d4a958baf99b2f2ed5c3d38a2ebf9d0/src/libstd/collections/hash/map.rs#L70-L178
//
// Indexing a container, `c[i]`, uses the integral offset stored in the index
// to access the elements referenced by the container. Generally, an index into
// one container has no meaning for another. However copy-on-write currently
// preserves indices under insertion, as long as reallocation doesn't occur:
//
// var (i, found) = d.find(k) // i is associated with d's storage
// if found {
// var e = d // now d is sharing its data with e
// e[newKey] = newValue // e now has a unique copy of the data
// return e[i] // use i to access e
// }
//
// The result should be a set of iterator invalidation rules familiar to anyone
// familiar with the C++ standard library. Note that because all accesses to a
// dictionary storage are bounds-checked, this scheme never compromises memory
// safety.
//
// As a safeguard against using invalid indices, Set and Dictionary maintain a
// mutation counter in their storage header (`_age`). This counter gets bumped
// every time an element is removed and whenever the contents are
// rehashed. Native indices include a copy of this counter so that index
// validation can verify it matches with current storage. This can't catch all
// misuse, because counters may match by accident; but it does make indexing a
// lot more reliable.
//
// Bridging
// ========
//
// Bridging `NSDictionary` to `Dictionary`
// ---------------------------------------
//
// FIXME(eager-bridging): rewrite this based on modern constraints.
//
// `NSDictionary` bridges to `Dictionary<NSObject, AnyObject>` in `O(1)`,
// without memory allocation.
//
// Bridging to `Dictionary<AnyHashable, AnyObject>` takes `O(n)` time, as the
// keys need to be fully rehashed after conversion to `AnyHashable`.
//
// Bridging `NSDictionary` to `Dictionary<Key, Value>` is O(1) if both Key and
// Value are bridged verbatim.
//
// Bridging `Dictionary` to `NSDictionary`
// ---------------------------------------
//
// `Dictionary<K, V>` bridges to `NSDictionary` in O(1)
// but may incur an allocation depending on the following conditions:
//
// * If the Dictionary is freshly allocated without any elements, then it
// contains the empty singleton Storage which is returned as a toll-free
// implementation of `NSDictionary`.
//
// * If both `K` and `V` are bridged verbatim, then `Dictionary<K, V>` is
// still toll-free bridged to `NSDictionary` by returning its Storage.
//
// * If the Dictionary is actually a lazily bridged NSDictionary, then that
// NSDictionary is returned.
//
// * Otherwise, bridging the `Dictionary` is done by wrapping it in a
// `_SwiftDeferredNSDictionary<K, V>`. This incurs an O(1)-sized allocation.
//
// Complete bridging of the native Storage's elements to another Storage
// is performed on first access. This is O(n) work, but is hopefully amortized
// by future accesses.
//
// This design ensures that:
// - Every time keys or values are accessed on the bridged `NSDictionary`,
// new objects are not created.
// - Accessing the same element (key or value) multiple times will return
// the same pointer.
//
// Bridging `NSSet` to `Set` and vice versa
// ----------------------------------------
//
// Bridging guarantees for `Set<Element>` are the same as for
// `Dictionary<Element, NSObject>`.
//
/// A collection whose elements are key-value pairs.
///
/// A dictionary is a type of hash table, providing fast access to the entries
/// it contains. Each entry in the table is identified using its key, which is
/// a hashable type such as a string or number. You use that key to retrieve
/// the corresponding value, which can be any object. In other languages,
/// similar data types are known as hashes or associated arrays.
///
/// Create a new dictionary by using a dictionary literal. A dictionary literal
/// is a comma-separated list of key-value pairs, in which a colon separates
/// each key from its associated value, surrounded by square brackets. You can
/// assign a dictionary literal to a variable or constant or pass it to a
/// function that expects a dictionary.
///
/// Here's how you would create a dictionary of HTTP response codes and their
/// related messages:
///
/// var responseMessages = [200: "OK",
/// 403: "Access forbidden",
/// 404: "File not found",
/// 500: "Internal server error"]
///
/// The `responseMessages` variable is inferred to have type `[Int: String]`.
/// The `Key` type of the dictionary is `Int`, and the `Value` type of the
/// dictionary is `String`.
///
/// To create a dictionary with no key-value pairs, use an empty dictionary
/// literal (`[:]`).
///
/// var emptyDict: [String: String] = [:]
///
/// Any type that conforms to the `Hashable` protocol can be used as a
/// dictionary's `Key` type, including all of Swift's basic types. You can use
/// your own custom types as dictionary keys by making them conform to the
/// `Hashable` protocol.
///
/// Getting and Setting Dictionary Values
/// =====================================
///
/// The most common way to access values in a dictionary is to use a key as a
/// subscript. Subscripting with a key takes the following form:
///
/// print(responseMessages[200])
/// // Prints "Optional("OK")"
///
/// Subscripting a dictionary with a key returns an optional value, because a
/// dictionary might not hold a value for the key that you use in the
/// subscript.
///
/// The next example uses key-based subscripting of the `responseMessages`
/// dictionary with two keys that exist in the dictionary and one that does
/// not.
///
/// let httpResponseCodes = [200, 403, 301]
/// for code in httpResponseCodes {
/// if let message = responseMessages[code] {
/// print("Response \(code): \(message)")
/// } else {
/// print("Unknown response \(code)")
/// }
/// }
/// // Prints "Response 200: OK"
/// // Prints "Response 403: Access Forbidden"
/// // Prints "Unknown response 301"
///
/// You can also update, modify, or remove keys and values from a dictionary
/// using the key-based subscript. To add a new key-value pair, assign a value
/// to a key that isn't yet a part of the dictionary.
///
/// responseMessages[301] = "Moved permanently"
/// print(responseMessages[301])
/// // Prints "Optional("Moved permanently")"
///
/// Update an existing value by assigning a new value to a key that already
/// exists in the dictionary. If you assign `nil` to an existing key, the key
/// and its associated value are removed. The following example updates the
/// value for the `404` code to be simply "Not found" and removes the
/// key-value pair for the `500` code entirely.
///
/// responseMessages[404] = "Not found"
/// responseMessages[500] = nil
/// print(responseMessages)
/// // Prints "[301: "Moved permanently", 200: "OK", 403: "Access forbidden", 404: "Not found"]"
///
/// In a mutable `Dictionary` instance, you can modify in place a value that
/// you've accessed through a keyed subscript. The code sample below declares a
/// dictionary called `interestingNumbers` with string keys and values that
/// are integer arrays, then sorts each array in-place in descending order.
///
/// var interestingNumbers = ["primes": [2, 3, 5, 7, 11, 13, 17],
/// "triangular": [1, 3, 6, 10, 15, 21, 28],
/// "hexagonal": [1, 6, 15, 28, 45, 66, 91]]
/// for key in interestingNumbers.keys {
/// interestingNumbers[key]?.sort(by: >)
/// }
///
/// print(interestingNumbers["primes"]!)
/// // Prints "[17, 13, 11, 7, 5, 3, 2]"
///
/// Iterating Over the Contents of a Dictionary
/// ===========================================
///
/// Every dictionary is an unordered collection of key-value pairs. You can
/// iterate over a dictionary using a `for`-`in` loop, decomposing each
/// key-value pair into the elements of a tuple.
///
/// let imagePaths = ["star": "/glyphs/star.png",
/// "portrait": "/images/content/portrait.jpg",
/// "spacer": "/images/shared/spacer.gif"]
///
/// for (name, path) in imagePaths {
/// print("The path to '\(name)' is '\(path)'.")
/// }
/// // Prints "The path to 'star' is '/glyphs/star.png'."
/// // Prints "The path to 'portrait' is '/images/content/portrait.jpg'."
/// // Prints "The path to 'spacer' is '/images/shared/spacer.gif'."
///
/// The order of key-value pairs in a dictionary is stable between mutations
/// but is otherwise unpredictable. If you need an ordered collection of
/// key-value pairs and don't need the fast key lookup that `Dictionary`
/// provides, see the `KeyValuePairs` type for an alternative.
///
/// You can search a dictionary's contents for a particular value using the
/// `contains(where:)` or `firstIndex(where:)` methods supplied by default
/// implementation. The following example checks to see if `imagePaths` contains
/// any paths in the `"/glyphs"` directory:
///
/// let glyphIndex = imagePaths.firstIndex(where: { $0.value.hasPrefix("/glyphs") })
/// if let index = glyphIndex {
/// print("The '\(imagesPaths[index].key)' image is a glyph.")
/// } else {
/// print("No glyphs found!")
/// }
/// // Prints "The 'star' image is a glyph.")
///
/// Note that in this example, `imagePaths` is subscripted using a dictionary
/// index. Unlike the key-based subscript, the index-based subscript returns
/// the corresponding key-value pair as a non-optional tuple.
///
/// print(imagePaths[glyphIndex!])
/// // Prints "("star", "/glyphs/star.png")"
///
/// A dictionary's indices stay valid across additions to the dictionary as
/// long as the dictionary has enough capacity to store the added values
/// without allocating more buffer. When a dictionary outgrows its buffer,
/// existing indices may be invalidated without any notification.
///
/// When you know how many new values you're adding to a dictionary, use the
/// `init(minimumCapacity:)` initializer to allocate the correct amount of
/// buffer.
///
/// Bridging Between Dictionary and NSDictionary
/// ============================================
///
/// You can bridge between `Dictionary` and `NSDictionary` using the `as`
/// operator. For bridging to be possible, the `Key` and `Value` types of a
/// dictionary must be classes, `@objc` protocols, or types that bridge to
/// Foundation types.
///
/// Bridging from `Dictionary` to `NSDictionary` always takes O(1) time and
/// space. When the dictionary's `Key` and `Value` types are neither classes
/// nor `@objc` protocols, any required bridging of elements occurs at the
/// first access of each element. For this reason, the first operation that
/// uses the contents of the dictionary may take O(*n*).
///
/// Bridging from `NSDictionary` to `Dictionary` first calls the `copy(with:)`
/// method (`- copyWithZone:` in Objective-C) on the dictionary to get an
/// immutable copy and then performs additional Swift bookkeeping work that
/// takes O(1) time. For instances of `NSDictionary` that are already
/// immutable, `copy(with:)` usually returns the same dictionary in O(1) time;
/// otherwise, the copying performance is unspecified. The instances of
/// `NSDictionary` and `Dictionary` share buffer using the same copy-on-write
/// optimization that is used when two instances of `Dictionary` share
/// buffer.
@_fixed_layout
public struct Dictionary<Key: Hashable, Value> {
/// The element type of a dictionary: a tuple containing an individual
/// key-value pair.
public typealias Element = (key: Key, value: Value)
@usableFromInline
internal var _variant: _Variant
@inlinable
internal init(_native: __owned _NativeDictionary<Key, Value>) {
_variant = _Variant(native: _native)
}
#if _runtime(_ObjC)
@inlinable
internal init(_cocoa: __owned _CocoaDictionary) {
_variant = _Variant(cocoa: _cocoa)
}
/// Private initializer used for bridging.
///
/// Only use this initializer when both conditions are true:
///
/// * it is statically known that the given `NSDictionary` is immutable;
/// * `Key` and `Value` are bridged verbatim to Objective-C (i.e.,
/// are reference types).
@inlinable
public // SPI(Foundation)
init(_immutableCocoaDictionary: __owned AnyObject) {
_internalInvariant(
_isBridgedVerbatimToObjectiveC(Key.self) &&
_isBridgedVerbatimToObjectiveC(Value.self),
"""
Dictionary can be backed by NSDictionary buffer only when both Key \
and Value are bridged verbatim to Objective-C
""")
self.init(_cocoa: _CocoaDictionary(_immutableCocoaDictionary))
}
#endif
/// Creates an empty dictionary.
@inlinable
public init() {
self.init(_native: _NativeDictionary())
}
/// Creates an empty dictionary with preallocated space for at least the
/// specified number of elements.
///
/// Use this initializer to avoid intermediate reallocations of a dictionary's
/// storage buffer when you know how many key-value pairs you are adding to a
/// dictionary after creation.
///
/// - Parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
/// reallocating its storage buffer.
public // FIXME(reserveCapacity): Should be inlinable
init(minimumCapacity: Int) {
_variant = _Variant(native: _NativeDictionary(capacity: minimumCapacity))
}
/// Creates a new dictionary from the key-value pairs in the given sequence.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples with unique keys. Passing a sequence with duplicate
/// keys to this initializer results in a runtime error. If your
/// sequence might have duplicate keys, use the
/// `Dictionary(_:uniquingKeysWith:)` initializer instead.
///
/// The following example creates a new dictionary using an array of strings
/// as the keys and the integers in a countable range as the values:
///
/// let digitWords = ["one", "two", "three", "four", "five"]
/// let wordToValue = Dictionary(uniqueKeysWithValues: zip(digitWords, 1...5))
/// print(wordToValue["three"]!)
/// // Prints "3"
/// print(wordToValue)
/// // Prints "["three": 3, "four": 4, "five": 5, "one": 1, "two": 2]"
///
/// - Parameter keysAndValues: A sequence of key-value pairs to use for
/// the new dictionary. Every key in `keysAndValues` must be unique.
/// - Returns: A new dictionary initialized with the elements of
/// `keysAndValues`.
/// - Precondition: The sequence must not have duplicate keys.
@inlinable
public init<S: Sequence>(
uniqueKeysWithValues keysAndValues: __owned S
) where S.Element == (Key, Value) {
if let d = keysAndValues as? Dictionary<Key, Value> {
self = d
return
}
var native = _NativeDictionary<Key, Value>(
capacity: keysAndValues.underestimatedCount)
// '_MergeError.keyCollision' is caught and handled with an appropriate
// error message one level down, inside native.merge(_:...). We throw an
// error instead of calling fatalError() directly because we want the
// message to include the duplicate key, and the closure only has access to
// the conflicting values.
try! native.merge(
keysAndValues,
isUnique: true,
uniquingKeysWith: { _, _ in throw _MergeError.keyCollision })
self.init(_native: native)
}
/// Creates a new dictionary from the key-value pairs in the given sequence,
/// using a combining closure to determine the value for any duplicate keys.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples that might have duplicate keys. As the dictionary is
/// built, the initializer calls the `combine` closure with the current and
/// new values for any duplicate keys. Pass a closure as `combine` that
/// returns the value to use in the resulting dictionary: The closure can
/// choose between the two values, combine them to produce a new value, or
/// even throw an error.
///
/// The following example shows how to choose the first and last values for
/// any duplicate keys:
///
/// let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
///
/// let firstValues = Dictionary(pairsWithDuplicateKeys,
/// uniquingKeysWith: { (first, _) in first })
/// // ["b": 2, "a": 1]
///
/// let lastValues = Dictionary(pairsWithDuplicateKeys,
/// uniquingKeysWith: { (_, last) in last })
/// // ["b": 4, "a": 3]
///
/// - Parameters:
/// - keysAndValues: A sequence of key-value pairs to use for the new
/// dictionary.
/// - combine: A closure that is called with the values for any duplicate
/// keys that are encountered. The closure returns the desired value for
/// the final dictionary.
@inlinable
public init<S: Sequence>(
_ keysAndValues: __owned S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Element == (Key, Value) {
var native = _NativeDictionary<Key, Value>(
capacity: keysAndValues.underestimatedCount)
try native.merge(keysAndValues, isUnique: true, uniquingKeysWith: combine)
self.init(_native: native)
}
/// Creates a new dictionary whose keys are the groupings returned by the
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// The arrays in the "values" position of the new dictionary each contain at
/// least one element, with the elements in the same order as the source
/// sequence.
///
/// The following example declares an array of names, and then creates a
/// dictionary from that array by grouping the names by first letter:
///
/// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
/// let studentsByLetter = Dictionary(grouping: students, by: { $0.first! })
/// // ["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]]
///
/// The new `studentsByLetter` dictionary has three entries, with students'
/// names grouped by the keys `"E"`, `"K"`, and `"A"`.
///
/// - Parameters:
/// - values: A sequence of values to group into a dictionary.
/// - keyForValue: A closure that returns a key for each element in
/// `values`.
@inlinable
public init<S: Sequence>(
grouping values: __owned S,
by keyForValue: (S.Element) throws -> Key
) rethrows where Value == [S.Element] {
try self.init(_native: _NativeDictionary(grouping: values, by: keyForValue))
}
}
//
// All APIs below should dispatch to `_variant`, without doing any
// additional processing.
//
extension Dictionary: Sequence {
/// Returns an iterator over the dictionary's key-value pairs.
///
/// Iterating over a dictionary yields the key-value pairs as two-element
/// tuples. You can decompose the tuple in a `for`-`in` loop, which calls
/// `makeIterator()` behind the scenes, or when calling the iterator's
/// `next()` method directly.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// for (name, hueValue) in hues {
/// print("The hue of \(name) is \(hueValue).")
/// }
/// // Prints "The hue of Heliotrope is 296."
/// // Prints "The hue of Coral is 16."
/// // Prints "The hue of Aquamarine is 156."
///
/// - Returns: An iterator over the dictionary with elements of type
/// `(key: Key, value: Value)`.
@inlinable
@inline(__always)
public __consuming func makeIterator() -> Iterator {
return _variant.makeIterator()
}
}
// This is not quite Sequence.filter, because that returns [Element], not Self
extension Dictionary {
/// Returns a new dictionary containing the key-value pairs of the dictionary
/// that satisfy the given predicate.
///
/// - Parameter isIncluded: A closure that takes a key-value pair as its
/// argument and returns a Boolean value indicating whether the pair
/// should be included in the returned dictionary.
/// - Returns: A dictionary of the key-value pairs that `isIncluded` allows.
@inlinable
@available(swift, introduced: 4.0)
public __consuming func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Key: Value] {
// FIXME(performance): Try building a bitset of elements to keep, so that we
// eliminate rehashings during insertion.
var result = _NativeDictionary<Key, Value>()
for element in self {
if try isIncluded(element) {
result.insertNew(key: element.key, value: element.value)
}
}
return Dictionary(_native: result)
}
}
extension Dictionary: Collection {
public typealias SubSequence = Slice<Dictionary>
/// The position of the first element in a nonempty dictionary.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
///
/// - Complexity: Amortized O(1) if the dictionary does not wrap a bridged
/// `NSDictionary`. If the dictionary wraps a bridged `NSDictionary`, the
/// performance is unspecified.
@inlinable
public var startIndex: Index {
return _variant.startIndex
}
/// The dictionary's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
///
/// - Complexity: Amortized O(1) if the dictionary does not wrap a bridged
/// `NSDictionary`; otherwise, the performance is unspecified.
@inlinable
public var endIndex: Index {
return _variant.endIndex
}
@inlinable
public func index(after i: Index) -> Index {
return _variant.index(after: i)
}
@inlinable
public func formIndex(after i: inout Index) {
_variant.formIndex(after: &i)
}
/// Returns the index for the given key.
///
/// If the given key is found in the dictionary, this method returns an index
/// into the dictionary that corresponds with the key-value pair.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// let index = countryCodes.index(forKey: "JP")
///
/// print("Country code for \(countryCodes[index!].value): '\(countryCodes[index!].key)'.")
/// // Prints "Country code for Japan: 'JP'."
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The index for `key` and its associated value if `key` is in
/// the dictionary; otherwise, `nil`.
@inlinable
@inline(__always)
public func index(forKey key: Key) -> Index? {
// Complexity: amortized O(1) for native dictionary, O(*n*) when wrapping an
// NSDictionary.
return _variant.index(forKey: key)
}
/// Accesses the key-value pair at the specified position.
///
/// This subscript takes an index into the dictionary, instead of a key, and
/// returns the corresponding key-value pair as a tuple. When performing
/// collection-based operations that return an index into a dictionary, use
/// this subscript with the resulting value.
///
/// For example, to find the key for a particular value in a dictionary, use
/// the `firstIndex(where:)` method.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// if let index = countryCodes.firstIndex(where: { $0.value == "Japan" }) {
/// print(countryCodes[index])
/// print("Japan's country code is '\(countryCodes[index].key)'.")
/// } else {
/// print("Didn't find 'Japan' as a value in the dictionary.")
/// }
/// // Prints "("JP", "Japan")"
/// // Prints "Japan's country code is 'JP'."
///
/// - Parameter position: The position of the key-value pair to access.
/// `position` must be a valid index of the dictionary and not equal to
/// `endIndex`.
/// - Returns: A two-element tuple with the key and value corresponding to
/// `position`.
@inlinable
public subscript(position: Index) -> Element {
return _variant.lookup(position)
}
/// The number of key-value pairs in the dictionary.
///
/// - Complexity: O(1).
@inlinable
public var count: Int {
return _variant.count
}
//
// `Sequence` conformance
//
/// A Boolean value that indicates whether the dictionary is empty.
///
/// Dictionaries are empty when created with an initializer or an empty
/// dictionary literal.
///
/// var frequencies: [String: Int] = [:]
/// print(frequencies.isEmpty)
/// // Prints "true"
@inlinable
public var isEmpty: Bool {
return count == 0
}
}
extension Dictionary {
/// Accesses the value associated with the given key for reading and writing.
///
/// This *key-based* subscript returns the value for the given key if the key
/// is found in the dictionary, or `nil` if the key is not found.
///
/// The following example creates a new dictionary and prints the value of a
/// key found in the dictionary (`"Coral"`) and a key not found in the
/// dictionary (`"Cerise"`).
///
/// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// print(hues["Coral"])
/// // Prints "Optional(16)"
/// print(hues["Cerise"])
/// // Prints "nil"
///
/// When you assign a value for a key and that key already exists, the
/// dictionary overwrites the existing value. If the dictionary doesn't
/// contain the key, the key and value are added as a new key-value pair.
///
/// Here, the value for the key `"Coral"` is updated from `16` to `18` and a
/// new key-value pair is added for the key `"Cerise"`.
///
/// hues["Coral"] = 18
/// print(hues["Coral"])
/// // Prints "Optional(18)"
///
/// hues["Cerise"] = 330
/// print(hues["Cerise"])
/// // Prints "Optional(330)"
///
/// If you assign `nil` as the value for the given key, the dictionary
/// removes that key and its associated value.
///
/// In the following example, the key-value pair for the key `"Aquamarine"`
/// is removed from the dictionary by assigning `nil` to the key-based
/// subscript.
///
/// hues["Aquamarine"] = nil
/// print(hues)
/// // Prints "["Coral": 18, "Heliotrope": 296, "Cerise": 330]"
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The value associated with `key` if `key` is in the dictionary;
/// otherwise, `nil`.
@inlinable
public subscript(key: Key) -> Value? {
get {
return _variant.lookup(key)
}
set(newValue) {
if let x = newValue {
_variant.setValue(x, forKey: key)
} else {
removeValue(forKey: key)
}
}
_modify {
defer { _fixLifetime(self) }
yield &_variant[key]
}
}
}
extension Dictionary: ExpressibleByDictionaryLiteral {
/// Creates a dictionary initialized with a dictionary literal.
///
/// Do not call this initializer directly. It is called by the compiler to
/// handle dictionary literals. To use a dictionary literal as the initial
/// value of a dictionary, enclose a comma-separated list of key-value pairs
/// in square brackets.
///
/// For example, the code sample below creates a dictionary with string keys
/// and values.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// - Parameter elements: The key-value pairs that will make up the new
/// dictionary. Each key in `elements` must be unique.
@inlinable
@_effects(readonly)
@_semantics("optimize.sil.specialize.generic.size.never")
public init(dictionaryLiteral elements: (Key, Value)...) {
let native = _NativeDictionary<Key, Value>(capacity: elements.count)
for (key, value) in elements {
let (bucket, found) = native.find(key)
_precondition(!found, "Dictionary literal contains duplicate keys")
native._insert(at: bucket, key: key, value: value)
}
self.init(_native: native)
}
}
extension Dictionary {
/// Accesses the value with the given key. If the dictionary doesn't contain
/// the given key, accesses the provided default value as if the key and
/// default value existed in the dictionary.
///
/// Use this subscript when you want either the value for a particular key
/// or, when that key is not present in the dictionary, a default value. This
/// example uses the subscript with a message to use in case an HTTP response
/// code isn't recognized:
///
/// var responseMessages = [200: "OK",
/// 403: "Access forbidden",
/// 404: "File not found",
/// 500: "Internal server error"]
///
/// let httpResponseCodes = [200, 403, 301]
/// for code in httpResponseCodes {
/// let message = responseMessages[code, default: "Unknown response"]
/// print("Response \(code): \(message)")
/// }
/// // Prints "Response 200: OK"
/// // Prints "Response 403: Access Forbidden"
/// // Prints "Response 301: Unknown response"
///
/// When a dictionary's `Value` type has value semantics, you can use this
/// subscript to perform in-place operations on values in the dictionary.
/// The following example uses this subscript while counting the occurences
/// of each letter in a string:
///
/// let message = "Hello, Elle!"
/// var letterCounts: [Character: Int] = [:]
/// for letter in message {
/// letterCounts[letter, defaultValue: 0] += 1
/// }
/// // letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...]
///
/// When `letterCounts[letter, defaultValue: 0] += 1` is executed with a
/// value of `letter` that isn't already a key in `letterCounts`, the
/// specified default value (`0`) is returned from the subscript,
/// incremented, and then added to the dictionary under that key.
///
/// - Note: Do not use this subscript to modify dictionary values if the
/// dictionary's `Value` type is a class. In that case, the default value
/// and key are not written back to the dictionary after an operation.
///
/// - Parameters:
/// - key: The key the look up in the dictionary.
/// - defaultValue: The default value to use if `key` doesn't exist in the
/// dictionary.
/// - Returns: The value associated with `key` in the dictionary`; otherwise,
/// `defaultValue`.
@inlinable
public subscript(
key: Key, default defaultValue: @autoclosure () -> Value
) -> Value {
@inline(__always)
get {
return _variant.lookup(key) ?? defaultValue()
}
@inline(__always)
_modify {
let (bucket, found) = _variant.mutatingFind(key)
let native = _variant.asNative
if !found {
let value = defaultValue()
native._insert(at: bucket, key: key, value: value)
}
let address = native._values + bucket.offset
defer { _fixLifetime(self) }
yield &address.pointee
}
}
/// Returns a new dictionary containing the keys of this dictionary with the
/// values transformed by the given closure.
///
/// - Parameter transform: A closure that transforms a value. `transform`
/// accepts each value of the dictionary as its parameter and returns a
/// transformed value of the same or of a different type.
/// - Returns: A dictionary containing the keys and transformed values of
/// this dictionary.
///
/// - Complexity: O(*n*), where *n* is the length of the dictionary.
@inlinable
public func mapValues<T>(
_ transform: (Value) throws -> T
) rethrows -> Dictionary<Key, T> {
return try Dictionary<Key, T>(_native: _variant.mapValues(transform))
}
/// Returns a new dictionary containing only the key-value pairs that have
/// non-`nil` values as the result from the transform by the given closure.
///
/// Use this method to receive a dictionary of non-optional values when your
/// transformation can produce an optional value.
///
/// In this example, note the difference in the result of using `mapValues`
/// and `compactMapValues` with a transformation that returns an optional
/// `Int` value.
///
/// let data = ["a": "1", "b": "three", "c": "///4///"]
///
/// let m: [String: Int?] = data.mapValues { str in Int(str) }
/// // ["a": 1, "b": nil, "c": nil]
///
/// let c: [String: Int] = data.compactMapValues { str in Int(str) }
/// // ["a": 1]
///
/// - Parameter transform: A closure that transforms a value. `transform`
/// accepts each value of the dictionary as its parameter and returns an
/// optional transformed value of the same or of a different type.
/// - Returns: A dictionary containing the keys and non-`nil` transformed
/// values of this dictionary.
///
/// - Complexity: O(*m* + *n*), where *n* is the length of the original
/// dictionary and *m* is the length of the resulting dictionary.
@inlinable
public func compactMapValues<T>(
_ transform: (Value) throws -> T?
) rethrows -> Dictionary<Key, T> {
let result: _NativeDictionary<Key, T> =
try self.reduce(into: _NativeDictionary<Key, T>()) { (result, element) in
if let value = try transform(element.value) {
result.insertNew(key: element.key, value: value)
}
}
return Dictionary<Key, T>(_native: result)
}
/// Updates the value stored in the dictionary for the given key, or adds a
/// new key-value pair if the key does not exist.
///
/// Use this method instead of key-based subscripting when you need to know
/// whether the new value supplants the value of an existing key. If the
/// value of an existing key is updated, `updateValue(_:forKey:)` returns
/// the original value.
///
/// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
///
/// if let oldValue = hues.updateValue(18, forKey: "Coral") {
/// print("The old value of \(oldValue) was replaced with a new one.")
/// }
/// // Prints "The old value of 16 was replaced with a new one."
///
/// If the given key is not present in the dictionary, this method adds the
/// key-value pair and returns `nil`.
///
/// if let oldValue = hues.updateValue(330, forKey: "Cerise") {
/// print("The old value of \(oldValue) was replaced with a new one.")
/// } else {
/// print("No value was found in the dictionary for that key.")
/// }
/// // Prints "No value was found in the dictionary for that key."
///
/// - Parameters:
/// - value: The new value to add to the dictionary.
/// - key: The key to associate with `value`. If `key` already exists in
/// the dictionary, `value` replaces the existing associated value. If
/// `key` isn't already a key of the dictionary, the `(key, value)` pair
/// is added.
/// - Returns: The value that was replaced, or `nil` if a new key-value pair
/// was added.
@inlinable
@discardableResult
public mutating func updateValue(
_ value: __owned Value,
forKey key: Key
) -> Value? {
return _variant.updateValue(value, forKey: key)
}
/// Merges the key-value pairs in the given sequence into the dictionary,
/// using a combining closure to determine the value for any duplicate keys.
///
/// Use the `combine` closure to select a value to use in the updated
/// dictionary, or to combine existing and new values. As the key-value
/// pairs are merged with the dictionary, the `combine` closure is called
/// with the current and new values for any duplicate keys that are
/// encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// var dictionary = ["a": 1, "b": 2]
///
/// // Keeping existing value for key "a":
/// dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current }
/// // ["b": 2, "a": 1, "c": 4]
///
/// // Taking the new value for key "a":
/// dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new }
/// // ["b": 2, "a": 5, "c": 4, "d": 6]
///
/// - Parameters:
/// - other: A sequence of key-value pairs.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
@inlinable
public mutating func merge<S: Sequence>(
_ other: __owned S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Element == (Key, Value) {
try _variant.merge(other, uniquingKeysWith: combine)
}
/// Merges the given dictionary into this dictionary, using a combining
/// closure to determine the value for any duplicate keys.
///
/// Use the `combine` closure to select a value to use in the updated
/// dictionary, or to combine existing and new values. As the key-values
/// pairs in `other` are merged with this dictionary, the `combine` closure
/// is called with the current and new values for any duplicate keys that
/// are encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// var dictionary = ["a": 1, "b": 2]
///
/// // Keeping existing value for key "a":
/// dictionary.merge(["a": 3, "c": 4]) { (current, _) in current }
/// // ["b": 2, "a": 1, "c": 4]
///
/// // Taking the new value for key "a":
/// dictionary.merge(["a": 5, "d": 6]) { (_, new) in new }
/// // ["b": 2, "a": 5, "c": 4, "d": 6]
///
/// - Parameters:
/// - other: A dictionary to merge.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
@inlinable
public mutating func merge(
_ other: __owned [Key: Value],
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows {
try _variant.merge(
other.lazy.map { ($0, $1) }, uniquingKeysWith: combine)
}
/// Creates a dictionary by merging key-value pairs in a sequence into the
/// dictionary, using a combining closure to determine the value for
/// duplicate keys.
///
/// Use the `combine` closure to select a value to use in the returned
/// dictionary, or to combine existing and new values. As the key-value
/// pairs are merged with the dictionary, the `combine` closure is called
/// with the current and new values for any duplicate keys that are
/// encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// let dictionary = ["a": 1, "b": 2]
/// let newKeyValues = zip(["a", "b"], [3, 4])
///
/// let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
/// // ["b": 2, "a": 1]
/// let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
/// // ["b": 4, "a": 3]
///
/// - Parameters:
/// - other: A sequence of key-value pairs.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
/// - Returns: A new dictionary with the combined keys and values of this
/// dictionary and `other`.
@inlinable
public __consuming func merging<S: Sequence>(
_ other: __owned S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows -> [Key: Value] where S.Element == (Key, Value) {
var result = self
try result._variant.merge(other, uniquingKeysWith: combine)
return result
}
/// Creates a dictionary by merging the given dictionary into this
/// dictionary, using a combining closure to determine the value for
/// duplicate keys.
///
/// Use the `combine` closure to select a value to use in the returned
/// dictionary, or to combine existing and new values. As the key-value
/// pairs in `other` are merged with this dictionary, the `combine` closure
/// is called with the current and new values for any duplicate keys that
/// are encountered.
///
/// This example shows how to choose the current or new values for any
/// duplicate keys:
///
/// let dictionary = ["a": 1, "b": 2]
/// let otherDictionary = ["a": 3, "b": 4]
///
/// let keepingCurrent = dictionary.merging(otherDictionary)
/// { (current, _) in current }
/// // ["b": 2, "a": 1]
/// let replacingCurrent = dictionary.merging(otherDictionary)
/// { (_, new) in new }
/// // ["b": 4, "a": 3]
///
/// - Parameters:
/// - other: A dictionary to merge.
/// - combine: A closure that takes the current and new values for any
/// duplicate keys. The closure returns the desired value for the final
/// dictionary.
/// - Returns: A new dictionary with the combined keys and values of this
/// dictionary and `other`.
@inlinable
public __consuming func merging(
_ other: __owned [Key: Value],
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows -> [Key: Value] {
var result = self
try result.merge(other, uniquingKeysWith: combine)
return result
}
/// Removes and returns the key-value pair at the specified index.
///
/// Calling this method invalidates any existing indices for use with this
/// dictionary.
///
/// - Parameter index: The position of the key-value pair to remove. `index`
/// must be a valid index of the dictionary, and must not equal the
/// dictionary's end index.
/// - Returns: The key-value pair that correspond to `index`.
///
/// - Complexity: O(*n*), where *n* is the number of key-value pairs in the
/// dictionary.
@inlinable
@discardableResult
public mutating func remove(at index: Index) -> Element {
return _variant.remove(at: index)
}
/// Removes the given key and its associated value from the dictionary.
///
/// If the key is found in the dictionary, this method returns the key's
/// associated value. On removal, this method invalidates all indices with
/// respect to the dictionary.
///
/// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// if let value = hues.removeValue(forKey: "Coral") {
/// print("The value \(value) was removed.")
/// }
/// // Prints "The value 16 was removed."
///
/// If the key isn't found in the dictionary, `removeValue(forKey:)` returns
/// `nil`.
///
/// if let value = hues.removeValueForKey("Cerise") {
/// print("The value \(value) was removed.")
/// } else {
/// print("No value found for that key.")
/// }
/// // Prints "No value found for that key.""
///
/// - Parameter key: The key to remove along with its associated value.
/// - Returns: The value that was removed, or `nil` if the key was not
/// present in the dictionary.
///
/// - Complexity: O(*n*), where *n* is the number of key-value pairs in the
/// dictionary.
@inlinable
@discardableResult
public mutating func removeValue(forKey key: Key) -> Value? {
return _variant.removeValue(forKey: key)
}
/// Removes all key-value pairs from the dictionary.
///
/// Calling this method invalidates all indices with respect to the
/// dictionary.
///
/// - Parameter keepCapacity: Whether the dictionary should keep its
/// underlying buffer. If you pass `true`, the operation preserves the
/// buffer capacity that the collection has, otherwise the underlying
/// buffer is released. The default is `false`.
///
/// - Complexity: O(*n*), where *n* is the number of key-value pairs in the
/// dictionary.
@inlinable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
// The 'will not decrease' part in the documentation comment is worded very
// carefully. The capacity can increase if we replace Cocoa dictionary with
// native dictionary.
_variant.removeAll(keepingCapacity: keepCapacity)
}
}
extension Dictionary {
/// A collection containing just the keys of the dictionary.
///
/// When iterated over, keys appear in this collection in the same order as
/// they occur in the dictionary's key-value pairs. Each key in the keys
/// collection has a unique value.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// for k in countryCodes.keys {
/// print(k)
/// }
/// // Prints "BR"
/// // Prints "JP"
/// // Prints "GH"
@inlinable
@available(swift, introduced: 4.0)
public var keys: Keys {
// FIXME(accessors): Provide a _read
get {
return Keys(_dictionary: self)
}
}
/// A collection containing just the values of the dictionary.
///
/// When iterated over, values appear in this collection in the same order as
/// they occur in the dictionary's key-value pairs.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// for v in countryCodes.values {
/// print(v)
/// }
/// // Prints "Brazil"
/// // Prints "Japan"
/// // Prints "Ghana"
@inlinable
@available(swift, introduced: 4.0)
public var values: Values {
// FIXME(accessors): Provide a _read
get {
return Values(_dictionary: self)
}
_modify {
var values = Values(_variant: _Variant(dummy: ()))
swap(&values._variant, &_variant)
defer { self._variant = values._variant }
yield &values
}
}
/// A view of a dictionary's keys.
@_fixed_layout
public struct Keys
: Collection, Equatable,
CustomStringConvertible, CustomDebugStringConvertible {
public typealias Element = Key
public typealias SubSequence = Slice<Dictionary.Keys>
@usableFromInline
internal var _variant: Dictionary<Key, Value>._Variant
@inlinable
internal init(_dictionary: __owned Dictionary) {
self._variant = _dictionary._variant
}
// Collection Conformance
// ----------------------
@inlinable
public var startIndex: Index {
return _variant.startIndex
}
@inlinable
public var endIndex: Index {
return _variant.endIndex
}
@inlinable
public func index(after i: Index) -> Index {
return _variant.index(after: i)
}
@inlinable
public func formIndex(after i: inout Index) {
_variant.formIndex(after: &i)
}
@inlinable
public subscript(position: Index) -> Element {
return _variant.key(at: position)
}
// Customization
// -------------
/// The number of keys in the dictionary.
///
/// - Complexity: O(1).
@inlinable
public var count: Int {
return _variant.count
}
@inlinable
public var isEmpty: Bool {
return count == 0
}
@inlinable
@inline(__always)
public func _customContainsEquatableElement(_ element: Element) -> Bool? {
return _variant.contains(element)
}
@inlinable
@inline(__always)
public func _customIndexOfEquatableElement(_ element: Element) -> Index?? {
return Optional(_variant.index(forKey: element))
}
@inlinable
@inline(__always)
public func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? {
// The first and last elements are the same because each element is unique.
return _customIndexOfEquatableElement(element)
}
@inlinable
public static func ==(lhs: Keys, rhs: Keys) -> Bool {
// Equal if the two dictionaries share storage.
#if _runtime(_ObjC)
if
lhs._variant.isNative,
rhs._variant.isNative,
lhs._variant.asNative._storage === rhs._variant.asNative._storage
{
return true
}
if
!lhs._variant.isNative,
!rhs._variant.isNative,
lhs._variant.asCocoa.object === rhs._variant.asCocoa.object
{
return true
}
#else
if lhs._variant.asNative._storage === rhs._variant.asNative._storage {
return true
}
#endif
// Not equal if the dictionaries are different sizes.
if lhs.count != rhs.count {
return false
}
// Perform unordered comparison of keys.
for key in lhs {
if !rhs.contains(key) {
return false
}
}
return true
}
public var description: String {
return _makeCollectionDescription()
}
public var debugDescription: String {
return _makeCollectionDescription(withTypeName: "Dictionary.Keys")
}
}
/// A view of a dictionary's values.
@_fixed_layout
public struct Values
: MutableCollection, CustomStringConvertible, CustomDebugStringConvertible {
public typealias Element = Value
@usableFromInline
internal var _variant: Dictionary<Key, Value>._Variant
@inlinable
internal init(_variant: __owned Dictionary<Key, Value>._Variant) {
self._variant = _variant
}
@inlinable
internal init(_dictionary: __owned Dictionary) {
self._variant = _dictionary._variant
}
// Collection Conformance
// ----------------------
@inlinable
public var startIndex: Index {
return _variant.startIndex
}
@inlinable
public var endIndex: Index {
return _variant.endIndex
}
@inlinable
public func index(after i: Index) -> Index {
return _variant.index(after: i)
}
@inlinable
public func formIndex(after i: inout Index) {
_variant.formIndex(after: &i)
}
@inlinable
public subscript(position: Index) -> Element {
// FIXME(accessors): Provide a _read
get {
return _variant.value(at: position)
}
_modify {
let native = _variant.ensureUniqueNative()
let bucket = native.validatedBucket(for: position)
let address = native._values + bucket.offset
defer { _fixLifetime(self) }
yield &address.pointee
}
}
// Customization
// -------------
/// The number of values in the dictionary.
///
/// - Complexity: O(1).
@inlinable
public var count: Int {
return _variant.count
}
@inlinable
public var isEmpty: Bool {
return count == 0
}
public var description: String {
return _makeCollectionDescription()
}
public var debugDescription: String {
return _makeCollectionDescription(withTypeName: "Dictionary.Values")
}
@inlinable
public mutating func swapAt(_ i: Index, _ j: Index) {
guard i != j else { return }
#if _runtime(_ObjC)
if !_variant.isNative {
_variant = .init(native: _NativeDictionary(_variant.asCocoa))
}
#endif
let isUnique = _variant.isUniquelyReferenced()
let native = _variant.asNative
let a = native.validatedBucket(for: i)
let b = native.validatedBucket(for: j)
_variant.asNative.swapValuesAt(a, b, isUnique: isUnique)
}
}
}
extension Dictionary.Keys {
@_fixed_layout
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _base: Dictionary<Key, Value>.Iterator
@inlinable
@inline(__always)
internal init(_ base: Dictionary<Key, Value>.Iterator) {
self._base = base
}
@inlinable
@inline(__always)
public mutating func next() -> Key? {
#if _runtime(_ObjC)
if case .cocoa(let cocoa) = _base._variant {
_base._cocoaPath()
guard let cocoaKey = cocoa.nextKey() else { return nil }
return _forceBridgeFromObjectiveC(cocoaKey, Key.self)
}
#endif
return _base._asNative.nextKey()
}
}
@inlinable
@inline(__always)
public __consuming func makeIterator() -> Iterator {
return Iterator(_variant.makeIterator())
}
}
extension Dictionary.Values {
@_fixed_layout
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _base: Dictionary<Key, Value>.Iterator
@inlinable
@inline(__always)
internal init(_ base: Dictionary<Key, Value>.Iterator) {
self._base = base
}
@inlinable
@inline(__always)
public mutating func next() -> Value? {
#if _runtime(_ObjC)
if case .cocoa(let cocoa) = _base._variant {
_base._cocoaPath()
guard let (_, cocoaValue) = cocoa.next() else { return nil }
return _forceBridgeFromObjectiveC(cocoaValue, Value.self)
}
#endif
return _base._asNative.nextValue()
}
}
@inlinable
@inline(__always)
public __consuming func makeIterator() -> Iterator {
return Iterator(_variant.makeIterator())
}
}
extension Dictionary: Equatable where Value: Equatable {
@inlinable
public static func == (lhs: [Key: Value], rhs: [Key: Value]) -> Bool {
#if _runtime(_ObjC)
switch (lhs._variant.isNative, rhs._variant.isNative) {
case (true, true):
return lhs._variant.asNative.isEqual(to: rhs._variant.asNative)
case (false, false):
return lhs._variant.asCocoa.isEqual(to: rhs._variant.asCocoa)
case (true, false):
return lhs._variant.asNative.isEqual(to: rhs._variant.asCocoa)
case (false, true):
return rhs._variant.asNative.isEqual(to: lhs._variant.asCocoa)
}
#else
return lhs._variant.asNative.isEqual(to: rhs._variant.asNative)
#endif
}
}
extension Dictionary: Hashable where Value: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
var commutativeHash = 0
for (k, v) in self {
// Note that we use a copy of our own hasher here. This makes hash values
// dependent on its state, eliminating static collision patterns.
var elementHasher = hasher
elementHasher.combine(k)
elementHasher.combine(v)
commutativeHash ^= elementHasher._finalize()
}
hasher.combine(commutativeHash)
}
}
extension Dictionary: _HasCustomAnyHashableRepresentation
where Value: Hashable {
public __consuming func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(_box: _DictionaryAnyHashableBox(self))
}
}
internal struct _DictionaryAnyHashableBox<Key: Hashable, Value: Hashable>
: _AnyHashableBox {
internal let _value: Dictionary<Key, Value>
internal let _canonical: Dictionary<AnyHashable, AnyHashable>
internal init(_ value: __owned Dictionary<Key, Value>) {
self._value = value
self._canonical = value as Dictionary<AnyHashable, AnyHashable>
}
internal var _base: Any {
return _value
}
internal var _canonicalBox: _AnyHashableBox {
return _DictionaryAnyHashableBox<AnyHashable, AnyHashable>(_canonical)
}
internal func _isEqual(to other: _AnyHashableBox) -> Bool? {
guard
let other = other as? _DictionaryAnyHashableBox<AnyHashable, AnyHashable>
else {
return nil
}
return _canonical == other._value
}
internal var _hashValue: Int {
return _canonical.hashValue
}
internal func _hash(into hasher: inout Hasher) {
_canonical.hash(into: &hasher)
}
internal func _rawHashValue(_seed: Int) -> Int {
return _canonical._rawHashValue(seed: _seed)
}
internal func _unbox<T: Hashable>() -> T? {
return _value as? T
}
internal func _downCastConditional<T>(
into result: UnsafeMutablePointer<T>
) -> Bool {
guard let value = _value as? T else { return false }
result.initialize(to: value)
return true
}
}
extension Collection {
// Utility method for KV collections that wish to implement
// CustomStringConvertible and CustomDebugStringConvertible using a bracketed
// list of elements.
// FIXME: Doesn't use the withTypeName argument yet
internal func _makeKeyValuePairDescription<K, V>(
withTypeName type: String? = nil
) -> String where Element == (key: K, value: V) {
if self.count == 0 {
return "[:]"
}
var result = "["
var first = true
for (k, v) in self {
if first {
first = false
} else {
result += ", "
}
debugPrint(k, terminator: "", to: &result)
result += ": "
debugPrint(v, terminator: "", to: &result)
}
result += "]"
return result
}
}
extension Dictionary: CustomStringConvertible, CustomDebugStringConvertible {
/// A string that represents the contents of the dictionary.
public var description: String {
return _makeKeyValuePairDescription()
}
/// A string that represents the contents of the dictionary, suitable for
/// debugging.
public var debugDescription: String {
return _makeKeyValuePairDescription()
}
}
@usableFromInline
@_frozen
internal enum _MergeError: Error {
case keyCollision
}
extension Dictionary {
/// The position of a key-value pair in a dictionary.
///
/// Dictionary has two subscripting interfaces:
///
/// 1. Subscripting with a key, yielding an optional value:
///
/// v = d[k]!
///
/// 2. Subscripting with an index, yielding a key-value pair:
///
/// (k, v) = d[i]
@_fixed_layout
public struct Index {
// Index for native dictionary is efficient. Index for bridged NSDictionary
// is not, because neither NSEnumerator nor fast enumeration support moving
// backwards. Even if they did, there is another issue: NSEnumerator does
// not support NSCopying, and fast enumeration does not document that it is
// safe to copy the state. So, we cannot implement Index that is a value
// type for bridged NSDictionary in terms of Cocoa enumeration facilities.
@_frozen
@usableFromInline
internal enum _Variant {
case native(_HashTable.Index)
#if _runtime(_ObjC)
case cocoa(_CocoaDictionary.Index)
#endif
}
@usableFromInline
internal var _variant: _Variant
@inlinable
@inline(__always)
internal init(_variant: __owned _Variant) {
self._variant = _variant
}
@inlinable
@inline(__always)
internal init(_native index: _HashTable.Index) {
self.init(_variant: .native(index))
}
#if _runtime(_ObjC)
@inlinable
@inline(__always)
internal init(_cocoa index: __owned _CocoaDictionary.Index) {
self.init(_variant: .cocoa(index))
}
#endif
}
}
extension Dictionary.Index {
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var _guaranteedNative: Bool {
return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0
}
// Allow the optimizer to consider the surrounding code unreachable if Element
// is guaranteed to be native.
@usableFromInline @_transparent
internal func _cocoaPath() {
if _guaranteedNative {
_conditionallyUnreachable()
}
}
@inlinable
@inline(__always)
internal mutating func _isUniquelyReferenced() -> Bool {
defer { _fixLifetime(self) }
var handle = _asCocoa.handleBitPattern
return handle == 0 || _isUnique_native(&handle)
}
@usableFromInline @_transparent
internal var _isNative: Bool {
switch _variant {
case .native:
return true
case .cocoa:
_cocoaPath()
return false
}
}
#endif
@usableFromInline @_transparent
internal var _asNative: _HashTable.Index {
switch _variant {
case .native(let nativeIndex):
return nativeIndex
#if _runtime(_ObjC)
case .cocoa:
_preconditionFailure(
"Attempting to access Dictionary elements using an invalid index")
#endif
}
}
#if _runtime(_ObjC)
@usableFromInline
internal var _asCocoa: _CocoaDictionary.Index {
@_transparent
get {
switch _variant {
case .native:
_preconditionFailure(
"Attempting to access Dictionary elements using an invalid index")
case .cocoa(let cocoaIndex):
return cocoaIndex
}
}
_modify {
guard case .cocoa(var cocoa) = _variant else {
_preconditionFailure(
"Attempting to access Dictionary elements using an invalid index")
}
let dummy = _HashTable.Index(bucket: _HashTable.Bucket(offset: 0), age: 0)
_variant = .native(dummy)
defer { _variant = .cocoa(cocoa) }
yield &cocoa
}
}
#endif
}
extension Dictionary.Index: Equatable {
@inlinable
public static func == (
lhs: Dictionary<Key, Value>.Index,
rhs: Dictionary<Key, Value>.Index
) -> Bool {
switch (lhs._variant, rhs._variant) {
case (.native(let lhsNative), .native(let rhsNative)):
return lhsNative == rhsNative
#if _runtime(_ObjC)
case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)):
lhs._cocoaPath()
return lhsCocoa == rhsCocoa
default:
_preconditionFailure("Comparing indexes from different dictionaries")
#endif
}
}
}
extension Dictionary.Index: Comparable {
@inlinable
public static func < (
lhs: Dictionary<Key, Value>.Index,
rhs: Dictionary<Key, Value>.Index
) -> Bool {
switch (lhs._variant, rhs._variant) {
case (.native(let lhsNative), .native(let rhsNative)):
return lhsNative < rhsNative
#if _runtime(_ObjC)
case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)):
lhs._cocoaPath()
return lhsCocoa < rhsCocoa
default:
_preconditionFailure("Comparing indexes from different dictionaries")
#endif
}
}
}
extension Dictionary.Index: Hashable {
public // FIXME(cocoa-index): Make inlinable
func hash(into hasher: inout Hasher) {
#if _runtime(_ObjC)
guard _isNative else {
hasher.combine(1 as UInt8)
hasher.combine(_asCocoa._offset)
return
}
hasher.combine(0 as UInt8)
hasher.combine(_asNative.bucket.offset)
#else
hasher.combine(_asNative.bucket.offset)
#endif
}
}
extension Dictionary {
/// An iterator over the members of a `Dictionary<Key, Value>`.
@_fixed_layout
public struct Iterator {
// Dictionary has a separate IteratorProtocol and Index because of
// efficiency and implementability reasons.
//
// Native dictionaries have efficient indices.
// Bridged NSDictionary instances don't.
//
// Even though fast enumeration is not suitable for implementing
// Index, which is multi-pass, it is suitable for implementing a
// IteratorProtocol, which is being consumed as iteration proceeds.
@usableFromInline
@_frozen
internal enum _Variant {
case native(_NativeDictionary<Key, Value>.Iterator)
#if _runtime(_ObjC)
case cocoa(_CocoaDictionary.Iterator)
#endif
}
@usableFromInline
internal var _variant: _Variant
@inlinable
internal init(_variant: __owned _Variant) {
self._variant = _variant
}
@inlinable
internal init(_native: __owned _NativeDictionary<Key, Value>.Iterator) {
self.init(_variant: .native(_native))
}
#if _runtime(_ObjC)
@inlinable
internal init(_cocoa: __owned _CocoaDictionary.Iterator) {
self.init(_variant: .cocoa(_cocoa))
}
#endif
}
}
extension Dictionary.Iterator {
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var _guaranteedNative: Bool {
return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0
}
/// Allow the optimizer to consider the surrounding code unreachable if
/// Dictionary<Key, Value> is guaranteed to be native.
@usableFromInline @_transparent
internal func _cocoaPath() {
if _guaranteedNative {
_conditionallyUnreachable()
}
}
@usableFromInline @_transparent
internal var _isNative: Bool {
switch _variant {
case .native:
return true
case .cocoa:
_cocoaPath()
return false
}
}
#endif
@usableFromInline @_transparent
internal var _asNative: _NativeDictionary<Key, Value>.Iterator {
get {
switch _variant {
case .native(let nativeIterator):
return nativeIterator
#if _runtime(_ObjC)
case .cocoa:
_internalInvariantFailure("internal error: does not contain a native index")
#endif
}
}
set {
self._variant = .native(newValue)
}
}
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var _asCocoa: _CocoaDictionary.Iterator {
get {
switch _variant {
case .native:
_internalInvariantFailure("internal error: does not contain a Cocoa index")
case .cocoa(let cocoa):
return cocoa
}
}
}
#endif
}
extension Dictionary.Iterator: IteratorProtocol {
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable
@inline(__always)
public mutating func next() -> (key: Key, value: Value)? {
#if _runtime(_ObjC)
guard _isNative else {
if let (cocoaKey, cocoaValue) = _asCocoa.next() {
let nativeKey = _forceBridgeFromObjectiveC(cocoaKey, Key.self)
let nativeValue = _forceBridgeFromObjectiveC(cocoaValue, Value.self)
return (nativeKey, nativeValue)
}
return nil
}
#endif
return _asNative.next()
}
}
extension Dictionary.Iterator: CustomReflectable {
/// A mirror that reflects the iterator.
public var customMirror: Mirror {
return Mirror(
self,
children: EmptyCollection<(label: String?, value: Any)>())
}
}
extension Dictionary: CustomReflectable {
/// A mirror that reflects the dictionary.
public var customMirror: Mirror {
let style = Mirror.DisplayStyle.dictionary
return Mirror(self, unlabeledChildren: self, displayStyle: style)
}
}
extension Dictionary {
/// Removes and returns the first key-value pair of the dictionary if the
/// dictionary isn't empty.
///
/// The first element of the dictionary is not necessarily the first element
/// added. Don't expect any particular ordering of key-value pairs.
///
/// - Returns: The first key-value pair of the dictionary if the dictionary
/// is not empty; otherwise, `nil`.
///
/// - Complexity: Averages to O(1) over many calls to `popFirst()`.
@inlinable
public mutating func popFirst() -> Element? {
guard !isEmpty else { return nil }
return remove(at: startIndex)
}
/// The total number of key-value pairs that the dictionary can contain without
/// allocating new storage.
@inlinable
public var capacity: Int {
return _variant.capacity
}
/// Reserves enough space to store the specified number of key-value pairs.
///
/// If you are adding a known number of key-value pairs to a dictionary, use this
/// method to avoid multiple reallocations. This method ensures that the
/// dictionary has unique, mutable, contiguous storage, with space allocated
/// for at least the requested number of key-value pairs.
///
/// Calling the `reserveCapacity(_:)` method on a dictionary with bridged
/// storage triggers a copy to contiguous storage even if the existing
/// storage has room to store `minimumCapacity` key-value pairs.
///
/// - Parameter minimumCapacity: The requested number of key-value pairs to
/// store.
public // FIXME(reserveCapacity): Should be inlinable
mutating func reserveCapacity(_ minimumCapacity: Int) {
_variant.reserveCapacity(minimumCapacity)
_internalInvariant(self.capacity >= minimumCapacity)
}
}
public typealias DictionaryIndex<Key: Hashable, Value> =
Dictionary<Key, Value>.Index
public typealias DictionaryIterator<Key: Hashable, Value> =
Dictionary<Key, Value>.Iterator
| apache-2.0 | c6da6f1df26aee2148a659e9a267366b | 34.307949 | 126 | 0.631797 | 4.246251 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/BaseTest/BaseTest/Class_Struct_Enum/AttributeSummary.swift | 1 | 1388 | //
// AttributeSummary.swift
// BaseTest
//
// Created by wuyp on 2016/12/16.
// Copyright © 2016年 raymond. All rights reserved.
//
import Foundation
class Student: NSObject {
var id: Int
var name:String
var score:Float
init(id:Int = 0, name:String = "", score:Float = 0) {
self.id = id
self.name = name
self.score = score
}
}
class Group: NSObject {
deinit {
}
/// 容器
lazy var stuArray:Array<Student>? = {
return [Student]()
}()
/// 索引器
subscript(index: Int) -> Student? {
get {
if !((stuArray?.isEmpty)!) && (stuArray?.count)! < index {
return stuArray?[index]
}
return nil
}
set(newValue) {
checkArray(index: index)
stuArray?[index] = newValue!
}
}
private func checkArray(index: Int) {
let range = abs((self.stuArray?.count)! - 1 - index)
for _ in 0...range {
self.stuArray?.append(Student())
}
}
}
/*******/
class TestAttributeSummary {
class func testSubscript() {
let group = Group()
for i in 0...5 {
let temp = Student(id: i, name: "Jack\(i)", score: Float(arc4random() % 100))
group[i] = temp
}
}
}
| apache-2.0 | cacdff235280c1a16a17b3164b61d558 | 18.642857 | 89 | 0.481455 | 3.928571 | false | false | false | false |
marcbaldwin/AutoLayoutBuilder | AutoLayoutBuilder/LayoutGuideExpression.swift | 1 | 578 | import UIKit
public class LayoutGuideExpression {
let layoutGuide: UILayoutSupport
let attribute: VerticalAttribute
var constant: CGFloat = 0
init(layoutGuide: UILayoutSupport, attribute: VerticalAttribute) {
self.layoutGuide = layoutGuide
self.attribute = attribute
}
}
// MARK: Operators
public func +(lhs: LayoutGuideExpression, rhs: CGFloat) -> LayoutGuideExpression {
lhs.constant = rhs
return lhs
}
public func -(lhs: LayoutGuideExpression, rhs: CGFloat) -> LayoutGuideExpression {
lhs.constant = -rhs
return lhs
} | mit | fd61f50e82c39b116e61540e298c1a76 | 22.16 | 82 | 0.714533 | 4.77686 | false | false | false | false |
Ju2ender/objective-c-e | SnapKit-0.13.0/Source/ConstraintMaker.swift | 2 | 9222 | //
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS)
import UIKit
#else
import AppKit
#endif
/**
Used to make constraints
*/
public class ConstraintMaker {
/// left edge
public var left: ConstraintDescriptionExtendable {
return self.makeConstraintDescription(ConstraintAttributes.Left)
}
/// top edge
public var top: ConstraintDescriptionExtendable {
return self.makeConstraintDescription(ConstraintAttributes.Top)
}
/// right edge
public var right: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Right) }
/// bottom edge
public var bottom: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Bottom) }
/// leading edge
public var leading: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Leading) }
/// trailing edge
public var trailing: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Trailing) }
/// width dimension
public var width: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Width) }
/// height dimension
public var height: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Height) }
/// centerX dimension
public var centerX: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.CenterX) }
/// centerY dimension
public var centerY: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.CenterY) }
/// baseline position
public var baseline: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Baseline) }
#if os(iOS)
/// firse baseline position
public var firstBaseline: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.FirstBaseline) }
/// left margin
public var leftMargin: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.LeftMargin) }
/// right margin
public var rightMargin: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.RightMargin) }
/// top margin
public var topMargin: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.TopMargin) }
/// bottom margin
public var bottomMargin: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.BottomMargin) }
/// leading margin
public var leadingMargin: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.LeadingMargin) }
/// trailing margin
public var trailingMargin: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.TrailingMargin) }
/// centerX within margins
public var centerXWithinMargins: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.CenterXWithinMargins) }
/// centerY within margins
public var centerYWithinMargins: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.CenterYWithinMargins) }
#endif
/// top + left + bottom + right edges
public var edges: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Edges) }
/// width + height dimensions
public var size: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Size) }
// centerX + centerY positions
public var center: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Center) }
#if os(iOS)
// top + left + bottom + right margins
public var margins: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.Margins) }
// centerX + centerY within margins
public var centerWithinMargins: ConstraintDescriptionExtendable { return self.makeConstraintDescription(ConstraintAttributes.CenterWithinMargins) }
#endif
internal init(view: View, file: String, line: UInt) {
self.view = view
self.file = file
self.line = line
}
internal let file: String
internal let line: UInt
internal let view: View
internal var constraintDescriptions = [ConstraintDescription]()
internal func makeConstraintDescription(attributes: ConstraintAttributes) -> ConstraintDescription {
let item = ConstraintItem(object: self.view, attributes: attributes)
let constraintDescription = ConstraintDescription(fromItem: item)
self.constraintDescriptions.append(constraintDescription)
return constraintDescription
}
internal class func prepareConstraints(#view: View, file: String = "Unknown", line: UInt = 0, @noescape closure: (make: ConstraintMaker) -> Void) -> [Constraint] {
let maker = ConstraintMaker(view: view, file: file, line: line)
closure(make: maker)
let constraints = maker.constraintDescriptions.map { $0.constraint }
for constraint in constraints {
constraint.makerFile = maker.file
constraint.makerLine = maker.line
}
return constraints
}
internal class func makeConstraints(#view: View, file: String = "Unknown", line: UInt = 0, @noescape closure: (make: ConstraintMaker) -> Void) {
#if os(iOS)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
#else
view.translatesAutoresizingMaskIntoConstraints = false
#endif
let maker = ConstraintMaker(view: view, file: file, line: line)
closure(make: maker)
let constraints = maker.constraintDescriptions.map { $0.constraint as! ConcreteConstraint }
for constraint in constraints {
constraint.makerFile = maker.file
constraint.makerLine = maker.line
constraint.installOnView(updateExisting: false)
}
}
internal class func remakeConstraints(#view: View, file: String = "Unknown", line: UInt = 0, @noescape closure: (make: ConstraintMaker) -> Void) {
#if os(iOS)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
#else
view.translatesAutoresizingMaskIntoConstraints = false
#endif
let maker = ConstraintMaker(view: view, file: file, line: line)
closure(make: maker)
self.removeConstraints(view: view)
let constraints = maker.constraintDescriptions.map { $0.constraint as! ConcreteConstraint }
for constraint in constraints {
constraint.makerFile = maker.file
constraint.makerLine = maker.line
constraint.installOnView(updateExisting: false)
}
}
internal class func updateConstraints(#view: View, file: String = "Unknown", line: UInt = 0, @noescape closure: (make: ConstraintMaker) -> Void) {
#if os(iOS)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
#else
view.translatesAutoresizingMaskIntoConstraints = false
#endif
let maker = ConstraintMaker(view: view, file: file, line: line)
closure(make: maker)
let constraints = maker.constraintDescriptions.map { $0.constraint as! ConcreteConstraint}
for constraint in constraints {
constraint.makerFile = maker.file
constraint.makerLine = maker.line
constraint.installOnView(updateExisting: true)
}
}
internal class func removeConstraints(#view: View) {
for existingLayoutConstraint in view.snp_installedLayoutConstraints {
existingLayoutConstraint.snp_constraint?.uninstall()
}
}
} | gpl-3.0 | 7af416780ccce27334558ff46b9be6bb | 43.129187 | 167 | 0.720776 | 5.858958 | false | false | false | false |
motocodeltd/MCAssertReflectiveEqual | Example/Tests/Tester.swift | 1 | 1300 | //
// Created by Stefanos Zachariadis first name at last name dot net
// Copyright (c) 2017 motocode ltd. All rights reserved. MIT license
//
import Foundation
@testable import MCAssertReflectiveEqual
class Tester {
private var equal: Bool?
private func failFunction(message: String, file: StaticString, line: UInt) {
equal = false
}
private func nsObjectCheckFunction(expected: NSObject, actual: NSObject, message: String, file: StaticString, line: UInt) {
if let equal = equal {
if (!equal) {
return
}
}
equal = actual == expected
}
private func optionalStringFunction(expected: String?, actual: String?, message: String, file: StaticString, line: UInt) {
if let equal = equal {
if (!equal) {
return
}
}
equal = actual == expected
}
func areEqual<T>(_ expected: T, _ actual: T, matchers: [Matcher] = []) -> Bool {
equal = nil
internalMCAssertReflectiveEqual(expected, actual, matchers: matchers,
nsObjectCheckFunction: nsObjectCheckFunction,
optionalStringEqualsFunction: optionalStringFunction,
failFunction: failFunction)
return equal ?? true
}
} | mit | e6fbc55236ebcf77da7019b7695490d8 | 29.97619 | 127 | 0.611538 | 4.710145 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-ios | Pod/Classes/Common/Components/UserAgentProvider.swift | 1 | 1174 | //
// UserAgentProvider.swift
// SuperAwesome
//
// Created by Gunhan Sancar on 01/04/2020.
//
import WebKit
/**
* Class that provides the current User Agent using WKWebView object.
*/
protocol UserAgentProviderType {
var name: String { get }
}
class UserAgentProvider: UserAgentProviderType {
public var name: String
private var webView: WKWebView?
private var preferencesRepository: PreferencesRepositoryType
init(device: DeviceType, preferencesRepository: PreferencesRepositoryType) {
self.preferencesRepository = preferencesRepository
self.name = preferencesRepository.userAgent ?? device.userAgent
evaluateUserAgent()
}
private func evaluateUserAgent() {
webView = WKWebView()
webView?.evaluateJavaScript("navigator.userAgent", completionHandler: { (result, error) in
if error != nil {
print("UserAgent.evaluateUserAgent.error:", String(describing: error))
} else if let res = result as? String {
self.name = res
self.preferencesRepository.userAgent = res
}
self.webView = nil
})
}
}
| lgpl-3.0 | 6a59691fecd85d41fdf86d6214b0ce6f | 27.634146 | 98 | 0.660988 | 5.149123 | false | false | false | false |
wangxin20111/WXWeiBo | WXWeibo/WXWeibo/AppDelegate.swift | 1 | 3549 |
//
// AppDelegate.swift
// WXWeibo
//
// Created by 王鑫 on 16/6/13.
// Copyright © 2016年 王鑫. All rights reserved.
//
import UIKit
//发送通知更新rootVC
let WXChangeRootViewControllerNotification = "WXChangeRootViewControllerNotification"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//0.设置nav,tab 的tintColor
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
UITabBar.appearance().tintColor = UIColor.orangeColor()
//1创建
window = UIWindow()
window?.frame = UIScreen.mainScreen().bounds
//2设置根目录,WXMainController
window?.rootViewController = defaultRootController()
//3设置可视化
window?.makeKeyAndVisible()
//4注册监听通知
WXNotificationCenter.addObserver(self, selector: "updateRootViewController:", name: WXChangeRootViewControllerNotification, object: nil)
return true
}
deinit{
WXNotificationCenter.removeObserver(self, name: WXChangeRootViewControllerNotification, object: nil)
}
/**
返回默认的根控制器
:returns: 跟控制器
*/
private func defaultRootController() -> UIViewController{
//判断是否登录
if WXUser.isLogin() //登录了
{
//判断是不是新的版本
return isNewUpdateVersion() ? WXNewFeatureController() : WXWelcomeController()
}else{//没有登录
return WXMainController()
}
}
/**
当接收通知的时候,用来去更新rootViewcontroller
ps:接收通知的时候,调用的方法,千万不要去用private修饰,有问题
:param: notifi 接收的通知
*/
func updateRootViewController(notifi : NSNotification){
/**
NSConcreteNotification 0x7f9be950f2a0 {name = WXChangeRootViewControllerNotification; object = 1}
*/
let isMainVc = notifi.object as! Bool
if isMainVc == true {
window?.rootViewController = WXMainController()
}else{
window?.rootViewController = WXWelcomeController()
}
}
/**
判断是不是新的版本
:returns: 是或者不是新版本
*/
private func isNewUpdateVersion() -> Bool{
/**
* 如果是给公司开发些项目,我们比较版本号的规则是:1.冲网络上获取版本号,2.通过键“shortString”来获取该版本号,然后比较,基本不用保存到本地
但是微博等项目,我们比较的方法确不同:1.通过“shortString”获取该版本号,2.冲本地获取保存的版本号
*/
//1.通过“shortString”获取该版本号
let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
//2.本地获取版本
let saveVersion = NSUserDefaults.standardUserDefaults().objectForKey("BundleVersionString") as? String ?? ""
//3.比较连个版本
if currentVersion.compare(saveVersion) == NSComparisonResult.OrderedDescending
{
//4.保存新的版本号
NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "BundleVersionString")
return true
}
return false
}
}
| mit | ca93f835d475e71d957a00e2feb7dd66 | 29.545455 | 143 | 0.644511 | 4.638037 | false | false | false | false |
tardieu/swift | stdlib/public/SDK/Dispatch/IO.swift | 6 | 3518 | //===----------------------------------------------------------------------===//
//
// 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 extension DispatchIO {
public enum StreamType : UInt {
case stream = 0
case random = 1
}
public struct CloseFlags : OptionSet, RawRepresentable {
public let rawValue: UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let stop = CloseFlags(rawValue: 1)
}
public struct IntervalFlags : OptionSet, RawRepresentable {
public let rawValue: UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public init(nilLiteral: ()) { self.rawValue = 0 }
public static let strictInterval = IntervalFlags(rawValue: 1)
}
public class func read(fromFileDescriptor: Int32, maxLength: Int, runningHandlerOn queue: DispatchQueue, handler: @escaping (_ data: DispatchData, _ error: Int32) -> Void) {
__dispatch_read(fromFileDescriptor, maxLength, queue) { (data: __DispatchData, error: Int32) in
handler(DispatchData(data: data), error)
}
}
public class func write(toFileDescriptor: Int32, data: DispatchData, runningHandlerOn queue: DispatchQueue, handler: @escaping (_ data: DispatchData?, _ error: Int32) -> Void) {
__dispatch_write(toFileDescriptor, data as __DispatchData, queue) { (data: __DispatchData?, error: Int32) in
handler(data.flatMap { DispatchData(data: $0) }, error)
}
}
public convenience init(
type: StreamType,
fileDescriptor: Int32,
queue: DispatchQueue,
cleanupHandler: @escaping (_ error: Int32) -> Void)
{
self.init(__type: type.rawValue, fd: fileDescriptor, queue: queue, handler: cleanupHandler)
}
public convenience init(
type: StreamType,
path: UnsafePointer<Int8>,
oflag: Int32,
mode: mode_t,
queue: DispatchQueue,
cleanupHandler: @escaping (_ error: Int32) -> Void)
{
self.init(__type: type.rawValue, path: path, oflag: oflag, mode: mode, queue: queue, handler: cleanupHandler)
}
public convenience init(
type: StreamType,
io: DispatchIO,
queue: DispatchQueue,
cleanupHandler: @escaping (_ error: Int32) -> Void)
{
self.init(__type: type.rawValue, io: io, queue: queue, handler: cleanupHandler)
}
public func read(offset: off_t, length: Int, queue: DispatchQueue, ioHandler: @escaping (_ done: Bool, _ data: DispatchData?, _ error: Int32) -> Void) {
__dispatch_io_read(self, offset, length, queue) { (done: Bool, data: __DispatchData?, error: Int32) in
ioHandler(done, data.flatMap { DispatchData(data: $0) }, error)
}
}
public func write(offset: off_t, data: DispatchData, queue: DispatchQueue, ioHandler: @escaping (_ done: Bool, _ data: DispatchData?, _ error: Int32) -> Void) {
__dispatch_io_write(self, offset, data as __DispatchData, queue) { (done: Bool, data: __DispatchData?, error: Int32) in
ioHandler(done, data.flatMap { DispatchData(data: $0) }, error)
}
}
public func setInterval(interval: DispatchTimeInterval, flags: IntervalFlags = []) {
__dispatch_io_set_interval(self, UInt64(interval.rawValue), flags.rawValue)
}
public func close(flags: CloseFlags = []) {
__dispatch_io_close(self, flags.rawValue)
}
}
| apache-2.0 | 329122065dd05f29edb7ca994b9acac4 | 35.645833 | 178 | 0.676521 | 3.726695 | false | false | false | false |
codePrincess/playgrounds | Kick start Cognitive Services.playground/Pages/ComputerVision.xcplaygroundpage/Contents.swift | 1 | 3456 | /*:
# Describe your picture!
It's time to get life into our app! Want to get your picture described by a remote service? Yes? YES? So get ready - and get to know the * *drumroooooll* * **COGNITIVE SERVICES**!
We will start with the Computer Vision API. So let's see, what the "computer" can "see" on our image.
*/
//#-hidden-code
import PlaygroundSupport
import UIKit
import Foundation
guard #available(iOS 9, OSX 10.11, *) else {
fatalError("Life? Don't talk to me about life. Here I am, brain the size of a planet, and they tell me to run a 'playground'. Call that job satisfaction? I don't.")
}
let myView = UIView(frame: CGRect(x: 0, y: 0, width: 450, height: 600))
let preview = UIImageView(frame: myView.bounds)
//#-end-hidden-code
/*:
* experiment:
Choose your preferred image right here or take a new one
*/
preview.image = /*#-editable-code*/#imageLiteral(resourceName: "containers.png")/*#-end-editable-code*/
//#-hidden-code
preview.contentMode = .scaleAspectFit
let textLabel = UILabel(frame: CGRect(x: 30, y: myView.bounds.height-200, width: 350, height: 200))
textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 5
textLabel.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
let backgroundView = UIView(frame: CGRect(x: 0, y: myView.bounds.height-170, width: myView.bounds.width, height: 200))
backgroundView.backgroundColor = #colorLiteral(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
backgroundView.alpha = 0.7
myView.addSubview(preview)
myView.addSubview(backgroundView)
myView.addSubview(textLabel)
func showTagsForImage (_ photo : UIImageView, _ confidence : Double) {
let manager = CognitiveServices()
textLabel.text = "... gimme a sec - getting your tags!"
manager.retrievePlausibleTagsForImage(photo.image!, confidence) { (result, error) -> (Void) in
DispatchQueue.main.async(execute: {
if let _ = error {
print("omg something bad happened: \(String(describing: error))")
} else {
print("seems like all went well: \(String(describing: result))")
}
setTagsAsDescription(result)
})
}
}
func setTagsAsDescription (_ tags : [String]?) {
if (tags?.count)! > 0 {
textLabel.text = "Look what I detected:\n"
for tag in tags! {
textLabel.text = textLabel.text! + "#" + tag + " "
}
} else {
textLabel.text = "Uh noez! No tags could be found for this image :("
}
}
//#-end-hidden-code
/*:
* experiment:
Every part of the description of the picture will be returned with a certain confidence. A good value is 0.85 for nice fitting results. But go a head and play around with this value and see, with what funky descriptions the "computer" may come along
*/
showTagsForImage(preview, /*#-editable-code*/0.1/*#-end-editable-code*/)
//#-hidden-code
PlaygroundPage.current.liveView = myView
//#-end-hidden-code
/*:
* callout(What did we learn?):
Wonderful! So you just called your first API from the Cognitive Services Suite. The Computer Vision API. If you want to have a detailed look at the documentation - where you can find further examples - visit the dedicated [Computer Vision documentation](https://www.microsoft.com/cognitive-services/en-us/computer-vision-api).
*/
//: Enough of just describing photos. Let's catch a face and let the API know! Let's rock on and continue by [using the FACE API](@next)!
| mit | 5bb2d8be97d38c8ebf48e5739fd7286b | 39.658824 | 327 | 0.690683 | 3.772926 | false | false | false | false |
darthpelo/SurviveAmsterdam | mobile/SurviveAmsterdam/Location/Manager/LocationManager.swift | 1 | 2827 | //
// LocationManager.swift
// SurviveAmsterdam
//
// Created by Alessio Roberto on 20/03/16.
// Copyright © 2016 Alessio Roberto. All rights reserved.
//
import QuadratTouch
import CoreLocation
import Foundation
class LocationManager: NSObject, CLLocationManagerDelegate {
class var sharedInstance: LocationManager {
struct Singleton {
static let instance = LocationManager()
}
return Singleton.instance
}
private let manager = CLLocationManager()
var shopsList: [NearShop] = []
private var lastLocation = CLLocation()
func setupLocationManager() {
manager.delegate = self
manager.requestWhenInUseAuthorization()
if #available(iOS 9, *) {
manager.requestLocation()
} else {
manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
manager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first where location != lastLocation {
lastLocation = location
let session = Session.sharedSession()
var parameters = location.parameters()
let cat = Constants().categoryID() ?? ""
parameters += [Parameter.categoryId:cat]
parameters += [Parameter.intent:"browse"]
parameters += [Parameter.radius:"800"]
parameters += [Parameter.limit:"20"]
let searchTask = session.venues.search(parameters) { (result) -> Void in
if let response = result.response,
let venues = response["venues"] as? NSArray where venues.count > 0 {
self.shopsList.removeAll()
for i in 0..<venues.count {
if let dict = venues[i] as? NSDictionary,
let name = dict["name"] as? String,
let location = dict["location"] as? NSDictionary,
let address = location["address"] as? String {
if !name.containsString("Coffeeshop") {
let shop = NearShop(shopName: name, address: address)
self.shopsList.append(shop)
}
}
}
NSNotificationCenter.defaultCenter().postNotificationName(Constants.observer.newShopsList, object: nil)
}
}
searchTask.start()
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Failed to find user's location: \(error.localizedDescription)")
}
} | mit | 8459a32081c1d0986eb1bd5fb87fcfaf | 36.693333 | 123 | 0.561925 | 5.743902 | false | false | false | false |
Daemon-Devarshi/MedicationSchedulerSwift3.0 | Medication/DataModels/Nurse+CoreDataClass.swift | 1 | 3422 | //
// Nurse+CoreDataClass.swift
// Medication
//
// Created by Devarshi Kulshreshtha on 9/9/16.
// Copyright © 2016 Devarshi. All rights reserved.
//
import Foundation
import CoreData
enum CoreDataCustomErrorCodes: Int {
case duplicateRecord = 801
case unableToSaveData = 999
var domain:String {
switch self {
case .duplicateRecord:
return "Duplicate Data"
case .unableToSaveData:
return "Unable to save data"
}
}
}
public class Nurse: NSManagedObject {
//MARK:- Class functions
// check for duplicate nurse record
class func isDuplicate(email: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> Bool {
var isDuplicate = true
let fetchRequest: NSFetchRequest<Nurse> = Nurse.fetchRequest()
let predicate = NSPredicate(format: "email = %@",email)
fetchRequest.predicate = predicate
do {
let duplicateCount = try managedObjectContext.count(for: fetchRequest)
if duplicateCount == 0 {
// insert nurse since it is unique
isDuplicate = false
}
else {
// is duplicate
}
} catch {
let error = error as NSError
print("\(error), \(error.userInfo)")
}
return isDuplicate
}
// adding nurse to local db
class func addNurse(withEmail email: String, password: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> NSError? {
var insertError : NSError? = nil
// Check if it is a duplicate entry
if isDuplicate(email: email, inManagedObjectContext: managedObjectContext) {
// is duplicate
let userInfo = [NSLocalizedDescriptionKey : NSLocalizedString("Duplicate Nurse!", value: "Nurse with same email already exists.", comment: "")]
insertError = NSError(domain: CoreDataCustomErrorCodes.duplicateRecord.domain, code: CoreDataCustomErrorCodes.duplicateRecord.rawValue, userInfo: userInfo)
}
else {
// email does not exist 😊
let newNurse = Nurse(context: managedObjectContext)
newNurse.email = email
newNurse.password = password
do {
try managedObjectContext.save()
} catch {
let error = error as NSError
print("\(error), \(error.userInfo)")
insertError = error
}
}
return insertError
}
// retrieve nurse
class func getNurse(withEmail email: String, password: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> Nurse? {
var nurse: Nurse?
let fetchRequest: NSFetchRequest<Nurse> = Nurse.fetchRequest()
let predicate = NSPredicate(format: "email = %@ AND password = %@",email, password)
fetchRequest.predicate = predicate
do {
let returnArray = try managedObjectContext.fetch(fetchRequest)
if returnArray.count > 0 {
nurse = returnArray.last
}
} catch let error as NSError {
print(error)
} catch {
print("Unknown error")
}
return nurse
}
}
| mit | 0ed954aa4406895bc5ab73ea1b4506af | 31.865385 | 167 | 0.588356 | 5.539708 | false | false | false | false |
yaslab/ZipArchive.swift | Sources/ZipArchive/ZipReader.swift | 1 | 3389 | import struct Foundation.Date
import ZipIO
import ZipModel
public class ZipReader {
private let input: RandomAccessInputStream
private let encoding: String.Encoding
private var filters: [Zip.Method: ZipReaderFilter.Type]
private let endOfCentralDirectoryRecord: EndOfCentralDirectoryRecord
private var nextOffset: Int64?
public init(_ input: RandomAccessInputStream, encoding: String.Encoding = .utf8) throws {
guard let e = EndOfCentralDirectoryRecord.search(input) else {
throw EEEE(message: "End of central directory record not exist.")
}
self.input = input
self.encoding = encoding
self.filters = [
.store: StoreInputFilter.self,
.deflate: DeflateInputFilter.self
]
self.endOfCentralDirectoryRecord = e
self.nextOffset = Int64(endOfCentralDirectoryRecord.centralDirectoryOffset)
}
public func register(_ filter: ZipReaderFilter.Type, for method: Zip.Method) {
filters[method] = filter
}
public var hasNext: Bool {
if nextOffset == nil {
return false
}
return true
}
public func read<T>(_ block: (Zip.Header, InputStream) throws -> T) throws -> T {
guard let nextOffset = self.nextOffset else {
throw EEEE(message: "EOF")
}
guard input.seek(offset: nextOffset, origin: .begin) else {
// FIXME: can not seek
throw EEEE(message: "can not seek")
}
guard let centralHeader = EntryHeader(stream: input, kind: .central, encoding: encoding) else {
// FIXME: can not read central header
throw EEEE(message: "can not read central header")
}
let method = Zip.Method(rawValue: Int(centralHeader.method))
guard let filter = filters[method] else {
throw EEEE(message: "Decompression filter not exist.")
}
let newNextOffset = input.tell()
let result: T
do {
let offset = Int64(centralHeader.localHeaderOffset)
input.seek(offset: offset, origin: .begin)
guard let localHeader = EntryHeader(stream: input, kind: .local, encoding: encoding) else {
// FIXME: can not read local header
throw EEEE(message: "can not read local header")
}
let localHeaderSize = input.tell() - offset
let h = Zip.Header(
name: centralHeader.name,
method: method,
fileTime: .now()) // FIXME:
let f = filter.init(input, originalSize: Int(centralHeader.size))
result = try block(h, f)
}
let startOffset = Int64(endOfCentralDirectoryRecord.centralDirectoryOffset) // FIXME:
let size = Int64(endOfCentralDirectoryRecord.centralDirectorySize) // FIXME:
if (newNextOffset - startOffset) < size {
self.nextOffset = newNextOffset
} else {
self.nextOffset = nil
}
return result
}
public func close() throws {
input.close()
}
}
extension ZipReader {
public convenience init(path: String) throws {
guard let input = ReadOnlyFileStream(fileAtPath: path) else {
throw EEEE(message: "Cannot open file.")
}
try self.init(input)
}
}
| mit | 2b5d77cfdb3c0c1fa001f518b898d754 | 28.72807 | 103 | 0.606669 | 4.73324 | false | false | false | false |
jeffreybergier/WaterMe2 | WaterMe/WaterMe/ReminderVesselMain/ReminderVesselEdit/ReminderVesselEditViewController+Delegate.swift | 1 | 7894 | //
// ReminderVesselEditViewController+ReminderVesselEditTableViewControllerDelegate.swift
// WaterMe
//
// Created by Jeffrey Bergier on 10/11/18.
// Copyright © 2018 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WaterMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import Datum
import IntentsUI
import UIKit
extension ReminderVesselEditViewController: ReminderVesselEditTableViewControllerDelegate {
func userChosePhotoChange(controller: ReminderVesselEditTableViewController?,
sender: PopoverSender)
{
self.view.endEditing(false)
let imageAlreadyChosen = self.vesselResult?.value?.icon?.image != nil
let vc = UIAlertController.emojiPhotoActionSheet(withAlreadyChosenImage: imageAlreadyChosen)
{ choice in
switch choice {
case .camera:
let vc = ImagePickerCropperViewController.newCameraVC() { image, vc in
vc.dismiss(animated: true, completion: nil)
guard let image = image else { return }
self.updateIcon(ReminderVesselIcon(rawImage: image))
}
self.present(vc, animated: true, completion: nil)
case .photos:
let vc = ImagePickerCropperViewController.newPhotosVC() { image, vc in
vc.dismiss(animated: true, completion: nil)
guard let image = image else { return }
self.updateIcon(ReminderVesselIcon(rawImage: image))
}
self.present(vc, animated: true, completion: nil)
case .emoji:
let vc = EmojiPickerViewController.newVC() { emoji, vc in
vc.dismiss(animated: true, completion: nil)
guard let emoji = emoji else { return }
self.updateIcon(.emoji(emoji))
}
self.present(vc, animated: true, completion: nil)
case .viewCurrentPhoto:
guard let image = self.vesselResult?.value?.icon?.image else { return }
let config = DismissHandlingImageViewerConfiguration(image: image) { vc in
vc.dismiss(animated: true, completion: nil)
}
let vc = DismissHandlingImageViewerController(configuration: config)
self.present(vc, animated: true, completion: nil)
case .error(let errorVC):
self.present(errorVC, animated: true, completion: nil)
}
}
switch sender {
case .left(let sender):
vc.popoverPresentationController?.sourceView = sender
vc.popoverPresentationController?.sourceRect = sender.bounds.centerRect
case .right(let sender):
vc.popoverPresentationController?.barButtonItem = sender
}
self.present(vc, animated: true, completion: nil)
}
func userChangedName(to newName: String, controller: ReminderVesselEditTableViewController?) {
guard let vessel = self.vesselResult?.value, let basicRC = self.basicRC else {
assertionFailure("Missing ReminderVessel or Realm Controller")
return
}
self.notificationToken?.invalidate() // stop the update notifications from causing the tableview to reload
let updateResult = basicRC.update(displayName: newName, icon: nil, in: vessel)
switch updateResult {
case .failure(let error):
UIAlertController.presentAlertVC(for: error, over: self) { _ in
self.completionHandler?(self)
}
case .success:
self.startNotifications()
// Item changed outside of the change block, time to dirty
self.userDirtiedUserActivity()
}
}
func userChoseAddReminder(controller: ReminderVesselEditTableViewController?) {
self.view.endEditing(false)
guard let vessel = self.vesselResult?.value else {
assertionFailure("Missing ReminderVessel")
return
}
let addReminderVC = ReminderEditViewController.newVC(basicController: basicRC, purpose: .new(vessel)) { vc in
vc.dismiss(animated: true, completion: nil)
}
self.present(addReminderVC, animated: true, completion: nil)
}
func userChose(reminder: Reminder,
deselectRowAnimated: ((Bool) -> Void)?,
controller: ReminderVesselEditTableViewController?)
{
self.view.endEditing(false)
let editReminderVC = ReminderEditViewController.newVC(basicController: basicRC,
purpose: .existing(reminder))
{ vc in
vc.dismiss(animated: true, completion: { deselectRowAnimated?(true) })
}
self.present(editReminderVC, animated: true, completion: nil)
}
func userChose(siriShortcut: ReminderVesselEditTableViewController.SiriShortcut,
deselectRowAnimated: ((Bool) -> Void)?,
controller: ReminderVesselEditTableViewController?)
{
guard #available(iOS 12.0, *) else {
let vc = UIAlertController(localizedSiriShortcutsUnavailableAlertWithCompletionHandler: {
deselectRowAnimated?(true)
})
self.present(vc, animated: true, completion: nil)
return
}
guard
let activity = self.userActivity,
activity.activityType == RawUserActivity.editReminderVessel.rawValue
else {
assertionFailure("Unexpected User Activity")
return
}
let shortcut = INShortcut(userActivity: activity)
let vc = ClosureDelegatingAddVoiceShortcutViewController(shortcut: shortcut)
vc.completionHandler = { vc, result in
vc.dismiss(animated: true) {
deselectRowAnimated?(true)
guard case .failure(let error) = result else { return }
UIAlertController.presentAlertVC(for: error, over: self)
}
}
self.present(vc, animated: true, completion: nil)
}
func userDeleted(reminder: Reminder,
controller: ReminderVesselEditTableViewController?) -> Bool
{
self.view.endEditing(false)
guard let basicRC = self.basicRC else {
assertionFailure("Missing Realm Controller.")
return false
}
let deleteResult = basicRC.delete(reminder: reminder)
switch deleteResult {
case .success:
return true
case .failure(let error):
UIAlertController.presentAlertVC(for: error, over: self)
return false
}
}
private func updateIcon(_ icon: ReminderVesselIcon) {
guard let vessel = self.vesselResult?.value, let basicRC = self.basicRC else {
assertionFailure("Missing ReminderVessel or Realm Controller")
return
}
let updateResult = basicRC.update(displayName: nil, icon: icon, in: vessel)
guard case .failure(let error) = updateResult else { return }
UIAlertController.presentAlertVC(for: error, over: self)
}
}
| gpl-3.0 | 49f6c496575508292b5aa26fd51bc830 | 42.607735 | 117 | 0.622197 | 5.27607 | false | false | false | false |
DianQK/Flix | Example/Example/CalendarEvent/Event/TextFieldProvider.swift | 1 | 958 | //
// TextFieldProvider.swift
// Example
//
// Created by DianQK on 27/10/2017.
// Copyright © 2017 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Flix
class TextFieldProvider: UITextField, UniqueAnimatableTableViewProvider {
typealias Cell = UITableViewCell
func onCreate(_ tableView: UITableView, cell: UITableViewCell, indexPath: IndexPath) {
cell.contentView.addSubview(self)
self.clearButtonMode = .whileEditing
self.translatesAutoresizingMaskIntoConstraints = false
self.topAnchor.constraint(equalTo: cell.contentView.topAnchor).isActive = true
self.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor).isActive = true
self.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: 20).isActive = true
self.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor, constant: -20).isActive = true
}
}
| mit | dd5a2d517d786cc492d2e813cd85fea4 | 33.178571 | 111 | 0.750261 | 4.833333 | false | false | false | false |
brightify/torch | Source/Predicate/ValueType/String+Predicate.swift | 1 | 3454 | //
// String+Predicate.swift
// Torch
//
// Created by Tadeas Kriz on 7/5/17.
// Copyright © 2017 Brightify. All rights reserved.
//
#if swift(>=3.1)
public struct StringComparsionOptions: OptionSet, CustomStringConvertible {
public static let caseInsensitive = StringComparsionOptions(rawValue: 1 << 0)
public static let diacriticsInsensitive = StringComparsionOptions(rawValue: 1 << 1)
public let rawValue: Int
public var description: String {
var flags = [] as [String]
if self.contains(.caseInsensitive) {
flags.append("c")
}
if self.contains(.diacriticsInsensitive) {
flags.append("d")
}
guard !flags.isEmpty else { return "" }
return "[\(flags.joined())]"
}
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
public extension Property where T == String {
func hasPrefix(_ value: T, options: StringComparsionOptions = []) -> Predicate<PARENT> {
return Predicate.singleValuePredicate(name, value: value.toAnyObject(), operatorString: "BEGINSWITH\(options)")
}
func hasSuffix(_ value: T, options: StringComparsionOptions = []) -> Predicate<PARENT> {
return Predicate.singleValuePredicate(name, value: value.toAnyObject(), operatorString: "ENDSWITH\(options)")
}
func contains(_ value: T, options: StringComparsionOptions = []) -> Predicate<PARENT> {
return Predicate.singleValuePredicate(name, value: value.toAnyObject(), operatorString: "CONTAINS\(options)")
}
func like(_ value: T, options: StringComparsionOptions = []) -> Predicate<PARENT> {
return Predicate.singleValuePredicate(name, value: value.toAnyObject(), operatorString: "LIKE\(options)")
}
func matches(regex: T, options: StringComparsionOptions = []) -> Predicate<PARENT> {
return Predicate.singleValuePredicate(name, value: regex.toAnyObject(), operatorString: "MATCHES\(options)")
}
func equalTo(_ value: T, options: StringComparsionOptions) -> Predicate<PARENT> {
return Predicate.singleValuePredicate(name, value: value.toAnyObject(), operatorString: "==\(options)")
}
func notEqualTo(_ value: T, options: StringComparsionOptions) -> Predicate<PARENT> {
return Predicate.singleValuePredicate(name, value: value.toAnyObject(), operatorString: "!=\(options)")
}
func lessThan(_ value: T, options: StringComparsionOptions) -> Predicate<PARENT> {
return Predicate.singleValuePredicate(name, value: value.toAnyObject(), operatorString: "<\(options)")
}
func lessThanOrEqualTo(_ value: T, options: StringComparsionOptions) -> Predicate<PARENT> {
return Predicate.singleValuePredicate(name, value: value.toAnyObject(), operatorString: "<=\(options)")
}
func greaterThanOrEqualTo(_ value: T, options: StringComparsionOptions) -> Predicate<PARENT> {
return Predicate.singleValuePredicate(name, value: value.toAnyObject(), operatorString: ">=\(options)")
}
func greaterThan(_ value: T, options: StringComparsionOptions) -> Predicate<PARENT> {
return Predicate.singleValuePredicate(name, value: value.toAnyObject(), operatorString: ">\(options)")
}
}
#endif
| mit | f0b6332a786205bee9541649ca997fcd | 43.269231 | 123 | 0.641471 | 5.231818 | false | false | false | false |
NicholasMata/SimpleTabBarController | SimpleTabBarController/SimpleBarItem.swift | 1 | 5233 | //
// SimpleBarItem.swift
// Pods
//
// Created by Nicholas Mata on 10/25/16.
//
//
import Foundation
import UIKit
@IBDesignable
open class SimpleBarItem: UITabBarItem {
@IBInspectable
open var selectedColor: UIColor = .red {
didSet {
content?.appearance.highlightIconColor = selectedColor
}
}
@IBInspectable
open var unselectedColor: UIColor = UIColor(white: 146.0 / 255.0, alpha: 1.0) {
didSet {
content?.appearance.iconColor = unselectedColor
}
}
open weak var tabBarController: SimpleTabBarController?
/**
The index position in the tabbar where the item is.
*/
open var index: Int = 0
/**
The item content for the tabbaritem.
*/
open var content: SimpleBarItemContent?
/**
The badge for this tabbaritem.
*/
open var badge: SimpleTabBarBadge? {
get {
return content?.badgeView
}
}
/**
The image used to represent the item.
If selectedImage is nil then this will also be the
image displayed when the tabbaritem is selected.
*/
open override var image: UIImage? {
set {
self.content?.image = newValue
// Must set the super to nil because we don't want UITabbar
// displaying the image we will handle it.
super.image = nil
}
get {
// Get should only return the super because
// we need to get the initial value from storyboard.
return super.image
}
}
/**
The image used to represent the item when selected.
*/
open override var selectedImage: UIImage? {
didSet {
self.content?.selectedImage = selectedImage
}
}
/**
The title that will be displayed on the item.
If nil the no title will be displayed.
*/
open override var title: String? {
set { self.content?.title = newValue }
get { return nil }
}
override init() {
super.init()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let content = SimpleBarItemContent(appearance: SimpleBounceAppearance())
content.item = self
content.selectedImage = selectedImage
if image != nil {
content.image = image
super.image = nil
}
self.content = content
self.content?.deselect(animated: false, completion: nil)
}
public convenience init(appearance: SimpleBarItemAppearance) {
self.init()
let content = SimpleBarItemContent(appearance: appearance)
content.item = self
self.content = content
self.content?.deselect(animated: false, completion: nil)
}
public convenience init(content: SimpleBarItemContent?) {
self.init()
self.content = content
self.content?.item = self
self.content?.deselect(animated: false, completion: nil)
}
open func select(animated: Bool, completion: (() -> ())?){
content?.select(animated: animated, completion: completion)
}
open func reselect(animated: Bool, completion: (() -> ())?){
content?.reselect(animated: animated, completion: completion)
}
open func deselect(animated: Bool, completion: (() -> ())?){
content?.deselect(animated: animated, completion: completion)
}
open func highlight(highlight: Bool, animated: Bool, completion: (() -> ())?){
content?.highlight(highlight: highlight, animated: animated, completion: completion)
}
}
// MARK: - Badge Extensions
extension SimpleBarItem {
/**
The value of the badge if nil the badge will not be displayed.
*/
open override var badgeValue: String? {
get {
return badge?.badgeValue ?? nil
}
set(newValue) {
self.content?.badgeValue = newValue
}
}
/**
The color of the badge the default is red.
*/
open override var badgeColor: UIColor? {
get {
return badge?.badgeColor ?? nil
}
set(newValue) {
if newValue == nil {
self.badge?.badgeColor = .red
} else {
self.badge?.badgeColor = newValue!
}
}
}
}
private var kSelectEnabledAssociateKey: String = ""
extension UITabBarItem {
var selectEnabled: Bool? {
get {
let obj = (objc_getAssociatedObject(self, &kSelectEnabledAssociateKey) as? NSNumber)
return obj?.boolValue
}
set(newValue) {
if let newValue = newValue {
objc_setAssociatedObject(self, &kSelectEnabledAssociateKey, NSNumber.init(value: newValue as Bool), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
}
}
extension NSObjectProtocol where Self: UITabBarControllerDelegate {
func tabBarController(_ tabBarcontroller: UITabBarController?, shouldSelectViewController viewController: UIViewController) -> Bool {
return viewController.tabBarItem.selectEnabled ?? true
}
}
| mit | b8590850c2260a12767b9b2fa66419c7 | 27.134409 | 163 | 0.592777 | 4.96019 | false | false | false | false |
mshhmzh/firefox-ios | Client/Frontend/AuthenticationManager/AuthenticationSettingsViewController.swift | 1 | 12545 | /* 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 UIKit
import Shared
import SwiftKeychainWrapper
import LocalAuthentication
private let logger = Logger.browserLogger
private func presentNavAsFormSheet(presented: UINavigationController, presenter: UINavigationController?) {
presented.modalPresentationStyle = .FormSheet
presenter?.presentViewController(presented, animated: true, completion: nil)
}
class TurnPasscodeOnSetting: Setting {
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) {
super.init(title: NSAttributedString.tableRowTitle(AuthenticationStrings.turnOnPasscode),
delegate: delegate)
}
override func onClick(navigationController: UINavigationController?) {
presentNavAsFormSheet(UINavigationController(rootViewController: SetupPasscodeViewController()),
presenter: navigationController)
}
}
class TurnPasscodeOffSetting: Setting {
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) {
super.init(title: NSAttributedString.tableRowTitle(AuthenticationStrings.turnOffPasscode),
delegate: delegate)
}
override func onClick(navigationController: UINavigationController?) {
presentNavAsFormSheet(UINavigationController(rootViewController: RemovePasscodeViewController()),
presenter: navigationController)
}
}
class ChangePasscodeSetting: Setting {
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool) {
let attributedTitle: NSAttributedString = (enabled ?? false) ?
NSAttributedString.tableRowTitle(AuthenticationStrings.changePasscode) :
NSAttributedString.disabledTableRowTitle(AuthenticationStrings.changePasscode)
super.init(title: attributedTitle,
delegate: delegate,
enabled: enabled)
}
override func onClick(navigationController: UINavigationController?) {
presentNavAsFormSheet(UINavigationController(rootViewController: ChangePasscodeViewController()),
presenter: navigationController)
}
}
class RequirePasscodeSetting: Setting {
private weak var navigationController: UINavigationController?
override var accessoryType: UITableViewCellAccessoryType { return .DisclosureIndicator }
override var style: UITableViewCellStyle { return .Value1 }
override var status: NSAttributedString {
// Only show the interval if we are enabled and have an interval set.
let authenticationInterval = KeychainWrapper.authenticationInfo()
if let interval = authenticationInterval?.requiredPasscodeInterval where enabled {
return NSAttributedString.disabledTableRowTitle(interval.settingTitle)
}
return NSAttributedString(string: "")
}
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) {
self.navigationController = settings.navigationController
let title = AuthenticationStrings.requirePasscode
let attributedTitle = (enabled ?? true) ? NSAttributedString.tableRowTitle(title) : NSAttributedString.disabledTableRowTitle(title)
super.init(title: attributedTitle,
delegate: delegate,
enabled: enabled)
}
override func onClick(_: UINavigationController?) {
guard let authInfo = KeychainWrapper.authenticationInfo() else {
navigateToRequireInterval()
return
}
if authInfo.requiresValidation() {
AppAuthenticator.presentAuthenticationUsingInfo(authInfo,
touchIDReason: AuthenticationStrings.requirePasscodeTouchReason,
success: {
self.navigateToRequireInterval()
},
cancel: nil,
fallback: {
AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self)
})
} else {
self.navigateToRequireInterval()
}
}
private func navigateToRequireInterval() {
navigationController?.pushViewController(RequirePasscodeIntervalViewController(), animated: true)
}
}
extension RequirePasscodeSetting: PasscodeEntryDelegate {
@objc func passcodeValidationDidSucceed() {
navigationController?.dismissViewControllerAnimated(true) {
self.navigateToRequireInterval()
}
}
}
class TouchIDSetting: Setting {
private let authInfo: AuthenticationKeychainInfo?
private weak var navigationController: UINavigationController?
private weak var switchControl: UISwitch?
private var touchIDSuccess: (() -> Void)? = nil
private var touchIDFallback: (() -> Void)? = nil
init(
title: NSAttributedString?,
navigationController: UINavigationController? = nil,
delegate: SettingsDelegate? = nil,
enabled: Bool? = nil,
touchIDSuccess: (() -> Void)? = nil,
touchIDFallback: (() -> Void)? = nil)
{
self.touchIDSuccess = touchIDSuccess
self.touchIDFallback = touchIDFallback
self.navigationController = navigationController
self.authInfo = KeychainWrapper.authenticationInfo()
super.init(title: title, delegate: delegate, enabled: enabled)
}
override func onConfigureCell(cell: UITableViewCell) {
super.onConfigureCell(cell)
// In order for us to recognize a tap gesture without toggling the switch,
// the switch is wrapped in a UIView which has a tap gesture recognizer. This way
// we can disable interaction of the switch and still handle tap events.
let control = UISwitch()
control.onTintColor = UIConstants.ControlTintColor
control.on = authInfo?.useTouchID ?? false
control.userInteractionEnabled = false
switchControl = control
let accessoryContainer = UIView(frame: control.frame)
accessoryContainer.addSubview(control)
let gesture = UITapGestureRecognizer(target: self, action: #selector(TouchIDSetting.switchTapped))
accessoryContainer.addGestureRecognizer(gesture)
cell.accessoryView = accessoryContainer
}
@objc private func switchTapped() {
guard let authInfo = authInfo else {
logger.error("Authentication info should always be present when modifying Touch ID preference.")
return
}
if authInfo.useTouchID {
AppAuthenticator.presentAuthenticationUsingInfo(
authInfo,
touchIDReason: AuthenticationStrings.disableTouchReason,
success: self.touchIDSuccess,
cancel: nil,
fallback: self.touchIDFallback
)
} else {
toggleTouchID(enabled: true)
}
}
func toggleTouchID(enabled enabled: Bool) {
authInfo?.useTouchID = enabled
KeychainWrapper.setAuthenticationInfo(authInfo)
switchControl?.setOn(enabled, animated: true)
}
}
class AuthenticationSettingsViewController: SettingsTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
updateTitleForTouchIDState()
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: #selector(AuthenticationSettingsViewController.refreshSettings(_:)), name: NotificationPasscodeDidRemove, object: nil)
notificationCenter.addObserver(self, selector: #selector(AuthenticationSettingsViewController.refreshSettings(_:)), name: NotificationPasscodeDidCreate, object: nil)
notificationCenter.addObserver(self, selector: #selector(AuthenticationSettingsViewController.refreshSettings(_:)), name: UIApplicationDidBecomeActiveNotification, object: nil)
tableView.accessibilityIdentifier = "AuthenticationManager.settingsTableView"
}
deinit {
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.removeObserver(self, name: NotificationPasscodeDidRemove, object: nil)
notificationCenter.removeObserver(self, name: NotificationPasscodeDidCreate, object: nil)
notificationCenter.removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
}
override func generateSettings() -> [SettingSection] {
if let _ = KeychainWrapper.authenticationInfo() {
return passcodeEnabledSettings()
} else {
return passcodeDisabledSettings()
}
}
private func updateTitleForTouchIDState() {
if LAContext().canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil) {
navigationItem.title = AuthenticationStrings.touchIDPasscodeSetting
} else {
navigationItem.title = AuthenticationStrings.passcode
}
}
private func passcodeEnabledSettings() -> [SettingSection] {
var settings = [SettingSection]()
let passcodeSectionTitle = NSAttributedString(string: AuthenticationStrings.passcode)
let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [
TurnPasscodeOffSetting(settings: self),
ChangePasscodeSetting(settings: self, delegate: nil, enabled: true)
])
var requirePasscodeSectionChildren: [Setting] = [RequirePasscodeSetting(settings: self)]
let localAuthContext = LAContext()
if localAuthContext.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil) {
requirePasscodeSectionChildren.append(
TouchIDSetting(
title: NSAttributedString.tableRowTitle(
NSLocalizedString("Use Touch ID", tableName: "AuthenticationManager", comment: "List section title for when to use Touch ID")
),
navigationController: self.navigationController,
delegate: nil,
enabled: true,
touchIDSuccess: { [unowned self] in
self.touchIDAuthenticationSucceeded()
},
touchIDFallback: { [unowned self] in
self.fallbackOnTouchIDFailure()
}
)
)
}
let requirePasscodeSection = SettingSection(title: nil, children: requirePasscodeSectionChildren)
settings += [
passcodeSection,
requirePasscodeSection,
]
return settings
}
private func passcodeDisabledSettings() -> [SettingSection] {
var settings = [SettingSection]()
let passcodeSectionTitle = NSAttributedString(string: AuthenticationStrings.passcode)
let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [
TurnPasscodeOnSetting(settings: self),
ChangePasscodeSetting(settings: self, delegate: nil, enabled: false)
])
let requirePasscodeSection = SettingSection(title: nil, children: [
RequirePasscodeSetting(settings: self, delegate: nil, enabled: false),
])
settings += [
passcodeSection,
requirePasscodeSection,
]
return settings
}
}
extension AuthenticationSettingsViewController {
func refreshSettings(notification: NSNotification) {
updateTitleForTouchIDState()
settings = generateSettings()
tableView.reloadData()
}
}
extension AuthenticationSettingsViewController: PasscodeEntryDelegate {
private func getTouchIDSetting() -> TouchIDSetting? {
guard settings.count >= 2 && settings[1].count >= 2 else {
return nil
}
return settings[1][1] as? TouchIDSetting
}
func touchIDAuthenticationSucceeded() {
getTouchIDSetting()?.toggleTouchID(enabled: false)
}
func fallbackOnTouchIDFailure() {
AppAuthenticator.presentPasscodeAuthentication(self.navigationController, delegate: self)
}
@objc func passcodeValidationDidSucceed() {
getTouchIDSetting()?.toggleTouchID(enabled: false)
navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
}
| mpl-2.0 | 487f9ff7af6ef79e1cea30ed872aa970 | 38.952229 | 184 | 0.684496 | 6.104623 | false | false | false | false |
frootloops/swift | stdlib/public/SwiftOnoneSupport/SwiftOnoneSupport.swift | 1 | 4734 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Pre-specialization of some popular generic classes and functions.
//===----------------------------------------------------------------------===//
import Swift
struct _Prespecialize {
// Create specializations for the arrays of most
// popular builtin integer and floating point types.
static internal func _specializeArrays() {
func _createArrayUser<Element : Comparable>(_ sampleValue: Element) {
// Initializers.
let _: [Element] = [sampleValue]
var a = [Element](repeating: sampleValue, count: 1)
// Read array element
let _ = a[0]
// Set array elements
for j in 1..<a.count {
a[0] = a[j]
a[j-1] = a[j]
}
for i1 in 0..<a.count {
for i2 in 0..<a.count {
a[i1] = a[i2]
}
}
a[0] = sampleValue
// Get count and capacity
let _ = a.count + a.capacity
// Iterate over array
for e in a {
print(e)
print("Value: \(e)")
}
// Iterate in reverse
for e in a.reversed() {
print(e)
print("Value: \(e)")
}
print(a)
// Reserve capacity
a.removeAll()
a.reserveCapacity(100)
// Sort array
let _ = a.sorted { (a: Element, b: Element) in a < b }
a.sort { (a: Element, b: Element) in a < b }
// force specialization of append.
a.append(a[0])
// force specialization of print<Element>
print(sampleValue)
print("Element:\(sampleValue)")
}
func _createArrayUserWithoutSorting<Element>(_ sampleValue: Element) {
// Initializers.
let _: [Element] = [sampleValue]
var a = [Element](repeating: sampleValue, count: 1)
// Read array element
let _ = a[0]
// Set array elements
for j in 0..<a.count {
a[0] = a[j]
}
for i1 in 0..<a.count {
for i2 in 0..<a.count {
a[i1] = a[i2]
}
}
a[0] = sampleValue
// Get length and capacity
let _ = a.count + a.capacity
// Iterate over array
for e in a {
print(e)
print("Value: \(e)")
}
// Iterate in reverse
for e in a.reversed() {
print(e)
print("Value: \(e)")
}
print(a)
// Reserve capacity
a.removeAll()
a.reserveCapacity(100)
// force specialization of append.
a.append(a[0])
// force specialization of print<Element>
print(sampleValue)
print("Element:\(sampleValue)")
}
// Force pre-specialization of arrays with elements of different
// integer types.
_createArrayUser(1 as Int)
_createArrayUser(1 as Int8)
_createArrayUser(1 as Int16)
_createArrayUser(1 as Int32)
_createArrayUser(1 as Int64)
_createArrayUser(1 as UInt)
_createArrayUser(1 as UInt8)
_createArrayUser(1 as UInt16)
_createArrayUser(1 as UInt32)
_createArrayUser(1 as UInt64)
// Force pre-specialization of arrays with elements of different
// floating point types.
_createArrayUser(1.5 as Float)
_createArrayUser(1.5 as Double)
// Force pre-specialization of string arrays
_createArrayUser("a" as String)
// Force pre-specialization of arrays with elements of different
// character and unicode scalar types.
_createArrayUser("a" as Character)
_createArrayUser("a" as Unicode.Scalar)
_createArrayUserWithoutSorting("a".utf8)
_createArrayUserWithoutSorting("a".utf16)
_createArrayUserWithoutSorting("a".unicodeScalars)
_createArrayUserWithoutSorting("a")
}
// Force pre-specialization of Range<Int>
@discardableResult
static internal func _specializeRanges() -> Int {
let a = [Int](repeating: 1, count: 10)
var count = 0
// Specialize Range for integers
for i in 0..<a.count {
count += a[i]
}
// Specialize Range for integers
for j in 0...a.count - 1{
count += a[j]
}
return count
}
}
// Mark with optimize(none) to make sure its not get
// rid of by dead function elimination.
@_optimize(none)
internal func _swift_forcePrespecializations() {
_Prespecialize._specializeArrays()
_Prespecialize._specializeRanges()
}
| apache-2.0 | 91028c6e418614ce3acc24bdecd449ca | 25.3 | 80 | 0.573933 | 4.230563 | false | false | false | false |
murilloarturo/CurrencyConverter | CurrencyConverter/App/Home/Router/HomeRouter.swift | 1 | 948 | //
// HomeRouter.swift
// CurrencyConverter
//
// Created by Arturo on 5/12/18.
// Copyright © 2018 AM. All rights reserved.
//
import UIKit
class HomeRouter {
private let navigation: UINavigationController
init() {
self.navigation = UINavigationController()
}
func showHome(with presenter: HomePresenter) {
let viewController = HomeViewController(presenter: presenter)
navigation.viewControllers = [viewController]
}
func setupApplicationWindow(_ window: UIWindow?) {
window?.rootViewController = navigation
window?.makeKeyAndVisible()
}
func showAlert(with message: String) {
let alert = UIAlertController(title: "", message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
navigation.present(alert, animated: true, completion: nil)
}
}
| mit | 32731d604d5dc08f33a8677dc99613d4 | 27.69697 | 112 | 0.674762 | 4.831633 | false | false | false | false |
pnhechim/Fiestapp-iOS | Fiestapp/Fiestapp/ViewControllers/MeGustas/BackgroundKolodaAnimator.swift | 5 | 1186 | //
// BackgroundKolodaAnimator.swift
// Koloda
//
// Created by Eugene Andreyev on 4/2/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import Koloda
import pop
class BackgroundKolodaAnimator: KolodaViewAnimator {
override func applyScaleAnimation(_ card: DraggableCardView, scale: CGSize, frame: CGRect, duration: TimeInterval, completion: AnimationCompletionBlock) {
let scaleAnimation = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
scaleAnimation?.springBounciness = 9
scaleAnimation?.springSpeed = 16
scaleAnimation?.toValue = NSValue(cgSize: scale)
card.layer.pop_add(scaleAnimation, forKey: "scaleAnimation")
let frameAnimation = POPSpringAnimation(propertyNamed: kPOPViewFrame)
frameAnimation?.springBounciness = 9
frameAnimation?.springSpeed = 16
frameAnimation?.toValue = NSValue(cgRect: frame)
if let completion = completion {
frameAnimation?.completionBlock = { _, finished in
completion(finished)
}
}
card.pop_add(frameAnimation, forKey: "frameAnimation")
}
}
| mit | 39420cf24d4ff95f9389c7045a3c0f08 | 32.857143 | 158 | 0.6827 | 5.313901 | false | false | false | false |
NorthernRealities/Rainbow-NSColor | NSColor+RainbowX11.swift | 1 | 65489 | //
// NSColor+RainbowX11.swift
// Rainbow X11 NSColor Extension
//
// Created by Reid Gravelle on 2015-04-02.
// Copyright (c) 2015 Northern Realities Inc. 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 NON-INFRINGEMENT. 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 AppKit
extension NSColor {
/**
Returns a NSColor object representing the color Alice Blue, whose RBG values are (240, 248, 255), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func aliceBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 240.0/255.0, green: 248.0/255.0, blue: 255.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Antique White, whose RBG values are (250, 235, 215), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func antiqueWhiteColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 250.0/255.0, green: 235.0/255.0, blue: 215.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Aqua, whose RBG values are (0, 255, 255), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func aquaColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Aquamarine, whose RBG values are (127, 255, 212), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func aquamarineColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 127.0/255.0, green: 255.0/255.0, blue: 212.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Azure (Web Color), whose RBG values are (240, 255, 255), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func azureWebColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 240.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Beige, whose RBG values are (245, 245, 220), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func beigeColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 245.0/255.0, green: 245.0/255.0, blue: 220.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Bisque, whose RBG values are (255, 228, 196), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func bisqueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 228.0/255.0, blue: 196.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Blanched Almond, whose RBG values are (255, 235, 205), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func blanchedAlmondColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 235.0/255.0, blue: 205.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Blue-Violet, whose RBG values are (138, 43, 226), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func blueVioletColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 138.0/255.0, green: 43.0/255.0, blue: 226.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Brown (Web), whose RBG values are (165, 42, 42), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func brownWebColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 165.0/255.0, green: 42.0/255.0, blue: 42.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Burlywood, whose RBG values are (222, 184, 135), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func burlywoodColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 222.0/255.0, green: 184.0/255.0, blue: 135.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Cadet Blue, whose RBG values are (95, 158, 160), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func cadetBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 95.0/255.0, green: 158.0/255.0, blue: 160.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Chartreuse (Web), whose RBG values are (127, 255, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func chartreuseWebColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 127.0/255.0, green: 255.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Chocolate (Web), whose RBG values are (210, 105, 30), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func chocolateWebColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 210.0/255.0, green: 105.0/255.0, blue: 30.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Coral, whose RBG values are (255, 127, 80), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func coralColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 127.0/255.0, blue: 80.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Cornflower Blue, whose RBG values are (100, 149, 237), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func cornflowerBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 100.0/255.0, green: 149.0/255.0, blue: 237.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Cornsilk, whose RBG values are (255, 248, 220), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func cornsilkColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 248.0/255.0, blue: 220.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Crimson, whose RBG values are (220, 20, 60), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func crimsonColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 220.0/255.0, green: 20.0/255.0, blue: 60.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Blue, whose RBG values are (0, 0, 139), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 0.0/255.0, blue: 139.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Cyan, whose RBG values are (0, 139, 139), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkCyanColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 139.0/255.0, blue: 139.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Goldenrod, whose RBG values are (184, 134, 11), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkGoldenrodColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 184.0/255.0, green: 134.0/255.0, blue: 11.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Gray (X11), whose RBG values are (169, 169, 169), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkGrayX11Color ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 169.0/255.0, green: 169.0/255.0, blue: 169.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Green (X11), whose RBG values are (0, 100, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkGreenX11Color ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 100.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Khaki, whose RBG values are (189, 183, 107), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkKhakiColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 189.0/255.0, green: 183.0/255.0, blue: 107.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Magenta, whose RBG values are (139, 0, 139), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkMagentaColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 139.0/255.0, green: 0.0/255.0, blue: 139.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Olive Green, whose RBG values are (85, 107, 47), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkOliveGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 85.0/255.0, green: 107.0/255.0, blue: 47.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Orange, whose RBG values are (255, 140, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkOrangeColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 140.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Orchid, whose RBG values are (153, 50, 204), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkOrchidColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 153.0/255.0, green: 50.0/255.0, blue: 204.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Red, whose RBG values are (139, 0, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkRedColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 139.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Salmon, whose RBG values are (233, 150, 122), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkSalmonColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 233.0/255.0, green: 150.0/255.0, blue: 122.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Sea Green, whose RBG values are (143, 188, 143), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkSeaGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 143.0/255.0, green: 188.0/255.0, blue: 143.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Slate Blue, whose RBG values are (72, 61, 139), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkSlateBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 72.0/255.0, green: 61.0/255.0, blue: 139.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Slate Gray, whose RBG values are (47, 79, 79), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkSlateGrayColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 47.0/255.0, green: 79.0/255.0, blue: 79.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Turquoise, whose RBG values are (0, 206, 209), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkTurquoiseColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 206.0/255.0, blue: 209.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dark Violet, whose RBG values are (148, 0, 211), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func darkVioletColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 148.0/255.0, green: 0.0/255.0, blue: 211.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Deep Pink, whose RBG values are (255, 20, 147), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func deepPinkColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 20.0/255.0, blue: 147.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Deep Sky Blue, whose RBG values are (0, 191, 255), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func deepSkyBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 191.0/255.0, blue: 255.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dim Gray, whose RBG values are (105, 105, 105), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func dimGrayColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 105.0/255.0, green: 105.0/255.0, blue: 105.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Dodger Blue, whose RBG values are (30, 144, 255), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func dodgerBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 30.0/255.0, green: 144.0/255.0, blue: 255.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Firebrick, whose RBG values are (178, 34, 34), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func firebrickColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 178.0/255.0, green: 34.0/255.0, blue: 34.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Floral White, whose RBG values are (255, 250, 240), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func floralWhiteColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 250.0/255.0, blue: 240.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Forest Green (Web), whose RBG values are (34, 139, 34), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func forestGreenWebColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 34.0/255.0, green: 139.0/255.0, blue: 34.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Fuchsia, whose RBG values are (255, 0, 255), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func fuchsiaColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 0.0/255.0, blue: 255.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Gainsboro, whose RBG values are (220, 220, 220), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func gainsboroColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 220.0/255.0, green: 220.0/255.0, blue: 220.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Ghost White, whose RBG values are (248, 248, 255), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func ghostWhiteColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 248.0/255.0, green: 248.0/255.0, blue: 255.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Gold (Web) (Golden), whose RBG values are (255, 215, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func goldWebGoldenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 215.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Goldenrod, whose RBG values are (218, 165, 32), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func goldenrodColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 218.0/255.0, green: 165.0/255.0, blue: 32.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Gray (X11 Gray), whose RBG values are (190, 190, 190), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func grayX11GrayColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 190.0/255.0, green: 190.0/255.0, blue: 190.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Green (Color Wheel) (X11 Green), whose RBG values are (0, 255, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func greenColorWheelX11GreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 255.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Green Yellow, whose RBG values are (173, 255, 47), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func greenYellowColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 173.0/255.0, green: 255.0/255.0, blue: 47.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Honeydew, whose RBG values are (240, 255, 240), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func honeydewColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 240.0/255.0, green: 255.0/255.0, blue: 240.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Hot Pink, whose RBG values are (255, 105, 180), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func hotPinkColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 105.0/255.0, blue: 180.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Indian Red, whose RBG values are (205, 92, 92), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func indianRedColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 205.0/255.0, green: 92.0/255.0, blue: 92.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Indigo, whose RBG values are (75, 0, 130), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func indigoColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 75.0/255.0, green: 0.0/255.0, blue: 130.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Ivory, whose RBG values are (255, 255, 240), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func ivoryColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 255.0/255.0, blue: 240.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Khaki, whose RBG values are (189, 183, 107), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func khakiColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 189.0/255.0, green: 183.0/255.0, blue: 107.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Lavender (Web), whose RBG values are (230, 230, 250), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lavenderWebColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 230.0/255.0, green: 230.0/255.0, blue: 250.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Lavender Blush, whose RBG values are (255, 240, 245), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lavenderBlushColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 240.0/255.0, blue: 245.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Lawn Green, whose RBG values are (124, 252, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lawnGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 124.0/255.0, green: 252.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Lemon Chiffon, whose RBG values are (255, 250, 205), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lemonChiffonColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 250.0/255.0, blue: 205.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Blue, whose RBG values are (173, 216, 230), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 173.0/255.0, green: 216.0/255.0, blue: 230.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Coral, whose RBG values are (240, 128, 128), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightCoralColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 240.0/255.0, green: 128.0/255.0, blue: 128.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Cyan, whose RBG values are (224, 255, 255), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightCyanColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 224.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Goldenrod Yellow, whose RBG values are (250, 250, 210), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightGoldenrodYellowColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 250.0/255.0, green: 250.0/255.0, blue: 210.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Gray (Alternate), whose RBG values are (211, 211, 211), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightGrayAlternateColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 211.0/255.0, green: 211.0/255.0, blue: 211.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Green, whose RBG values are (144, 238, 144), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 144.0/255.0, green: 238.0/255.0, blue: 144.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Pink, whose RBG values are (255, 182, 193), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightPinkColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 182.0/255.0, blue: 193.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Salmon, whose RBG values are (255, 160, 122), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightSalmonColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 160.0/255.0, blue: 122.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Sea Green, whose RBG values are (32, 178, 170), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightSeaGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 32.0/255.0, green: 178.0/255.0, blue: 170.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Sky Blue, whose RBG values are (135, 206, 250), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightSkyBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 135.0/255.0, green: 206.0/255.0, blue: 250.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Slate Gray, whose RBG values are (119, 136, 153), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightSlateGrayColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 119.0/255.0, green: 136.0/255.0, blue: 153.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Steel Blue, whose RBG values are (176, 196, 222), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightSteelBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 176.0/255.0, green: 196.0/255.0, blue: 222.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Light Yellow, whose RBG values are (255, 255, 224), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func lightYellowColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 255.0/255.0, blue: 224.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Lime (Web) (X11 Green), whose RBG values are (0, 255, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func limeWebX11GreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 255.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Lime Green, whose RBG values are (50, 205, 50), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func limeGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 50.0/255.0, green: 205.0/255.0, blue: 50.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Linen, whose RBG values are (250, 240, 230), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func linenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 250.0/255.0, green: 240.0/255.0, blue: 230.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Maroon (X11), whose RBG values are (176, 48, 96), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func maroonX11Color ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 176.0/255.0, green: 48.0/255.0, blue: 96.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Medium Aquamarine, whose RBG values are (102, 221, 170), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func mediumAquamarineColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 102.0/255.0, green: 221.0/255.0, blue: 170.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Medium Blue, whose RBG values are (0, 0, 205), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func mediumBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 0.0/255.0, blue: 205.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Medium Orchid, whose RBG values are (186, 85, 211), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func mediumOrchidColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 186.0/255.0, green: 85.0/255.0, blue: 211.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Medium Purple, whose RBG values are (147, 112, 219), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func mediumPurpleColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 147.0/255.0, green: 112.0/255.0, blue: 219.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Medium Sea Green, whose RBG values are (60, 179, 113), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func mediumSeaGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 60.0/255.0, green: 179.0/255.0, blue: 113.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Medium Slate Blue, whose RBG values are (123, 104, 238), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func mediumSlateBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 123.0/255.0, green: 104.0/255.0, blue: 238.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Medium Spring Green, whose RBG values are (0, 250, 154), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func mediumSpringGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 250.0/255.0, blue: 154.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Medium Turquoise, whose RBG values are (72, 209, 204), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func mediumTurquoiseColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 72.0/255.0, green: 209.0/255.0, blue: 204.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Medium Violet-Red, whose RBG values are (199, 21, 133), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func mediumVioletRedColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 199.0/255.0, green: 21.0/255.0, blue: 133.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Midnight Blue, whose RBG values are (25, 25, 112), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func midnightBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 25.0/255.0, green: 25.0/255.0, blue: 112.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Mint Cream, whose RBG values are (245, 255, 250), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func mintCreamColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 245.0/255.0, green: 255.0/255.0, blue: 250.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Misty Rose, whose RBG values are (255, 228, 225), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func mistyRoseColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 228.0/255.0, blue: 225.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Moccasin, whose RBG values are (250, 235, 215), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func moccasinColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 250.0/255.0, green: 235.0/255.0, blue: 215.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Navajo White, whose RBG values are (255, 222, 173), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func navajoWhiteColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 222.0/255.0, blue: 173.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Navy Blue, whose RBG values are (0, 0, 128), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func navyBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 0.0/255.0, blue: 128.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Old Lace, whose RBG values are (253, 245, 230), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func oldLaceColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 253.0/255.0, green: 245.0/255.0, blue: 230.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Olive, whose RBG values are (128, 128, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func oliveColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 128.0/255.0, green: 128.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Olive Drab #3, whose RBG values are (107, 142, 35), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func oliveDrabNumber3Color ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 107.0/255.0, green: 142.0/255.0, blue: 35.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Orange (Web), whose RBG values are (255, 165, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func orangeWebColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 165.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Orange-Red, whose RBG values are (255, 69, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func orangeRedColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 69.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Orchid, whose RBG values are (218, 112, 214), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func orchidColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 218.0/255.0, green: 112.0/255.0, blue: 214.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Pale Goldenrod, whose RBG values are (238, 232, 170), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func paleGoldenrodColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 238.0/255.0, green: 232.0/255.0, blue: 170.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Pale Green, whose RBG values are (152, 251, 152), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func paleGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 152.0/255.0, green: 251.0/255.0, blue: 152.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Pale Turquoise, whose RBG values are (175, 238, 238), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func paleTurquoiseColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 175.0/255.0, green: 238.0/255.0, blue: 238.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Pale Violet-Red, whose RBG values are (219, 112, 147), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func paleVioletRedColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 219.0/255.0, green: 112.0/255.0, blue: 147.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Papaya Whip, whose RBG values are (255, 239, 213), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func papayaWhipColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 239.0/255.0, blue: 213.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Peach Puff, whose RBG values are (255, 218, 185), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func peachPuffColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 218.0/255.0, blue: 185.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Peru, whose RBG values are (205, 133, 63), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func peruColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 205.0/255.0, green: 133.0/255.0, blue: 63.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Pink, whose RBG values are (255, 192, 203), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func pinkColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 192.0/255.0, blue: 203.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Plum (Web), whose RBG values are (221, 160, 221), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func plumWebColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 221.0/255.0, green: 160.0/255.0, blue: 221.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Powder Blue, whose RBG values are (176, 224, 230), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func powderBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 176.0/255.0, green: 224.0/255.0, blue: 230.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Purple (X11), whose RBG values are (160, 32, 240), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func purpleX11Color ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 160.0/255.0, green: 32.0/255.0, blue: 240.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Rebecca Purple, whose RBG values are (102, 52, 153), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func rebeccaPurpleColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 102.0/255.0, green: 52.0/255.0, blue: 153.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Rosy Brown, whose RBG values are (188, 143, 143), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func rosyBrownColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 188.0/255.0, green: 143.0/255.0, blue: 143.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Royal Blue, whose RBG values are (65, 105, 225), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func royalBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 65.0/255.0, green: 105.0/255.0, blue: 225.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Saddle Brown, whose RBG values are (139, 69, 19), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func saddleBrownColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 139.0/255.0, green: 69.0/255.0, blue: 19.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Salmon, whose RBG values are (250, 128, 114), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func salmonColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 250.0/255.0, green: 128.0/255.0, blue: 114.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Sandy Brown, whose RBG values are (244, 164, 96), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func sandyBrownColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 244.0/255.0, green: 164.0/255.0, blue: 96.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Sea Green, whose RBG values are (46, 139, 87), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func seaGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 46.0/255.0, green: 139.0/255.0, blue: 87.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Seashell, whose RBG values are (255, 245, 238), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func seashellColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 245.0/255.0, blue: 238.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Sienna (X11), whose RBG values are (160, 82, 45), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func siennaX11Color ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 160.0/255.0, green: 82.0/255.0, blue: 45.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Silver, whose RBG values are (192, 192, 192), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func silverColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 192.0/255.0, green: 192.0/255.0, blue: 192.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Sky Blue, whose RBG values are (135, 206, 235), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func skyBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 135.0/255.0, green: 206.0/255.0, blue: 235.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Slate Blue, whose RBG values are (106, 90, 205), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func slateBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 106.0/255.0, green: 90.0/255.0, blue: 205.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Slate Gray, whose RBG values are (112, 128, 144), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func slateGrayColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 112.0/255.0, green: 128.0/255.0, blue: 144.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Snow, whose RBG values are (255, 250, 250), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func snowColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 250.0/255.0, blue: 250.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Spring Green, whose RBG values are (0, 255, 127), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func springGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 255.0/255.0, blue: 127.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Steel Blue, whose RBG values are (70, 130, 180), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func steelBlueColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 70.0/255.0, green: 130.0/255.0, blue: 180.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Tan, whose RBG values are (210, 180, 140), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func tanColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 210.0/255.0, green: 180.0/255.0, blue: 140.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Teal, whose RBG values are (0, 128, 128), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func tealColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 128.0/255.0, blue: 128.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Thistle, whose RBG values are (216, 191, 216), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func thistleColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 216.0/255.0, green: 191.0/255.0, blue: 216.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Tomato, whose RBG values are (255, 99, 71), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func tomatoColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 255.0/255.0, green: 99.0/255.0, blue: 71.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Turquoise, whose RBG values are (64, 224, 208), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func turquoiseColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 64.0/255.0, green: 224.0/255.0, blue: 208.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Violet (Web), whose RBG values are (238, 130, 238), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func violetWebColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 238.0/255.0, green: 130.0/255.0, blue: 238.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Web Gray, whose RBG values are (128, 128, 128), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func webGrayColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 128.0/255.0, green: 128.0/255.0, blue: 128.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Web Green, whose RBG values are (0, 128, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func webGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 0.0/255.0, green: 128.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Web Maroon, whose RBG values are (127, 0, 0), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func webMaroonColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 127.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Web Purple, whose RBG values are (127, 0, 127), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func webPurpleColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 127.0/255.0, green: 0.0/255.0, blue: 127.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Wheat, whose RBG values are (245, 222, 179), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func wheatColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 245.0/255.0, green: 222.0/255.0, blue: 179.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color White Smoke, whose RBG values are (245, 245, 245), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func whiteSmokeColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 245.0/255.0, green: 245.0/255.0, blue: 245.0/255.0, alpha: alpha ) }
/**
Returns a NSColor object representing the color Yellow Green, whose RBG values are (154, 205, 50), and has the specified opacity.
:param: alpha A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
:returns: The NSColor object
*/
class func yellowGreenColor ( alpha: CGFloat = 1.0 ) -> NSColor {
return NSColor.init ( SRGBRed: 154.0/255.0, green: 205.0/255.0, blue: 50.0/255.0, alpha: alpha ) }
}
| mit | a9001c5ec4e62eb36ab26e57dab5f151 | 37.819798 | 149 | 0.667944 | 3.673173 | false | false | false | false |
josherick/DailySpend | DailySpend/Image+CoreDataClass.swift | 1 | 3744 | //
// Image+CoreDataClass.swift
// DailySpend
//
// Created by Josh Sherick on 6/29/17.
// Copyright © 2017 Josh Sherick. All rights reserved.
//
import Foundation
import CoreData
@objc(Image)
class Image: NSManagedObject {
func json() -> [String: Any]? {
var jsonObj = [String: Any]()
if let imageName = imageName {
jsonObj["imageName"] = imageName
} else {
Logger.debug("couldn't unwrap imageName in Image")
return nil
}
if let dateCreated = dateCreated {
let num = dateCreated.timeIntervalSince1970 as NSNumber
jsonObj["dateCreated"] = num
} else {
Logger.debug("couldn't unwrap dateCreated in Image")
return nil
}
return jsonObj
}
func serialize() -> Data? {
if let jsonObj = self.json() {
let serialization = try? JSONSerialization.data(withJSONObject: jsonObj)
return serialization
}
return nil
}
class func create(context: NSManagedObjectContext,
json: [String: Any]) -> Image? {
let image = Image(context: context)
if let imageName = json["imageName"] as? String {
if imageName.count == 0 {
Logger.debug("imageName is empty in Image")
return nil
}
image.imageName = imageName
} else {
Logger.debug("couldn't unwrap imageName in Image")
return nil
}
if let dateCreated = json["dateCreated"] as? NSNumber {
let date = Date(timeIntervalSince1970: dateCreated.doubleValue)
if date > Date() {
Logger.debug("dateCreated after today in Image")
return nil
}
image.dateCreated = date
} else {
Logger.debug("couldn't unwrap dateCreated in Image")
return nil
}
return image
}
var dateCreated: Date? {
get {
return dateCreated_ as Date?
}
set {
if newValue != nil {
dateCreated_ = newValue! as NSDate
} else {
dateCreated_ = nil
}
}
}
var imageName: String? {
get {
return imageName_
}
set {
imageName_ = newValue
}
}
var imageURL: URL? {
if let imageName = self.imageName {
let fm = FileManager.default
let urls = fm.urls(for: .documentDirectory, in: .userDomainMask)
let imagesDirUrl = urls[0].appendingPathComponent("images",
isDirectory: true)
return imagesDirUrl.appendingPathComponent(imageName,
isDirectory: false)
} else {
return nil
}
}
var image: UIImage? {
return imageURL != nil ? UIImage(contentsOfFile: imageURL!.path) : nil
}
var expense: Expense? {
get {
return expense_
}
set {
expense_ = newValue
}
}
override func prepareForDeletion() {
if let imageURL = self.imageURL {
// Attempt to delete our image.
do {
try FileManager.default.removeItem(at: imageURL)
} catch {
// We don't *really* care, but log for good measure.
Logger.warning("The file at at \(imageURL) wasn't able to be deleted.")
}
}
}
}
| mit | b66414ee30de41cae4ea97f2438c9600 | 26.321168 | 87 | 0.491317 | 5.416787 | false | false | false | false |
aidenluo177/Weather-Swift | Weather/Carthage/Checkouts/SwiftyJSON/Tests/PrintableTests.swift | 116 | 3599 | // PrintableTests.swift
//
// Copyright (c) 2014 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 XCTest
import SwiftyJSON
class PrintableTests: XCTestCase {
func testNumber() {
var json:JSON = 1234567890.876623
XCTAssertEqual(json.description, "1234567890.876623")
XCTAssertEqual(json.debugDescription, "1234567890.876623")
}
func testBool() {
var jsonTrue:JSON = true
XCTAssertEqual(jsonTrue.description, "true")
XCTAssertEqual(jsonTrue.debugDescription, "true")
var jsonFalse:JSON = false
XCTAssertEqual(jsonFalse.description, "false")
XCTAssertEqual(jsonFalse.debugDescription, "false")
}
func testString() {
var json:JSON = "abcd efg, HIJK;LMn"
XCTAssertEqual(json.description, "abcd efg, HIJK;LMn")
XCTAssertEqual(json.debugDescription, "abcd efg, HIJK;LMn")
}
func testNil() {
var jsonNil_1:JSON = nil
XCTAssertEqual(jsonNil_1.description, "null")
XCTAssertEqual(jsonNil_1.debugDescription, "null")
var jsonNil_2:JSON = JSON(NSNull())
XCTAssertEqual(jsonNil_2.description, "null")
XCTAssertEqual(jsonNil_2.debugDescription, "null")
}
func testArray() {
var json:JSON = [1,2,"4",5,"6"]
var description = json.description.stringByReplacingOccurrencesOfString("\n", withString: "")
description = description.stringByReplacingOccurrencesOfString(" ", withString: "")
XCTAssertEqual(description, "[1,2,\"4\",5,\"6\"]")
XCTAssertTrue(json.description.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0)
XCTAssertTrue(json.debugDescription.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0)
}
func testDictionary() {
var json:JSON = ["1":2,"2":"two", "3":3]
var debugDescription = json.debugDescription.stringByReplacingOccurrencesOfString("\n", withString: "")
debugDescription = debugDescription.stringByReplacingOccurrencesOfString(" ", withString: "")
XCTAssertTrue(json.description.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0)
XCTAssertTrue(debugDescription.rangeOfString("\"1\":2", options: NSStringCompareOptions.CaseInsensitiveSearch) != nil)
XCTAssertTrue(debugDescription.rangeOfString("\"2\":\"two\"", options: NSStringCompareOptions.CaseInsensitiveSearch) != nil)
XCTAssertTrue(debugDescription.rangeOfString("\"3\":3", options: NSStringCompareOptions.CaseInsensitiveSearch) != nil)
}
}
| mit | 071489af0a5b0efefb8c1a2b4b89ad5a | 46.986667 | 132 | 0.707419 | 4.741765 | false | true | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/DynamicButton/Sources/DynamicButtonStyles/DynamicButtonStyleStop.swift | 3 | 2120 | /*
* DynamicButton
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
/// Stop symbol style: ◼ \{U+2588}
final public class DynamicButtonStyleStop: DynamicButtonStyle {
convenience required public init(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) {
let thirdSize = size / 3
let a = CGPoint(x: center.x - thirdSize, y: center.y - thirdSize)
let b = CGPoint(x: center.x - thirdSize, y: center.y + thirdSize)
let c = CGPoint(x: center.x + thirdSize, y: center.y + thirdSize)
let d = CGPoint(x: center.x + thirdSize, y: center.y - thirdSize)
let p1 = PathHelper.line(from: a, to: b)
let p2 = PathHelper.line(from: b, to: c)
let p3 = PathHelper.line(from: c, to: d)
let p4 = PathHelper.line(from: d, to: a)
self.init(pathVector: (p1, p2, p3, p4))
}
// MARK: - Conforming the CustomStringConvertible Protocol
/// A textual representation of "Stop" style.
public override var description: String {
return "Stop"
}
}
| mit | 6e534b373052d641d3e355a6ba0f5b96 | 38.962264 | 105 | 0.716242 | 3.981203 | false | false | false | false |
DenisSamokhin/test-server | Sources/App/Models/Person.swift | 1 | 1724 | //
// Person.swift
// test-server
//
// Created by Denis on 28.03.17.
//
//
import Foundation
import Vapor
import Fluent
final class Human: Model {
var name: String
var email: String
var id: Node?
var age: Int
var imageURL: String
var exists: Bool = false
init(name:String, email:String, age:Int, imageURL:String) {
self.name = name
self.email = email
self.age = age
self.imageURL = imageURL
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
name = try node.extract("name")
email = try node.extract("email")
age = try node.extract("age")
imageURL = try node.extract("image_url")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"name": name,
"email": email,
"age": age,
"image_url":imageURL
])
}
static func prepare(_ database: Database) throws {
try database.create("test_users") { (person) in
person.id()
person.string("name")
person.string("email")
person.int("age")
person.string("image_url")
}
}
static func revert(_ database: Database) throws {
try database.delete("test_users")
}
}
struct AddImageUrlToHumans: Preparation {
static func prepare(_ database: Database) throws {
try database.modify("humans", closure: { bar in
bar.string("image_url", length: 250, optional: false, unique: false, default: nil)
})
}
static func revert(_ database: Database) throws {
}
}
| mit | 3fe54e6ef813f1e65aeff9c6e29f3898 | 23.28169 | 94 | 0.548724 | 4.085308 | false | false | false | false |
dclelland/AudioKit | AudioKit/OSX/AudioKit/AudioKit for OSX.playground/Sources/AKPlaygroundView.swift | 1 | 4468 | //
// AKPlaygroundView.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import Cocoa
public typealias Label = AKLabel
public typealias Slider = AKSlider
public class AKLabel: NSTextField {
override public init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public var text: String = "" {
didSet {
stringValue = text
}
}
}
public class AKSlider: NSSlider {
override public init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public var value: Float {
get {
return floatValue
}
set {
floatValue = value
}
}
}
public class AKPlaygroundView: NSView {
public var elementHeight: CGFloat = 30
public var yPosition: Int = 80
public var horizontalSpacing = 40
public var lastButton: NSButton?
override public init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setup()
}
public func setup() {
}
override public func drawRect(dirtyRect: NSRect) {
NSColor.whiteColor().setFill()
NSRectFill(dirtyRect)
super.drawRect(dirtyRect)
}
public func addLineBreak() {
lastButton = nil
}
public func addTitle(text: String) -> NSTextField {
let newLabel = NSTextField(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: 2 * elementHeight))
newLabel.stringValue = text
newLabel.editable = false
newLabel.drawsBackground = false
newLabel.bezeled = false
newLabel.alignment = NSCenterTextAlignment
newLabel.frame.origin.y = self.bounds.height - CGFloat(2 * horizontalSpacing)
newLabel.font = NSFont.boldSystemFontOfSize(24)
self.addSubview(newLabel)
yPosition += horizontalSpacing
return newLabel
}
public func addButton(label: String, action: Selector) -> NSButton {
let newButton = NSButton(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: elementHeight))
newButton.title = "\(label) "
newButton.font = NSFont.systemFontOfSize(18)
// Line up multiple buttons in a row
if let button = lastButton {
newButton.frame.origin.x += button.frame.origin.x + button.frame.width + 10
yPosition -= horizontalSpacing
}
newButton.frame.origin.y = self.bounds.height - CGFloat(yPosition)
newButton.sizeToFit()
newButton.bezelStyle = NSBezelStyle.ShadowlessSquareBezelStyle
newButton.target = self
newButton.action = action
self.addSubview(newButton)
yPosition += horizontalSpacing
lastButton = newButton
return newButton
}
public func addLabel(text: String) -> AKLabel {
lastButton = nil
let newLabel = AKLabel(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: elementHeight))
newLabel.stringValue = text
newLabel.editable = false
newLabel.drawsBackground = false
newLabel.bezeled = false
newLabel.font = NSFont.systemFontOfSize(18)
newLabel.frame.origin.y = self.bounds.height - CGFloat(yPosition)
self.addSubview(newLabel)
yPosition += horizontalSpacing
return newLabel
}
public func addSlider(action: Selector, value: Double = 0, minimum: Double = 0, maximum: Double = 1) -> AKSlider {
lastButton = nil
let newSlider = AKSlider(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: 20))
newSlider.frame.origin.y = self.bounds.height - CGFloat(yPosition)
newSlider.minValue = Double(minimum)
newSlider.maxValue = Double(maximum)
newSlider.floatValue = Float(value)
newSlider.setNeedsDisplay()
newSlider.target = self
newSlider.action = action
self.addSubview(newSlider)
yPosition += horizontalSpacing
return newSlider
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 20ec5a48e453aef6fed835a1067995d0 | 29.813793 | 118 | 0.62735 | 4.74814 | false | false | false | false |
yaroslav-zhurakovskiy/PainlessInjection | Tests/Fixtures/Modules.swift | 1 | 893 | //
// Modules.swift
// PainlessInjection
//
// Created by Yaroslav Zhurakovskiy on 7/11/16.
// Copyright © 2016 Yaroslav Zhurakovskiy. All rights reserved.
//
import Foundation
import PainlessInjection
import XCTest
class EmptyTestModule: Module {
override func load() {
}
}
class ModuleWithDependency: Module {
var dependency: Dependency!
required init() {
super.init()
}
override func load() {
define(String.self) { "Hello" } . decorate { dependency in
self.dependency = dependency
return dependency
}
}
func assertDependencyType(_ type: Any.Type, file: StaticString = #file, line: UInt = #line) {
XCTAssertTrue(
dependency.type == type,
"Type should be String but got \(dependency.type)",
file: file,
line: line
)
}
}
| mit | a866304ba59f634fde16447ac69957f4 | 20.756098 | 97 | 0.596413 | 4.46 | false | false | false | false |
benzguo/MusicKit | MusicKit/ChordExtensions.swift | 1 | 931 | // Copyright (c) 2015 Ben Guo. All rights reserved.
import Foundation
extension Chord {
/// Creates a new `Harmonizer` using the (1-indexed) indices of the given harmonizer
public static func create(_ harmonizer: Harmonizer, indices: [UInt]) -> Harmonizer {
if indices.count < 2 || indices.contains(0) {
return Harmony.IdentityHarmonizer
}
// sort and convert to zero-indexed indices
let sortedIndices = (indices.map { $0 - 1 }).sorted()
let maxIndex = Int(sortedIndices.last!)
var scalePitches = harmonizer(Chroma.c*0)
// extend scale until it covers the max index
while (scalePitches.count < maxIndex + 1) {
scalePitches = scalePitches.extend(1)
}
let chosenPitches = PitchSet(sortedIndices.map { scalePitches[Int($0)] })
return Harmony.create(MKUtil.intervals(chosenPitches.semitoneIndices()))
}
}
| mit | 49c15ae83af5e39957eea1668f7a6112 | 36.24 | 88 | 0.647691 | 4.15625 | false | false | false | false |
easyui/EZPlayer | EZPlayer/EZPlayerFullScreenViewController.swift | 1 | 4498 | //
// EZFullScreenViewController.swift
// EZPlayer
//
// Created by yangjun zhu on 2016/12/28.
// Copyright © 2016年 yangjun zhu. All rights reserved.
//
import UIKit
open class EZPlayerFullScreenViewController: UIViewController {
weak var player: EZPlayer!
private var statusbarBackgroundView: UIView!
public var preferredlandscapeForPresentation = UIInterfaceOrientation.landscapeLeft
public var currentOrientation = UIDevice.current.orientation
// MARK: - Life cycle
deinit {
NotificationCenter.default.removeObserver(self)
}
override open func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.playerControlsHiddenDidChange(_:)), name: NSNotification.Name.EZPlayerControlsHiddenDidChange, object: nil)
self.view.backgroundColor = UIColor.black
self.statusbarBackgroundView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: UIApplication.shared.statusBarFrame.size.height))
self.statusbarBackgroundView.backgroundColor = self.player.fullScreenStatusbarBackgroundColor
self.statusbarBackgroundView.autoresizingMask = [ .flexibleWidth,.flexibleLeftMargin,.flexibleRightMargin,.flexibleBottomMargin]
self.view.addSubview(self.statusbarBackgroundView)
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override open func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
// MARK: - Orientations
override open var shouldAutorotate : Bool {
return true
}
override open var supportedInterfaceOrientations : UIInterfaceOrientationMask {
switch self.player.fullScreenMode {
case .portrait:
return [.portrait]
case .landscape:
return [.landscapeLeft,.landscapeRight]
}
}
override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
self.currentOrientation = preferredlandscapeForPresentation == .landscapeLeft ? .landscapeRight : .landscapeLeft
switch self.player.fullScreenMode {
case .portrait:
self.currentOrientation = .portrait
return .portrait
case .landscape:
// self.statusbarBackgroundView.isHidden = (EZPlayerUtils.hasSafeArea || (ProcessInfo.processInfo.operatingSystemVersion.majorVersion >= 13))
return self.preferredlandscapeForPresentation
}
}
// MARK: - status bar
private var statusBarHiddenAnimated = true
override open var prefersStatusBarHidden: Bool{
self.statusbarBackgroundView.frame = CGRect(x: 0, y: 0, width: self.statusbarBackgroundView.bounds.width, height: (self.player.fullScreenMode == .portrait) ? EZPlayerUtils.statusBarHeight : 20.0)
if self.statusBarHiddenAnimated {
UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: {
self.statusbarBackgroundView.alpha = self.player.controlsHidden ? 0 : 1
}, completion: {finished in
})
}else{
self.statusbarBackgroundView.alpha = self.player.controlsHidden ? 0 : 1
}
return self.player.controlsHidden
}
override open var preferredStatusBarStyle: UIStatusBarStyle{
return self.player.fullScreenPreferredStatusBarStyle
}
// MARK: - notification
@objc func playerControlsHiddenDidChange(_ notifiaction: Notification) {
self.statusBarHiddenAnimated = notifiaction.userInfo?[Notification.Key.EZPlayerControlsHiddenDidChangeByAnimatedKey] as? Bool ?? true
_ = self.prefersStatusBarHidden
self.setNeedsStatusBarAppearanceUpdate()
if #available(iOS 11.0, *) {
self.setNeedsUpdateOfHomeIndicatorAutoHidden()
}
}
override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.currentOrientation = UIDevice.current.orientation
}
open override var prefersHomeIndicatorAutoHidden: Bool{
return self.player.controlsHidden
}
}
| mit | b62758e1766d2e3d42e4b66a7795da6b | 35.544715 | 203 | 0.709677 | 5.61875 | false | false | false | false |
tnantoka/Gradientor | Gradientor/Models/Gradient.swift | 1 | 3496 | //
// Gradient.swift
// Gradientor
//
// Created by Tatsuya Tobioka on 2017/04/24.
// Copyright © 2017 tnantoka. All rights reserved.
//
import UIKit
import ChameleonFramework
struct Gradient {
enum Direction: Int {
case horizontal
case vertical
case radial
case diagonalLR
case diagonalRL
}
var layer: GradientLayer = LinerLayer()
var colors = [UIColor]() {
didSet {
layer.colors = colors.map { $0.cgColor }
}
}
var frame = CGRect.zero {
didSet {
layer.frame = frame
}
}
var direction = Direction.horizontal {
didSet {
switch direction {
case .horizontal:
if layer.isKind(of: RadialLayer.self) {
layer = LinerLayer()
}
layer.startPoint = CGPoint(x: 0.5, y: 0.0)
layer.endPoint = CGPoint(x: 0.5, y: 1.0)
case .vertical:
if layer.isKind(of: RadialLayer.self) {
layer = LinerLayer()
}
layer.startPoint = CGPoint(x: 0.0, y: 0.5)
layer.endPoint = CGPoint(x: 1.0, y: 0.5)
case .radial:
if !layer.isKind(of: RadialLayer.self) {
layer = RadialLayer()
}
case .diagonalLR:
if layer.isKind(of: RadialLayer.self) {
layer = LinerLayer()
}
layer.startPoint = CGPoint(x: 0.0, y: 0.0)
layer.endPoint = CGPoint(x: 1.0, y: 1.0)
case .diagonalRL:
if layer.isKind(of: RadialLayer.self) {
layer = LinerLayer()
}
layer.startPoint = CGPoint(x: 1.0, y: 0.0)
layer.endPoint = CGPoint(x: 0.0, y: 1.0)
}
}
}
var image: UIImage {
UIGraphicsBeginImageContextWithOptions(frame.size, false, 1.0)
defer {
UIGraphicsEndImageContext()
}
guard let context = UIGraphicsGetCurrentContext() else { return UIImage() }
layer.render(in: context)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage() }
return image
}
var text: String {
return colors.map { $0.hexValue() }.joined(separator: ", ")
}
}
class GradientLayer: CAGradientLayer {
}
class LinerLayer: GradientLayer {
}
class RadialLayer: GradientLayer {
override var colors: [Any]? {
didSet {
setNeedsDisplay()
}
}
override var frame: CGRect {
didSet {
setNeedsDisplay()
}
}
override func draw(in ctx: CGContext) {
guard let colors = colors, colors.count > 1 else { return }
let locations = stride(from: 0.0, to: 1.0, by: 1.0 / Double(colors.count)).map { CGFloat($0) }
guard let gradient = CGGradient(
colorsSpace: CGColorSpaceCreateDeviceRGB(),
colors: colors as CFArray,
locations: locations
) else { return }
let center = CGPoint(x: bounds.midX, y: bounds.midY)
ctx.drawRadialGradient(
gradient,
startCenter: center,
startRadius: 0.0,
endCenter: center,
endRadius: min(bounds.width, bounds.height),
options: [.drawsBeforeStartLocation, .drawsAfterEndLocation]
)
}
}
| mit | a068b4c1ca1e2a8a419c41cbdb7f45d8 | 26.96 | 102 | 0.523891 | 4.574607 | false | false | false | false |
jamesdouble/JDGamesLoading | JDGamesLoading/JDGamesLoading/JDSnackScene.swift | 1 | 16404 | //
// JDSnackScene.swift
// JDGamesLoading
//
// Created by 郭介騵 on 2017/2/14.
// Copyright © 2017年 james12345. All rights reserved.
//
import SpriteKit
import GameplayKit
struct SnackBasicSetting {
static let SnackHeadCategoryName = "SnackHead"
static let SnackBodyCategoryName = "SnackBody"
static let FoodCategoryName = "Food"
static let SnackHeadCategory : UInt32 = 0x1 << 0
static let SnackBodyCategory : UInt32 = 0x1 << 1
static let FoodCategory : UInt32 = 0x1 << 2
static var SnackPixelColor:UIColor = UIColor.green
}
struct TurnRoundPoint {
var turnRoundPosition:CGPoint = CGPoint.zero
var turnRoundDirection:CGVector = CGVector.zero
var PassBodyID:[Int] = []
}
class SnackShapeNode:SKShapeNode
{
var PixelSize:CGSize = CGSize.zero
var InstanceDirection:CGVector = CGVector.zero
init(size:CGSize) {
super.init()
let rect = CGRect(origin: CGPoint.zero, size: size)
self.path = CGPath(rect: rect, transform: nil)
PixelSize = size
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class SnackHeadNode:SnackShapeNode
{
override init(size:CGSize) {
super.init(size:size)
self.fillColor = SnackBasicSetting.SnackPixelColor
self.name = SnackBasicSetting.SnackHeadCategoryName
self.physicsBody = SKPhysicsBody(rectangleOf: PixelSize)
self.physicsBody!.categoryBitMask = SnackBasicSetting.SnackHeadCategory
self.physicsBody!.contactTestBitMask = SnackBasicSetting.FoodCategory
self.physicsBody!.isDynamic = true
self.physicsBody!.collisionBitMask = 0
self.zPosition = 2
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class SnackBodyNode:SnackShapeNode
{
var BodyID:Int = 0
override init(size:CGSize) {
super.init(size:size)
self.position = CGPoint.zero
self.fillColor = SnackBasicSetting.SnackPixelColor
self.name = SnackBasicSetting.SnackBodyCategoryName
self.physicsBody = SKPhysicsBody(rectangleOf: PixelSize)
self.physicsBody!.categoryBitMask = SnackBasicSetting.SnackBodyCategory
self.physicsBody!.isDynamic = false
self.physicsBody!.collisionBitMask = 0
self.zPosition = 2
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class JDSnackScene: SKScene{
/*
Window Size
*/
var defaultwindowwidth:CGFloat = 200.0
var windowscale:CGFloat
{
get{
return (self.frame.width / defaultwindowwidth)
}
}
/*
Pixel Size
*/
var d_PixelSize:CGSize = CGSize(width: 15.0, height: 15.0)
var PixelSize:CGSize
{
get{
let size:CGSize = CGSize(width: d_PixelSize.width * windowscale, height: d_PixelSize.width * windowscale)
return size
}
}
/*
Pixel Color
*/
var FoodPixelColor:UIColor = UIColor.white
/*
Snack
*/
var SnackBodyNodeCount:Int = 0
var SncakSpeed:CGFloat = 50
var HeadPixel:SKShapeNode!
/*
Direction
*/
var NowDirection:CGVector = CGVector(dx: 0.0, dy: 1.0)
var LastTimeInterval:TimeInterval?
var turnroundArr:[TurnRoundPoint] = [TurnRoundPoint]()
override func update(_ currentTime: TimeInterval) {
//Speed
if(LastTimeInterval == nil)
{
LastTimeInterval = currentTime
return
}
let InstanceScale:CGFloat = CGFloat(currentTime - LastTimeInterval!)
let InstanceSpeed:CGFloat = self.SncakSpeed * InstanceScale
let Vecter:CGVector = CGVector(dx: InstanceSpeed * NowDirection.dx, dy: InstanceSpeed * NowDirection.dy)
//Update All Snack
//SnackHead
var LastPixelPoint:CGPoint?
self.enumerateChildNodes(withName: SnackBasicSetting.SnackHeadCategoryName) {
node, stop in
if let snackHead:SnackHeadNode = node as? SnackHeadNode
{
LastPixelPoint = node.position
let newPostition = CGPoint(x: (node.position.x) + (Vecter.dx), y: (node.position.y) + (Vecter.dy))
snackHead.position = self.TouchTheWallDetect(input: newPostition)
}
}
//SnackBody
var LastDirection:CGVector = NowDirection
self.enumerateChildNodes(withName: SnackBasicSetting.SnackBodyCategoryName)
{
node, stop in
if let NewPosition = LastPixelPoint,let snackBody:SnackBodyNode = node as? SnackBodyNode
{
if(snackBody.InstanceDirection == CGVector.zero) //NewPixel
{
snackBody.position.x = NewPosition.x - LastDirection.dx * self.PixelSize.width
snackBody.position.y = NewPosition.y - LastDirection.dy * self.PixelSize.width
snackBody.InstanceDirection = LastDirection
}
else if(self.turnroundArr.count == 0) //Direct Forward
{
let newPostition = CGPoint(x: snackBody.position.x + snackBody.InstanceDirection.dx * InstanceSpeed, y: snackBody.position.y + snackBody.InstanceDirection.dy * InstanceSpeed)
snackBody.position = self.TouchTheWallDetect(input: newPostition)
}
else //TurnRound
{
var HasMove:Bool = false
let NewX = snackBody.position.x + snackBody.InstanceDirection.dx * InstanceSpeed
let NewY = snackBody.position.y + snackBody.InstanceDirection.dy * InstanceSpeed
var index:Int = 0
for turnRound in self.turnroundArr
{
if(turnRound.PassBodyID.contains(snackBody.BodyID)) //已走過,Pass到下一個turnRound
{
index += 1
continue
}
else if(abs(snackBody.InstanceDirection.dx) == 1 && abs(snackBody.position.y - turnRound.turnRoundPosition.y) < 0.1) //橫向超越
{
let PostiveOrNegative:Bool = (snackBody.InstanceDirection.dx > 0)
let ChekingExceed:Bool = PostiveOrNegative ? (NewX > turnRound.turnRoundPosition.x) : (NewX < turnRound.turnRoundPosition.x)
if(!ChekingExceed)
{
let newPostition = CGPoint(x: NewX, y: NewY)
snackBody.position = self.TouchTheWallDetect(input: newPostition)
HasMove = true
break
}
//確定要轉彎
self.turnroundArr[index].PassBodyID.append(snackBody.BodyID)
let ExceedLength:CGFloat = PostiveOrNegative ? (NewX - turnRound.turnRoundPosition.x) : (turnRound.turnRoundPosition.x - NewX)
let NewX = turnRound.turnRoundPosition.x
let NewY = snackBody.position.y + turnRound.turnRoundDirection.dy * ExceedLength
let newPostition = CGPoint(x: NewX, y: NewY)
snackBody.position = self.TouchTheWallDetect(input: newPostition)
snackBody.InstanceDirection = turnRound.turnRoundDirection
HasMove = true
break
}
else if(abs(snackBody.InstanceDirection.dy) == 1 && abs(snackBody.position.x - turnRound.turnRoundPosition.x) < 0.1) //垂直
{
let PostiveOrNegative:Bool = (snackBody.InstanceDirection.dy > 0)
let ChekingExceed:Bool = PostiveOrNegative ? (NewY > turnRound.turnRoundPosition.y) : (NewY < turnRound.turnRoundPosition.y)
if(!ChekingExceed)
{
let newPostition = CGPoint(x: NewX, y: NewY)
snackBody.position = self.TouchTheWallDetect(input: newPostition)
HasMove = true
break
}
self.turnroundArr[index].PassBodyID.append(snackBody.BodyID)
let ExceedLength:CGFloat = PostiveOrNegative ? (NewY - turnRound.turnRoundPosition.y) : (turnRound.turnRoundPosition.y - NewY)
let NewX = snackBody.position.x + turnRound.turnRoundDirection.dx * ExceedLength
let NewY = turnRound.turnRoundPosition.y
let newPostition = CGPoint(x: NewX, y: NewY)
snackBody.position = self.TouchTheWallDetect(input: newPostition)
snackBody.InstanceDirection = turnRound.turnRoundDirection
HasMove = true
break
}
index += 1
}
if(!HasMove) //No Turn Round
{
let newPostition = CGPoint(x: NewX, y: NewY)
snackBody.position = self.TouchTheWallDetect(input: newPostition)
}
}
LastDirection = snackBody.InstanceDirection
LastPixelPoint = snackBody.position
}
}
//
var Index:Int = 0
for turnRound in self.turnroundArr
{
if(turnRound.PassBodyID.count >= self.SnackBodyNodeCount)
{
self.turnroundArr.remove(at: Index)
continue
}
Index += 1
}
LastTimeInterval = currentTime
}
override init(size: CGSize) {
super.init(size: size)
self.backgroundColor = UIColor.clear
}
init(size: CGSize,configuration:JDSnackGameConfiguration) {
super.init(size: size)
SnackBasicSetting.SnackPixelColor = configuration.Snack_color
FoodPixelColor = configuration.Food_color
SncakSpeed = configuration.Snack_Speed
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMove(to view: SKView) {
super.didMove(to: view)
//Set Border
let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
borderBody.friction = 0
self.physicsBody = borderBody
self.physicsWorld.gravity = CGVector.zero
self.physicsWorld.contactDelegate = self
//
initSnack()
AddrandomFood()
//
let swipeRight:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedRight(sender:)))
swipeRight.direction = .right
view.addGestureRecognizer(swipeRight)
let swipeLeft:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedLeft(sender:)))
swipeLeft.direction = .left
view.addGestureRecognizer(swipeLeft)
let swipeUp:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedUp(sender:)))
swipeUp.direction = .up
view.addGestureRecognizer(swipeUp)
let swipeDown:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedDown(sender:)))
swipeDown.direction = .down
view.addGestureRecognizer(swipeDown)
}
func initSnack()
{
HeadPixel = SnackHeadNode(size: PixelSize)
HeadPixel.position = CGPoint(x: self.frame.width * 0.5 , y: self.frame.width * 0.5)
self.addChild(HeadPixel)
}
func AddrandomFood()
{
let randomX:CGFloat = randomFloat(from: 0, to: self.frame.width)
let randomY:CGFloat = randomFloat(from: 0, to: self.frame.height)
let Food:SKShapeNode = SKShapeNode(rectOf: PixelSize)
Food.position = CGPoint(x: randomX, y: randomY)
Food.name = SnackBasicSetting.FoodCategoryName
Food.fillColor = FoodPixelColor
Food.physicsBody = SKPhysicsBody(rectangleOf: PixelSize)
Food.physicsBody!.categoryBitMask = SnackBasicSetting.FoodCategory
Food.physicsBody!.contactTestBitMask = SnackBasicSetting.SnackHeadCategory
Food.physicsBody!.isDynamic = false
Food.physicsBody!.collisionBitMask = 0
Food.zPosition = 2
self.addChild(Food)
}
func TouchTheWallDetect(input:CGPoint)->CGPoint
{
var result = input
if(input.x > self.frame.width)
{
let exceedLength:CGFloat = input.x - self.frame.width
result.x = exceedLength
}
else if(input.x < 0)
{
let exceedLength:CGFloat = 0 - input.x
result.x = self.frame.width - exceedLength
}
if(input.y > self.frame.height)
{
let exceedLength:CGFloat = input.y - self.frame.height
result.y = exceedLength
}
else if(input.y < 0)
{
let exceedLength:CGFloat = 0 - input.y
result.y = self.frame.height - exceedLength
}
return result
}
func randomFloat(from: CGFloat, to: CGFloat) -> CGFloat {
let rand: CGFloat = CGFloat(Float(arc4random()) / 0xFFFFFFFF)
return (rand) * (to - from) + from
}
}
extension JDSnackScene
{
func swipedRight(sender:UISwipeGestureRecognizer){
self.NowDirection = CGVector(dx: 1.0, dy: 0.0)
let NewTureRoundPoint:TurnRoundPoint = TurnRoundPoint.init(turnRoundPosition: HeadPixel.position, turnRoundDirection: NowDirection, PassBodyID: [])
turnroundArr.append(NewTureRoundPoint)
}
func swipedLeft(sender:UISwipeGestureRecognizer){
self.NowDirection = CGVector(dx: -1.0, dy: 0.0)
let NewTureRoundPoint:TurnRoundPoint = TurnRoundPoint.init(turnRoundPosition: HeadPixel.position, turnRoundDirection: NowDirection, PassBodyID: [])
turnroundArr.append(NewTureRoundPoint)
}
func swipedUp(sender:UISwipeGestureRecognizer){
self.NowDirection = CGVector(dx: 0.0, dy: 1.0)
let NewTureRoundPoint:TurnRoundPoint = TurnRoundPoint.init(turnRoundPosition: HeadPixel.position, turnRoundDirection: NowDirection, PassBodyID: [])
turnroundArr.append(NewTureRoundPoint)
}
func swipedDown(sender:UISwipeGestureRecognizer){
self.NowDirection = CGVector(dx: 0.0, dy: -1.0)
let NewTureRoundPoint:TurnRoundPoint = TurnRoundPoint.init(turnRoundPosition: HeadPixel.position, turnRoundDirection: NowDirection, PassBodyID: [])
turnroundArr.append(NewTureRoundPoint)
}
}
extension JDSnackScene:SKPhysicsContactDelegate
{
/*
Delegate
*/
func didBegin(_ contact: SKPhysicsContact) {
// 1
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
// 2
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if firstBody.categoryBitMask == SnackBasicSetting.SnackHeadCategory && secondBody.categoryBitMask == SnackBasicSetting.FoodCategory {
if let food = secondBody.node
{
food.removeFromParent()
AddrandomFood()
let newBodyPixel = SnackBodyNode(size: PixelSize)
self.addChild(newBodyPixel)
newBodyPixel.BodyID = SnackBodyNodeCount
SnackBodyNodeCount += 1
}
}
}
}
| mit | bc5ef057ce2fe829c7cb3da418a4b719 | 37.401408 | 194 | 0.589034 | 5.186747 | false | false | false | false |
ljcoder2015/LJTool | LJTool/Font/LJTool+UIFont.swift | 1 | 2509 | //
// LJTool+UIFont.swift
// LJTool
//
// Created by ljcoder on 2021/4/15.
// Copyright © 2021 ljcoder. All rights reserved.
//
import UIKit
extension UIFont: LJToolCompatible {
}
public extension LJTool where Base: UIFont {
static var display1: UIFont {
UIFont.lj.scaled(baseFont: .systemFont(ofSize: 42, weight: .semibold), forTextStyle: .largeTitle, maximumFactor: 1.5)
}
static var display2: UIFont {
UIFont.lj.scaled(baseFont: .systemFont(ofSize: 36, weight: .semibold), forTextStyle: .largeTitle, maximumFactor: 1.5)
}
static var title1: UIFont {
UIFont.lj.scaled(baseFont: .systemFont(ofSize: 24, weight: .semibold), forTextStyle: .title1)
}
static var title2: UIFont {
UIFont.lj.scaled(baseFont: .systemFont(ofSize: 20, weight: .semibold), forTextStyle: .title2)
}
static var title3: UIFont {
UIFont.lj.scaled(baseFont: .systemFont(ofSize: 18, weight: .semibold), forTextStyle: .title3)
}
static var title4: UIFont {
UIFont.lj.scaled(baseFont: .systemFont(ofSize: 14, weight: .regular), forTextStyle: .headline)
}
static var title5: UIFont {
UIFont.lj.scaled(baseFont: .systemFont(ofSize: 12, weight: .regular), forTextStyle: .subheadline)
}
static var bodyBold: UIFont {
UIFont.lj.scaled(baseFont: .systemFont(ofSize: 16, weight: .semibold), forTextStyle: .body)
}
static var body: UIFont {
UIFont.lj.scaled(baseFont: .systemFont(ofSize: 16, weight: .light), forTextStyle: .body)
}
static var captionBold: UIFont {
UIFont.lj.scaled(baseFont: .systemFont(ofSize: 14, weight: .semibold), forTextStyle: .caption1)
}
static var caption: UIFont {
UIFont.lj.scaled(baseFont: .systemFont(ofSize: 14, weight: .light), forTextStyle: .caption1)
}
static var small: UIFont {
UIFont.lj.scaled(baseFont: .systemFont(ofSize: 12, weight: .light), forTextStyle: .footnote)
}
}
private extension LJTool where Base: UIFont {
static func scaled(baseFont: UIFont, forTextStyle textStyle: UIFont.TextStyle = .body, maximumFactor: CGFloat? = nil) -> UIFont {
let fontMetrics = UIFontMetrics(forTextStyle: textStyle)
if let maximumFactor = maximumFactor {
let maximumPointSize = baseFont.pointSize * maximumFactor
return fontMetrics.scaledFont(for: baseFont, maximumPointSize: maximumPointSize)
}
return fontMetrics.scaledFont(for: baseFont)
}
}
| mit | a1c436bc154411c6ff2918661607acba | 32.44 | 133 | 0.676236 | 4.045161 | false | false | false | false |
JimCampagno/Marvel-iOS | Marvel/MarvelCharacter.swift | 1 | 2678 | //
// MarvelCharacter.swift
// Marvel
//
// Created by Jim Campagno on 12/2/16.
// Copyright © 2016 Jim Campagno. All rights reserved.
//
import Foundation
import RealmSwift
final class MarvelCharacter: Object {
dynamic var name: String?
dynamic var id: Int = 0
dynamic var heroDescription: String?
dynamic var thumbnailPath: String?
dynamic var canDownloadImage: Bool = true
dynamic var modified: String?
dynamic var isAvenger: Bool = false
dynamic var localImagePath: String? // TODO: Implement
let series = LinkingObjects(fromType: MarvelSeries.self, property: "marvelCharacters") // TODO: Implement
dynamic var isDownloadingImage: Bool = false
var image: UIImage?
override static func ignoredProperties() -> [String] {
return ["image", "isDownloadingImage"]
}
override static func indexedProperties() -> [String] {
return ["id"]
}
override static func primaryKey() -> String? {
return "id"
}
}
// MARK: - Configure Methods
extension MarvelCharacter {
func configure(json: JSON) {
id = json["id"] as? Int ?? 0
name = json["name"] as? String
heroDescription = json["description"] as? String
modified = json["modified"] as? String ?? "n/a"
thumbnailPath = generateThumbnailPath(with: json)
}
func generateThumbnailPath(with dictionary: JSON) -> String? {
guard let dictionary = dictionary["thumbnail"] as? [String : String] else { return nil }
let path = dictionary["path"]
let pathExtension = dictionary["extension"]
guard let thePath = path, let thePathExt = pathExtension else { return nil }
if thePath.contains("image_not_available") { canDownloadImage = false }
return thePath + "." + thePathExt
}
}
// MARK: - Download Image Methods
extension MarvelCharacter {
func downloadImage(handler: @escaping (Bool) -> Void) {
guard let path = thumbnailPath, let url = URL(string: path) else { handler(false); return }
isDownloadingImage = true
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
DispatchQueue.main.async {
guard let rawData = data, let thumbnailImage = UIImage(data: rawData) else { handler(false); return }
self?.image = thumbnailImage
self?.isDownloadingImage = false
handler(true)
}
}.resume()
}
func setNoImage() {
image = #imageLiteral(resourceName: "NoImage")
}
}
| mit | c774915c1bc00818a8c48c6318a87797 | 29.420455 | 117 | 0.62458 | 4.576068 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/Views/SendViewCells/DescriptionSendCell.swift | 1 | 2739 | //
// DescriptionSendCell.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-12-16.
// Copyright © 2016-2019 Breadwinner AG. All rights reserved.
//
import UIKit
class DescriptionSendCell: SendCell {
init(placeholder: String) {
super.init()
textView.delegate = self
textView.textColor = .darkText
textView.font = .customBody(size: 20.0)
textView.returnKeyType = .done
self.placeholder.text = placeholder
setupViews()
}
var didBeginEditing: (() -> Void)?
var didReturn: ((UITextView) -> Void)?
var didChange: ((String) -> Void)?
var content: String? {
didSet {
textView.text = content
textViewDidChange(textView)
}
}
let textView = UITextView()
fileprivate let placeholder = UILabel(font: .customBody(size: 16.0), color: .grayTextTint)
private func setupViews() {
textView.isScrollEnabled = false
addSubview(textView)
textView.constrain([
textView.constraint(.leading, toView: self, constant: 11.0),
textView.topAnchor.constraint(equalTo: topAnchor, constant: C.padding[2]),
textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 30.0),
textView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -C.padding[2]) ])
textView.addSubview(placeholder)
placeholder.constrain([
placeholder.centerYAnchor.constraint(equalTo: textView.centerYAnchor),
placeholder.leadingAnchor.constraint(equalTo: textView.leadingAnchor, constant: 5.0) ])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension DescriptionSendCell: UITextViewDelegate {
func textViewDidBeginEditing(_ textView: UITextView) {
didBeginEditing?()
}
func textViewDidChange(_ textView: UITextView) {
placeholder.isHidden = !textView.text.utf8.isEmpty
if let text = textView.text {
didChange?(text)
}
}
func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
return true
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard text.rangeOfCharacter(from: CharacterSet.newlines) == nil else {
textView.resignFirstResponder()
return false
}
let count = (textView.text ?? "").utf8.count + text.utf8.count
if count > C.maxMemoLength {
return false
} else {
return true
}
}
func textViewDidEndEditing(_ textView: UITextView) {
didReturn?(textView)
}
}
| mit | cb6b1182071672a42228d66e7af10fd7 | 30.113636 | 116 | 0.637327 | 4.88057 | false | false | false | false |
HabitRPG/habitrpg-ios | Habitica API Client/Habitica API Client/Models/User/APIAuthentication.swift | 1 | 1194 | //
// APIAuthentication.swift
// Habitica API Client
//
// Created by Phillip Thelen on 09.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
class SocialAuth: Decodable {
var id: String?
}
class APIAuthentication: AuthenticationProtocol, Decodable {
var timestamps: AuthenticationTimestampsProtocol?
var local: LocalAuthenticationProtocol?
var facebookID: String?
var googleID: String?
var appleID: String?
enum CodingKeys: String, CodingKey {
case timestamps
case local
case facebook
case google
case apple
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
timestamps = try? values.decode(APIAuthenticationTimestamps.self, forKey: .timestamps)
local = try? values.decode(APILocalAuthentication.self, forKey: .local)
facebookID = (try? values.decode(SocialAuth.self, forKey: .facebook))?.id
googleID = (try? values.decode(SocialAuth.self, forKey: .google))?.id
appleID = (try? values.decode(SocialAuth.self, forKey: .apple))?.id
}
}
| gpl-3.0 | d080f6e9da18924442efe0f7addfacf9 | 29.589744 | 94 | 0.685666 | 4.275986 | false | false | false | false |
fastred/IBAnalyzer | Pods/SourceKittenFramework/Source/SourceKittenFramework/String+SourceKitten.swift | 1 | 24487 | //
// String+SourceKitten.swift
// SourceKitten
//
// Created by JP Simard on 2015-01-05.
// Copyright (c) 2015 SourceKitten. All rights reserved.
//
import Foundation
// swiftlint:disable file_length
// This file could easily be split up
/// Representation of line in String
public struct Line {
/// origin = 0
public let index: Int
/// Content
public let content: String
/// UTF16 based range in entire String. Equivalent to Range<UTF16Index>
public let range: NSRange
/// Byte based range in entire String. Equivalent to Range<UTF8Index>
public let byteRange: NSRange
}
/**
* For "wall of asterisk" comment blocks, such as this one.
*/
private let commentLinePrefixCharacterSet: CharacterSet = {
var characterSet = CharacterSet.whitespacesAndNewlines
characterSet.insert(charactersIn: "*")
return characterSet
}()
extension NSString {
/**
CacheContainer caches:
- UTF16-based NSRange
- UTF8-based NSRange
- Line
*/
private class CacheContainer {
let lines: [Line]
let utf8View: String.UTF8View
init(_ string: NSString) {
// Make a copy of the string to avoid holding a circular reference, which would leak
// memory.
//
// If the string is a `Swift.String`, strongly referencing that in `CacheContainer` does
// not cause a circular reference, because casting `String` to `NSString` makes a new
// `NSString` instance.
//
// If the string is a native `NSString` instance, a circular reference is created when
// assigning `self.utf8View = (string as String).utf8`.
//
// A reference to `NSString` is held by every cast `String` along with their views and
// indices.
let string = (string.mutableCopy() as! NSMutableString).bridge()
utf8View = string.utf8
var utf16CountSoFar = 0
var bytesSoFar = 0
var lines = [Line]()
let lineContents = string.components(separatedBy: .newlines)
// Be compatible with `NSString.getLineStart(_:end:contentsEnd:forRange:)`
let endsWithNewLineCharacter: Bool
if let lastChar = string.utf16.last,
let lastCharScalar = UnicodeScalar(lastChar) {
endsWithNewLineCharacter = CharacterSet.newlines.contains(lastCharScalar)
} else {
endsWithNewLineCharacter = false
}
// if string ends with new line character, no empty line is generated after that.
let enumerator = endsWithNewLineCharacter
? AnySequence(lineContents.dropLast().enumerated())
: AnySequence(lineContents.enumerated())
for (index, content) in enumerator {
let index = index + 1
let rangeStart = utf16CountSoFar
let utf16Count = content.utf16.count
utf16CountSoFar += utf16Count
let byteRangeStart = bytesSoFar
let byteCount = content.lengthOfBytes(using: .utf8)
bytesSoFar += byteCount
let newlineLength = index != lineContents.count ? 1 : 0 // FIXME: assumes \n
let line = Line(
index: index,
content: content,
range: NSRange(location: rangeStart, length: utf16Count + newlineLength),
byteRange: NSRange(location: byteRangeStart, length: byteCount + newlineLength)
)
lines.append(line)
utf16CountSoFar += newlineLength
bytesSoFar += newlineLength
}
self.lines = lines
}
/**
Returns UTF16 offset from UTF8 offset.
- parameter byteOffset: UTF8-based offset of string.
- returns: UTF16 based offset of string.
*/
func location(fromByteOffset byteOffset: Int) -> Int {
if lines.isEmpty {
return 0
}
let index = lines.index(where: { NSLocationInRange(byteOffset, $0.byteRange) })
// byteOffset may be out of bounds when sourcekitd points end of string.
guard let line = (index.map { lines[$0] } ?? lines.last) else {
fatalError()
}
let diff = byteOffset - line.byteRange.location
if diff == 0 {
return line.range.location
} else if line.byteRange.length == diff {
return NSMaxRange(line.range)
}
let utf8View = line.content.utf8
let endUTF16index = utf8View.index(utf8View.startIndex, offsetBy: diff, limitedBy: utf8View.endIndex)!
.samePosition(in: line.content.utf16)!
let utf16Diff = line.content.utf16.distance(from: line.content.utf16.startIndex, to: endUTF16index)
return line.range.location + utf16Diff
}
/**
Returns UTF8 offset from UTF16 offset.
- parameter location: UTF16-based offset of string.
- returns: UTF8 based offset of string.
*/
func byteOffset(fromLocation location: Int) -> Int {
if lines.isEmpty {
return 0
}
let index = lines.index(where: { NSLocationInRange(location, $0.range) })
// location may be out of bounds when NSRegularExpression points end of string.
guard let line = (index.map { lines[$0] } ?? lines.last) else {
fatalError()
}
let diff = location - line.range.location
if diff == 0 {
return line.byteRange.location
} else if line.range.length == diff {
return NSMaxRange(line.byteRange)
}
let utf16View = line.content.utf16
let endUTF8index = utf16View.index(utf16View.startIndex, offsetBy: diff, limitedBy: utf16View.endIndex)!
.samePosition(in: line.content.utf8)!
let byteDiff = line.content.utf8.distance(from: line.content.utf8.startIndex, to: endUTF8index)
return line.byteRange.location + byteDiff
}
func lineAndCharacter(forCharacterOffset offset: Int, expandingTabsToWidth tabWidth: Int) -> (line: Int, character: Int)? {
assert(tabWidth > 0)
let index = lines.index(where: { NSLocationInRange(offset, $0.range) })
return index.map {
let line = lines[$0]
let prefixLength = offset - line.range.location
let character: Int
if tabWidth == 1 {
character = prefixLength
} else {
character = line.content.prefix(prefixLength).reduce(0) { sum, character in
if character == "\t" {
return sum - (sum % tabWidth) + tabWidth
} else {
return sum + 1
}
}
}
return (line: line.index, character: character + 1)
}
}
func lineAndCharacter(forByteOffset offset: Int, expandingTabsToWidth tabWidth: Int) -> (line: Int, character: Int)? {
let characterOffset = location(fromByteOffset: offset)
return lineAndCharacter(forCharacterOffset: characterOffset, expandingTabsToWidth: tabWidth)
}
}
static private var stringCache = [NSString: CacheContainer]()
static private var stringCacheLock = NSLock()
/**
CacheContainer instance is stored to instance of NSString as associated object.
*/
private var cacheContainer: CacheContainer {
NSString.stringCacheLock.lock()
defer { NSString.stringCacheLock.unlock() }
if let cache = NSString.stringCache[self] {
return cache
}
let cache = CacheContainer(self)
NSString.stringCache[self] = cache
return cache
}
/**
Returns line number and character for utf16 based offset.
- parameter offset: utf16 based index.
- parameter tabWidth: the width in spaces to expand tabs to.
*/
public func lineAndCharacter(forCharacterOffset offset: Int, expandingTabsToWidth tabWidth: Int = 1) -> (line: Int, character: Int)? {
return cacheContainer.lineAndCharacter(forCharacterOffset: offset, expandingTabsToWidth: tabWidth)
}
/**
Returns line number and character for byte offset.
- parameter offset: byte offset.
- parameter tabWidth: the width in spaces to expand tabs to.
*/
public func lineAndCharacter(forByteOffset offset: Int, expandingTabsToWidth tabWidth: Int = 1) -> (line: Int, character: Int)? {
return cacheContainer.lineAndCharacter(forByteOffset: offset, expandingTabsToWidth: tabWidth)
}
/**
Returns a copy of `self` with the trailing contiguous characters belonging to `characterSet`
removed.
- parameter characterSet: Character set to check for membership.
*/
public func trimmingTrailingCharacters(in characterSet: CharacterSet) -> String {
guard length > 0 else {
return ""
}
var unicodeScalars = self.bridge().unicodeScalars
while let scalar = unicodeScalars.last {
if !characterSet.contains(scalar) {
return String(unicodeScalars)
}
unicodeScalars.removeLast()
}
return ""
}
/**
Returns self represented as an absolute path.
- parameter rootDirectory: Absolute parent path if not already an absolute path.
*/
public func absolutePathRepresentation(rootDirectory: String = FileManager.default.currentDirectoryPath) -> String {
if isAbsolutePath { return bridge() }
#if os(Linux)
return NSURL(fileURLWithPath: NSURL.fileURL(withPathComponents: [rootDirectory, bridge()])!.path).standardizingPath!.path
#else
return NSString.path(withComponents: [rootDirectory, bridge()]).bridge().standardizingPath
#endif
}
/**
Converts a range of byte offsets in `self` to an `NSRange` suitable for filtering `self` as an
`NSString`.
- parameter start: Starting byte offset.
- parameter length: Length of bytes to include in range.
- returns: An equivalent `NSRange`.
*/
public func byteRangeToNSRange(start: Int, length: Int) -> NSRange? {
if self.length == 0 { return nil }
let utf16Start = cacheContainer.location(fromByteOffset: start)
if length == 0 {
return NSRange(location: utf16Start, length: 0)
}
let utf16End = cacheContainer.location(fromByteOffset: start + length)
return NSRange(location: utf16Start, length: utf16End - utf16Start)
}
/**
Converts an `NSRange` suitable for filtering `self` as an
`NSString` to a range of byte offsets in `self`.
- parameter start: Starting character index in the string.
- parameter length: Number of characters to include in range.
- returns: An equivalent `NSRange`.
*/
public func NSRangeToByteRange(start: Int, length: Int) -> NSRange? {
let string = bridge()
let utf16View = string.utf16
let startUTF16Index = utf16View.index(utf16View.startIndex, offsetBy: start)
let endUTF16Index = utf16View.index(startUTF16Index, offsetBy: length)
let utf8View = string.utf8
guard let startUTF8Index = startUTF16Index.samePosition(in: utf8View),
let endUTF8Index = endUTF16Index.samePosition(in: utf8View) else {
return nil
}
// Don't using `CacheContainer` if string is short.
// There are two reasons for:
// 1. Avoid using associatedObject on NSTaggedPointerString (< 7 bytes) because that does
// not free associatedObject.
// 2. Using cache is overkill for short string.
let byteOffset: Int
if utf16View.count > 50 {
byteOffset = cacheContainer.byteOffset(fromLocation: start)
} else {
byteOffset = utf8View.distance(from: utf8View.startIndex, to: startUTF8Index)
}
// `cacheContainer` will hit for below, but that will be calculated from startUTF8Index
// in most case.
let length = utf8View.distance(from: startUTF8Index, to: endUTF8Index)
return NSRange(location: byteOffset, length: length)
}
/**
Returns a substring with the provided byte range.
- parameter start: Starting byte offset.
- parameter length: Length of bytes to include in range.
*/
public func substringWithByteRange(start: Int, length: Int) -> String? {
return byteRangeToNSRange(start: start, length: length).map(substring)
}
/**
Returns a substring starting at the beginning of `start`'s line and ending at the end of `end`'s
line. Returns `start`'s entire line if `end` is nil.
- parameter start: Starting byte offset.
- parameter length: Length of bytes to include in range.
*/
public func substringLinesWithByteRange(start: Int, length: Int) -> String? {
return byteRangeToNSRange(start: start, length: length).map { range in
var lineStart = 0, lineEnd = 0
getLineStart(&lineStart, end: &lineEnd, contentsEnd: nil, for: range)
return substring(with: NSRange(location: lineStart, length: lineEnd - lineStart))
}
}
public func substringStartingLinesWithByteRange(start: Int, length: Int) -> String? {
return byteRangeToNSRange(start: start, length: length).map { range in
var lineStart = 0, lineEnd = 0
getLineStart(&lineStart, end: &lineEnd, contentsEnd: nil, for: range)
return substring(with: NSRange(location: lineStart, length: NSMaxRange(range) - lineStart))
}
}
/**
Returns line numbers containing starting and ending byte offsets.
- parameter start: Starting byte offset.
- parameter length: Length of bytes to include in range.
*/
public func lineRangeWithByteRange(start: Int, length: Int) -> (start: Int, end: Int)? {
return byteRangeToNSRange(start: start, length: length).flatMap { range in
var numberOfLines = 0, index = 0, lineRangeStart = 0
while index < self.length {
numberOfLines += 1
if index <= range.location {
lineRangeStart = numberOfLines
}
index = NSMaxRange(lineRange(for: NSRange(location: index, length: 1)))
if index > NSMaxRange(range) {
return (lineRangeStart, numberOfLines)
}
}
return nil
}
}
/**
Returns an array of Lines for each line in the file.
*/
public func lines() -> [Line] {
return cacheContainer.lines
}
/**
Returns true if self is an Objective-C header file.
*/
public func isObjectiveCHeaderFile() -> Bool {
return ["h", "hpp", "hh"].contains(pathExtension)
}
/**
Returns true if self is a Swift file.
*/
public func isSwiftFile() -> Bool {
return pathExtension == "swift"
}
#if !os(Linux)
/**
Returns a substring from a start and end SourceLocation.
*/
public func substringWithSourceRange(start: SourceLocation, end: SourceLocation) -> String? {
return substringWithByteRange(start: Int(start.offset), length: Int(end.offset - start.offset))
}
#endif
}
extension String {
internal var isFile: Bool {
return FileManager.default.fileExists(atPath: self)
}
internal func capitalizingFirstLetter() -> String {
return String(prefix(1)).capitalized + String(dropFirst())
}
#if !os(Linux)
/// Returns the `#pragma mark`s in the string.
/// Just the content; no leading dashes or leading `#pragma mark`.
public func pragmaMarks(filename: String, excludeRanges: [NSRange], limit: NSRange?) -> [SourceDeclaration] {
let regex = try! NSRegularExpression(pattern: "(#pragma\\smark|@name)[ -]*([^\\n]+)", options: []) // Safe to force try
let range: NSRange
if let limit = limit {
range = NSRange(location: limit.location, length: min(utf16.count - limit.location, limit.length))
} else {
range = NSRange(location: 0, length: utf16.count)
}
let matches = regex.matches(in: self, options: [], range: range)
return matches.flatMap { match in
let markRange = match.range(at: 2)
for excludedRange in excludeRanges {
if NSIntersectionRange(excludedRange, markRange).length > 0 {
return nil
}
}
let markString = (self as NSString).substring(with: markRange).trimmingCharacters(in: .whitespaces)
if markString.isEmpty {
return nil
}
guard let markByteRange = self.NSRangeToByteRange(start: markRange.location, length: markRange.length) else {
return nil
}
let location = SourceLocation(file: filename,
line: UInt32((self as NSString).lineRangeWithByteRange(start: markByteRange.location, length: 0)!.start),
column: 1, offset: UInt32(markByteRange.location))
return SourceDeclaration(type: .mark, location: location, extent: (location, location), name: markString,
usr: nil, declaration: nil, documentation: nil, commentBody: nil, children: [],
swiftDeclaration: nil, swiftName: nil, availability: nil)
}
}
#endif
/**
Returns whether or not the `token` can be documented. Either because it is a
`SyntaxKind.Identifier` or because it is a function treated as a `SyntaxKind.Keyword`:
- `subscript`
- `init`
- `deinit`
- parameter token: Token to process.
*/
public func isTokenDocumentable(token: SyntaxToken) -> Bool {
if token.type == SyntaxKind.keyword.rawValue {
let keywordFunctions = ["subscript", "init", "deinit"]
return bridge().substringWithByteRange(start: token.offset, length: token.length)
.map(keywordFunctions.contains) ?? false
}
return token.type == SyntaxKind.identifier.rawValue
}
/**
Find integer offsets of documented Swift tokens in self.
- parameter syntaxMap: Syntax Map returned from SourceKit editor.open request.
- returns: Array of documented token offsets.
*/
public func documentedTokenOffsets(syntaxMap: SyntaxMap) -> [Int] {
let documentableOffsets = syntaxMap.tokens.filter(isTokenDocumentable).map {
$0.offset
}
let regex = try! NSRegularExpression(pattern: "(///.*\\n|\\*/\\n)", options: []) // Safe to force try
let range = NSRange(location: 0, length: utf16.count)
let matches = regex.matches(in: self, options: [], range: range)
return matches.flatMap { match in
documentableOffsets.first { $0 >= match.range.location }
}
}
/**
Returns the body of the comment if the string is a comment.
- parameter range: Range to restrict the search for a comment body.
*/
public func commentBody(range: NSRange? = nil) -> String? {
let nsString = bridge()
let patterns: [(pattern: String, options: NSRegularExpression.Options)] = [
("^\\s*\\/\\*\\*\\s*(.*?)\\*\\/", [.anchorsMatchLines, .dotMatchesLineSeparators]), // multi: ^\s*\/\*\*\s*(.*?)\*\/
("^\\s*\\/\\/\\/(.+)?", .anchorsMatchLines) // single: ^\s*\/\/\/(.+)?
// swiftlint:disable:previous comma
]
let range = range ?? NSRange(location: 0, length: nsString.length)
for pattern in patterns {
let regex = try! NSRegularExpression(pattern: pattern.pattern, options: pattern.options) // Safe to force try
let matches = regex.matches(in: self, options: [], range: range)
let bodyParts = matches.flatMap { match -> [String] in
let numberOfRanges = match.numberOfRanges
if numberOfRanges < 1 {
return []
}
return (1..<numberOfRanges).map { rangeIndex in
let range = match.range(at: rangeIndex)
if range.location == NSNotFound {
return "" // empty capture group, return empty string
}
var lineStart = 0
var lineEnd = nsString.length
let indexRange = NSRange(location: range.location, length: 0)
nsString.getLineStart(&lineStart, end: &lineEnd, contentsEnd: nil, for: indexRange)
let leadingWhitespaceCountToAdd = nsString.substring(with: NSRange(location: lineStart, length: lineEnd - lineStart))
.countOfLeadingCharacters(in: .whitespacesAndNewlines)
let leadingWhitespaceToAdd = String(repeating: " ", count: leadingWhitespaceCountToAdd)
let bodySubstring = nsString.substring(with: range)
if bodySubstring.contains("@name") {
return "" // appledoc directive, return empty string
}
return leadingWhitespaceToAdd + bodySubstring
}
}
if !bodyParts.isEmpty {
return bodyParts.joined(separator: "\n").bridge()
.trimmingTrailingCharacters(in: .whitespacesAndNewlines)
.removingCommonLeadingWhitespaceFromLines()
}
}
return nil
}
/// Returns a copy of `self` with the leading whitespace common in each line removed.
public func removingCommonLeadingWhitespaceFromLines() -> String {
var minLeadingCharacters = Int.max
let lineComponents = components(separatedBy: .newlines)
for line in lineComponents {
let lineLeadingWhitespace = line.countOfLeadingCharacters(in: .whitespacesAndNewlines)
let lineLeadingCharacters = line.countOfLeadingCharacters(in: commentLinePrefixCharacterSet)
// Is this prefix smaller than our last and not entirely whitespace?
if lineLeadingCharacters < minLeadingCharacters && lineLeadingWhitespace != line.count {
minLeadingCharacters = lineLeadingCharacters
}
}
return lineComponents.map { line in
if line.count >= minLeadingCharacters {
return String(line[line.index(line.startIndex, offsetBy: minLeadingCharacters)...])
}
return line
}.joined(separator: "\n")
}
/**
Returns the number of contiguous characters at the start of `self` belonging to `characterSet`.
- parameter characterSet: Character set to check for membership.
*/
public func countOfLeadingCharacters(in characterSet: CharacterSet) -> Int {
let characterSet = characterSet.bridge()
var count = 0
for char in utf16 {
if !characterSet.characterIsMember(char) {
break
}
count += 1
}
return count
}
/// Returns a copy of the string by trimming whitespace and the opening curly brace (`{`).
internal func trimmingWhitespaceAndOpeningCurlyBrace() -> String? {
var unwantedSet = CharacterSet.whitespacesAndNewlines
unwantedSet.insert(charactersIn: "{")
return trimmingCharacters(in: unwantedSet)
}
/// Returns the byte offset of the section of the string following the last dot ".", or 0 if no dots.
internal func byteOffsetOfInnerTypeName() -> Int64 {
guard let range = range(of: ".", options: .backwards) else {
return 0
}
#if swift(>=4.0)
let utf8pos = index(after: range.lowerBound).samePosition(in: utf8)!
#else
let utf8pos = index(after: range.lowerBound).samePosition(in: utf8)
#endif
return Int64(utf8.distance(from: utf8.startIndex, to: utf8pos))
}
}
| mit | 0d9763a6190180dfda6035434b92fc8a | 39.341021 | 138 | 0.605178 | 4.937891 | false | false | false | false |
dricard/dolog | DayOneLoggerPlus.swift | 1 | 4371 | #!/usr/bin/env xcrun swift
import Foundation
/* *********************************
DOLOG Script
********************************* */
/* *********************************
MODIFY THESE PROPERTIES
AS NEEDED
********************************* */
// the journal to log to in Day One
// To use two words insert \\ after the first word, eg: "Daily\\ Log"
let dayOneJournal = "log"
// the default tag(s) to add to all entries. If you don't
// add at least one default tag, you'll have to modify the code below.
// tags *can* have spaces
let defaultTags = ["dolog", "completed tasks"]
// the entry prefix
let entryPrefix = "completed task:"
/* ********************************* */
// requires Swift 4.0
//-- get parameter input
// `argument` holds the text entered in Alfred by the user
// I initialize it with an example of something the user could enter
// for testing.
var argument = "-t workflow @Switched to Mailmate as my email client"
#if swift(>=4.0)
if CommandLine.arguments.count > 1 {
argument = CommandLine.arguments[1]
}
#elseif swift(>=1.0)
print("Unsupported version of Swift (<= 4.0) please update to Swift 4.0")
break
#endif
let charactersToEscape = [ "!", "?", "$", "%", "#", "&", "*", "(", ")", "|", "'", ";", "<", ">", "\\", "~", "`", "[", "]", "{", "}" ]
// MARK: - Utilities
func replaceSpaces(in tag: String) -> String {
return tag.replacingOccurrences(of: "_", with: "\\ ")
}
func escape(_ character: String, in tag: String) -> String {
return tag.replacingOccurrences(of: character, with: "\\\(character)")
}
func removeSpecialCharacters(in tag: String) -> String {
// escape special characters
// ! ? $ % # & * ( ) | ; < > \ ~ ` [ ] { }
var returnedTag = tag
for character in charactersToEscape {
returnedTag = escape(character, in: returnedTag)
}
return returnedTag
}
// MARK: - Properties
// variable 'task' will hold the completed task passed in
var task = ""
// `outputString` is the result of the script that will be passed to the CLI,
// we initialize it with the Day One CLI command, setting the default journal
// and the default tags.
var outputString = "dayone2 --journal "
// MARK: - Process
// add journal name and default tags
outputString += dayOneJournal + " --tags "
for defaulTag in defaultTags {
let tag = defaulTag.replacingOccurrences(of: " ", with: "\\ ")
outputString += tag + " "
}
// MARK: - Process input
//-- Process tags if present, otherwise just pass the input
if argument.hasPrefix("-t") {
// find the index of the tags separator
if let endOfTags = argument.index(of: "@") {
// Map the tags into an array. The first tag (index 0) will be the tag option marker (-t) and will be
// omitted
let tags = String(argument.prefix(upTo: endOfTags)).split(separator: " ").map{ String($0) }
// Now process the task part to remove the end of tags marker
// get the task part of the input
let taskSection = String(argument.suffix(from: endOfTags))
// find the index of the tags separator in this string (different than above)
let endTagIndex = taskSection.index(of: "@")!
// The task proper starts after the tags separator
let tagIndex = taskSection.index(after: endTagIndex)
// get the task
task = String(taskSection.suffix(from: tagIndex))
// Now we have the task, we then process and format the tags
// Add the tags to the output string separated by spaces
// skipping the first one which is the `-t` marker
for tag in tags.dropFirst() {
// first we process underscores (_) in tags to replace them with escaped spaces so they're
// treated as a single tag
var processedTag = replaceSpaces(in: tag)
processedTag = removeSpecialCharacters(in: processedTag)
// add this processed tag to the output string
outputString += processedTag + " "
}
} else {
// user forgot the '@' separator so just pass the input string (task) as received
task = argument
}
} else {
// no tags, so just pass the input string (task) as received
task = argument
}
// Add the task to the output string (enclosed in quotes to prevent the CLI to interpret special characters)
outputString += " -- new" + " \"" + entryPrefix + " " + task + "\""
// pass the result of the script, we suppress the newline character in the output
print(outputString, terminator:"")
| mit | 181703b1ad6c98c0b89aa47fd0882617 | 25.331325 | 133 | 0.635095 | 3.827496 | false | false | false | false |
vscarpenter/PhotoWatch | PhotoWatch/PhotoViewController.swift | 2 | 3539 | //
// PhotoViewController.swift
// PhotoWatch
//
// Created by Leah Culver on 5/14/15.
// Copyright (c) 2015 Dropbox. All rights reserved.
//
import UIKit
import ImageIO
import SwiftyDropbox
class PhotoViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var filename: String?
override func viewDidLoad() {
super.viewDidLoad()
// Display photo for page
if let filename = self.filename {
// Get app group shared by phone and watch
let containerURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.Dropbox.DropboxPhotoWatch")
if let fileURL = containerURL?.URLByAppendingPathComponent(filename) {
println("Finding file at URL: \(fileURL)")
if let data = NSData(contentsOfURL: fileURL) {
println("Image found in cache.")
// Display image
self.imageView.image = UIImage(data: data)
} else {
println("Image not cached!")
// Download the photo from Dropbox
// A thumbnail would be better but there's no endpoint for that in API v2 yet!
Dropbox.authorizedClient!.filesDownload(path: "/\(filename)").response { response, error in
if let (metadata, data) = response, image = UIImage(data: data) {
println("Dowloaded file name: \(metadata.name)")
// Resize image for watch (so it's not huge)
let resizedImage = self.resizeImage(image)
// Display image
self.imageView.image = resizedImage
// Save image to local filesystem app group - allows us to access in the watch
let resizedImageData = UIImageJPEGRepresentation(resizedImage, 1.0)
resizedImageData.writeToURL(fileURL, atomically: true)
} else {
println("Error downloading file from Dropbox: \(error!)")
}
}
}
}
}
}
private func resizeImage(image: UIImage) -> UIImage {
// Resize and crop to fit Apple watch (square for now, because it's easy)
let maxSize: CGFloat = 200.0
var size: CGSize?
if image.size.width >= image.size.height {
size = CGSizeMake((maxSize / image.size.height) * image.size.width, maxSize)
} else {
size = CGSizeMake(maxSize, (maxSize / image.size.width) * image.size.height)
}
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(size!, !hasAlpha, scale)
var rect = CGRect(origin: CGPointZero, size: size!)
UIRectClip(rect)
image.drawInRect(rect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
} | mit | 31d5c8a185fe023af9247356dd4eb41d | 36.263158 | 150 | 0.51427 | 6.133449 | false | false | false | false |
uasys/swift | test/stdlib/TestTimeZone.swift | 16 | 3736 | // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// RUN: %empty-directory(%t)
//
// RUN: %target-clang %S/Inputs/FoundationBridge/FoundationBridge.m -c -o %t/FoundationBridgeObjC.o -g
// RUN: %target-build-swift %s -I %S/Inputs/FoundationBridge/ -Xlinker %t/FoundationBridgeObjC.o -o %t/TestTimeZone
// RUN: %target-run %t/TestTimeZone > %t.txt
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
import FoundationBridgeObjC
#if FOUNDATION_XCTEST
import XCTest
class TestTimeZoneSuper : XCTestCase { }
#else
import StdlibUnittest
class TestTimeZoneSuper { }
#endif
class TestTimeZone : TestTimeZoneSuper {
func test_timeZoneBasics() {
let tz = TimeZone(identifier: "America/Los_Angeles")!
expectTrue(!tz.identifier.isEmpty)
}
func test_bridgingAutoupdating() {
let tester = TimeZoneBridgingTester()
do {
let tz = TimeZone.autoupdatingCurrent
let result = tester.verifyAutoupdating(tz)
expectTrue(result)
}
// Round trip an autoupdating calendar
do {
let tz = tester.autoupdatingCurrentTimeZone()
let result = tester.verifyAutoupdating(tz)
expectTrue(result)
}
}
func test_equality() {
let autoupdating = TimeZone.autoupdatingCurrent
let autoupdating2 = TimeZone.autoupdatingCurrent
expectEqual(autoupdating, autoupdating2)
let current = TimeZone.current
expectNotEqual(autoupdating, current)
}
func test_AnyHashableContainingTimeZone() {
let values: [TimeZone] = [
TimeZone(identifier: "America/Los_Angeles")!,
TimeZone(identifier: "Europe/Kiev")!,
TimeZone(identifier: "Europe/Kiev")!,
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(TimeZone.self, type(of: anyHashables[0].base))
expectEqual(TimeZone.self, type(of: anyHashables[1].base))
expectEqual(TimeZone.self, type(of: anyHashables[2].base))
expectNotEqual(anyHashables[0], anyHashables[1])
expectEqual(anyHashables[1], anyHashables[2])
}
func test_AnyHashableCreatedFromNSTimeZone() {
let values: [NSTimeZone] = [
NSTimeZone(name: "America/Los_Angeles")!,
NSTimeZone(name: "Europe/Kiev")!,
NSTimeZone(name: "Europe/Kiev")!,
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(TimeZone.self, type(of: anyHashables[0].base))
expectEqual(TimeZone.self, type(of: anyHashables[1].base))
expectEqual(TimeZone.self, type(of: anyHashables[2].base))
expectNotEqual(anyHashables[0], anyHashables[1])
expectEqual(anyHashables[1], anyHashables[2])
}
}
#if !FOUNDATION_XCTEST
var TimeZoneTests = TestSuite("TestTimeZone")
TimeZoneTests.test("test_timeZoneBasics") { TestTimeZone().test_timeZoneBasics() }
TimeZoneTests.test("test_bridgingAutoupdating") { TestTimeZone().test_bridgingAutoupdating() }
TimeZoneTests.test("test_equality") { TestTimeZone().test_equality() }
TimeZoneTests.test("test_AnyHashableContainingTimeZone") { TestTimeZone().test_AnyHashableContainingTimeZone() }
TimeZoneTests.test("test_AnyHashableCreatedFromNSTimeZone") { TestTimeZone().test_AnyHashableCreatedFromNSTimeZone() }
runAllTests()
#endif
| apache-2.0 | 7fd114380443295293bbe75d1a889058 | 35.627451 | 118 | 0.659529 | 4.675845 | false | true | false | false |
edulpn/giphysearch | giphysearch/giphysearch/Classes/Utils.swift | 1 | 673 | //
// Utils.swift
// giphysearch
//
// Created by Eduardo Pinto on 26/10/16.
// Copyright © 2016 Eduardo Pinto. All rights reserved.
//
import UIKit
class Utils: NSObject {
static func date(from: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale.current
return dateFormatter.date(from: from)
}
static func string(from: Date) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
dateFormatter.locale = Locale.current
return dateFormatter.string(from: from)
}
}
| mit | 324b16c9ce085f4a7cc276af80415b98 | 24.846154 | 56 | 0.644345 | 4.097561 | false | false | false | false |
SRandazzo/Moya | Demo/DemoTests/SignalProducer+MoyaSpec.swift | 1 | 10259 | import Quick
import Moya
import ReactiveCocoa
import Nimble
// Necessary since UIImage(named:) doesn't work correctly in the test bundle
private extension UIImage {
class func testPNGImage(named name: String) -> UIImage {
class TestClass { }
let bundle = NSBundle(forClass: TestClass().dynamicType)
let path = bundle.pathForResource(name, ofType: "png")
return UIImage(contentsOfFile: path!)!
}
}
private func signalSendingData(data: NSData, statusCode: Int = 200) -> SignalProducer<Response, Error> {
return SignalProducer(value: Response(statusCode: statusCode, data: data, response: nil))
}
class SignalProducerMoyaSpec: QuickSpec {
override func spec() {
describe("status codes filtering") {
it("filters out unrequested status codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 10)
var errored = false
signal.filterStatusCodes(0...9).start { (event) -> Void in
switch event {
case .Next(let object):
fail("called on non-correct status code: \(object)")
case .Failed:
errored = true
default:
break
}
}
expect(errored).to(beTruthy())
}
it("filters out non-successful status codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 404)
var errored = false
signal.filterSuccessfulStatusCodes().start { (event) -> Void in
switch event {
case .Next(let object):
fail("called on non-success status code: \(object)")
case .Failed:
errored = true
default:
break
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = NSData()
let signal = signalSendingData(data)
var called = false
signal.filterSuccessfulStatusCodes().startWithNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("filters out non-successful status and redirect codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 404)
var errored = false
signal.filterSuccessfulStatusAndRedirectCodes().start { (event) -> Void in
switch event {
case .Next(let object):
fail("called on non-success status code: \(object)")
case .Failed:
errored = true
default:
break
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = NSData()
let signal = signalSendingData(data)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().startWithNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("passes through correct redirect codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 304)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().startWithNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("knows how to filter individual status codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 42)
var called = false
signal.filterStatusCode(42).startWithNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("filters out different individual status code") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 43)
var errored = false
signal.filterStatusCode(42).start { (event) -> Void in
switch event {
case .Next(let object):
fail("called on non-success status code: \(object)")
case .Failed:
errored = true
default:
break
}
}
expect(errored).to(beTruthy())
}
}
describe("image maping") {
it("maps data representing an image to an image") {
let image = UIImage.testPNGImage(named: "testImage")
let data = UIImageJPEGRepresentation(image, 0.75)
let signal = signalSendingData(data!)
var size: CGSize?
signal.mapImage().startWithNext { (image) -> Void in
size = image.size
}
expect(size).to(equal(image.size))
}
it("ignores invalid data") {
let data = NSData()
let signal = signalSendingData(data)
var receivedError: Error?
signal.mapImage().start { (event) -> Void in
switch event {
case .Next:
fail("next called for invalid data")
case .Failed(let error):
receivedError = error
default:
break
}
}
expect(receivedError).toNot(beNil())
let expectedError = Error.ImageMapping(Response(statusCode: 200, data: NSData(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
describe("JSON mapping") {
it("maps data representing some JSON to that JSON") {
let json = ["name": "John Crighton", "occupation": "Astronaut"]
let data = try! NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
let signal = signalSendingData(data)
var receivedJSON: [String: String]?
signal.mapJSON().startWithNext { (json) -> Void in
if let json = json as? [String: String] {
receivedJSON = json
}
}
expect(receivedJSON?["name"]).to(equal(json["name"]))
expect(receivedJSON?["occupation"]).to(equal(json["occupation"]))
}
it("returns a Cocoa error domain for invalid JSON") {
let json = "{ \"name\": \"john }"
let data = json.dataUsingEncoding(NSUTF8StringEncoding)
let signal = signalSendingData(data!)
var receivedError: Error?
signal.mapJSON().start { (event) -> Void in
switch event {
case .Next:
fail("next called for invalid data")
case .Failed(let error):
receivedError = error
default:
break
}
}
expect(receivedError).toNot(beNil())
switch receivedError {
case .Some(.Underlying(let error as NSError)):
expect(error.domain).to(equal("\(NSCocoaErrorDomain)"))
default:
fail("expected NSError with \(NSCocoaErrorDomain) domain")
}
}
}
describe("string mapping") {
it("maps data representing a string to a string") {
let string = "You have the rights to the remains of a silent attorney."
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
let signal = signalSendingData(data!)
var receivedString: String?
signal.mapString().startWithNext { (string) -> Void in
receivedString = string
}
expect(receivedString).to(equal(string))
}
it("ignores invalid data") {
let data = NSData(bytes: [0x11FFFF] as [UInt32], length: 1) //Byte exceeding UTF8
let signal = signalSendingData(data)
var receivedError: Error?
signal.mapString().start { (event) -> Void in
switch event {
case .Next:
fail("next called for invalid data")
case .Failed(let error):
receivedError = error
default:
break
}
}
expect(receivedError).toNot(beNil())
let expectedError = Error.StringMapping(Response(statusCode: 200, data: NSData(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
}
}
| mit | 8d06c5d346b5f1c551bf7ae5c22cb09c | 37.859848 | 113 | 0.450239 | 6.415885 | false | false | false | false |
taxfix/native-navigation | lib/ios/native-navigation/UIView+Snapshot.swift | 2 | 3453 | //
// UIView+Snapshot.swift
// NativeNavigation
//
// Created by Laura Skelton on 2/17/16.
// Copyright © 2016 Airbnb. All rights reserved.
//
import UIKit
public protocol StandardSnapshot {
func removeFromSuperview()
}
public protocol ViewSnapshot: StandardSnapshot {
var view: UIView { get }
var backgroundColor: UIColor? { get }
var alpha: CGFloat { get }
var hidden: Bool { get }
}
public extension ViewSnapshot {
public func removeFromSuperview() {
view.removeFromSuperview()
}
}
public struct UIViewSnapshot: ViewSnapshot {
public init(
view: UIView,
backgroundColor: UIColor?,
alpha: CGFloat,
hidden: Bool)
{
self.view = view
self.backgroundColor = backgroundColor
self.alpha = alpha
self.hidden = hidden
}
public let view: UIView
public let backgroundColor: UIColor?
public let alpha: CGFloat
public let hidden: Bool
}
public extension UIView {
public func getScaleRatioToView(_ view: UIView) -> CGSize {
let width: CGFloat = (frame.width > 0) ? frame.width : 1
let height: CGFloat = (frame.height > 0) ? frame.height : 1
return CGSize(
width: view.frame.width / width,
height: view.frame.height / height)
}
@discardableResult func snapshotInContainerView(
_ containerView: UIView,
afterScreenUpdates: Bool = true,
completion: (()->())? = nil) -> UIViewSnapshot
{
// TODO: handle snapshot failure
let view = snapshotView(afterScreenUpdates: afterScreenUpdates)!
view.frame = containerView.convert(bounds, from: self)
containerView.addSubview(view)
let snapshot = UIViewSnapshot(
view: view,
backgroundColor: backgroundColor,
alpha: alpha,
hidden: isHidden)
if let completion = completion {
DispatchQueue.main.async(execute: completion)
}
return snapshot
}
}
// MARK: Lazy Snapshot
public protocol StandardLazySnapshot {
@discardableResult func lazySnapshotInContainerView(_ containerView: UIView) -> UIView
func setHidden(_ hidden: Bool)
func reset()
func getFrameInView(_ view: UIView) -> CGRect
func getBackgroundColor() -> UIColor?
func getAlpha() -> CGFloat
}
public struct SnapshottableUIView: StandardLazySnapshot {
public init(
view: UIView,
originallyHidden: Bool) {
self.view = view
self.originallyHidden = originallyHidden
}
public func lazySnapshotInContainerView(_ containerView: UIView) -> UIView {
return view.lazySnapshotInContainerView(containerView)
}
public func setHidden(_ hidden: Bool) {
view.isHidden = hidden
}
public func reset() {
view.isHidden = originallyHidden
}
public func getFrameInView(_ view: UIView) -> CGRect {
return self.view.convert(self.view.bounds, to: view)
}
public func getBackgroundColor() -> UIColor? {
return view.backgroundColor
}
public func getAlpha() -> CGFloat {
return view.alpha
}
fileprivate let view: UIView
fileprivate let originallyHidden: Bool
}
public extension UIView {
func snapshottableView() -> SnapshottableUIView {
return SnapshottableUIView(
view: self,
originallyHidden: isHidden)
}
func lazySnapshotInContainerView(_ containerView: UIView) -> UIView {
// TODO: handle snapshot failure
let view = snapshotView(afterScreenUpdates: true)!
view.frame = containerView.convert(bounds, from: self)
containerView.addSubview(view)
return view
}
}
| mit | c81588fc6ede7e7501056f9b9febecea | 21.710526 | 88 | 0.696408 | 4.437018 | false | false | false | false |
hejunbinlan/BFKit-Swift | Source/Extensions/UIKit/UIScrollView+BFKit.swift | 3 | 2406 | //
// UIScrollView+BFKit.swift
// BFKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Fabrizio Brancati. 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 Foundation
import UIKit
/// This extesion adds some useful functions to UIScrollView
public extension UIScrollView
{
// MARK: - Init functions -
/**
Create an UIScrollView and set some parameters
:param: frame ScrollView's frame
:param: contentSize ScrollView's content size
:param: clipsToBounds Set if ScrollView has to clips to bounds
:param: pagingEnabled Set if ScrollView has paging enabled
:param: showScrollIndicators Set if ScrollView has to show the scroll indicators, vertical and horizontal
:param: delegate ScrollView's delegate
:returns: Returns the created UIScrollView
*/
public convenience init(frame: CGRect, contentSize: CGSize, clipsToBounds: Bool, pagingEnabled: Bool, showScrollIndicators: Bool, delegate: UIScrollViewDelegate?)
{
self.init(frame: frame)
self.delegate = delegate
self.pagingEnabled = pagingEnabled
self.clipsToBounds = clipsToBounds
self.showsVerticalScrollIndicator = false
self.showsHorizontalScrollIndicator = false
self.contentSize = contentSize
}
}
| mit | f31a9e156ec22784e9cf8b4149b619a7 | 41.210526 | 166 | 0.719867 | 4.880325 | false | false | false | false |
LaChapeliere/FirstApp | FirstApp/LogViewController.swift | 1 | 2408 | //
// LogViewController.swift
// FirstApp
//
// Created by Emma Barme on 16/09/2015.
// Copyright (c) 2015 Emma Barme. All rights reserved.
//
import UIKit
class LogViewController: UIViewController {
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
let userLogModel = UserLogModel()
@IBAction func actionButtons(sender: UIButton) {
let actionDescription = sender.titleLabel?.text
switch actionDescription! {
case "Log In":
let log = userLogModel.logInUser(usernameField.text, password: passwordField.text)
if log == nil {
performSegueWithIdentifier("logInSegue", sender: self)
}
else {
let alertUsernameAlreadyRegistered = UIAlertController(title: "Error",
message: log,
preferredStyle: .Alert)
alertUsernameAlreadyRegistered.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
presentViewController(alertUsernameAlreadyRegistered, animated: true, completion: nil)
}
case "Register":
let addedUser = userLogModel.addUser(usernameField.text, password: passwordField.text)
if addedUser {
performSegueWithIdentifier("logInSegue", sender: self)
}
else {
let alertUsernameAlreadyRegistered = UIAlertController(title: "Error",
message: "This username is already registered.",
preferredStyle: .Alert)
alertUsernameAlreadyRegistered.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
presentViewController(alertUsernameAlreadyRegistered, animated: true, completion: nil)
}
case "Clear fields":
usernameField.text = nil
passwordField.text = nil
default:
break
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "logInSegue" {
if let destination = segue.destinationViewController as? UserLoggedViewController {
destination.username = usernameField.text
destination.userLogModel = userLogModel
}
}
}
}
| mit | c38557b026474eb1cdd2ed5cc2b41b34 | 37.83871 | 133 | 0.620017 | 5.639344 | false | false | false | false |
abunur/quran-ios | Quran/AyahWord.swift | 1 | 1337 | //
// AyahWord.swift
// Quran
//
// Created by Mohamed Afifi on 6/19/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
struct AyahWord {
enum TextType: Int {
case translation
case transliteration
}
enum WordType: String {
case word
case end
case pause
case sajdah
case rubHizb = "rub-el-hizb"
}
struct Position: Equatable {
let ayah: AyahNumber
let position: Int
let frame: CGRect
static func == (lhs: Position, rhs: Position) -> Bool {
return lhs.ayah == rhs.ayah && lhs.position == rhs.position && lhs.frame == rhs.frame
}
}
let position: Position
let text: String?
let textType: TextType
let wordType: WordType
}
| gpl-3.0 | be05e4fea4159faf56ba6545bd32e151 | 25.74 | 97 | 0.643979 | 4.101227 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalServiceKit/src/Messages/Stickers/StickerManager.swift | 1 | 47617 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
import HKDFKit
// Stickers
//
// * Stickers are either "installed" or not.
// * We can only send installed stickers.
// * When we receive a sticker, we download it like any other attachment...
// ...unless we have it installed in which case we skip the download as
// an optimization.
//
// Sticker Packs
//
// * Some "default" sticker packs ship in the app. See DefaultStickerPack.
// Some "default" packs auto-install, others don't.
// * Other packs can be installed from "sticker pack shares" and "sticker pack URLs".
// * There are also "known" packs, e.g. packs the client knows about because
// we received a sticker from that pack.
// * All of the above (default packs, packs installed from shares, known packs)
// show up in the sticker management view. Those that are installed are
// shown as such; the others are shown as "available".
// * We download pack manifests & covers for "default" but not "known" packs.
// Once we've download the manifest the pack is "saved" but not "installed".
// * We discard sticker and pack info once it is no longer in use.
@objc
public class StickerManager: NSObject {
// MARK: - Constants
@objc
public static let packKeyLength: UInt = 32
// MARK: - Notifications
@objc
public static let stickersOrPacksDidChange = Notification.Name("stickersOrPacksDidChange")
@objc
public static let recentStickersDidChange = Notification.Name("recentStickersDidChange")
@objc
public static let isStickerSendEnabledDidChange = Notification.Name("isStickerSendEnabledDidChange")
// MARK: - Dependencies
@objc
public class var shared: StickerManager {
return SSKEnvironment.shared.stickerManager
}
private static var databaseStorage: SDSDatabaseStorage {
return SDSDatabaseStorage.shared
}
private var databaseStorage: SDSDatabaseStorage {
return SDSDatabaseStorage.shared
}
private static var messageSenderJobQueue: MessageSenderJobQueue {
return SSKEnvironment.shared.messageSenderJobQueue
}
private static var tsAccountManager: TSAccountManager {
return TSAccountManager.sharedInstance()
}
// MARK: - Properties
private static let operationQueue: OperationQueue = {
let operationQueue = OperationQueue()
operationQueue.name = "org.signal.StickerManager"
operationQueue.maxConcurrentOperationCount = 4
return operationQueue
}()
public static let store = SDSKeyValueStore(collection: "recentStickers")
public static let emojiMapStore = SDSKeyValueStore(collection: "emojiMap")
private static let serialQueue = DispatchQueue(label: "org.signal.stickers")
@objc
public enum InstallMode: Int {
case doNotInstall
case install
// For default packs that should be auto-installed,
// we only want to install the first time we save them.
// If a user subsequently uninstalls the pack, we want
// to honor that.
case installIfUnsaved
}
// MARK: - Initializers
@objc
public override init() {
super.init()
// Resume sticker and sticker pack downloads when app is ready.
AppReadiness.runNowOrWhenAppWillBecomeReady {
// Warm the caches.
StickerManager.shared.warmIsStickerSendEnabled()
StickerManager.shared.warmTooltipState()
}
AppReadiness.runNowOrWhenAppDidBecomeReady {
StickerManager.cleanupOrphans()
if TSAccountManager.sharedInstance().isRegisteredAndReady {
StickerManager.refreshContents()
}
}
}
// The sticker manager is responsible for downloading more than one kind
// of content; those downloads can fail. Therefore the sticker manager
// retries those downloads, sometimes in response to user activity.
@objc
public class func refreshContents() {
// Try to download the manifests for "default" sticker packs.
tryToDownloadDefaultStickerPacks(shouldInstall: false)
// Try to download the stickers for "installed" sticker packs.
ensureAllStickerDownloadsAsync()
}
// MARK: - Paths
private class func ensureCacheDirUrl() -> URL {
var url = URL(fileURLWithPath: OWSFileSystem.appSharedDataDirectoryPath())
url.appendPathComponent("StickerManager")
OWSFileSystem.ensureDirectoryExists(url.path)
return url
}
private static let _cacheDirUrl = {
return ensureCacheDirUrl()
}()
@objc
public class func cacheDirUrl() -> URL {
// In test we need to compute the sticker cache dir every time we use it,
// since it will change from test to test.
//
// In production, we should only ensure it once because ensuring:
//
// * Makes sure it exists on disk which is expensive.
// * Makes sure it is protected on disk which is expensive.
// * Does some logging which really clutters up the logs once you have
// a bunch of stickers installed.
if CurrentAppContext().isRunningTests {
return ensureCacheDirUrl()
} else {
return _cacheDirUrl
}
}
private class func stickerUrl(stickerInfo: StickerInfo) -> URL {
let uniqueId = InstalledSticker.uniqueId(for: stickerInfo)
var url = cacheDirUrl()
// All stickers are .webp.
url.appendPathComponent("\(uniqueId).webp")
return url
}
// MARK: - Sticker Packs
@objc
public class func allStickerPacks() -> [StickerPack] {
var result = [StickerPack]()
databaseStorage.read { (transaction) in
result += allStickerPacks(transaction: transaction)
}
return result
}
@objc
public class func allStickerPacks(transaction: SDSAnyReadTransaction) -> [StickerPack] {
return StickerPack.anyFetchAll(transaction: transaction)
}
@objc
public class func installedStickerPacks(transaction: SDSAnyReadTransaction) -> [StickerPack] {
return allStickerPacks(transaction: transaction).filter {
$0.isInstalled
}
}
@objc
public class func availableStickerPacks(transaction: SDSAnyReadTransaction) -> [StickerPack] {
return allStickerPacks(transaction: transaction).filter {
!$0.isInstalled
}
}
@objc
public class func isStickerPackSaved(stickerPackInfo: StickerPackInfo) -> Bool {
var result = false
databaseStorage.read { (transaction) in
result = isStickerPackSaved(stickerPackInfo: stickerPackInfo,
transaction: transaction)
}
return result
}
@objc
public class func isStickerPackSaved(stickerPackInfo: StickerPackInfo,
transaction: SDSAnyReadTransaction) -> Bool {
return nil != fetchStickerPack(stickerPackInfo: stickerPackInfo, transaction: transaction)
}
@objc
public class func uninstallStickerPack(stickerPackInfo: StickerPackInfo,
transaction: SDSAnyWriteTransaction) {
uninstallStickerPack(stickerPackInfo: stickerPackInfo,
uninstallEverything: false,
transaction: transaction)
}
private class func uninstallStickerPack(stickerPackInfo: StickerPackInfo,
uninstallEverything: Bool,
transaction: SDSAnyWriteTransaction) {
guard let stickerPack = fetchStickerPack(stickerPackInfo: stickerPackInfo, transaction: transaction) else {
Logger.info("Skipping uninstall; not saved or installed.")
return
}
Logger.verbose("Uninstalling sticker pack: \(stickerPackInfo).")
let isDefaultStickerPack = DefaultStickerPack.isDefaultStickerPack(stickerPackInfo: stickerPackInfo)
let shouldRemove = uninstallEverything || !isDefaultStickerPack
if shouldRemove {
uninstallSticker(stickerInfo: stickerPack.coverInfo,
transaction: transaction)
for stickerInfo in stickerPack.stickerInfos {
if stickerInfo == stickerPack.coverInfo {
// Don't uninstall the cover for saved packs.
continue
}
uninstallSticker(stickerInfo: stickerInfo,
transaction: transaction)
}
stickerPack.anyRemove(transaction: transaction)
} else {
stickerPack.update(withIsInstalled: false, transaction: transaction)
}
enqueueStickerSyncMessage(operationType: .remove,
packs: [stickerPackInfo],
transaction: transaction)
NotificationCenter.default.postNotificationNameAsync(stickersOrPacksDidChange, object: nil)
}
@objc
public class func installStickerPack(stickerPack: StickerPack,
transaction: SDSAnyWriteTransaction) {
upsertStickerPack(stickerPack: stickerPack,
installMode: .install,
transaction: transaction)
}
@objc
public class func fetchStickerPack(stickerPackInfo: StickerPackInfo) -> StickerPack? {
var result: StickerPack?
databaseStorage.read { (transaction) in
result = fetchStickerPack(stickerPackInfo: stickerPackInfo,
transaction: transaction)
}
return result
}
@objc
public class func fetchStickerPack(stickerPackInfo: StickerPackInfo,
transaction: SDSAnyReadTransaction) -> StickerPack? {
let uniqueId = StickerPack.uniqueId(for: stickerPackInfo)
return StickerPack.anyFetch(uniqueId: uniqueId, transaction: transaction)
}
private class func tryToDownloadAndSaveStickerPack(stickerPackInfo: StickerPackInfo,
installMode: InstallMode) {
return tryToDownloadStickerPack(stickerPackInfo: stickerPackInfo)
.done(on: DispatchQueue.global()) { (stickerPack) in
self.upsertStickerPack(stickerPack: stickerPack,
installMode: installMode)
}.retainUntilComplete()
}
// This method is public so that we can download "transient" (uninstalled) sticker packs.
public class func tryToDownloadStickerPack(stickerPackInfo: StickerPackInfo) -> Promise<StickerPack> {
let (promise, resolver) = Promise<StickerPack>.pending()
let operation = DownloadStickerPackOperation(stickerPackInfo: stickerPackInfo,
success: resolver.fulfill,
failure: resolver.reject)
operationQueue.addOperation(operation)
return promise
}
private class func upsertStickerPack(stickerPack: StickerPack,
installMode: InstallMode) {
databaseStorage.write { (transaction) in
upsertStickerPack(stickerPack: stickerPack,
installMode: installMode,
transaction: transaction)
}
}
private class func upsertStickerPack(stickerPack: StickerPack,
installMode: InstallMode,
transaction: SDSAnyWriteTransaction) {
let oldCopy = fetchStickerPack(stickerPackInfo: stickerPack.info, transaction: transaction)
let wasSaved = oldCopy != nil
// Preserve old mutable state.
if let oldCopy = oldCopy {
stickerPack.update(withIsInstalled: oldCopy.isInstalled, transaction: transaction)
} else {
stickerPack.anyInsert(transaction: transaction)
}
self.shared.stickerPackWasInstalled(transaction: transaction)
if stickerPack.isInstalled {
enqueueStickerSyncMessage(operationType: .install,
packs: [stickerPack.info],
transaction: transaction)
}
// If the pack is already installed, make sure all stickers are installed.
if stickerPack.isInstalled {
installStickerPackContents(stickerPack: stickerPack, transaction: transaction).retainUntilComplete()
} else {
switch installMode {
case .doNotInstall:
break
case .install:
self.markSavedStickerPackAsInstalled(stickerPack: stickerPack, transaction: transaction)
case .installIfUnsaved:
if !wasSaved {
self.markSavedStickerPackAsInstalled(stickerPack: stickerPack, transaction: transaction)
}
}
}
NotificationCenter.default.postNotificationNameAsync(stickersOrPacksDidChange, object: nil)
}
private class func markSavedStickerPackAsInstalled(stickerPack: StickerPack,
transaction: SDSAnyWriteTransaction) {
if stickerPack.isInstalled {
return
}
Logger.verbose("Installing sticker pack: \(stickerPack.info).")
stickerPack.update(withIsInstalled: true, transaction: transaction)
if !isDefaultStickerPack(stickerPack.info) {
shared.setHasUsedStickers(transaction: transaction)
}
installStickerPackContents(stickerPack: stickerPack, transaction: transaction).retainUntilComplete()
enqueueStickerSyncMessage(operationType: .install,
packs: [stickerPack.info],
transaction: transaction)
}
private class func installStickerPackContents(stickerPack: StickerPack,
transaction: SDSAnyReadTransaction,
onlyInstallCover: Bool = false) -> Promise<Void> {
// Note: It's safe to kick off downloads of stickers that are already installed.
var fetches = [Promise<Void>]()
// The cover.
fetches.append(tryToDownloadAndInstallSticker(stickerPack: stickerPack, item: stickerPack.cover, transaction: transaction))
guard !onlyInstallCover else {
return when(fulfilled: fetches)
}
// The stickers.
for item in stickerPack.items {
fetches.append(tryToDownloadAndInstallSticker(stickerPack: stickerPack, item: item, transaction: transaction))
}
return when(fulfilled: fetches)
}
private class func tryToDownloadDefaultStickerPacks(shouldInstall: Bool) {
tryToDownloadStickerPacks(stickerPacks: DefaultStickerPack.packsToAutoInstall,
installMode: .installIfUnsaved)
tryToDownloadStickerPacks(stickerPacks: DefaultStickerPack.packsToNotAutoInstall,
installMode: .doNotInstall)
}
@objc
public class func installedStickers(forStickerPack stickerPack: StickerPack) -> [StickerInfo] {
var result = [StickerInfo]()
databaseStorage.read { (transaction) in
result = self.installedStickers(forStickerPack: stickerPack,
transaction: transaction)
}
return result
}
@objc
public class func installedStickers(forStickerPack stickerPack: StickerPack,
transaction: SDSAnyReadTransaction) -> [StickerInfo] {
var result = [StickerInfo]()
for stickerInfo in stickerPack.stickerInfos {
if isStickerInstalled(stickerInfo: stickerInfo, transaction: transaction) {
#if DEBUG
if nil == self.filepathForInstalledSticker(stickerInfo: stickerInfo, transaction: transaction) {
owsFailDebug("Missing sticker data for installed sticker.")
}
#endif
result.append(stickerInfo)
}
}
return result
}
@objc
public class func isDefaultStickerPack(_ packInfo: StickerPackInfo) -> Bool {
return DefaultStickerPack.isDefaultStickerPack(stickerPackInfo: packInfo)
}
@objc
public class func isStickerPackInstalled(stickerPackInfo: StickerPackInfo) -> Bool {
var result = false
databaseStorage.read { (transaction) in
result = isStickerPackInstalled(stickerPackInfo: stickerPackInfo,
transaction: transaction)
}
return result
}
@objc
public class func isStickerPackInstalled(stickerPackInfo: StickerPackInfo,
transaction: SDSAnyReadTransaction) -> Bool {
guard let pack = fetchStickerPack(stickerPackInfo: stickerPackInfo, transaction: transaction) else {
return false
}
return pack.isInstalled
}
// MARK: - Stickers
@objc
public class func filepathForInstalledSticker(stickerInfo: StickerInfo) -> String? {
var result: String?
databaseStorage.read { (transaction) in
result = filepathForInstalledSticker(stickerInfo: stickerInfo,
transaction: transaction)
}
return result
}
@objc
public class func filepathForInstalledSticker(stickerInfo: StickerInfo,
transaction: SDSAnyReadTransaction) -> String? {
if isStickerInstalled(stickerInfo: stickerInfo,
transaction: transaction) {
return stickerUrl(stickerInfo: stickerInfo).path
} else {
return nil
}
}
@objc
public class func filepathsForAllInstalledStickers(transaction: SDSAnyReadTransaction) -> [String] {
var filePaths = [String]()
let installedStickers = InstalledSticker.anyFetchAll(transaction: transaction)
for installedSticker in installedStickers {
let filePath = stickerUrl(stickerInfo: installedSticker.info).path
filePaths.append(filePath)
}
return filePaths
}
@objc
public class func isStickerInstalled(stickerInfo: StickerInfo) -> Bool {
var result = false
databaseStorage.read { (transaction) in
result = isStickerInstalled(stickerInfo: stickerInfo,
transaction: transaction)
}
return result
}
@objc
public class func isStickerInstalled(stickerInfo: StickerInfo,
transaction: SDSAnyReadTransaction) -> Bool {
return nil != fetchInstalledSticker(stickerInfo: stickerInfo, transaction: transaction)
}
internal typealias CleanupCompletion = () -> Void
internal class func uninstallSticker(stickerInfo: StickerInfo,
transaction: SDSAnyWriteTransaction) {
guard let installedSticker = fetchInstalledSticker(stickerInfo: stickerInfo, transaction: transaction) else {
Logger.info("Skipping uninstall; not installed.")
return
}
Logger.verbose("Uninstalling sticker: \(stickerInfo).")
installedSticker.anyRemove(transaction: transaction)
removeFromRecentStickers(stickerInfo, transaction: transaction)
removeStickerFromEmojiMap(installedSticker, transaction: transaction)
// Cleans up the sticker data on disk. We want to do these deletions
// after the transaction is complete so that other transactions aren't
// blocked.
DispatchQueue.global(qos: .background).async {
let url = stickerUrl(stickerInfo: stickerInfo)
OWSFileSystem.deleteFileIfExists(url.path)
}
// No need to post stickersOrPacksDidChange; caller will do that.
}
@objc
public class func fetchInstalledSticker(stickerInfo: StickerInfo,
transaction: SDSAnyReadTransaction) -> InstalledSticker? {
let uniqueId = InstalledSticker.uniqueId(for: stickerInfo)
return InstalledSticker.anyFetch(uniqueId: uniqueId, transaction: transaction)
}
@objc
public class func installSticker(stickerInfo: StickerInfo,
stickerData: Data,
emojiString: String?,
completion: (() -> Void)? = nil) {
assert(stickerData.count > 0)
var hasInstalledSticker = false
databaseStorage.read { (transaction) in
hasInstalledSticker = nil != fetchInstalledSticker(stickerInfo: stickerInfo, transaction: transaction)
}
if hasInstalledSticker {
// Sticker already installed, skip.
return
}
Logger.verbose("Installing sticker: \(stickerInfo).")
DispatchQueue.global().async {
let url = stickerUrl(stickerInfo: stickerInfo)
do {
try stickerData.write(to: url, options: .atomic)
} catch let error as NSError {
owsFailDebug("File write failed: \(error)")
return
}
let installedSticker = InstalledSticker(info: stickerInfo, emojiString: emojiString)
databaseStorage.write { (transaction) in
installedSticker.anyInsert(transaction: transaction)
#if DEBUG
guard self.isStickerInstalled(stickerInfo: stickerInfo, transaction: transaction) else {
owsFailDebug("Skipping redundant sticker install.")
return
}
if nil == self.filepathForInstalledSticker(stickerInfo: stickerInfo, transaction: transaction) {
owsFailDebug("Missing sticker data for installed sticker.")
}
#endif
self.addStickerToEmojiMap(installedSticker, transaction: transaction)
}
if let completion = completion {
completion()
}
}
NotificationCenter.default.postNotificationNameAsync(stickersOrPacksDidChange, object: nil)
}
private class func tryToDownloadAndInstallSticker(stickerPack: StickerPack,
item: StickerPackItem,
transaction: SDSAnyReadTransaction) -> Promise<Void> {
let stickerInfo: StickerInfo = item.stickerInfo(with: stickerPack)
let emojiString = item.emojiString
guard !self.isStickerInstalled(stickerInfo: stickerInfo, transaction: transaction) else {
Logger.verbose("Skipping redundant sticker install \(stickerInfo).")
return Promise.value(())
}
return tryToDownloadSticker(stickerPack: stickerPack, stickerInfo: stickerInfo)
.done(on: DispatchQueue.global()) { (stickerData) in
self.installSticker(stickerInfo: stickerInfo, stickerData: stickerData, emojiString: emojiString)
}
}
// This method is public so that we can download "transient" (uninstalled) stickers.
public class func tryToDownloadSticker(stickerPack: StickerPack,
stickerInfo: StickerInfo) -> Promise<Data> {
let (promise, resolver) = Promise<Data>.pending()
let operation = DownloadStickerOperation(stickerInfo: stickerInfo,
success: resolver.fulfill,
failure: resolver.reject)
operationQueue.addOperation(operation)
return promise
}
// MARK: - Emoji
@objc
public class func allEmoji(inEmojiString emojiString: String?) -> [String] {
guard let emojiString = emojiString else {
return []
}
return emojiString.map(String.init).filter {
$0.containsOnlyEmoji
}
}
@objc
public class func firstEmoji(inEmojiString emojiString: String?) -> String? {
return allEmoji(inEmojiString: emojiString).first
}
private class func addStickerToEmojiMap(_ installedSticker: InstalledSticker,
transaction: SDSAnyWriteTransaction) {
guard let emojiString = installedSticker.emojiString else {
return
}
let stickerId = installedSticker.uniqueId
for emoji in allEmoji(inEmojiString: emojiString) {
emojiMapStore.appendToStringSet(key: emoji,
value: stickerId,
transaction: transaction)
}
shared.clearSuggestedStickersCache()
}
private class func removeStickerFromEmojiMap(_ installedSticker: InstalledSticker,
transaction: SDSAnyWriteTransaction) {
guard let emojiString = installedSticker.emojiString else {
return
}
let stickerId = installedSticker.uniqueId
for emoji in allEmoji(inEmojiString: emojiString) {
emojiMapStore.removeFromStringSet(key: emoji,
value: stickerId,
transaction: transaction)
}
shared.clearSuggestedStickersCache()
}
private static let cacheQueue = DispatchQueue(label: "stickerManager.cacheQueue")
// This cache shoud only be accessed on cacheQueue.
private var suggestedStickersCache = NSCache<NSString, NSArray>()
// We clear the cache every time we install or uninstall a sticker.
private func clearSuggestedStickersCache() {
StickerManager.cacheQueue.sync {
self.suggestedStickersCache.removeAllObjects()
}
}
@objc
public func suggestedStickers(forTextInput textInput: String) -> [InstalledSticker] {
return StickerManager.cacheQueue.sync {
if let suggestions = suggestedStickersCache.object(forKey: textInput as NSString) as? [InstalledSticker] {
return suggestions
}
let suggestions = StickerManager.suggestedStickers(forTextInput: textInput)
suggestedStickersCache.setObject(suggestions as NSArray, forKey: textInput as NSString)
return suggestions
}
}
internal class func suggestedStickers(forTextInput textInput: String) -> [InstalledSticker] {
var result = [InstalledSticker]()
databaseStorage.read { (transaction) in
result = self.suggestedStickers(forTextInput: textInput, transaction: transaction)
}
return result
}
internal class func suggestedStickers(forTextInput textInput: String,
transaction: SDSAnyReadTransaction) -> [InstalledSticker] {
guard let emoji = firstEmoji(inEmojiString: textInput) else {
// Text input contains no emoji.
return []
}
guard emoji == textInput else {
// Text input contains more than just a single emoji.
return []
}
let stickerIds = emojiMapStore.stringSet(forKey: emoji, transaction: transaction)
return stickerIds.compactMap { (stickerId) in
guard let installedSticker = InstalledSticker.anyFetch(uniqueId: stickerId, transaction: transaction) else {
owsFailDebug("Missing installed sticker.")
return nil
}
return installedSticker
}
}
// MARK: - Known Sticker Packs
@objc
public class func addKnownStickerInfo(_ stickerInfo: StickerInfo,
transaction: SDSAnyWriteTransaction) {
let packInfo = stickerInfo.packInfo
let uniqueId = KnownStickerPack.uniqueId(for: packInfo)
if let existing = KnownStickerPack.anyFetch(uniqueId: uniqueId, transaction: transaction) {
let pack = existing
pack.anyUpdate(transaction: transaction) { pack in
pack.referenceCount += 1
}
} else {
let pack = KnownStickerPack(info: packInfo)
pack.referenceCount += 1
pack.anyInsert(transaction: transaction)
}
}
@objc
public class func removeKnownStickerInfo(_ stickerInfo: StickerInfo,
transaction: SDSAnyWriteTransaction) {
let packInfo = stickerInfo.packInfo
let uniqueId = KnownStickerPack.uniqueId(for: packInfo)
guard let pack = KnownStickerPack.anyFetch(uniqueId: uniqueId, transaction: transaction) else {
owsFailDebug("Missing known sticker pack.")
return
}
if pack.referenceCount <= 1 {
pack.anyRemove(transaction: transaction)
} else {
pack.anyUpdate(transaction: transaction) { (pack) in
pack.referenceCount -= 1
}
}
}
@objc
public class func allKnownStickerPackInfos(transaction: SDSAnyReadTransaction) -> [StickerPackInfo] {
return allKnownStickerPacks(transaction: transaction).map { $0.info }
}
@objc
public class func allKnownStickerPacks(transaction: SDSAnyReadTransaction) -> [KnownStickerPack] {
var result = [KnownStickerPack]()
KnownStickerPack.anyEnumerate(transaction: transaction) { (knownStickerPack, _) in
result.append(knownStickerPack)
}
return result
}
private class func tryToDownloadStickerPacks(stickerPacks: [StickerPackInfo],
installMode: InstallMode) {
var stickerPacksToDownload = [StickerPackInfo]()
StickerManager.databaseStorage.read { (transaction) in
for stickerPackInfo in stickerPacks {
if !StickerManager.isStickerPackSaved(stickerPackInfo: stickerPackInfo, transaction: transaction) {
stickerPacksToDownload.append(stickerPackInfo)
}
}
}
for stickerPackInfo in stickerPacksToDownload {
StickerManager.tryToDownloadAndSaveStickerPack(stickerPackInfo: stickerPackInfo,
installMode: installMode)
}
}
// MARK: - Missing Packs
// Track which sticker packs downloads have failed permanently.
private static var missingStickerPacks = Set<String>()
@objc
public class func markStickerPackAsMissing(stickerPackInfo: StickerPackInfo) {
DispatchQueue.main.async {
self.missingStickerPacks.insert(stickerPackInfo.asKey())
}
}
@objc
public class func isStickerPackMissing(stickerPackInfo: StickerPackInfo) -> Bool {
AssertIsOnMainThread()
return missingStickerPacks.contains(stickerPackInfo.asKey())
}
// MARK: - Recents
private static let kRecentStickersKey = "recentStickers"
private static let kRecentStickersMaxCount: Int = 25
@objc
public class func stickerWasSent(_ stickerInfo: StickerInfo,
transaction: SDSAnyWriteTransaction) {
store.appendToStringSet(key: kRecentStickersKey,
value: stickerInfo.asKey(),
transaction: transaction,
maxCount: kRecentStickersMaxCount)
NotificationCenter.default.postNotificationNameAsync(recentStickersDidChange, object: nil)
}
private class func removeFromRecentStickers(_ stickerInfo: StickerInfo,
transaction: SDSAnyWriteTransaction) {
store.removeFromStringSet(key: kRecentStickersKey,
value: stickerInfo.asKey(),
transaction: transaction)
NotificationCenter.default.postNotificationNameAsync(recentStickersDidChange, object: nil)
}
// Returned in descending order of recency.
//
// Only returns installed stickers.
@objc
public class func recentStickers() -> [StickerInfo] {
var result = [StickerInfo]()
databaseStorage.read { (transaction) in
result = self.recentStickers(transaction: transaction)
}
return result
}
// Returned in descending order of recency.
//
// Only returns installed stickers.
private class func recentStickers(transaction: SDSAnyReadTransaction) -> [StickerInfo] {
let keys = store.stringSet(forKey: kRecentStickersKey, transaction: transaction)
var result = [StickerInfo]()
for key in keys {
guard let sticker = InstalledSticker.anyFetch(uniqueId: key, transaction: transaction) else {
owsFailDebug("Couldn't fetch sticker")
continue
}
#if DEBUG
if nil == self.filepathForInstalledSticker(stickerInfo: sticker.info, transaction: transaction) {
owsFailDebug("Missing sticker data for installed sticker.")
}
#endif
result.append(sticker.info)
}
return result
}
// MARK: - Auto-Enable
private let kHasReceivedStickersKey = "hasReceivedStickersKey"
// This property should only be accessed on serialQueue.
private var isStickerSendEnabledCached = false
@objc
public func setHasUsedStickers(transaction: SDSAnyWriteTransaction) {
var shouldSet = false
StickerManager.serialQueue.sync {
guard !self.isStickerSendEnabledCached else {
return
}
self.isStickerSendEnabledCached = true
shouldSet = true
}
guard shouldSet else {
return
}
StickerManager.store.setBool(true, key: kHasReceivedStickersKey, transaction: transaction)
NotificationCenter.default.postNotificationNameAsync(StickerManager.isStickerSendEnabledDidChange, object: nil)
}
@objc
public var isStickerSendEnabled: Bool {
if FeatureFlags.stickerSend {
return true
}
guard FeatureFlags.stickerAutoEnable else {
return false
}
return StickerManager.serialQueue.sync {
return isStickerSendEnabledCached
}
}
private func warmIsStickerSendEnabled() {
let value = databaseStorage.readReturningResult { transaction in
return StickerManager.store.getBool(self.kHasReceivedStickersKey, defaultValue: false, transaction: transaction)
}
StickerManager.serialQueue.sync {
isStickerSendEnabledCached = value
}
}
// MARK: - Tooltips
@objc
public enum TooltipState: UInt {
case unknown = 1
case shouldShowTooltip = 2
case hasShownTooltip = 3
}
private let kShouldShowTooltipKey = "shouldShowTooltip"
// This property should only be accessed on serialQueue.
private var tooltipState = TooltipState.unknown
private func stickerPackWasInstalled(transaction: SDSAnyWriteTransaction) {
setTooltipState(.shouldShowTooltip, transaction: transaction)
}
@objc
public func stickerTooltipWasShown(transaction: SDSAnyWriteTransaction) {
setTooltipState(.hasShownTooltip, transaction: transaction)
}
@objc
public func setTooltipState(_ value: TooltipState, transaction: SDSAnyWriteTransaction) {
var shouldSet = false
StickerManager.serialQueue.sync {
// Don't "downgrade" this state; only raise to higher values.
guard self.tooltipState.rawValue < value.rawValue else {
return
}
self.tooltipState = value
shouldSet = true
}
guard shouldSet else {
return
}
StickerManager.store.setUInt(value.rawValue, key: kShouldShowTooltipKey, transaction: transaction)
}
@objc
public var shouldShowStickerTooltip: Bool {
guard isStickerSendEnabled else {
return false
}
return StickerManager.serialQueue.sync {
return self.tooltipState == .shouldShowTooltip
}
}
private func warmTooltipState() {
let value = databaseStorage.readReturningResult { transaction in
return StickerManager.store.getUInt(self.kShouldShowTooltipKey, defaultValue: TooltipState.unknown.rawValue, transaction: transaction)
}
StickerManager.serialQueue.sync {
if let tooltipState = TooltipState(rawValue: value) {
self.tooltipState = tooltipState
}
}
}
// MARK: - Misc.
// Data might be a sticker or a sticker pack manifest.
public class func decrypt(ciphertext: Data,
packKey: Data) throws -> Data {
guard packKey.count == packKeyLength else {
owsFailDebug("Invalid pack key length: \(packKey.count).")
throw StickerError.invalidInput
}
guard let stickerKeyInfo: Data = "Sticker Pack".data(using: .utf8) else {
owsFailDebug("Couldn't convert info data.")
throw StickerError.assertionFailure
}
let stickerSalt = Data(repeating: 0, count: 32)
let stickerKeyLength: Int32 = 64
let stickerKey =
try HKDFKit.deriveKey(packKey, info: stickerKeyInfo, salt: stickerSalt, outputSize: stickerKeyLength)
return try Cryptography.decryptStickerData(ciphertext, withKey: stickerKey)
}
private class func ensureAllStickerDownloadsAsync() {
DispatchQueue.global().async {
databaseStorage.read { (transaction) in
for stickerPack in self.allStickerPacks(transaction: transaction) {
ensureDownloads(forStickerPack: stickerPack, transaction: transaction).retainUntilComplete()
}
}
}
}
public class func ensureDownloadsAsync(forStickerPack stickerPack: StickerPack) -> Promise<Void> {
let (promise, resolver) = Promise<Void>.pending()
DispatchQueue.global().async {
databaseStorage.read { (transaction) in
ensureDownloads(forStickerPack: stickerPack, transaction: transaction)
.done {
resolver.fulfill(())
}.catch { (error) in
resolver.reject(error)
}.retainUntilComplete()
}
}
return promise
}
private class func ensureDownloads(forStickerPack stickerPack: StickerPack, transaction: SDSAnyReadTransaction) -> Promise<Void> {
// TODO: As an optimization, we could flag packs as "complete" if we know all
// of their stickers are installed.
// Install the covers for available sticker packs.
let onlyInstallCover = !stickerPack.isInstalled
return installStickerPackContents(stickerPack: stickerPack, transaction: transaction, onlyInstallCover: onlyInstallCover)
}
private class func cleanupOrphans() {
guard !FeatureFlags.suppressBackgroundActivity else {
// Don't clean up.
return
}
DispatchQueue.global().async {
databaseStorage.write { (transaction) in
var stickerPackMap = [String: StickerPack]()
for stickerPack in StickerPack.anyFetchAll(transaction: transaction) {
stickerPackMap[stickerPack.info.asKey()] = stickerPack
}
// Cull any orphan packs.
let savedStickerPacks = Array(stickerPackMap.values)
for stickerPack in savedStickerPacks {
let isDefaultStickerPack = self.isDefaultStickerPack(stickerPack.info)
let isInstalled = stickerPack.isInstalled
if !isDefaultStickerPack && !isInstalled {
owsFailDebug("Removing orphan pack")
stickerPack.anyRemove(transaction: transaction)
stickerPackMap.removeValue(forKey: stickerPack.info.asKey())
}
}
var stickersToUninstall = [InstalledSticker]()
InstalledSticker.anyEnumerate(transaction: transaction) { (sticker, _) in
guard let pack = stickerPackMap[sticker.info.packInfo.asKey()] else {
stickersToUninstall.append(sticker)
return
}
if pack.isInstalled {
return
}
if pack.coverInfo == sticker.info {
return
}
stickersToUninstall.append(sticker)
return
}
if stickersToUninstall.count > 0 {
owsFailDebug("Removing \(stickersToUninstall.count) orphan stickers.")
}
for sticker in stickersToUninstall {
self.uninstallSticker(stickerInfo: sticker.info, transaction: transaction)
}
}
}
}
// MARK: - Sync Messages
private class func enqueueStickerSyncMessage(operationType: StickerPackOperationType,
packs: [StickerPackInfo],
transaction: SDSAnyWriteTransaction) {
guard tsAccountManager.isRegisteredAndReady else {
return
}
guard let thread = TSAccountManager.getOrCreateLocalThread(transaction: transaction) else {
owsFailDebug("Missing thread.")
return
}
let message = OWSStickerPackSyncMessage(thread: thread, packs: packs, operationType: operationType)
self.messageSenderJobQueue.add(message: message.asPreparer, transaction: transaction)
}
@objc
public class func syncAllInstalledPacks(transaction: SDSAnyWriteTransaction) {
guard tsAccountManager.isRegisteredAndReady else {
return
}
let stickerPackInfos = installedStickerPacks(transaction: transaction).map { $0.info }
guard stickerPackInfos.count > 0 else {
return
}
enqueueStickerSyncMessage(operationType: .install,
packs: stickerPackInfos,
transaction: transaction)
}
@objc
public class func processIncomingStickerPackOperation(_ proto: SSKProtoSyncMessageStickerPackOperation,
transaction: SDSAnyWriteTransaction) {
guard tsAccountManager.isRegisteredAndReady else {
return
}
let packID: Data = proto.packID
let packKey: Data = proto.packKey
guard let stickerPackInfo = StickerPackInfo.parse(packId: packID, packKey: packKey) else {
owsFailDebug("Invalid pack info.")
return
}
guard let type = proto.type else {
owsFailDebug("Pack operation missing type.")
return
}
switch type {
case .install:
tryToDownloadAndSaveStickerPack(stickerPackInfo: stickerPackInfo,
installMode: .install)
case .remove:
uninstallStickerPack(stickerPackInfo: stickerPackInfo, transaction: transaction)
@unknown default:
owsFailDebug("Unknown type.")
return
}
}
// MARK: - Debug
// This is only intended for use while debugging.
#if DEBUG
@objc
public class func uninstallAllStickerPacks() {
databaseStorage.write { (transaction) in
let stickerPacks = installedStickerPacks(transaction: transaction)
for stickerPack in stickerPacks {
uninstallStickerPack(stickerPackInfo: stickerPack.info,
transaction: transaction)
}
}
}
@objc
public class func removeAllStickerPacks() {
databaseStorage.write { (transaction) in
let stickerPacks = allStickerPacks(transaction: transaction)
for stickerPack in stickerPacks {
uninstallStickerPack(stickerPackInfo: stickerPack.info,
uninstallEverything: true,
transaction: transaction)
stickerPack.anyRemove(transaction: transaction)
}
}
}
@objc
public class func tryToInstallAllAvailableStickerPacks() {
databaseStorage.write { (transaction) in
for stickerPack in self.availableStickerPacks(transaction: transaction) {
self.installStickerPack(stickerPack: stickerPack, transaction: transaction)
}
}
tryToDownloadDefaultStickerPacks(shouldInstall: true)
}
#endif
}
// MARK: -
// These methods are used to maintain a "string set":
// A set (no duplicates) of strings stored as a list.
// As a bonus, the set is stored in order of descending recency.
extension SDSKeyValueStore {
func appendToStringSet(key: String,
value: String,
transaction: SDSAnyWriteTransaction,
maxCount: Int? = nil) {
// Prepend value to ensure descending order of recency.
var stringSet = [value]
if let storedValue = getObject(key, transaction: transaction) as? [String] {
stringSet += storedValue.filter {
$0 != value
}
}
if let maxCount = maxCount {
stringSet = Array(stringSet.prefix(maxCount))
}
setObject(stringSet, key: key, transaction: transaction)
}
func removeFromStringSet(key: String,
value: String,
transaction: SDSAnyWriteTransaction) {
var stringSet = [String]()
if let storedValue = getObject(key, transaction: transaction) as? [String] {
guard storedValue.contains(value) else {
// No work to do.
return
}
stringSet += storedValue.filter {
$0 != value
}
}
setObject(stringSet, key: key, transaction: transaction)
}
func stringSet(forKey key: String,
transaction: SDSAnyReadTransaction) -> [String] {
guard let object = self.getObject(key, transaction: transaction) else {
return []
}
guard let stringSet = object as? [String] else {
owsFailDebug("Value has unexpected type \(type(of: object)).")
return []
}
return stringSet
}
}
| gpl-3.0 | ec820d7bf063866c96c2efbcd503d5fa | 37.462843 | 146 | 0.611252 | 6.086017 | false | false | false | false |
mxcl/swift-package-manager | Sources/Build/Command.link(ClangModule).swift | 1 | 2266 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import PackageModel
import PackageLoading
import Utility
extension Command {
static func linkClangModule(_ product: Product, configuration conf: Configuration, prefix: AbsolutePath, otherArgs: [String], CC: String) throws -> Command {
precondition(product.containsOnlyClangModules)
let clangModules = product.modules.flatMap { $0 as? ClangModule }
var args = [String]()
// Collect all the objects.
var objects = [AbsolutePath]()
var inputs = [String]()
var linkFlags = [String]()
for module in clangModules {
let buildMeta = ClangModuleBuildMetadata(module: module, prefix: prefix, otherArgs: [])
objects += buildMeta.objects
inputs += buildMeta.inputs
linkFlags += buildMeta.linkDependenciesFlags
}
args += try ClangModuleBuildMetadata.basicArgs() + otherArgs
args += ["-L\(prefix.asString)"]
// Linux doesn't search executable directory for shared libs so embed runtime search path.
#if os(Linux)
args += ["-Xlinker", "-rpath=$ORIGIN"]
#endif
args += linkFlags
args += objects.map{ $0.asString }
switch product.type {
case .Executable: break
case .Library(.Dynamic):
args += ["-shared"]
case .Test, .Library(.Static):
fatalError("Can't build \(product.name), \(product.type) is not yet supported.")
}
let productPath = prefix.appending(product.outname)
args += ["-o", productPath.asString]
let shell = ShellTool(description: "Linking \(product.name)",
inputs: objects.map{ $0.asString } + inputs,
outputs: [productPath.asString, product.targetName],
args: [CC] + args)
return Command(node: product.targetName, tool: shell)
}
}
| apache-2.0 | 55913b9ee9424f41e7ff9d4e2e684105 | 36.147541 | 161 | 0.620918 | 4.800847 | false | false | false | false |
praveenb-ios/PBDataTableView | PBDataTable/ViewController.swift | 1 | 5538 | //
// ViewController.swift
// PBDataTable
//
// Created by praveen b on 6/10/16.
// Copyright © 2016 Praveen. All rights reserved.
//
import UIKit
class ViewController: UIViewController, PBDataTableViewDelegate {
var dataTableView: PBDataTableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
changeStatusBarColor()
dataTableView = Bundle.main.loadNibNamed("PBDataTableView", owner: self, options: nil)?.first as! PBDataTableView
dataTableView.frame = CGRect(x: 0, y: 20, width: self.view.frame.width, height: self.view.frame.height-20)
dataTableView.backgroundColor = UIColor(red: 225/255, green: 225/255, blue: 225/255, alpha: 1.0)
dataTableView.delegate = self
dataTableView.enableSorting = true
//Search bar can be customized, now it was set to default value. Search is enabled with first 2 columns.
dataTableView.enableSearchBar = true
//Header name and width size can be dynamic. Table view will be re-sized respectively, if total width exceeds the Super view Width table view will be scrolled.
dataTableView.columnDataArray = [["name":"FirstName","widthSize":110],["name":"LastName","widthSize":110],["name":"Address","widthSize":180],["name":"City","widthSize":110],["name":"Zip","widthSize":100],["name":"PhoneNumber","widthSize":158]]
//Not to change the Key of the Dictionaries if needs to be dynamic.
dataTableView.dataTableArray = dataTableViewdictParams()
//Only if you want the Last column to be button make use of below two lines of code. You can cutomize the Button from PBDataTableViewCell.
ApplicationDelegate.cellLastColumnButtonEnable = true
dataTableView.lastColumnButtonHeaderName = "Edit"
dataTableView.setupView()
self.view.addSubview(dataTableView)
}
override func viewDidAppear(_ animated: Bool) {
//T0 change the Constraints and make the view scrollable make sure you add this line in View Did Appear.
dataTableView.configureView()
}
func tableViewDidSelectedRow(_ indexPath: IndexPath) {
print("selected row: \(indexPath)")
}
func tableViewCellEditButtonTapped(_ indexPath: IndexPath) {
print("selected row: \(indexPath)")
}
func changeStatusBarColor() {
UIApplication.shared.isStatusBarHidden = false
UIApplication.shared.statusBarStyle = .lightContent
let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
statusBar.backgroundColor = UIColor(red: 64/255, green: 64/255, blue: 64/255, alpha: 1)
}
func dataTableViewdictParams() -> NSMutableArray {
let dataTableArray = [
["rowColumn1":"Ajay","rowColumn2":"Zener","rowColumn3":"23, Settembre","rowColumn4":"Rome","rowColumn5":NSNumber(value: 80099 as Int),"rowColumn6":NumberFormatter().number(from: "6766665")!],
["rowColumn1":"Peter","rowColumn2":"Hayes","rowColumn3":"Richmond Street","rowColumn4":"Hoboken","rowColumn5":NSNumber(value: 50043 as Int),"rowColumn6":NumberFormatter().number(from: "8676766665")!],
["rowColumn1":"Aaron","rowColumn2":"Joe","rowColumn3":"Goodman Susan E, 42 Grove St","rowColumn4":"NewYork","rowColumn5":NSNumber(value: 10014 as Int),"rowColumn6":NumberFormatter().number(from: "9889499449")!],
["rowColumn1":"Gabriel","rowColumn2":"Ella","rowColumn3":"9 Barrow Owners Corporation","rowColumn4":"NewYork","rowColumn5":NSNumber(value: 10033 as Int),"rowColumn6":NumberFormatter().number(from: "5676667667")!],
["rowColumn1":"Matthew","rowColumn2":"William","rowColumn3":"401-505 LaGuardia Pl","rowColumn4":"NewYork","rowColumn5":NSNumber(value: 10011 as Int),"rowColumn6":NumberFormatter().number(from: "8099078771")!],
["rowColumn1":"Scarlett","rowColumn2":"","rowColumn3":"301 Garden St Hoboken","rowColumn4":"Hoboken","rowColumn5":NSNumber(value: 10022 as Int),"rowColumn6":NumberFormatter().number(from: "4323445555")!],
["rowColumn1":"Hannah","rowColumn2":"Andrew","rowColumn3":"Sixteenth St Jersey City","rowColumn4":"New Jersey","rowColumn5":NSNumber(value: 13222 as Int),"rowColumn6":NumberFormatter().number(from: "7666676555")!],
["rowColumn1":"Alexa","rowColumn2":"Joe","rowColumn3":"211 County Ave Secaucus","rowColumn4":"New Jersey","rowColumn5":NSNumber(value: 12022 as Int),"rowColumn6":NumberFormatter().number(from: "9889888888")!],
["rowColumn1":"Hunter","rowColumn2":"Ryan","rowColumn3":"Edgmont Township","rowColumn4":"Philadelphia","rowColumn5":NSNumber(value: 11001 as Int),"rowColumn6":NumberFormatter().number(from: "6567766776")!],
["rowColumn1":"Lucy","rowColumn2":"Adrian","rowColumn3":"Secaucus, NJ","rowColumn4":"New Jersey","rowColumn5":NSNumber(value: 10003 as Int),"rowColumn6":NumberFormatter().number(from: "7455455551")!]] as NSMutableArray
return dataTableArray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 2b5c953f81a6ea802583c6a186aca8ea | 61.920455 | 251 | 0.653784 | 4.60266 | false | false | false | false |
eljeff/AudioKit | Sources/AudioKit/Operations/OperationEffect.swift | 1 | 7658 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
let floatRange = -Float.greatestFiniteMagnitude ... Float.greatestFiniteMagnitude
/// Operation-based effect
public class OperationEffect: Node, AudioUnitContainer, Tappable, Toggleable {
/// Internal audio unit type
public typealias AudioUnitType = InternalAU
/// Four letter unique description "cstm"
public static let ComponentDescription = AudioComponentDescription(effect: "cstm")
// MARK: - Properties
/// Internal audio unit
public private(set) var internalAU: AudioUnitType?
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU?.isStarted ?? false
}
// MARK: - Parameters
/// Specification for Parameter 1
public static let parameter1Def = OperationGenerator.makeParam(1)
/// Specification for Parameter 2
public static let parameter2Def = OperationGenerator.makeParam(2)
/// Specification for Parameter 3
public static let parameter3Def = OperationGenerator.makeParam(3)
/// Specification for Parameter 4
public static let parameter4Def = OperationGenerator.makeParam(4)
/// Specification for Parameter 5
public static let parameter5Def = OperationGenerator.makeParam(5)
/// Specification for Parameter 6
public static let parameter6Def = OperationGenerator.makeParam(6)
/// Specification for Parameter 7
public static let parameter7Def = OperationGenerator.makeParam(7)
/// Specification for Parameter 8
public static let parameter8Def = OperationGenerator.makeParam(8)
/// Specification for Parameter 9
public static let parameter9Def = OperationGenerator.makeParam(9)
/// Specification for Parameter 10
public static let parameter10Def = OperationGenerator.makeParam(10)
/// Specification for Parameter 11
public static let parameter11Def = OperationGenerator.makeParam(11)
/// Specification for Parameter 12
public static let parameter12Def = OperationGenerator.makeParam(12)
/// Specification for Parameter 13
public static let parameter13Def = OperationGenerator.makeParam(13)
/// Specification for Parameter 14
public static let parameter14Def = OperationGenerator.makeParam(14)
/// Operation parameter 1
@Parameter public var parameter1: AUValue
/// Operation parameter 2
@Parameter public var parameter2: AUValue
/// Operation parameter 3
@Parameter public var parameter3: AUValue
/// Operation parameter 4
@Parameter public var parameter4: AUValue
/// Operation parameter 5
@Parameter public var parameter5: AUValue
/// Operation parameter 6
@Parameter public var parameter6: AUValue
/// Operation parameter 7
@Parameter public var parameter7: AUValue
/// Operation parameter 8
@Parameter public var parameter8: AUValue
/// Operation parameter 9
@Parameter public var parameter9: AUValue
/// Operation parameter 10
@Parameter public var parameter10: AUValue
/// Operation parameter 11
@Parameter public var parameter11: AUValue
/// Operation parameter 12
@Parameter public var parameter12: AUValue
/// Operation parameter 13
@Parameter public var parameter13: AUValue
/// Operation parameter 14
@Parameter public var parameter14: AUValue
// MARK: - Audio Unit
/// Internal Audio Unit for Operation Effect
public class InternalAU: AudioUnitBase {
/// Get an array of the parameter definitions
/// - Returns: Array of parameter definitions
public override func getParameterDefs() -> [NodeParameterDef] {
[OperationEffect.parameter1Def,
OperationEffect.parameter2Def,
OperationEffect.parameter3Def,
OperationEffect.parameter4Def,
OperationEffect.parameter5Def,
OperationEffect.parameter6Def,
OperationEffect.parameter7Def,
OperationEffect.parameter8Def,
OperationEffect.parameter9Def,
OperationEffect.parameter10Def,
OperationEffect.parameter11Def,
OperationEffect.parameter12Def,
OperationEffect.parameter13Def,
OperationEffect.parameter14Def]
}
/// Create the DSP Refence for this node
/// - Returns: DSP Reference
public override func createDSP() -> DSPRef {
akCreateDSP("OperationEffectDSP")
}
/// Set sporth string
/// - Parameter sporth: Sporth string
public func setSporth(_ sporth: String) {
sporth.withCString { str -> Void in
akOperationEffectSetSporth(dsp, str, Int32(sporth.utf8CString.count))
}
}
}
// MARK: - Initializers
/// Initialize the generator for stereo (2 channels)
///
/// - Parameters:
/// - input: Node to use for processing
/// - channelCount: Only 2 channels are supported, but need to differentiate the initializer
/// - operations: Array of operations [left, right]
///
public convenience init(_ input: Node,
channelCount: Int,
operations: (StereoOperation, [Operation]) -> [Operation]) {
let computedParameters = operations(StereoOperation.input, Operation.parameters)
let left = computedParameters[0]
if channelCount == 2 {
let right = computedParameters[1]
self.init(input, sporth: "\(right.sporth) \(left.sporth)")
} else {
self.init(input, sporth: "\(left.sporth)")
}
}
/// Initialize the generator for stereo (2 channels)
///
/// - Parameters:
/// - input: Node to use for processing
/// - operation: Operation to generate, can be mono or stereo
///
public convenience init(_ input: Node,
operation: (StereoOperation, [Operation]) -> ComputedParameter) {
let computedParameter = operation(StereoOperation.input, Operation.parameters)
if type(of: computedParameter) == Operation.self {
if let monoOperation = computedParameter as? Operation {
self.init(input, sporth: monoOperation.sporth + " dup ")
return
}
} else {
if let stereoOperation = computedParameter as? StereoOperation {
self.init(input, sporth: stereoOperation.sporth + " swap ")
return
}
}
Log("Initialization failed.")
self.init(input, sporth: "")
}
/// Initializw with a stereo operation
/// - Parameters:
/// - input: Node to use for processing
/// - operation: Stereo operation
///
public convenience init(_ input: Node, operation: (StereoOperation) -> ComputedParameter) {
self.init(input, operation: { node, _ in operation(node) })
}
/// Initialize the effect with an input and a valid Sporth string
///
/// - Parameters:
/// - input: Node to use for processing
/// - sporth: String of valid Sporth code
///
public init(_ input: Node, sporth: String) {
super.init(avAudioNode: AVAudioNode())
instantiateAudioUnit { avAudioUnit in
self.avAudioUnit = avAudioUnit
self.avAudioNode = avAudioUnit
self.internalAU = avAudioUnit.auAudioUnit as? AudioUnitType
self.internalAU?.setSporth(sporth)
}
connections.append(input)
}
}
| mit | c47618ca4acb06591cf45c5c494ab398 | 36.539216 | 100 | 0.658005 | 5.285024 | false | false | false | false |
cocoatoucher/AICustomViewControllerTransition | Example/Example/VideoPlayerTransitionViewController.swift | 1 | 11345 | //
// VideoPlayerTransitionViewController.swift
// Example
//
// Created by cocoatoucher on 10/08/16.
// Copyright © 2016 cocoatoucher. All rights reserved.
//
import UIKit
import AICustomViewControllerTransition
class VideoPlayerTransitionViewController: UIViewController {
// Container view to display video player modal view controller when minimized
@IBOutlet weak var thumbnailVideoContainerView: UIView!
// Create an interactive transitioning delegate
let customTransitioningDelegate: InteractiveTransitioningDelegate = InteractiveTransitioningDelegate()
lazy var videoPlayerViewController: VideoPlayerModalViewController = {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "videoPlayerViewController") as! VideoPlayerModalViewController
vc.modalPresentationStyle = .custom
vc.transitioningDelegate = self.customTransitioningDelegate
// Pan gesture recognizer feedback from VideoPlayerModalViewController
vc.handlePan = {(panGestureRecozgnizer) in
let translatedPoint = panGestureRecozgnizer.translation(in: self.view)
if (panGestureRecozgnizer.state == .began) {
self.customTransitioningDelegate.beginDismissing(viewController: vc)
self.lastVideoPlayerOriginY = vc.view.frame.origin.y
} else if (panGestureRecozgnizer.state == .changed) {
let ratio = max(min(((self.lastVideoPlayerOriginY + translatedPoint.y) / self.thumbnailVideoContainerView.frame.minY), 1), 0)
// Store lastPanRatio for next callback
self.lastPanRatio = ratio
// Update percentage of interactive transition
self.customTransitioningDelegate.update(self.lastPanRatio)
} else if (panGestureRecozgnizer.state == .ended) {
// If pan ratio exceeds the threshold then transition is completed, otherwise cancel dismissal and present the view controller again
let completed = (self.lastPanRatio > self.panRatioThreshold) || (self.lastPanRatio < -self.panRatioThreshold)
self.customTransitioningDelegate.finalizeInteractiveTransition(isTransitionCompleted: completed)
}
}
return vc
}()
let panRatioThreshold: CGFloat = 0.3
var lastPanRatio: CGFloat = 0.0
var lastVideoPlayerOriginY: CGFloat = 0.0
var videoPlayerViewControllerInitialFrame: CGRect?
override func viewDidLoad() {
super.viewDidLoad()
customTransitioningDelegate.transitionPresent = { [weak self] (fromViewController: UIViewController, toViewController: UIViewController, containerView: UIView, transitionType: TransitionType, completion: @escaping () -> Void) in
guard let weakSelf = self else {
return
}
let videoPlayerViewController = toViewController as! VideoPlayerModalViewController
if case .simple = transitionType {
if (weakSelf.videoPlayerViewControllerInitialFrame != nil) {
videoPlayerViewController.view.frame = weakSelf.videoPlayerViewControllerInitialFrame!
weakSelf.videoPlayerViewControllerInitialFrame = nil
} else {
videoPlayerViewController.view.frame = containerView.bounds.offsetBy(dx: 0, dy: videoPlayerViewController.view.frame.height)
videoPlayerViewController.backgroundView.alpha = 0.0
videoPlayerViewController.dismissButton.alpha = 0.0
}
}
UIView.animate(withDuration: defaultTransitionAnimationDuration, animations: {
videoPlayerViewController.view.transform = CGAffineTransform.identity
videoPlayerViewController.view.frame = containerView.bounds
videoPlayerViewController.backgroundView.alpha = 1.0
videoPlayerViewController.dismissButton.alpha = 1.0
}, completion: { (finished) in
completion()
// In order to disable user interaction with pan gesture recognizer
// It is important to do this after completion block, since user interaction is enabled after view controller transition completes
videoPlayerViewController.view.isUserInteractionEnabled = true
})
}
customTransitioningDelegate.transitionDismiss = { [weak self] (fromViewController: UIViewController, toViewController: UIViewController, containerView: UIView, transitionType: TransitionType, completion: @escaping () -> Void) in
guard let weakSelf = self else {
return
}
let videoPlayerViewController = fromViewController as! VideoPlayerModalViewController
let finalTransform = CGAffineTransform(scaleX: weakSelf.thumbnailVideoContainerView.bounds.width / videoPlayerViewController.view.bounds.width, y: weakSelf.thumbnailVideoContainerView.bounds.height * 3 / videoPlayerViewController.view.bounds.height)
UIView.animate(withDuration: defaultTransitionAnimationDuration, animations: {
videoPlayerViewController.view.transform = finalTransform
var finalRect = videoPlayerViewController.view.frame
finalRect.origin.x = weakSelf.thumbnailVideoContainerView.frame.minX
finalRect.origin.y = weakSelf.thumbnailVideoContainerView.frame.minY
videoPlayerViewController.view.frame = finalRect
videoPlayerViewController.backgroundView.alpha = 0.0
videoPlayerViewController.dismissButton.alpha = 0.0
}, completion: { (finished) in
completion()
videoPlayerViewController.view.isUserInteractionEnabled = false
weakSelf.addChildViewController(videoPlayerViewController)
var thumbnailRect = videoPlayerViewController.view.frame
thumbnailRect.origin = CGPoint.zero
videoPlayerViewController.view.frame = thumbnailRect
weakSelf.thumbnailVideoContainerView.addSubview(fromViewController.view)
fromViewController.didMove(toParentViewController: weakSelf)
})
}
customTransitioningDelegate.transitionPercentPresent = {[weak self] (fromViewController: UIViewController, toViewController: UIViewController, percentage: CGFloat, containerView: UIView) in
guard let weakSelf = self else {
return
}
let videoPlayerViewController = toViewController as! VideoPlayerModalViewController
if (weakSelf.videoPlayerViewControllerInitialFrame != nil) {
weakSelf.videoPlayerViewController.view.frame = weakSelf.videoPlayerViewControllerInitialFrame!
weakSelf.videoPlayerViewControllerInitialFrame = nil
}
let startXScale = weakSelf.thumbnailVideoContainerView.bounds.width / containerView.bounds.width
let startYScale = weakSelf.thumbnailVideoContainerView.bounds.height * 3 / containerView.bounds.height
let xScale = startXScale + ((1 - startXScale) * percentage)
let yScale = startYScale + ((1 - startYScale) * percentage)
toViewController.view.transform = CGAffineTransform(scaleX: xScale, y: yScale)
let startXPos = weakSelf.thumbnailVideoContainerView.frame.minX
let startYPos = weakSelf.thumbnailVideoContainerView.frame.minY
let horizontalMove = startXPos - (startXPos * percentage)
let verticalMove = startYPos - (startYPos * percentage)
var finalRect = toViewController.view.frame
finalRect.origin.x = horizontalMove
finalRect.origin.y = verticalMove
toViewController.view.frame = finalRect
videoPlayerViewController.backgroundView.alpha = percentage
videoPlayerViewController.dismissButton.alpha = percentage
}
customTransitioningDelegate.transitionPercentDismiss = {[weak self] (fromViewController: UIViewController, toViewController: UIViewController, percentage: CGFloat, containerView: UIView) in
guard let weakSelf = self else {
return
}
let videoPlayerViewController = fromViewController as! VideoPlayerModalViewController
let finalXScale = weakSelf.thumbnailVideoContainerView.bounds.width / videoPlayerViewController.view.bounds.width
let finalYScale = weakSelf.thumbnailVideoContainerView.bounds.height * 3 / videoPlayerViewController.view.bounds.height
let xScale = 1 - (percentage * (1 - finalXScale))
let yScale = 1 - (percentage * (1 - finalYScale))
videoPlayerViewController.view.transform = CGAffineTransform(scaleX: xScale, y: yScale)
let finalXPos = weakSelf.thumbnailVideoContainerView.frame.minX
let finalYPos = weakSelf.thumbnailVideoContainerView.frame.minY
let horizontalMove = min(weakSelf.thumbnailVideoContainerView.frame.minX * percentage, finalXPos)
let verticalMove = min(weakSelf.thumbnailVideoContainerView.frame.minY * percentage, finalYPos)
var finalRect = videoPlayerViewController.view.frame
finalRect.origin.x = horizontalMove
finalRect.origin.y = verticalMove
videoPlayerViewController.view.frame = finalRect
videoPlayerViewController.backgroundView.alpha = 1 - percentage
videoPlayerViewController.dismissButton.alpha = 1 - percentage
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func presentAction(_ sender: AnyObject) {
if (self.videoPlayerViewController.parent != nil) {
self.videoPlayerViewControllerInitialFrame = self.thumbnailVideoContainerView.convert(self.videoPlayerViewController.view.frame, to: self.view)
self.videoPlayerViewController.removeFromParentViewController()
}
self.present(self.videoPlayerViewController, animated: true, completion: nil)
}
@IBAction func presentFromThumbnailAction(_ sender: AnyObject) {
guard self.videoPlayerViewController.parent != nil else {
return
}
self.videoPlayerViewControllerInitialFrame = self.thumbnailVideoContainerView.convert(self.videoPlayerViewController.view.frame, to: self.view)
self.videoPlayerViewController.removeFromParentViewController()
self.present(self.videoPlayerViewController, animated: true, completion: nil)
}
@IBAction func handlePresentPan(_ panGestureRecozgnizer: UIPanGestureRecognizer) {
guard self.videoPlayerViewController.parent != nil || self.customTransitioningDelegate.isPresenting else {
return
}
let translatedPoint = panGestureRecozgnizer.translation(in: self.view)
if (panGestureRecozgnizer.state == .began) {
self.videoPlayerViewControllerInitialFrame = self.thumbnailVideoContainerView.convert(self.videoPlayerViewController.view.frame, to: self.view)
self.videoPlayerViewController.removeFromParentViewController()
self.customTransitioningDelegate.beginPresenting(viewController: self.videoPlayerViewController, fromViewController: self)
self.videoPlayerViewControllerInitialFrame = self.thumbnailVideoContainerView.convert(self.videoPlayerViewController.view.frame, to: self.view)
self.lastVideoPlayerOriginY = self.videoPlayerViewControllerInitialFrame!.origin.y
} else if (panGestureRecozgnizer.state == .changed) {
let ratio = max(min(((self.lastVideoPlayerOriginY + translatedPoint.y) / self.thumbnailVideoContainerView.frame.minY), 1), 0)
// Store lastPanRatio for next callback
self.lastPanRatio = 1 - ratio
// Update percentage of interactive transition
self.customTransitioningDelegate.update(self.lastPanRatio)
} else if (panGestureRecozgnizer.state == .ended) {
// If pan ratio exceeds the threshold then transition is completed, otherwise cancel dismissal and present the view controller again
let completed = (self.lastPanRatio > self.panRatioThreshold) || (self.lastPanRatio < -self.panRatioThreshold)
self.customTransitioningDelegate.finalizeInteractiveTransition(isTransitionCompleted: completed)
}
}
}
| mit | 127b6575ec3f86577e63742f93998a11 | 44.558233 | 252 | 0.781911 | 5.268927 | false | false | false | false |
achimk/Cars | CarsApp/Repositories/Cars/Models/CarCreateModel.swift | 1 | 692 | //
// CarCreateModel.swift
// CarsApp
//
// Created by Joachim Kret on 29/07/2017.
// Copyright © 2017 Joachim Kret. All rights reserved.
//
import Foundation
struct CarCreateModel: Equatable {
var name: String
var model: String
var brand: String
var year: String
init(name: String,
model: String,
brand: String,
year: String) {
self.name = name
self.model = model
self.brand = brand
self.year = year
}
}
func ==(lhs: CarCreateModel, rhs: CarCreateModel) -> Bool {
return lhs.name == rhs.name
&& lhs.model == rhs.model
&& lhs.brand == rhs.brand
&& lhs.year == rhs.year
}
| mit | cc14ee4ea67857b14b43e2cc3bf27c61 | 19.323529 | 59 | 0.581766 | 3.860335 | false | false | false | false |
antonzherdev/objd | ObjDLib/test-mdv/test-mdv/test-mdv/DetailViewController.swift | 1 | 2565 | //
// DetailViewController.swift
// test-mdv
//
// Created by Anton Zherdev on 05/06/14.
// Copyright (c) 2014 Anton Zherdev. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController, UISplitViewControllerDelegate {
@IBOutlet var detailDescriptionLabel: UILabel
var masterPopoverController: UIPopoverController? = nil
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
if self.masterPopoverController != nil {
self.masterPopoverController!.dismissPopoverAnimated(true)
}
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail: AnyObject = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.valueForKey("timeStamp").description
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Split view
func splitViewController(splitController: UISplitViewController, willHideViewController viewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController popoverController: UIPopoverController) {
barButtonItem.title = "Master" // NSLocalizedString(@"Master", @"Master")
self.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true)
self.masterPopoverController = popoverController
}
func splitViewController(splitController: UISplitViewController, willShowViewController viewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// Called when the view is shown again in the split view, invalidating the button and popover controller.
self.navigationItem.setLeftBarButtonItem(nil, animated: true)
self.masterPopoverController = nil
}
func splitViewController(splitController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
| lgpl-3.0 | 7149b714f09a32e4b48246c8bd47870b | 37.283582 | 238 | 0.712281 | 6.06383 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/SizeThatFitsView.swift | 1 | 1875 | import UIKit
// SizeThatFitsView is the base class of views that use manual layout.
// These views use a manual layout rather than auto layout for convienence within a CollectionViewCell
@objc(WMFSizeThatFitsView)
open class SizeThatFitsView: SetupView {
// MARK: - Methods for subclassing
// Subclassers should override setup instead of any of the initializers. Subclassers must call super.setup()
override open func setup() {
super.setup()
translatesAutoresizingMaskIntoConstraints = false
autoresizesSubviews = false
updateFonts(with: traitCollection)
setNeedsLayout()
}
// Subclassers should override sizeThatFits:apply: instead of layoutSubviews to lay out subviews.
// In this method, subclassers should calculate the appropriate layout size and if apply is `true`,
// apply the layout to the subviews.
open func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
return size
}
// Subclassers should override updateAccessibilityElements to update any accessibility elements
// that should be updated after layout. Subclassers must call super.updateAccessibilityElements()
open func updateAccessibilityElements() {
}
// MARK: - Layout
final override public func layoutSubviews() {
super.layoutSubviews()
let size = bounds.size
_ = sizeThatFits(size, apply: true)
updateAccessibilityElements()
#if DEBUG
for view in subviews {
assert(view.autoresizingMask == [])
assert(view.constraints == [])
}
#endif
}
final override public func sizeThatFits(_ size: CGSize) -> CGSize {
return sizeThatFits(size, apply: false)
}
open func updateFonts(with traitCollection: UITraitCollection) {
}
}
| mit | 42b83e4e7c8b8a3e46e8f209dee01445 | 33.090909 | 112 | 0.6704 | 5.563798 | false | false | false | false |
akrio714/Wbm | Wbm/Common/Http/SwfitJSON+Extension.swift | 1 | 3643 | //
// SwfitJSON+Extension.swift
// shop
//
// Created by akrio on 2017/4/22.
// Copyright © 2017年 zhangwangwang. All rights reserved.
//
import Foundation
import SwiftDate
import SwiftyJSON
extension JSON {
func dateFormatValue (_ formamt:DateFormat) -> DateInRegion {
return dateFormat (formamt) ?? (DateInRegion(string: "1970-01-01", format: .custom("YYYY-MM-dd"))!)
}
/// 将json对象转化成日期类型
///
/// - Parameter formamt: 格式化规则
/// - Returns: 转化后的日期
func dateFormat (_ formamt:DateFormat) -> DateInRegion? {
let str = self.stringValue
switch formamt {
case .custom(let formater):
return DateInRegion(string: str, format: .custom(formater))
case .strict(let formater):
return DateInRegion(string: str, format: .strict(formater))
case .iso8601(let options):
return DateInRegion(string: str, format: .iso8601(options: options))
case .iso8601Auto:
return DateInRegion(string: str, format: .iso8601Auto)
case .extended:
return DateInRegion(string: str, format: .extended)
case .rss(let alt):
return DateInRegion(string: str, format: .rss(alt:alt) )
case .dotNET:
return DateInRegion(string: str, format: .dotNET)
case .unix:
return unixFormat (str)
}
}
/// 将 unix 时间戳转化成DateInRegion类型
///
/// - Parameter str: 待转化的时间字符串
/// - Returns: 转化后的时间
private func unixFormat (_ str: String) -> DateInRegion?{
//尝试将字符串转成数字,格式化失败返回nil
guard let time = Double(str) else {
return nil
}
//13位说明是精确到毫秒的时间戳,那么将转化成10位的秒级别时间戳,如果都不是说明格式错误
if str.characters.count == 13 {
return DateInRegion(absoluteDate: Date(timeIntervalSince1970: time/1000.0))
}else if str.characters.count == 10 {
return DateInRegion(absoluteDate: Date(timeIntervalSince1970: time))
}else {
return nil
}
}
}
/// Available date formats used to parse strings and format date into string
///
/// - custom: custom format expressed in Unicode tr35-31 (see http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns and Apple's Date Formatting Guide). Formatter uses heuristics to guess the date if it's invalid.
/// This may end in a wrong parsed date. Use `strict` to disable heuristics parsing.
/// - strict: strict format is like custom but does not apply heuristics to guess at the date which is intended by the string.
/// So, if you pass an invalid date (like 1999-02-31) formatter fails instead of returning guessing date (in our case
/// 1999-03-03).
/// - iso8601: ISO8601 date format (see https://en.wikipedia.org/wiki/ISO_8601).
/// - iso8601Auto: ISO8601 date format. You should use it to parse a date (parsers evaluate automatically the format of
/// the ISO8601 string). Passed as options to transform a date to string it's equal to [.withInternetDateTime] options.
/// - extended: extended date format ("eee dd-MMM-yyyy GG HH:mm:ss.SSS zzz")
/// - rss: RSS and AltRSS date format
/// - dotNET: .NET date format
/// - unix: unix时间戳格式化
enum DateFormat {
case custom(String)
case strict(String)
case iso8601(options: ISO8601DateTimeFormatter.Options)
case iso8601Auto
case extended
case rss(alt: Bool)
case dotNET
case unix
}
| apache-2.0 | e25035d0d313a6ed65640a8c59bcc337 | 39.738095 | 241 | 0.655172 | 3.933333 | false | false | false | false |
nodekit-io/nodekit-darwin | src/nodekit/NKScripting/NKScriptValue.swift | 1 | 10214 | /*
* nodekit.io
*
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
* Portions Copyright 2015 XWebView
* Portions Copyright (c) 2014 Intel Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
public class NKScriptValue: NSObject {
public let namespace: String
private weak var _channel: NKScriptChannel?
public var channel: NKScriptChannel { return _channel!; }
public var context: NKScriptContext! { return _channel!.context!; }
weak var origin: NKScriptValue!
// This object is a plugin object.
init(namespace: String, channel: NKScriptChannel, origin: NKScriptValue?) {
self.namespace = namespace
self._channel = channel
super.init()
self.origin = origin ?? self
}
// The object is a stub for a JavaScript object which was retained as an argument.
private var reference = 0
convenience init(reference: Int, channel: NKScriptChannel, origin: NKScriptValue) {
let namespace = "\(origin.namespace).$references[\(reference)]"
self.init(namespace: namespace, channel: channel, origin: origin)
self.reference = reference
}
deinit {
let script: String
if reference == 0 {
script = "delete \(namespace)"
} else if origin != nil {
script = "\(origin.namespace).$releaseObject(\(reference))"
} else {
return
}
context?.evaluateJavaScript(script, completionHandler: nil)
}
// Async JavaScript object operations
public func constructWithArguments(arguments: [AnyObject]!, completionHandler: ((AnyObject?, NSError?) -> Void)? = nil) {
let exp = "new " + scriptForCallingMethod(nil, arguments: arguments)
evaluateExpression(exp, completionHandler: completionHandler)
}
public func callWithArguments(arguments: [AnyObject]!, completionHandler: ((AnyObject?, NSError?) -> Void)? = nil) {
dispatch_async(NKScriptContextFactory.defaultQueue) {() -> Void in
let exp = self.scriptForCallingMethod(nil, arguments: arguments)
self.evaluateExpression(exp, completionHandler: completionHandler)
}
}
public func invokeMethod(method: String!, withArguments arguments: [AnyObject]!, completionHandler: ((AnyObject?, NSError?) -> Void)? = nil) {
dispatch_async(NKScriptContextFactory.defaultQueue) {() -> Void in
let exp = self.scriptForCallingMethod(method, arguments: arguments)
self.evaluateExpression(exp, completionHandler: completionHandler)
}
}
public func defineProperty(property: String!, descriptor: AnyObject!) {
let exp = "Object.defineProperty(\(namespace), \(property), \(self.context.serialize(descriptor)))"
evaluateExpression(exp, completionHandler: nil)
}
public func deleteProperty(property: String!) -> Void {
evaluateExpression("delete \(scriptForFetchingProperty(property))", completionHandler: nil)
}
public func hasProperty(property: String!, completionHandler: ((AnyObject?, NSError?) -> Void)?) {
evaluateExpression("\(scriptForFetchingProperty(property)) != undefined", completionHandler: completionHandler)
}
public func valueForProperty(property: String!, completionHandler: ((AnyObject?, NSError?) -> Void)?) {
evaluateExpression(scriptForFetchingProperty(property), completionHandler: completionHandler)
}
public func setValue(value: AnyObject!, forProperty property: String!) {
context?.evaluateJavaScript(scriptForUpdatingProperty(property, value: value), completionHandler: nil)
}
public func valueAtIndex(index: Int, completionHandler: ((AnyObject?, NSError?) -> Void)?) {
evaluateExpression("\(namespace)[\(index)]", completionHandler: completionHandler)
}
public func setValue(value: AnyObject!, atIndex index: Int) {
context?.evaluateJavaScript("\(namespace)[\(index)] = \(self.context.serialize(value))", completionHandler: nil)
}
// Private JavaScript scripts and helpers
private func scriptForFetchingProperty(name: String!) -> String {
if name == nil {
return namespace
} else if name.isEmpty {
return "\(namespace)['']"
} else if let idx = Int(name) {
return "\(namespace)[\(idx)]"
} else {
return "\(namespace).\(name)"
}
}
private func scriptForUpdatingProperty(name: String!, value: AnyObject?) -> String {
return scriptForFetchingProperty(name) + " = " + self.context.serialize(value)
}
private func scriptForCallingMethod(name: String!, arguments: [AnyObject]?) -> String {
let args = arguments?.map(serialize) ?? []
let script = scriptForFetchingProperty(name) + "(" + args.joinWithSeparator(", ") + ")"
return "(function line_eval(){ try { return " + script + "} catch(ex) { console.log(ex.toString()); return ex} })()"
}
private func serialize(object: AnyObject?) -> String {
var obj: AnyObject? = object
if let val = obj as? NSValue {
obj = val as? NSNumber ?? val.nonretainedObjectValue
}
if let o = obj as? NKScriptValue {
return o.namespace
} else if let o1 = obj as? NKScriptExport {
if let o2 = o1 as? NSObject {
if let scriptObject = o2.NKscriptObject {
return scriptObject.namespace
} else {
let scriptObject = NKScriptValueNative(object: o2, inContext: self.context)
objc_setAssociatedObject(o2, unsafeAddressOf(NKScriptValue), scriptObject, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return scriptObject.namespace
}
}
} else if let s = obj as? String {
let d = try? NSJSONSerialization.dataWithJSONObject([s], options: NSJSONWritingOptions(rawValue: 0))
let json = NSString(data: d!, encoding: NSUTF8StringEncoding)!
return json.substringWithRange(NSMakeRange(1, json.length - 2))
} else if let n = obj as? NSNumber {
if CFGetTypeID(n) == CFBooleanGetTypeID() {
return n.boolValue.description
}
return n.stringValue
} else if let date = obj as? NSDate {
return "\"\(date.toJSONDate())\""
} else if let _ = obj as? NSData {
// TODO: map to Uint8Array object
} else if let a = obj as? [AnyObject] {
return "[" + a.map(self.serialize).joinWithSeparator(", ") + "]"
} else if let d = obj as? [String: AnyObject] {
return "{" + d.keys.map {"\"\($0)\": \(self.serialize(d[$0]!))"}.joinWithSeparator(", ") + "}"
} else if obj === NSNull() {
return "null"
} else if obj == nil {
return "undefined"
}
return "'\(obj!.description)'"
}
private func evaluateExpression(expression: String, completionHandler: ((AnyObject?, NSError?) -> Void)?)
{
guard let completionHandler = completionHandler else {
context?.evaluateJavaScript(expression, completionHandler: nil)
return
}
context?.evaluateJavaScript(scriptForRetaining(expression)) {
[weak self](result: AnyObject?, error: NSError?)->Void in
completionHandler(self?.wrapScriptObject(result) ?? result, error)
}
}
private func scriptForRetaining(script: String) -> String {
return origin != nil ? "\(origin.namespace).$retainObject(\(script))" : script
}
internal func wrapScriptObject(object: AnyObject!) -> AnyObject! {
if let dict = object as? [String: AnyObject] where dict["$sig"] as? NSNumber == 0x5857574F {
if let num = dict["$ref"] as? NSNumber {
return NKScriptValue(reference: num.integerValue, channel: channel, origin: self)
} else if let namespace = dict["$ns"] as? String {
return NKScriptValue(namespace: namespace, channel: channel, origin: self)
}
}
return object
}
}
extension NKScriptValue {
// DOM objects
public var windowObject: NKScriptValue { get {
return NKScriptValue(namespace: "window", channel: self.channel, origin: self.origin) }
}
public var documentObject: NKScriptValue { get {
return NKScriptValue(namespace: "document", channel: self.channel, origin: self.origin) }
}
}
| apache-2.0 | fb904f0649a3b8edc74f2ddcede14967 | 28.605797 | 152 | 0.567456 | 5.530049 | false | false | false | false |
brtterme/DouYuZB | DouYu/DouYu/class/Tools/Extension/File.swift | 1 | 1222 | //
// File.swift
// DouYu
//
// Created by dear on 16/12/30.
// Copyright © 2016年 dear. All rights reserved.
//
import UIKit
extension UIBarButtonItem{
//1.类方法
class func crearteItem(ImageName: String , LightName : String ,Size: CGSize) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named: ImageName), for: .normal)
btn.setImage(UIImage(named: LightName), for: .highlighted)
btn.frame = CGRect(origin: CGPoint.zero, size: Size)
return UIBarButtonItem(customView: btn)
}
//2.便利构造函数 1. convenience开头 2。构造函数必须明确调用一个设计的构造函数(self调用)
convenience init(ImageName: String , LightName : String = "",Size: CGSize = CGSize.zero) {
let btn = UIButton()
btn.setImage(UIImage(named: ImageName), for: .normal)
if LightName != "" {
btn.setImage(UIImage(named: LightName), for: .highlighted)
}
if Size == CGSize.zero{
btn.sizeToFit()
}
else
{
btn.frame = CGRect(origin: CGPoint.zero, size: Size)
}
self.init(customView : btn)
}
}
| mit | 134e19e03c88c6b27117581215676665 | 28.564103 | 101 | 0.584562 | 3.935154 | false | false | false | false |
cdillard/SwiftLint | Source/SwiftLintFramework/Rules/FunctionBodyLengthRule.swift | 2 | 2734 | //
// FunctionBodyLengthRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SourceKittenFramework
public struct FunctionBodyLengthRule: ASTRule, ConfigurationProviderRule {
public var configuration = SeverityLevelsConfiguration(warning: 40, error: 100)
public init() {}
public static let description = RuleDescription(
identifier: "function_body_length",
name: "Function Body Length",
description: "Functions bodies should not span too many lines."
)
public func validateFile(file: File,
kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
let functionKinds: [SwiftDeclarationKind] = [
.FunctionAccessorAddress,
.FunctionAccessorDidset,
.FunctionAccessorGetter,
.FunctionAccessorMutableaddress,
.FunctionAccessorSetter,
.FunctionAccessorWillset,
.FunctionConstructor,
.FunctionDestructor,
.FunctionFree,
.FunctionMethodClass,
.FunctionMethodInstance,
.FunctionMethodStatic,
.FunctionOperator,
.FunctionSubscript
]
if !functionKinds.contains(kind) {
return []
}
if let offset = (dictionary["key.offset"] as? Int64).flatMap({ Int($0) }),
let bodyOffset = (dictionary["key.bodyoffset"] as? Int64).flatMap({ Int($0) }),
let bodyLength = (dictionary["key.bodylength"] as? Int64).flatMap({ Int($0) }) {
let startLine = file.contents.lineAndCharacterForByteOffset(bodyOffset)
let endLine = file.contents.lineAndCharacterForByteOffset(bodyOffset + bodyLength)
if let startLine = startLine?.line, let endLine = endLine?.line {
for parameter in configuration.params {
let (exceeds, lineCount) = file.exceedsLineCountExcludingCommentsAndWhitespace(
startLine, endLine, parameter.value)
if exceeds {
return [StyleViolation(ruleDescription: self.dynamicType.description,
severity: parameter.severity,
location: Location(file: file, byteOffset: offset),
reason: "Function body should span \(parameter.value) lines or less " +
"excluding comments and whitespace: currently spans \(lineCount) " +
"lines")]
}
}
}
}
return []
}
}
| mit | be147553b4f8955d3514727df14c4ccb | 39.205882 | 100 | 0.582297 | 5.478958 | false | true | false | false |
alessiobrozzi/firefox-ios | Sync/HistoryPayload.swift | 2 | 2081 | /* 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 Storage
import SwiftyJSON
open class HistoryPayload: CleartextPayloadJSON {
open class func fromJSON(_ json: JSON) -> HistoryPayload? {
let p = HistoryPayload(json)
if p.isValid() {
return p
}
return nil
}
override open func isValid() -> Bool {
if !super.isValid() {
return false
}
if self["deleted"].bool ?? false {
return true
}
return self["histUri"].string != nil && // TODO: validate URI.
self["title"].isStringOrNull() &&
self["visits"].isArray()
}
open func asPlace() -> Place {
return Place(guid: self.id, url: self.histURI, title: self.title)
}
var visits: [Visit] {
let visits = self["visits"].arrayObject as! [[String: Any]]
return optFilter(visits.map(Visit.fromJSON))
}
fileprivate var histURI: String {
return self["histUri"].string!
}
var historyURI: URL {
return self.histURI.asURL!
}
var title: String {
return self["title"].string ?? ""
}
override open func equalPayloads(_ obj: CleartextPayloadJSON) -> Bool {
if let p = obj as? HistoryPayload {
if !super.equalPayloads(p) {
return false
}
if p.deleted {
return self.deleted == p.deleted
}
// If either record is deleted, these other fields might be missing.
// But we just checked, so we're good to roll on.
if p.title != self.title {
return false
}
if p.historyURI != self.historyURI {
return false
}
// TODO: compare visits.
return true
}
return false
}
}
| mpl-2.0 | c115fa17dc6b38caa6fb6475aad6bb40 | 24.378049 | 80 | 0.540125 | 4.553611 | false | false | false | false |
Eonil/EditorLegacy | Modules/EditorDebuggingFeature/EditorDebuggingFeature/LLDBController.swift | 1 | 9448 | ////
//// LLDBController.swift
//// EditorDebuggingFeature
////
//// Created by Hoon H. on 2015/01/19.
//// Copyright (c) 2015 Eonil. All rights reserved.
////
//
//import Foundation
//import PrecompilationOfExternalToolSupport
//
//class LLDBController {
// init() {
// }
//
// func launch(workingDirectoryURL:NSURL) {
// k.launch(workingDirectoryURL)
// k.run("____ID_TO_OBJ_MAP = {}")
// k.run("THE_DBG = None")
// }
// func createDebugger() {
// k.run("THE_DBG = lldb.SBDebugger.Create()")
// let idexpr = ("print(id(THE_DBG))")
//
// dbg = Debugger(controller: self, IDExpression: idexpr)
// }
// func destroyDebugger() {
// k.run("lldb.SBDebugger.Destory(THE_DBG)")
// k.run("THE_DBG = None")
// dbg = nil
// }
//
// var debuffer:Debugger {
// get {
// return dbg!
// }
// }
//
// ////
//
// private let k = SynchronousPythonLLDBShellKernelController()
// private var dbg = nil as Debugger?
//
// private func run
//}
//
//class PythonProxyObject {
// private let controller:LLDBController
// private let idexpr:String
//
// init(controller:LLDBController, IDExpression:String) {
// self.controller = controller
// self.idexpr = IDExpression
// }
//
// private var kernel:SynchronousPythonLLDBShellKernelController {
// get {
// return controller.k
// }
// }
//
// private func run(command:String) -> String {
// return kernel.run(command)
// }
//}
//
//class Debugger: PythonProxyObject {
// func createTargetWithFileAndArch(filename:String, archname:Arch) -> Target {
// run("temp = THE_DBG.CreateTargetWithFileAndArch(\(encodeAsPythonStringLiteralExpression(filename)), \(archname.rawValue))")
// let idexpr = run("print(id(temp))")
// }
// func deleteTarget(target:Target) {
//
// }
//}
//
//enum Arch: String {
// case Default = "LLDB_ARCH_DEFAULT"
// case Default32Bit = "LLDB_ARCH_DEFAULT_32BIT"
// case Default64Bit = "LLDB_ARCH_DEFAULT_64BIT"
//}
//
//private func encodeAsPythonStringLiteralExpression(s:String) -> String {
// let s1 = s.stringByReplacingOccurrencesOfString("\"", withString: "\\\"", options: NSStringCompareOptions.LiteralSearch, range: nil)
// return "\"\(s1)\""
//}
//
//
//
//
//class Target: PythonProxyObject {
//
//}
//
//
//
//
//
//
//
//
//
//
//
//
//struct RemotePythonUtility {
// func run(program:String) -> String {
//
// }
// func call(target:AnyObject?, methodName:String, arguments:[AnyObject?]) -> AnyObject? {
// let target1 = toPythonExpression(target)
// let args1 = arguments.map { (o:AnyObject?)->String in
// return self.toPythonExpression(o)
// }
// let args2 = join(", ", args1)
// run("____temp = \(target1).\(methodName)(\(args2))")
// run("if ____temp == None:")
// }
//
// func toSwiftObject(pythonExpression x:String) -> AnyObject? {
// if x == "None" {
// return nil
// }
// if
// }
// func toPythonExpression(o:AnyObject?) -> String {
// if o == nil {
// return "None"
// }
// if let p = o! as? PythonProxyObject {
// return "____ID_TO_OBJ_MAP[\(p.idexpr)]"
// }
// if let v = o! as? Int {
// return v.description
// }
// if let v = o! as? String {
// return v
// }
// fatalError("Unsupported data type.")
// }
//}
//
//
//
//
//
//
//
//
//
//
///// Python LLDB Shell Kernel is a small python script that interacts
///// via stdin/stdout. The kernel Accepts single-line command, and
///// produces at least single-line result. All input/output are fully
///// regularised as lines. (that means all transmissions are separated
///// by new-line character)
/////
///// Kernel may return more than one line by type of command. In that
///// case, each command need to manage that extra lines.
//class SynchronousPythonLLDBShellKernelController {
// init() {
// t.standardInput = inPipe
// t.standardOutput = outPipe
// t.standardError = errPipe
// }
//
// func launch(workingDirectoryURL:NSURL) {
// t.currentDirectoryPath = workingDirectoryURL.path!
// t.launchPath = "/bin/bash" // TODO: Need to use `sh` for regularity. But `sh` doesn't work for `cargo`, so temporarily fallback to `bash`.
// t.arguments = ["--login", "-s"]
// t.launch()
//
// let pp = "/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Versions/A/Resources/Python"
// inPipe.fileHandleForWriting.writeUTF8String("export PYTHONPATH=\(pp)\n")
//
// let b = NSBundle(forClass: self.dynamicType)
// let dbgpy = b.pathForResource("kernel", ofType: "py")!
//
// inPipe.fileHandleForWriting.writeUTF8String("exec python \(dbgpy)\n")
//
// }
//
// func run(command:String) -> String {
// sendLine(command)
// return receiveLine()
// }
//
// func sendLine(s:String) {
// assert(find(s, "\n") == nil)
// inPipe.fileHandleForWriting.writeUTF8String("\(s)\n")
// }
// func receiveLine() -> String {
// return outPipe.fileHandleForWriting.readUTF8StringToNewLineCharacter()
// }
//
// private let t = NSTask()
// private let inPipe = NSPipe()
// private let outPipe = NSPipe()
// private let errPipe = NSPipe()
//}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
////protocol PythonLLDBKernelControllerDelegate: class {
//// /// `line` includes ending new-line character.
//// func PythonLLDBKernelControllerDidReadLineFromStandardOutput(line:String)
//// /// `line` includes ending new-line character.
//// func PythonLLDBKernelControllerDidReadLineFromStandardError(line:String)
//// /// `ok` is `false` for any errors.
//// func PythonLLDBKernelControllerDidTerminate(ok:Bool)
////}
////class PythonLLDBKernelController {
//// weak var delegate:PythonLLDBKernelControllerDelegate?
////
//// init() {
//// sh.delegate = self
////
//// err.onLine = { s in
//// println("ERROR: \(s)")
//// }
////
//// out.onLine = { s in
//// println("OUT: \(s)")
//// }
//// }
//// func launch(workingDirectoryURL:NSURL) {
//// sh.launch(workingDirectoryURL: workingDirectoryURL)
////
//// let pp = "/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Versions/A/Resources/Python"
//// sh.writeToStandardInput("export PYTHONPATH=\(pp)\n")
////
//// let b = NSBundle(forClass: self.dynamicType)
//// let dbgpy = b.pathForResource("kernel", ofType: "py")!
////
//// sh.writeToStandardInput("exec python \(dbgpy)\n")
//// execute("import lldb")
//// }
//// func execute(s:String) {
//// sh.writeToStandardInput("\(s)\n")
//// println(s)
//// }
////
//// ////
////
//// private let sh = ShellTaskExecutionController()
//// private var out = LineDispatcher()
//// private var err = LineDispatcher()
////}
////
////extension PythonLLDBKernelController: ShellTaskExecutionControllerDelegate {
////
//// func shellTaskExecutableControllerDidReadFromStandardError(s: String) {
//// err.push(s)
//// }
//// func shellTaskExecutableControllerDidReadFromStandardOutput(s: String) {
//// out.push(s)
//// }
//// func shellTaskExecutableControllerRemoteProcessDidTerminate(#exitCode: Int32, reason: NSTaskTerminationReason) {
//// println("TERM: \(exitCode), \(reason)")
//// abort()
//// }
////}
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
////
//////protocol PythonLLDBKernelControllerDelegate: class {
////// /// `line` includes ending new-line character.
////// func PythonLLDBKernelControllerDidReadLineFromStandardOutput(line:String)
////// /// `line` includes ending new-line character.
////// func PythonLLDBKernelControllerDidReadLineFromStandardError(line:String)
////// /// `ok` is `false` for any errors.
////// func PythonLLDBKernelControllerDidTerminate(ok:Bool)
//////}
//////public class PythonLLDBKernelController {
////// weak var delegate:PythonLLDBKernelControllerDelegate?
//////
////// public init() {
////// sh.delegate = self
//////
////// err.onLine = { s in
////// println("ERROR: \(s)")
////// }
//////
////// out.onLine = { s in
////// println("OUT: \(s)")
////// }
////// }
////// public func launch(workingDirectoryURL:NSURL) {
////// let b = NSBundle(forClass: MarkerClass.self)
////// let dbgpy = b.pathForResource("dbg", ofType: "py")!
////// sh.launch(workingDirectoryURL: workingDirectoryURL, launchPath: "/usr/bin/python", arguments: [dbgpy])
//////// sh.writeToStandardInput("print \"aa\"\n\n\n")
////// }
//////
////// ////
//////
////// private let sh = TaskExecutionController()
////// private var out = UTF8StringLineDispatcher()
////// private var err = UTF8StringLineDispatcher()
//////}
//////
//////extension PythonLLDBKernelController: TaskExecutionControllerDelegate {
////// public func taskExecutableControllerDidReadFromStandardError(data: NSData) {
////// err.push(data)
////// }
////// public func taskExecutableControllerDidReadFromStandardOutput(data: NSData) {
////// out.push(data)
////// }
////// public func taskExecutableControllerRemoteProcessDidTerminate(#exitCode: Int32, reason: NSTaskTerminationReason) {
////// println("TERM: \(exitCode), \(reason)")
////// }
//////}
//////
//////
//////
//////
//////
//////
//////
//////
//////
//////struct UTF8StringLineDispatcher {
////// var onLine:(line:String)->() {
////// get {
////// return lp.onLine
////// }
////// set(v) {
////// lp.onLine = v
////// }
////// }
////// var sp = UTF8StringDispatcher()
////// var lp = LineDispatcher()
//////
////// init() {
////// sp.onString = { s in
////// self.lp.push(s)
////// }
////// }
////// func push(data:NSData) {
////// sp.push(data)
////// }
//////}
////
////
////
| mit | 268dd4781d1ee2ce57f377d0be730405 | 23.350515 | 146 | 0.615157 | 3.066537 | false | false | false | false |
alessiobrozzi/firefox-ios | Client/Frontend/Home/HistoryPanel.swift | 2 | 22805 | /* 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 Storage
import XCGLogger
import Deferred
private let log = Logger.browserLogger
private typealias SectionNumber = Int
private typealias CategoryNumber = Int
private typealias CategorySpec = (section: SectionNumber?, rows: Int, offset: Int)
private struct HistoryPanelUX {
static let WelcomeScreenItemTextColor = UIColor.gray
static let WelcomeScreenItemWidth = 170
static let IconSize = 23
static let IconBorderColor = UIColor(white: 0, alpha: 0.1)
static let IconBorderWidth: CGFloat = 0.5
}
private func getDate(_ dayOffset: Int) -> Date {
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let nowComponents = (calendar as NSCalendar).components([.year, .month, .day], from: Date())
let today = calendar.date(from: nowComponents)!
return (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.day, value: dayOffset, to: today, options: [])!
}
class HistoryPanel: SiteTableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate?
private var currentSyncedDevicesCount: Int?
var events = [NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory, NotificationDynamicFontChanged]
var refreshControl: UIRefreshControl?
private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverlayView()
private let QueryLimit = 100
private let NumSections = 5
private let Today = getDate(0)
private let Yesterday = getDate(-1)
private let ThisWeek = getDate(-7)
private var categories: [CategorySpec] = [CategorySpec]() // Category number (index) -> (UI section, row count, cursor offset).
private var sectionLookup = [SectionNumber: CategoryNumber]() // Reverse lookup from UI section to data category.
var syncDetailText = ""
var hasRecentlyClosed: Bool {
return self.profile.recentlyClosedTabs.tabs.count > 0
}
// MARK: - Lifecycle
init() {
super.init(nibName: nil, bundle: nil)
events.forEach { NotificationCenter.default.addObserver(self, selector: #selector(HistoryPanel.notificationReceived(_:)), name: $0, object: nil) }
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
events.forEach { NotificationCenter.default.removeObserver(self, name: $0, object: nil) }
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.accessibilityIdentifier = "History List"
updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in
self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Add a refresh control if the user is logged in and the control was not added before. If the user is not
// logged in, remove any existing control but only when it is not currently refreshing. Otherwise, wait for
// the refresh to finish before removing the control.
if profile.hasSyncableAccount() && refreshControl == nil {
addRefreshControl()
} else if refreshControl?.isRefreshing == false {
removeRefreshControl()
}
updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in
self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount)
}
}
// MARK: - History Data Store
func updateNumberOfSyncedDevices(_ count: Int?) {
if let count = count, count > 0 {
syncDetailText = String.localizedStringWithFormat(Strings.SyncedTabsTableViewCellDescription, count)
} else {
syncDetailText = ""
}
self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .automatic)
}
func updateSyncedDevicesCount() -> Success {
return chainDeferred(self.profile.getCachedClientsAndTabs()) { tabsAndClients in
self.currentSyncedDevicesCount = tabsAndClients.count
return succeed()
}
}
func notificationReceived(_ notification: Notification) {
switch notification.name {
case NotificationFirefoxAccountChanged, NotificationPrivateDataClearedHistory:
if self.profile.hasSyncableAccount() {
resyncHistory()
}
break
case NotificationDynamicFontChanged:
if emptyStateOverlayView.superview != nil {
emptyStateOverlayView.removeFromSuperview()
}
emptyStateOverlayView = createEmptyStateOverlayView()
resyncHistory()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
private func fetchData() -> Deferred<Maybe<Cursor<Site>>> {
return profile.history.getSitesByLastVisit(QueryLimit)
}
private func setData(_ data: Cursor<Site>) {
self.data = data
self.computeSectionOffsets()
}
func resyncHistory() {
profile.syncManager.syncHistory().uponQueue(DispatchQueue.main) { result in
if result.isSuccess {
self.reloadData()
} else {
self.endRefreshing()
}
self.updateSyncedDevicesCount().uponQueue(DispatchQueue.main) { result in
self.updateNumberOfSyncedDevices(self.currentSyncedDevicesCount)
}
}
}
// MARK: - Refreshing TableView
func addRefreshControl() {
let refresh = UIRefreshControl()
refresh.addTarget(self, action: #selector(HistoryPanel.refresh), for: UIControlEvents.valueChanged)
self.refreshControl = refresh
self.tableView.addSubview(refresh)
}
func removeRefreshControl() {
self.refreshControl?.removeFromSuperview()
self.refreshControl = nil
}
func endRefreshing() {
// Always end refreshing, even if we failed!
self.refreshControl?.endRefreshing()
// Remove the refresh control if the user has logged out in the meantime
if !self.profile.hasSyncableAccount() {
self.removeRefreshControl()
}
}
@objc func refresh() {
self.refreshControl?.beginRefreshing()
resyncHistory()
}
override func reloadData() {
self.fetchData().uponQueue(DispatchQueue.main) { result in
if let data = result.successValue {
self.setData(data)
self.tableView.reloadData()
self.updateEmptyPanelState()
}
self.endRefreshing()
}
}
// MARK: - Empty State
private func updateEmptyPanelState() {
if data.count == 0 {
if self.emptyStateOverlayView.superview == nil {
self.tableView.addSubview(self.emptyStateOverlayView)
self.emptyStateOverlayView.snp.makeConstraints { make -> Void in
make.left.right.bottom.equalTo(self.view)
make.top.equalTo(self.view).offset(100)
}
}
} else {
self.tableView.alwaysBounceVertical = true
self.emptyStateOverlayView.removeFromSuperview()
}
}
private func createEmptyStateOverlayView() -> UIView {
let overlayView = UIView()
overlayView.backgroundColor = UIColor.white
let welcomeLabel = UILabel()
overlayView.addSubview(welcomeLabel)
welcomeLabel.text = Strings.HistoryPanelEmptyStateTitle
welcomeLabel.textAlignment = NSTextAlignment.center
welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight
welcomeLabel.textColor = HistoryPanelUX.WelcomeScreenItemTextColor
welcomeLabel.numberOfLines = 0
welcomeLabel.adjustsFontSizeToFitWidth = true
welcomeLabel.snp.makeConstraints { make in
make.centerX.equalTo(overlayView)
// Sets proper top constraint for iPhone 6 in portait and for iPad.
make.centerY.equalTo(overlayView).offset(HomePanelUX.EmptyTabContentOffset).priority(100)
// Sets proper top constraint for iPhone 4, 5 in portrait.
make.top.greaterThanOrEqualTo(overlayView).offset(50)
make.width.equalTo(HistoryPanelUX.WelcomeScreenItemWidth)
}
return overlayView
}
// MARK: - TableView Row Helpers
func computeSectionOffsets() {
var counts = [Int](repeating: 0, count: NumSections)
// Loop over all the data. Record the start of each "section" of our list.
for i in 0..<data.count {
if let site = data[i] {
counts[categoryForDate(site.latestVisit!.date) + 1] += 1
}
}
var section = 0
var offset = 0
self.categories = [CategorySpec]()
for i in 0..<NumSections {
let count = counts[i]
if i == 0 {
sectionLookup[section] = i
section += 1
}
if count > 0 {
log.debug("Category \(i) has \(count) rows, and thus is section \(section).")
self.categories.append((section: section, rows: count, offset: offset))
sectionLookup[section] = i
offset += count
section += 1
} else {
log.debug("Category \(i) has 0 rows, and thus has no section.")
self.categories.append((section: nil, rows: 0, offset: offset))
}
}
}
private func siteForIndexPath(_ indexPath: IndexPath) -> Site? {
let offset = self.categories[sectionLookup[indexPath.section]!].offset
return data[indexPath.row + offset]
}
private func categoryForDate(_ date: MicrosecondTimestamp) -> Int {
let date = Double(date)
if date > (1000000 * Today.timeIntervalSince1970) {
return 0
}
if date > (1000000 * Yesterday.timeIntervalSince1970) {
return 1
}
if date > (1000000 * ThisWeek.timeIntervalSince1970) {
return 2
}
return 3
}
private func isInCategory(_ date: MicrosecondTimestamp, category: Int) -> Bool {
return self.categoryForDate(date) == category
}
// UI sections disappear as categories empty. We need to translate back and forth.
private func uiSectionToCategory(_ section: SectionNumber) -> CategoryNumber {
for i in 0..<self.categories.count {
if let s = self.categories[i].section, s == section {
return i
}
}
return 0
}
private func categoryToUISection(_ category: CategoryNumber) -> SectionNumber? {
return self.categories[category].section
}
// MARK: - TableView Delegate / DataSource
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.accessoryType = UITableViewCellAccessoryType.none
if indexPath.section == 0 {
cell.imageView!.layer.borderWidth = 0
return indexPath.row == 0 ? configureRecentlyClosed(cell, for: indexPath) : configureSyncedTabs(cell, for: indexPath)
} else {
return configureSite(cell, for: indexPath)
}
}
func configureRecentlyClosed(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell {
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell.textLabel!.text = Strings.RecentlyClosedTabsButtonTitle
cell.detailTextLabel!.text = ""
cell.imageView!.image = UIImage(named: "recently_closed")
cell.imageView?.backgroundColor = UIColor.white
if !hasRecentlyClosed {
cell.textLabel?.alpha = 0.5
cell.imageView!.alpha = 0.5
cell.selectionStyle = .none
}
return cell
}
func configureSyncedTabs(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell {
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
cell.textLabel!.text = Strings.SyncedTabsTableViewCellTitle
cell.detailTextLabel!.text = self.syncDetailText
cell.imageView!.image = UIImage(named: "synced_devices")
cell.imageView?.backgroundColor = UIColor.white
return cell
}
func configureSite(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell {
if let site = siteForIndexPath(indexPath), let cell = cell as? TwoLineTableViewCell {
cell.setLines(site.title, detailText: site.url)
cell.imageView!.layer.borderColor = HistoryPanelUX.IconBorderColor.cgColor
cell.imageView!.layer.borderWidth = HistoryPanelUX.IconBorderWidth
cell.imageView?.setIcon(site.icon, forURL: site.tileURL, completed: { (color, url) in
cell.imageView?.image = cell.imageView?.image?.createScaled(CGSize(width: HistoryPanelUX.IconSize, height: HistoryPanelUX.IconSize))
cell.imageView?.contentMode = .center
})
}
return cell
}
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
var count = 1
for category in self.categories {
if category.rows > 0 {
count += 1
}
}
return count
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
if indexPath.section == 0 {
self.tableView.deselectRow(at: indexPath, animated: true)
return indexPath.row == 0 ? self.showRecentlyClosed() : self.showSyncedTabs()
}
if let site = self.siteForIndexPath(indexPath), let url = URL(string: site.url) {
let visitType = VisitType.typed // Means History, too.
if let homePanelDelegate = homePanelDelegate {
homePanelDelegate.homePanel(self, didSelectURL: url, visitType: visitType)
}
return
}
log.warning("No site or no URL when selecting row.")
}
func showSyncedTabs() {
let nextController = RemoteTabsPanel()
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
self.refreshControl?.endRefreshing()
self.navigationController?.pushViewController(nextController, animated: true)
}
func showRecentlyClosed() {
guard hasRecentlyClosed else {
return
}
let nextController = RecentlyClosedTabsPanel()
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
self.refreshControl?.endRefreshing()
self.navigationController?.pushViewController(nextController, animated: true)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = String()
switch sectionLookup[section]! {
case 0: return nil
case 1: title = NSLocalizedString("Today", comment: "History tableview section header")
case 2: title = NSLocalizedString("Yesterday", comment: "History tableview section header")
case 3: title = NSLocalizedString("Last week", comment: "History tableview section header")
case 4: title = NSLocalizedString("Last month", comment: "History tableview section header")
default:
assertionFailure("Invalid history section \(section)")
}
return title
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
return nil
}
return super.tableView(tableView, viewForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 0
}
return super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
}
return self.categories[uiSectionToCategory(section)].rows
}
func tableView(_ tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: IndexPath) {
// Intentionally blank. Required to use UITableViewRowActions
}
func tableView(_ tableView: UITableView, editActionsForRowAtIndexPath indexPath: IndexPath) -> [AnyObject]? {
if indexPath.section == 0 {
return []
}
let title = NSLocalizedString("Remove", tableName: "HistoryPanel", comment: "Action button for deleting history entries in the history panel.")
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: title, handler: { (action, indexPath) in
if let site = self.siteForIndexPath(indexPath) {
// Why the dispatches? Because we call success and failure on the DB
// queue, and so calling anything else that calls through to the DB will
// deadlock. This problem will go away when the history API switches to
// Deferred instead of using callbacks.
self.profile.history.removeHistoryForURL(site.url)
.upon { res in
self.fetchData().uponQueue(DispatchQueue.main) { result in
// If a section will be empty after removal, we must remove the section itself.
if let data = result.successValue {
let oldCategories = self.categories
self.data = data
self.computeSectionOffsets()
let sectionsToDelete = NSMutableIndexSet()
var rowsToDelete = [IndexPath]()
let sectionsToAdd = NSMutableIndexSet()
var rowsToAdd = [IndexPath]()
for (index, category) in self.categories.enumerated() {
let oldCategory = oldCategories[index]
// don't bother if we're not displaying this category
if oldCategory.section == nil && category.section == nil {
continue
}
// 1. add a new section if the section didn't previously exist
if oldCategory.section == nil && category.section != oldCategory.section {
log.debug("adding section \(category.section)")
sectionsToAdd.add(category.section!)
}
// 2. add a new row if there are more rows now than there were before
if oldCategory.rows < category.rows {
log.debug("adding row to \(category.section) at \(category.rows-1)")
rowsToAdd.append(IndexPath(row: category.rows-1, section: category.section!))
}
// if we're dealing with the section where the row was deleted:
// 1. if the category no longer has a section, then we need to delete the entire section
// 2. delete a row if the number of rows has been reduced
// 3. delete the selected row and add a new one on the bottom of the section if the number of rows has stayed the same
if oldCategory.section == indexPath.section {
if category.section == nil {
log.debug("deleting section \(indexPath.section)")
sectionsToDelete.add(indexPath.section)
} else if oldCategory.section == category.section {
if oldCategory.rows > category.rows {
log.debug("deleting row from \(category.section) at \(indexPath.row)")
rowsToDelete.append(indexPath)
} else if category.rows == oldCategory.rows {
log.debug("in section \(category.section), removing row at \(indexPath.row) and inserting row at \(category.rows-1)")
rowsToDelete.append(indexPath)
rowsToAdd.append(IndexPath(row: category.rows-1, section: indexPath.section))
}
}
}
}
tableView.beginUpdates()
if sectionsToAdd.count > 0 {
tableView.insertSections(sectionsToAdd as IndexSet, with: UITableViewRowAnimation.left)
}
if sectionsToDelete.count > 0 {
tableView.deleteSections(sectionsToDelete as IndexSet, with: UITableViewRowAnimation.right)
}
if !rowsToDelete.isEmpty {
tableView.deleteRows(at: rowsToDelete, with: UITableViewRowAnimation.right)
}
if !rowsToAdd.isEmpty {
tableView.insertRows(at: rowsToAdd, with: UITableViewRowAnimation.right)
}
tableView.endUpdates()
self.updateEmptyPanelState()
}
}
}
}
})
return [delete]
}
}
| mpl-2.0 | 433f0a10f8dcd003f78fcd7ff5194d5c | 42.273245 | 165 | 0.593686 | 5.783667 | false | false | false | false |
ilyahal/VKMusic | VkPlaylist/MiniPlayerViewController.swift | 1 | 8272 | //
// MiniPlayerViewController.swift
// VkPlaylist
//
// MIT License
//
// Copyright (c) 2016 Ilya Khalyapin
//
// 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
/// ViewController с мини-плеером
class MiniPlayerViewController: UIViewController {
/// Цвет элементов управления
let tintColor = (UIApplication.sharedApplication().delegate as! AppDelegate).tintColor
/// Название аудиозаписи
@IBOutlet weak var titleLabel: UILabel!
/// Имя исполнителя
@IBOutlet weak var artistLabel: UILabel!
/// ImageView для иконки с Play/Пауза
@IBOutlet weak var controlImageView: UIImageView!
/// Бар отображающий прогесс воспроизведения
@IBOutlet weak var progressBar: UIProgressView!
/// Правило для высоты бара
@IBOutlet weak var progressBarHeightConstraint: NSLayoutConstraint!
/// Кнопка для перехода к полноэкранному плееру
@IBOutlet weak var miniPlayerButton: UIButton!
/// Иконка "Play"
var playIcon: UIImage!
/// Иконка "Пауза"
var pauseIcon: UIImage!
/// Иконка для кнопки "Play" или "Пауза"
var controlIcon: UIImage {
return isPlaying ? pauseIcon : playIcon
}
/// Состояние плеера
var state: PlayerState {
return PlayerManager.sharedInstance.state
}
/// Воспроизводится ли аудиозапись
var isPlaying: Bool {
get {
return PlayerManager.sharedInstance.isPlaying
}
}
/// Прогресс воспроизведения текущей аудиозаписи
var progress: Float {
return PlayerManager.sharedInstance.progress
}
/// Название исполняемой аудиозаписи
var trackTitle: String? {
return PlayerManager.sharedInstance.trackTitle
}
/// Имя исполнителя аудиозаписи
var artist: String? {
return PlayerManager.sharedInstance.artist
}
override func viewDidLoad() {
super.viewDidLoad()
// Инициализация переменных
playIcon = UIImage(named: "icon-MiniPlayerPlay")!.tintPicto(tintColor)
pauseIcon = UIImage(named: "icon-MiniPlayerPause")!.tintPicto(tintColor)
// Настройка UI
configureUI()
// Настройка бара с прогрессом воспроизведения
progressBar.setProgress(0, animated: false)
// Настройка надписей со именем исполнителя и названием аудиозаписи
titleLabel.text = nil
artistLabel.text = nil
// Настройка кнопки "Play" / "Пауза"
updateControlButton()
PlayerManager.sharedInstance.addDelegate(self)
}
deinit {
PlayerManager.sharedInstance.deleteDelegate(self)
}
// MARK: UI
/// Настройка интерфейса контроллера
func configureUI() {
// Настройка цвета основной кнопки
let highlightedColor = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 0.5)
miniPlayerButton.setBackgroundImage(UIImage.generateImageWithColor(highlightedColor, size: CGSizeMake(1, 1)), forState: .Highlighted)
// Настройка бара с прогрессом воспроизведения
progressBar.progressTintColor = tintColor
progressBar.trackTintColor = UIColor.clearColor()
progressBarHeightConstraint.constant = 1 // Устанавливаем высоту бара
}
/// Обновление иконки кнопки "Play" / "Пауза"
func updateControlButton() {
controlImageView.image = controlIcon
}
/// Отобразить мини-плеер
func showMiniPlayerAnimated(animated: Bool) {
if view.hidden {
view.hidden = false
UIView.animateWithDuration(animated ? 0.3 : 0) {
self.view.alpha = 1
}
PlayerManager.sharedInstance.miniPlayerDidShow()
}
}
/// Скрыть мини-плеер
func hideMiniPlayerAnimated(animated: Bool) {
if !view.hidden {
view.hidden = true
UIView.animateWithDuration(animated ? 0.3 : 0) {
self.view.alpha = 0
}
PlayerManager.sharedInstance.miniPlayerDidHide()
}
}
// MARK: Взаимодействие с пользователем
/// Была нажата кнопка "Play" / "Пауза"
@IBAction func controlButton(sender: UIButton) {
if isPlaying {
PlayerManager.sharedInstance.pauseTapped()
} else {
PlayerManager.sharedInstance.playTapped()
}
}
}
// MARK: PlayerManagerDelegate
extension MiniPlayerViewController: PlayerManagerDelegate {
// Менеджер плеера получил новое состояние плеера
func playerManagerGetNewState() {
switch state {
case .Ready:
hideMiniPlayerAnimated(true)
case .Paused, .Playing:
updateControlButton()
showMiniPlayerAnimated(true)
}
}
// Менеджер плеера получил новый элемент плеера
func playerManagerGetNewItem() {
titleLabel.text = trackTitle
artistLabel.text = artist
}
// Менеджер обновил слова аудиозаписи
func playerManagerUpdateLyrics() {}
// Менеджер получил обложку аудиозаписи
func playerManagerGetArtwork() {}
// Менеджер плеера получил новое значение прогресса
func playerManagerCurrentItemGetNewProgressValue() {
progressBar.setProgress(progress, animated: false)
}
// Менеджер плеера получил новое значение прогресса буфферизации
func playerManagerCurrentItemGetNewBufferingProgressValue() {}
// Менеджер плеера получил новое значение текущего времени
func playerManagerCurrentItemGetNewCurrentTime() {}
// Менеджер плеера изменил настройку "Отправлять ли музыку в статус"
func playerManagerShareToStatusSettingDidChange() {}
// Менеджер плеера изменил настройку "Перемешивать ли плейлист"
func playerManagerShuffleSettingDidChange() {}
// Менеджер плеера изменил настройку "Повторять ли плейлист"
func playerManagerRepeatTypeDidChange() {}
} | mit | fe44efe4ff10c844fbedab447b48e4ae | 30.798206 | 141 | 0.662482 | 4.646134 | false | false | false | false |
wireapp/wire-ios | Wire-iOS Share Extension/PreviewImageView.swift | 1 | 6108 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
/**
* The aspect ratio of the video view.
*/
enum PreviewDisplayMode {
case video
case link
case placeholder
indirect case mixed(Int, PreviewDisplayMode?)
/// The size of the preview, in points.
static var size: CGSize {
return CGSize(width: 70, height: 70)
}
/// The maximum size of a preview, adjusted for the device scale.
static var pixelSize: CGSize {
let scale = UIScreen.main.scale
return CGSize(width: 70 * scale, height: 70 * scale)
}
}
extension Optional where Wrapped == PreviewDisplayMode {
/// Combines the current display mode with the current one if they're compatible.
func combine(with otherMode: PreviewDisplayMode?) -> PreviewDisplayMode? {
guard let currentMode = self else {
return otherMode
}
guard case let .mixed(count, _) = currentMode else {
return currentMode
}
return .mixed(count, otherMode)
}
}
/**
* An image view used to preview the content of a post.
*/
final class PreviewImageView: UIImageView {
private let detailsContainer = UIView()
private let videoBadgeImageView = UIImageView()
private let countLabel = UILabel()
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
configureSubviews()
configureConstraints()
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init?(coder aDecoder: NSCoder) is not implemented")
}
private func configureSubviews() {
displayMode = nil
detailsContainer.backgroundColor = UIColor.black.withAlphaComponent(0.75)
videoBadgeImageView.setIcon(.movie, size: .small, color: .white)
countLabel.font = UIFont.systemFont(ofSize: 14)
countLabel.textColor = .white
countLabel.textAlignment = .natural
detailsContainer.addSubview(videoBadgeImageView)
detailsContainer.addSubview(countLabel)
addSubview(detailsContainer)
}
private func configureConstraints() {
detailsContainer.translatesAutoresizingMaskIntoConstraints = false
videoBadgeImageView.translatesAutoresizingMaskIntoConstraints = false
countLabel.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
// Video Indicator
videoBadgeImageView.heightAnchor.constraint(equalToConstant: 16),
videoBadgeImageView.widthAnchor.constraint(equalToConstant: 16),
videoBadgeImageView.leadingAnchor.constraint(equalTo: detailsContainer.leadingAnchor, constant: 4),
videoBadgeImageView.centerYAnchor.constraint(equalTo: detailsContainer.centerYAnchor),
// Count Label
countLabel.leadingAnchor.constraint(equalTo: detailsContainer.leadingAnchor, constant: 4),
countLabel.trailingAnchor.constraint(equalTo: detailsContainer.trailingAnchor, constant: -4),
countLabel.centerYAnchor.constraint(equalTo: detailsContainer.centerYAnchor),
// Details Container
detailsContainer.bottomAnchor.constraint(equalTo: bottomAnchor),
detailsContainer.leadingAnchor.constraint(equalTo: leadingAnchor),
detailsContainer.trailingAnchor.constraint(equalTo: trailingAnchor),
detailsContainer.heightAnchor.constraint(equalToConstant: 24)
]
NSLayoutConstraint.activate(constraints)
}
// MARK: - Display Mode
/// How the content should be displayed.
var displayMode: PreviewDisplayMode? {
didSet {
invalidateIntrinsicContentSize()
updateContentMode(for: displayMode)
updateBorders(for: displayMode)
updateDetailsBadge(for: displayMode)
}
}
private func updateContentMode(for displayMode: PreviewDisplayMode?) {
switch displayMode {
case .none:
contentMode = .scaleAspectFit
case .video?, .link?:
contentMode = .scaleAspectFill
case .placeholder?:
contentMode = .center
case .mixed(_, let mainMode)?:
updateContentMode(for: mainMode)
}
}
private func updateBorders(for displayMode: PreviewDisplayMode?) {
switch displayMode {
case .placeholder?, .link?:
layer.borderColor = UIColor.gray.cgColor
layer.borderWidth = UIScreen.hairline
case .mixed(_, let mainMode)?:
updateBorders(for: mainMode)
default:
layer.borderColor = nil
layer.borderWidth = 0
}
}
private func updateDetailsBadge(for displayMode: PreviewDisplayMode?) {
switch displayMode {
case .video?:
detailsContainer.isHidden = false
videoBadgeImageView.isHidden = false
countLabel.isHidden = true
case .mixed(let count, _)?:
detailsContainer.isHidden = false
videoBadgeImageView.isHidden = true
countLabel.isHidden = false
countLabel.text = String(count)
default:
detailsContainer.isHidden = true
videoBadgeImageView.isHidden = true
countLabel.isHidden = true
}
}
override var intrinsicContentSize: CGSize {
return PreviewDisplayMode.size
}
}
| gpl-3.0 | 7fc24b0815abe9149ac87ba3b1e38ac8 | 32.377049 | 111 | 0.665357 | 5.517615 | false | false | false | false |
Sage-Bionetworks/BridgeAppSDK | BridgeAppSDK/SBARootViewController.swift | 1 | 5821 | //
// SBARootViewController.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. 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(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// 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 OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import UIKit
@objc
public enum SBARootViewControllerState: Int {
// Initial launch view
case launch
// Main view showing activities, etc. for the signed in user
case main
// Study overview (onboarding) for the user who is *not* signed in
case studyOverview
// Participant is currently in the eligibility, consent, and registration flow
case signup
// Unrecoverable error state. Displayed when the app must be updated or has reached end-of-life
case catastrophicError
}
/**
`SBARootViewController` is a root view controller implementation that allows the current "root"
to be transitioned while there is a modal view controller displayed on top of the root. For
example, when displaying a passcode or during onboarding.
*/
@objc
open class SBARootViewController: UIViewController {
public var state: SBARootViewControllerState {
return _state
}
private var _state: SBARootViewControllerState = .launch
var contentHidden = false {
didSet {
guard contentHidden != oldValue && isViewLoaded else { return }
self.children.first?.view.isHidden = contentHidden
}
}
/**
The status bar style to use for the view controller currently being shown. This only works with projects
set with view-controller-based status bar style.
*/
open var statusBarStyle: UIStatusBarStyle = .default {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
override open var preferredStatusBarStyle: UIStatusBarStyle {
return statusBarStyle
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public init(rootViewController:UIViewController?) {
super.init(nibName: nil, bundle: nil)
_unloadedRootViewController = rootViewController
}
override open func viewDidLoad() {
super.viewDidLoad()
// If there is no root view controller already loaded then do so now
if self.children.first == nil {
let isBlankVC = _unloadedRootViewController == nil
let viewController = self.rootViewController
self.addChild(viewController)
viewController.view.frame = self.view.bounds
viewController.view.isHidden = contentHidden
if isBlankVC {
viewController.view.backgroundColor = UIColor.white
}
self.view.addSubview(viewController.view)
viewController.didMove(toParent: self)
}
}
public var rootViewController: UIViewController {
return self.children.first ?? {
if _unloadedRootViewController == nil {
_unloadedRootViewController = UIViewController()
}
return _unloadedRootViewController!
}()
}
private var _unloadedRootViewController: UIViewController?
public func set(viewController: UIViewController, state: SBARootViewControllerState, animated: Bool) {
guard isViewLoaded else {
_unloadedRootViewController = viewController
_state = state
return
}
// Setup state for view controllers
self.rootViewController.willMove(toParent: nil)
self.addChild(viewController)
_state = state
// Setup new view initial alpha and frame
viewController.view.frame = self.view.bounds
let duration = animated ? 1.0 : 0.0
self.transition(from: self.rootViewController, to: viewController, duration: duration, options: [.transitionCrossDissolve],
animations: {}) { (finished) in
self.rootViewController.removeFromParent()
viewController.didMove(toParent: self)
}
}
}
| bsd-3-clause | abbfcf92d0ca4efc06e716dc61b5a9a6 | 36.792208 | 131 | 0.680928 | 5.383904 | false | false | false | false |
khoren93/Fusuma | Sources/FSCameraView.swift | 1 | 13935 | //
// FSCameraView.swift
// Fusuma
//
// Created by Yuta Akizuki on 2015/11/14.
// Copyright © 2015年 ytakzk. All rights reserved.
//
import UIKit
import AVFoundation
@objc protocol FSCameraViewDelegate: class {
func cameraShotFinished(_ image: UIImage)
}
final class FSCameraView: UIView, UIGestureRecognizerDelegate {
@IBOutlet weak var previewViewContainer: UIView!
@IBOutlet weak var shotButton: UIButton!
@IBOutlet weak var flashButton: UIButton!
@IBOutlet weak var flipButton: UIButton!
@IBOutlet weak var croppedAspectRatioConstraint: NSLayoutConstraint!
@IBOutlet weak var fullAspectRatioConstraint: NSLayoutConstraint!
weak var delegate: FSCameraViewDelegate? = nil
var session: AVCaptureSession?
var device: AVCaptureDevice?
var videoInput: AVCaptureDeviceInput?
var imageOutput: AVCaptureStillImageOutput?
var focusView: UIView?
var flashOffImage: UIImage?
var flashOnImage: UIImage?
static func instance() -> FSCameraView {
return UINib(nibName: "FSCameraView", bundle: Bundle(for: self.classForCoder())).instantiate(withOwner: self, options: nil)[0] as! FSCameraView
}
func initialize() {
if session != nil {
return
}
self.backgroundColor = UIColor.hex("#FFFFFF", alpha: 1.0)
let bundle = Bundle(for: self.classForCoder)
flashOnImage = fusumaFlashOnImage != nil ? fusumaFlashOnImage : UIImage(named: "ic_flash_on", in: bundle, compatibleWith: nil)
flashOffImage = fusumaFlashOffImage != nil ? fusumaFlashOffImage : UIImage(named: "ic_flash_off", in: bundle, compatibleWith: nil)
let flipImage = fusumaFlipImage != nil ? fusumaFlipImage : UIImage(named: "ic_loop", in: bundle, compatibleWith: nil)
let shotImage = fusumaShotImage != nil ? fusumaShotImage : UIImage(named: "shutter_button", in: bundle, compatibleWith: nil)
if(fusumaTintIcons) {
flashButton.tintColor = fusumaBaseTintColor
flipButton.tintColor = fusumaBaseTintColor
shotButton.tintColor = fusumaBaseTintColor
flashButton.setImage(flashOffImage?.withRenderingMode(.alwaysOriginal), for: UIControlState())
flipButton.setImage(flipImage?.withRenderingMode(.alwaysOriginal), for: UIControlState())
shotButton.setImage(shotImage?.withRenderingMode(.alwaysOriginal), for: UIControlState())
} else {
flashButton.setImage(flashOffImage, for: UIControlState())
flipButton.setImage(flipImage, for: UIControlState())
shotButton.setImage(shotImage, for: UIControlState())
}
self.isHidden = false
// AVCapture
session = AVCaptureSession()
for device in AVCaptureDevice.devices() {
if let device = device as? AVCaptureDevice , device.position == AVCaptureDevicePosition.front {
self.device = device
if !device.hasFlash {
flashButton.isHidden = true
}
}
}
do {
if let session = session {
videoInput = try AVCaptureDeviceInput(device: device)
session.addInput(videoInput)
imageOutput = AVCaptureStillImageOutput()
session.addOutput(imageOutput)
let videoLayer = AVCaptureVideoPreviewLayer(session: session)
videoLayer?.frame = self.previewViewContainer.bounds
videoLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
self.previewViewContainer.layer.addSublayer(videoLayer!)
session.sessionPreset = AVCaptureSessionPresetPhoto
session.startRunning()
}
// Focus View
self.focusView = UIView(frame: CGRect(x: 0, y: 0, width: 90, height: 90))
let tapRecognizer = UITapGestureRecognizer(target: self, action:#selector(FSCameraView.focus(_:)))
tapRecognizer.delegate = self
self.previewViewContainer.addGestureRecognizer(tapRecognizer)
} catch {
}
flashConfiguration()
self.startCamera()
NotificationCenter.default.addObserver(self, selector: #selector(FSCameraView.willEnterForegroundNotification(_:)), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
}
func willEnterForegroundNotification(_ notification: Notification) {
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
if status == AVAuthorizationStatus.authorized {
session?.startRunning()
} else if status == AVAuthorizationStatus.denied || status == AVAuthorizationStatus.restricted {
session?.stopRunning()
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func startCamera() {
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
if status == AVAuthorizationStatus.authorized {
session?.startRunning()
} else if status == AVAuthorizationStatus.denied || status == AVAuthorizationStatus.restricted {
session?.stopRunning()
}
}
func stopCamera() {
session?.stopRunning()
}
@IBAction func shotButtonPressed(_ sender: UIButton) {
guard let imageOutput = imageOutput else {
return
}
DispatchQueue.global(qos: .default).async(execute: { () -> Void in
let videoConnection = imageOutput.connection(withMediaType: AVMediaTypeVideo)
let orientation: UIDeviceOrientation = UIDevice.current.orientation
switch (orientation) {
case .portrait:
videoConnection?.videoOrientation = .portrait
case .portraitUpsideDown:
videoConnection?.videoOrientation = .portraitUpsideDown
case .landscapeRight:
videoConnection?.videoOrientation = .landscapeLeft
case .landscapeLeft:
videoConnection?.videoOrientation = .landscapeRight
default:
videoConnection?.videoOrientation = .portrait
}
imageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (buffer, error) -> Void in
self.session?.stopRunning()
let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
if let image = UIImage(data: data!), let cgImage = image.cgImage, let delegate = self.delegate {
// Image size
var iw: CGFloat
var ih: CGFloat
switch (orientation) {
case .landscapeLeft, .landscapeRight:
// Swap width and height if orientation is landscape
iw = image.size.height
ih = image.size.width
default:
iw = image.size.width
ih = image.size.height
}
// Frame size
let sw = self.previewViewContainer.frame.width
// The center coordinate along Y axis
let rcy = ih * 0.5
let imageRef = cgImage.cropping(to: CGRect(x: rcy-iw*0.5, y: 0 , width: iw, height: iw))
DispatchQueue.main.async(execute: { () -> Void in
if fusumaCropImage {
let resizedImage = UIImage(cgImage: imageRef!, scale: sw/iw, orientation: image.imageOrientation)
delegate.cameraShotFinished(resizedImage)
} else {
delegate.cameraShotFinished(image)
}
self.session = nil
self.device = nil
self.imageOutput = nil
})
}
})
})
}
@IBAction func flipButtonPressed(_ sender: UIButton) {
if !cameraIsAvailable() {
return
}
session?.stopRunning()
do {
session?.beginConfiguration()
if let session = session {
for input in session.inputs {
session.removeInput(input as! AVCaptureInput)
}
let position = (videoInput?.device.position == AVCaptureDevicePosition.front) ? AVCaptureDevicePosition.back : AVCaptureDevicePosition.front
for device in AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) {
if let device = device as? AVCaptureDevice , device.position == position {
videoInput = try AVCaptureDeviceInput(device: device)
session.addInput(videoInput)
}
}
}
session?.commitConfiguration()
} catch {
}
session?.startRunning()
}
@IBAction func flashButtonPressed(_ sender: UIButton) {
if !cameraIsAvailable() {
return
}
do {
if let device = device {
guard device.hasFlash else { return }
try device.lockForConfiguration()
let mode = device.flashMode
if mode == AVCaptureFlashMode.off {
device.flashMode = AVCaptureFlashMode.on
flashButton.setImage(flashOnImage, for: UIControlState())
} else if mode == AVCaptureFlashMode.on {
device.flashMode = AVCaptureFlashMode.off
flashButton.setImage(flashOffImage, for: UIControlState())
}
device.unlockForConfiguration()
}
} catch _ {
flashButton.setImage(flashOffImage, for: UIControlState())
return
}
}
}
extension FSCameraView {
@objc func focus(_ recognizer: UITapGestureRecognizer) {
let point = recognizer.location(in: self)
let viewsize = self.bounds.size
let newPoint = CGPoint(x: point.y/viewsize.height, y: 1.0-point.x/viewsize.width)
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
try device?.lockForConfiguration()
} catch _ {
return
}
if device?.isFocusModeSupported(AVCaptureFocusMode.autoFocus) == true {
device?.focusMode = AVCaptureFocusMode.autoFocus
device?.focusPointOfInterest = newPoint
}
if device?.isExposureModeSupported(AVCaptureExposureMode.continuousAutoExposure) == true {
device?.exposureMode = AVCaptureExposureMode.continuousAutoExposure
device?.exposurePointOfInterest = newPoint
}
device?.unlockForConfiguration()
self.focusView?.alpha = 0.0
self.focusView?.center = point
self.focusView?.backgroundColor = UIColor.clear
self.focusView?.layer.borderColor = fusumaBaseTintColor.cgColor
self.focusView?.layer.borderWidth = 1.0
self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.addSubview(self.focusView!)
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.8,
initialSpringVelocity: 3.0, options: UIViewAnimationOptions.curveEaseIn, // UIViewAnimationOptions.BeginFromCurrentState
animations: {
self.focusView!.alpha = 1.0
self.focusView!.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}, completion: {(finished) in
self.focusView!.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.focusView!.removeFromSuperview()
})
}
func flashConfiguration() {
do {
if let device = device {
guard device.hasFlash else { return }
try device.lockForConfiguration()
device.flashMode = AVCaptureFlashMode.off
flashButton.setImage(flashOffImage, for: UIControlState())
device.unlockForConfiguration()
}
} catch _ {
return
}
}
func cameraIsAvailable() -> Bool {
let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
if status == AVAuthorizationStatus.authorized {
return true
}
return false
}
}
| mit | 4ffecd9891d839adfe0bb54411df4d96 | 32.571084 | 196 | 0.543282 | 6.574799 | false | false | false | false |
spotify/HubFramework | demo/sources/GitHubSearchBarContentOperation.swift | 1 | 2955 | /*
* Copyright (c) 2016 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 HubFramework
/// Content operation that adds a search bar for the GitHub search feature
class GitHubSearchBarContentOperation: HUBContentOperationActionObserver {
weak var delegate: HUBContentOperationDelegate?
private var searchString: String?
private var searchActionIdentifier: HUBIdentifier { return HUBIdentifier(namespace: "github", name: "search") }
func perform(forViewURI viewURI: URL, featureInfo: HUBFeatureInfo, connectivityState: HUBConnectivityState, viewModelBuilder: HUBViewModelBuilder, previousError: Error?) {
// Encode any search string that was passed from the search bar component
// (through an action) into the view model builder's custom data
viewModelBuilder.setCustomDataValue(searchString, forKey: GitHubSearchCustomDataKeys.searchString)
// Add the search bar
let searchBarBuilder = viewModelBuilder.builderForBodyComponentModel(withIdentifier: "searchBar")
searchBarBuilder.componentName = DefaultComponentNames.searchBar
searchBarBuilder.customData = [
SearchBarComponentCustomDataKeys.placeholder: "Search repositories on GitHub",
SearchBarComponentCustomDataKeys.actionIdentifier: searchActionIdentifier.identifierString
]
delegate?.contentOperationDidFinish(self)
}
func actionPerformed(with context: HUBActionContext, featureInfo: HUBFeatureInfo, connectivityState: HUBConnectivityState) {
guard context.customActionIdentifier == searchActionIdentifier else {
return
}
guard let searchString = context.customData?[SearchBarComponentCustomDataKeys.text] as? String else {
return
}
// Save the search sting that was entered, and reschedule this operation to fetch new results
// See `GitHubSearchResultsContentOperation`, which comes after this one, for the actual fetching
// of results.
self.searchString = searchString
delegate?.contentOperationRequiresRescheduling(self)
}
}
| apache-2.0 | 261e9bdc3664e2bd57ff2b2447f1c692 | 46.66129 | 175 | 0.737056 | 5.051282 | false | false | false | false |
welbesw/easypost-swift | Example/EasyPostApi/ViewController.swift | 1 | 9049 | //
// ViewController.swift
// EasyPostApi
//
// Created by William Welbes on 10/04/2015.
// Copyright (c) 2015 William Welbes. All rights reserved.
//
import UIKit
import EasyPostApi
class ViewController: UIViewController {
@IBOutlet weak var nameTextField:UITextField!
@IBOutlet weak var companyTextField:UITextField!
@IBOutlet weak var street1TextField:UITextField!
@IBOutlet weak var street2TextField:UITextField!
@IBOutlet weak var cityTextField:UITextField!
@IBOutlet weak var stateTextField:UITextField!
@IBOutlet weak var zipTextField:UITextField!
@IBOutlet weak var parcelLength:UITextField!
@IBOutlet weak var parcelWidth:UITextField!
@IBOutlet weak var parcelHeight:UITextField!
@IBOutlet weak var parcelWeight:UITextField!
var currentShipment:EasyPostShipment?
override func viewDidLoad() {
super.viewDidLoad()
EasyPostApi.sharedInstance.logHTTPRequestAndResponse = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//Check if the API credentials have been set and present the view controller if they have note been set
let defaultsManager = DefaultsManager.sharedInstance
if !defaultsManager.apiCredentialsAreSet {
self.performSegue(withIdentifier: "ModalCredentialsSegue", sender: nil)
} else {
//Set the API credentials
EasyPostApi.sharedInstance.setCredentials(defaultsManager.apiToken!, baseUrl: defaultsManager.apiBaseUrl!)
EasyPostApi.sharedInstance.getUserApiKeys({ (result) -> () in
switch(result) {
case .failure(let error):
print("Error getting user api keys: \((error as NSError).localizedDescription)")
case .success(let keys):
print("Got API keys: production:\(keys.productionKey ?? "") : test: \(keys.testKey ?? "")")
}
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didTapLogPredefinedPackageTypes() {
for predefinedPackage in easyPostParcelPredefinedPackages {
print("\(predefinedPackage.type) - \(predefinedPackage.typeDescription) - \(predefinedPackage.sizeDescription)")
}
}
@IBAction func didTapVerifyAddress(_ sender:AnyObject?) {
let address = EasyPostAddress()
address.name = nameTextField.text
address.company = companyTextField.text
address.street1 = street1TextField.text
address.street2 = street2TextField.text
address.city = cityTextField.text
address.state = stateTextField.text
address.zip = zipTextField.text
address.country = "US"
EasyPostApi.sharedInstance.postAddress(address) { (result) -> () in
DispatchQueue.main.async(execute: { () -> Void in
switch(result) {
case .success(let value):
print("Successfully posted address.")
if let id = value.id {
print("Verifying address: \(id)")
EasyPostApi.sharedInstance.verifyAddress(id, completion: { (verifyResult) -> () in
DispatchQueue.main.async(execute: { () -> Void in
switch(verifyResult) {
case .success(let easyPostAddress):
print("Successfully verified address.")
self.loadAddress(easyPostAddress)
case .failure(let error):
print("Error verifying address: \((error as NSError).localizedDescription)")
}
})
})
}
case .failure(let error):
print("Error posting address: \((error as NSError).localizedDescription)")
}
})
}
}
func loadAddress(_ address:EasyPostAddress) {
if let name = address.name {
self.nameTextField.text = name
}
if let company = address.company {
self.companyTextField.text = company
}
if let street1 = address.street1 {
self.street1TextField.text = street1
}
if let street2 = address.street2 {
self.street2TextField.text = street2
}
if let city = address.city {
self.cityTextField.text = city
}
if let state = address.state {
self.stateTextField.text = state
}
if let zip = address.zip {
self.zipTextField.text = zip
}
}
func parcelFromTextFields() -> EasyPostParcel {
let parcel = EasyPostParcel()
let numberFormatter = NumberFormatter()
if let stringValue = parcelLength.text {
parcel.length = numberFormatter.number(from: stringValue)
}
if let stringValue = parcelWidth.text {
parcel.width = numberFormatter.number(from: stringValue)
}
if let stringValue = parcelHeight.text {
parcel.height = numberFormatter.number(from: stringValue)
}
if let stringValue = parcelWeight.text {
if let numberValue = numberFormatter.number(from: stringValue) {
parcel.weight = numberValue
}
}
return parcel
}
@IBAction func didTapPostParcel(_ sender:AnyObject?) {
let parcel = parcelFromTextFields()
EasyPostApi.sharedInstance.postParcel(parcel) { (result) -> () in
DispatchQueue.main.async(execute: { () -> Void in
switch(result) {
case .success(let value):
print("Successfully posted parcel.")
if let id = value.id {
print("Parcel id: \(id)")
}
case .failure(let error):
print("Error posting parcel: \((error as NSError).localizedDescription)")
}
})
}
}
@IBAction func didTapPostShipment(_ sender:AnyObject?) {
let toAddress = EasyPostAddress()
toAddress.name = nameTextField.text
toAddress.company = companyTextField.text
toAddress.street1 = street1TextField.text
toAddress.street2 = street2TextField.text
toAddress.city = cityTextField.text
toAddress.state = stateTextField.text
toAddress.zip = zipTextField.text
toAddress.country = "US"
let fromAddress = toAddress
let parcel = parcelFromTextFields()
EasyPostApi.sharedInstance.postShipment(toAddress, fromAddress: fromAddress, parcel: parcel) { (result) -> () in
DispatchQueue.main.async(execute: { () -> Void in
switch(result) {
case .success(let shipment):
print("Successfully posted shipment.")
if let id = shipment.id {
print("Shipment id: \(id)")
self.currentShipment = shipment
if(shipment.rates.count < 1 && shipment.messages.count > 0) {
let alert = UIAlertController(title: "Error Getting Rates", message: shipment.messages[0].message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
} else {
self.performSegue(withIdentifier: "ModalShowRatesSegue", sender: nil)
}
}
case .failure(let error):
print("Error posting shipment: \((error as NSError).localizedDescription)")
}
})
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "ModalShowRatesSegue") {
if let navController = segue.destination as? UINavigationController {
if let ratesViewController = navController.topViewController as? RatesViewController {
if let shipment = self.currentShipment {
ratesViewController.shipment = shipment
}
}
}
}
}
}
| mit | ae8a6d854fdf1ae689c195e3a25b9861 | 37.67094 | 173 | 0.547906 | 5.662703 | false | false | false | false |
the-grid/Disc | Disc/Networking/Resources/User/Identity/AddIdentity.swift | 1 | 2292 | import Result
import Swish
private struct AddIdentityRequest: Request {
typealias ResponseObject = Identity
let token: String
let body: [String: String]
init(token: String, provider: Provider, providerAccessToken: String, providerTokenSecret: String?) {
self.token = token
body = createRequestParameters(provider: provider, token: providerAccessToken, secret: providerTokenSecret)
}
init(token: String, provider: Provider, authCode: String, redirectUri: String) {
self.token = token
body = createRequestParameters(provider: provider, code: authCode, redirectUri: redirectUri)
}
func build() -> URLRequest {
return createRequest(.POST, "api/user/identities", token: token, body: body as [String : AnyObject])
}
}
public extension APIClient {
/// Add an identity using an access token.
///
/// - parameter provider: The provider of the identity to add.
/// - parameter token: The access token for the `provider`.
/// - parameter secret: The token secret for the `provider`.
func addIdentity(_ provider: Provider, token providerAccessToken: String, secret providerTokenSecret: String? = nil, completionHandler: @escaping (Result<Identity, SwishError>) -> Void) {
let request = AddIdentityRequest(
token: token,
provider: provider,
providerAccessToken: providerAccessToken,
providerTokenSecret: providerTokenSecret
)
let _ = client.performRequest(request, completionHandler: completionHandler)
}
/// Add an identity using an auth code.
///
/// - parameter provider: The provider of the identity to add.
/// - parameter code: The auth code for the `provider`.
/// - parameter redirectUri: The redirect URI for the `provider`.
func addIdentity(_ provider: Provider, code authCode: String, redirectUri: String, completionHandler: @escaping (Result<Identity, SwishError>) -> Void) {
let request = AddIdentityRequest(
token: token,
provider: provider,
authCode: authCode,
redirectUri: redirectUri
)
let _ = client.performRequest(request, completionHandler: completionHandler)
}
}
| mit | b87c1b774b4e2ae3652ab77c6cd29a3b | 39.210526 | 191 | 0.664049 | 5.173815 | false | false | false | false |
PureSwift/GATT | Sources/DarwinGATT/DarwinCentral.swift | 1 | 68280 | //
// DarwinCentral.swift
// GATT
//
// Created by Alsey Coleman Miller on 4/3/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
#if swift(>=5.5) && canImport(CoreBluetooth)
import Foundation
import Dispatch
import CoreBluetooth
import Bluetooth
import GATT
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public final class DarwinCentral: CentralManager, ObservableObject {
// MARK: - Properties
public var log: ((String) -> ())?
public let options: Options
public var state: DarwinBluetoothState {
get async {
return await withUnsafeContinuation { [unowned self] continuation in
self.async { [unowned self] in
let state = unsafeBitCast(self.centralManager.state, to: DarwinBluetoothState.self)
continuation.resume(returning: state)
}
}
}
}
/// Currently scanned devices, or restored devices.
public var peripherals: [Peripheral: Bool] {
get async {
return await withUnsafeContinuation { [unowned self] continuation in
self.async { [unowned self] in
var peripherals = [Peripheral: Bool]()
peripherals.reserveCapacity(self.cache.peripherals.count)
for (peripheral, coreBluetoothPeripheral) in self.cache.peripherals {
peripherals[peripheral] = coreBluetoothPeripheral.state == .connected
}
continuation.resume(returning: peripherals)
}
}
}
}
private var centralManager: CBCentralManager!
private var delegate: Delegate!
private let queue = DispatchQueue(label: "org.pureswift.DarwinGATT.DarwinCentral")
@Published
fileprivate var cache = Cache()
fileprivate var continuation = Continuation()
// MARK: - Initialization
/// Initialize with the specified options.
///
/// - Parameter options: An optional dictionary containing initialization options for a central manager.
/// For available options, see [Central Manager Initialization Options](apple-reference-documentation://ts1667590).
public init(
options: Options = Options()
) {
self.options = options
self.delegate = options.restoreIdentifier == nil ? Delegate(self) : RestorableDelegate(self)
self.centralManager = CBCentralManager(
delegate: self.delegate,
queue: queue,
options: options.dictionary
)
}
// MARK: - Methods
/// Scans for peripherals that are advertising services.
public func scan(
filterDuplicates: Bool = true
) async throws -> AsyncCentralScan<DarwinCentral> {
return scan(with: [], filterDuplicates: filterDuplicates)
}
/// Scans for peripherals that are advertising services.
public func scan(
with services: Set<BluetoothUUID>,
filterDuplicates: Bool = true
) -> AsyncCentralScan<DarwinCentral> {
return AsyncCentralScan(onTermination: { [weak self] in
guard let self = self else { return }
self.async {
self.stopScan()
self.log?("Discovered \(self.cache.peripherals.count) peripherals")
}
}) { continuation in
self.async { [unowned self] in
self.stopScan()
}
Task {
await self.disconnectAll()
self.async { [unowned self] in
// queue scan operation
let operation = Operation.Scan(
services: services,
filterDuplicates: filterDuplicates,
continuation: continuation
)
self.continuation.scan = operation
self.execute(operation)
}
}
}
}
private func stopScan() {
if self.centralManager.isScanning {
self.centralManager.stopScan()
}
self.continuation.scan?.continuation.finish(throwing: CancellationError())
self.continuation.scan = nil
}
public func connect(
to peripheral: Peripheral
) async throws {
try await connect(to: peripheral, options: nil)
}
/// Connect to the specifed peripheral.
/// - Parameter peripheral: The peripheral to which the central is attempting to connect.
/// - Parameter options: A dictionary to customize the behavior of the connection.
/// For available options, see [Peripheral Connection Options](apple-reference-documentation://ts1667676).
public func connect(
to peripheral: Peripheral,
options: [String: Any]?
) async throws {
try await queue(for: peripheral) { continuation in
Operation.Connect(
peripheral: peripheral,
options: options,
continuation: continuation
)
}
}
public func disconnect(_ peripheral: Peripheral) async {
try? await queue(for: peripheral) { continuation in
Operation.Disconnect(
peripheral: peripheral,
continuation: continuation
)
}
}
public func disconnectAll() async {
let connected = await self.peripherals
.filter { $0.value }
.keys
for peripheral in connected {
await disconnect(peripheral)
}
}
public func discoverServices(
_ services: Set<BluetoothUUID> = [],
for peripheral: Peripheral
) async throws -> [DarwinCentral.Service] {
return try await queue(for: peripheral) { continuation in
Operation.DiscoverServices(
peripheral: peripheral,
services: services,
continuation: continuation
)
}
}
public func discoverIncludedServices(
_ services: Set<BluetoothUUID> = [],
for service: DarwinCentral.Service
) async throws -> [DarwinCentral.Service] {
return try await queue(for: service.peripheral) { continuation in
Operation.DiscoverIncludedServices(
service: service,
services: services,
continuation: continuation
)
}
}
public func discoverCharacteristics(
_ characteristics: Set<BluetoothUUID> = [],
for service: DarwinCentral.Service
) async throws -> [DarwinCentral.Characteristic] {
return try await queue(for: service.peripheral) { continuation in
Operation.DiscoverCharacteristics(
service: service,
characteristics: characteristics,
continuation: continuation
)
}
}
public func readValue(
for characteristic: DarwinCentral.Characteristic
) async throws -> Data {
return try await queue(for: characteristic.peripheral) { continuation in
Operation.ReadCharacteristic(
characteristic: characteristic,
continuation: continuation
)
}
}
public func writeValue(
_ data: Data,
for characteristic: DarwinCentral.Characteristic,
withResponse: Bool = true
) async throws {
if withResponse == false {
try await self.waitUntilCanSendWriteWithoutResponse(for: characteristic.peripheral)
}
try await self.write(data, withResponse: withResponse, for: characteristic)
}
public func discoverDescriptors(
for characteristic: DarwinCentral.Characteristic
) async throws -> [DarwinCentral.Descriptor] {
return try await queue(for: characteristic.peripheral) { continuation in
Operation.DiscoverDescriptors(
characteristic: characteristic,
continuation: continuation
)
}
}
public func readValue(
for descriptor: DarwinCentral.Descriptor
) async throws -> Data {
return try await queue(for: descriptor.peripheral) { continuation in
Operation.ReadDescriptor(
descriptor: descriptor,
continuation: continuation
)
}
}
public func writeValue(
_ data: Data,
for descriptor: DarwinCentral.Descriptor
) async throws {
try await queue(for: descriptor.peripheral) { continuation in
Operation.WriteDescriptor(
descriptor: descriptor,
data: data,
continuation: continuation
)
}
}
public func notify(
for characteristic: DarwinCentral.Characteristic
) async throws -> AsyncCentralNotifications<DarwinCentral> {
// enable notifications
try await self.setNotification(true, for: characteristic)
// central
return AsyncCentralNotifications(onTermination: { [unowned self] in
Task {
// disable notifications
do { try await self.setNotification(false, for: characteristic) }
catch CentralError.disconnected {
return
}
catch {
self.log?("Unable to stop notifications for \(characteristic.uuid). \(error.localizedDescription)")
}
// remove notification stream
self.async { [unowned self] in
let context = self.continuation(for: characteristic.peripheral)
context.notificationStream[characteristic.id] = nil
}
}
}, { continuation in
self.async { [unowned self] in
// store continuation
let context = self.continuation(for: characteristic.peripheral)
context.notificationStream[characteristic.id] = continuation
}
})
}
public func maximumTransmissionUnit(for peripheral: Peripheral) async throws -> MaximumTransmissionUnit {
self.log?("Will read MTU for \(peripheral)")
return try await withThrowingContinuation(for: peripheral) { [weak self] continuation in
guard let self = self else { return }
self.async {
do {
let mtu = try self._maximumTransmissionUnit(for: peripheral)
continuation.resume(returning: mtu)
}
catch {
continuation.resume(throwing: error)
}
}
}
}
public func rssi(for peripheral: Peripheral) async throws -> RSSI {
try await queue(for: peripheral) { continuation in
Operation.ReadRSSI(
peripheral: peripheral,
continuation: continuation
)
}
}
// MARK - Private Methods
@inline(__always)
private func async(_ body: @escaping () -> ()) {
queue.async(execute: body)
}
private func queue<Operation>(
for peripheral: Peripheral,
function: String = #function,
_ operation: (PeripheralContinuation<Operation.Success, Error>) -> Operation
) async throws -> Operation.Success where Operation: DarwinCentralOperation {
#if DEBUG
log?("Queue \(function) for peripheral \(peripheral)")
#endif
let value = try await withThrowingContinuation(for: peripheral, function: function) { continuation in
let queuedOperation = QueuedOperation(operation: operation(continuation))
self.async { [unowned self] in
self.stopScan() // stop scanning
let context = self.continuation(for: peripheral)
context.operations.push(queuedOperation)
}
}
try Task.checkCancellation()
return value
}
private func dequeue<Operation>(
for peripheral: Peripheral,
function: String = #function,
result: Result<Operation.Success, Error>,
filter: (DarwinCentral.Operation) -> (Operation?)
) where Operation: DarwinCentralOperation {
#if DEBUG
log?("Dequeue \(function) for peripheral \(peripheral)")
#endif
let context = self.continuation(for: peripheral)
context.operations.popFirst(where: { filter($0.operation) }) { (queuedOperation, operation) in
// resume continuation
if queuedOperation.isCancelled == false {
operation.continuation.resume(with: result)
}
}
}
private func continuation(for peripheral: Peripheral) -> PeripheralContinuationContext {
if let context = self.continuation.peripherals[peripheral] {
return context
} else {
let context = PeripheralContinuationContext(self)
self.continuation.peripherals[peripheral] = context
return context
}
}
private func write(
_ data: Data,
withResponse: Bool,
for characteristic: DarwinCentral.Characteristic
) async throws {
try await queue(for: characteristic.peripheral) { continuation in
Operation.WriteCharacteristic(
characteristic: characteristic,
data: data,
withResponse: withResponse,
continuation: continuation
)
}
}
private func waitUntilCanSendWriteWithoutResponse(
for peripheral: Peripheral
) async throws {
try await queue(for: peripheral) { continuation in
Operation.WriteWithoutResponseReady(
peripheral: peripheral,
continuation: continuation
)
}
}
private func setNotification(
_ isEnabled: Bool,
for characteristic: Characteristic
) async throws {
try await queue(for: characteristic.peripheral, { continuation in
Operation.NotificationState(
characteristic: characteristic,
isEnabled: isEnabled,
continuation: continuation
)
})
}
private func _maximumTransmissionUnit(for peripheral: Peripheral) throws -> MaximumTransmissionUnit {
// get peripheral
guard let peripheralObject = self.cache.peripherals[peripheral] else {
throw CentralError.unknownPeripheral
}
// get MTU
let rawValue = peripheralObject.maximumWriteValueLength(for: .withoutResponse) + 3
assert(peripheralObject.mtuLength.intValue == rawValue)
guard let mtu = MaximumTransmissionUnit(rawValue: UInt16(rawValue)) else {
assertionFailure("Invalid MTU \(rawValue)")
return .default
}
return mtu
}
}
// MARK: - Supporting Types
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public extension DarwinCentral {
typealias Advertisement = DarwinAdvertisementData
typealias State = DarwinBluetoothState
typealias AttributeID = ObjectIdentifier
typealias Service = GATT.Service<DarwinCentral.Peripheral, DarwinCentral.AttributeID>
typealias Characteristic = GATT.Characteristic<DarwinCentral.Peripheral, DarwinCentral.AttributeID>
typealias Descriptor = GATT.Descriptor<DarwinCentral.Peripheral, DarwinCentral.AttributeID>
/// Central Peer
///
/// Represents a remote central device that has connected to an app implementing the peripheral role on a local device.
struct Peripheral: Peer {
public let id: UUID
internal init(_ peripheral: CBPeripheral) {
self.id = peripheral.id
}
}
/**
Darwin GATT Central Options
*/
struct Options {
/**
A Boolean value that specifies whether the system should display a warning dialog to the user if Bluetooth is powered off when the peripheral manager is instantiated.
*/
public let showPowerAlert: Bool
/**
A string (an instance of NSString) containing a unique identifier (UID) for the peripheral manager that is being instantiated.
The system uses this UID to identify a specific peripheral manager. As a result, the UID must remain the same for subsequent executions of the app in order for the peripheral manager to be successfully restored.
*/
public let restoreIdentifier: String?
/**
Initialize options.
*/
public init(showPowerAlert: Bool = false,
restoreIdentifier: String? = nil) {
self.showPowerAlert = showPowerAlert
self.restoreIdentifier = restoreIdentifier
}
internal var dictionary: [String: Any] {
var options = [String: Any](minimumCapacity: 2)
if showPowerAlert {
options[CBCentralManagerOptionShowPowerAlertKey] = showPowerAlert as NSNumber
}
options[CBCentralManagerOptionRestoreIdentifierKey] = restoreIdentifier
return options
}
}
}
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
private extension DarwinCentral {
struct Cache {
var peripherals = [Peripheral: CBPeripheral]()
var services = [DarwinCentral.Service: CBService]()
var characteristics = [DarwinCentral.Characteristic: CBCharacteristic]()
var descriptors = [DarwinCentral.Descriptor: CBDescriptor]()
}
final class Continuation {
var scan: Operation.Scan?
var peripherals = [DarwinCentral.Peripheral: PeripheralContinuationContext]()
fileprivate init() { }
}
final class PeripheralContinuationContext {
var operations: Queue<QueuedOperation>
var notificationStream = [AttributeID: AsyncIndefiniteStream<Data>.Continuation]()
var readRSSI: Operation.ReadRSSI?
fileprivate init(_ central: DarwinCentral) {
operations = .init({ [unowned central] in
central.execute($0)
})
}
}
}
fileprivate extension DarwinCentral.PeripheralContinuationContext {
func didDisconnect(_ error: Swift.Error? = nil) {
let error = error ?? CentralError.disconnected
// resume all pending operations
while operations.isEmpty == false {
operations.pop {
$0.operation.resume(throwing: error)
}
}
// end all notifications with disconnect error
notificationStream.values.forEach {
$0.finish(throwing: error)
}
notificationStream.removeAll(keepingCapacity: true)
}
}
internal extension DarwinCentral {
final class QueuedOperation {
let operation: DarwinCentral.Operation
var isCancelled = false
fileprivate init<T: DarwinCentralOperation>(operation: T) {
self.operation = operation.operation
self.isCancelled = false
}
func cancel() {
guard !isCancelled else {
return
}
isCancelled = true
operation.cancel()
}
}
}
internal extension DarwinCentral {
enum Operation {
case connect(Connect)
case disconnect(Disconnect)
case discoverServices(DiscoverServices)
case discoverIncludedServices(DiscoverIncludedServices)
case discoverCharacteristics(DiscoverCharacteristics)
case readCharacteristic(ReadCharacteristic)
case writeCharacteristic(WriteCharacteristic)
case discoverDescriptors(DiscoverDescriptors)
case readDescriptor(ReadDescriptor)
case writeDescriptor(WriteDescriptor)
case isReadyToWriteWithoutResponse(WriteWithoutResponseReady)
case setNotification(NotificationState)
case readRSSI(ReadRSSI)
}
}
internal extension DarwinCentral.Operation {
func resume(throwing error: Swift.Error) {
switch self {
case let .connect(operation):
operation.continuation.resume(throwing: error)
case let .disconnect(operation):
operation.continuation.resume(throwing: error)
case let .discoverServices(operation):
operation.continuation.resume(throwing: error)
case let .discoverIncludedServices(operation):
operation.continuation.resume(throwing: error)
case let .discoverCharacteristics(operation):
operation.continuation.resume(throwing: error)
case let .writeCharacteristic(operation):
operation.continuation.resume(throwing: error)
case let .readCharacteristic(operation):
operation.continuation.resume(throwing: error)
case let .discoverDescriptors(operation):
operation.continuation.resume(throwing: error)
case let .readDescriptor(operation):
operation.continuation.resume(throwing: error)
case let .writeDescriptor(operation):
operation.continuation.resume(throwing: error)
case let .isReadyToWriteWithoutResponse(operation):
operation.continuation.resume(throwing: error)
case let .setNotification(operation):
operation.continuation.resume(throwing: error)
case let .readRSSI(operation):
operation.continuation.resume(throwing: error)
}
}
func cancel() {
resume(throwing: CancellationError())
}
}
internal protocol DarwinCentralOperation {
associatedtype Success
var continuation: PeripheralContinuation<Success, Error> { get }
var operation: DarwinCentral.Operation { get }
}
internal extension DarwinCentralOperation {
func resume(throwing error: Swift.Error) {
continuation.resume(throwing: error)
}
func cancel() {
resume(throwing: CancellationError())
}
}
internal extension DarwinCentral.Operation {
struct Connect: DarwinCentralOperation {
let peripheral: DarwinCentral.Peripheral
let options: [String: Any]?
let continuation: PeripheralContinuation<(), Error>
var operation: DarwinCentral.Operation { .connect(self) }
}
struct Disconnect: DarwinCentralOperation {
let peripheral: DarwinCentral.Peripheral
let continuation: PeripheralContinuation<(), Error>
var operation: DarwinCentral.Operation { .disconnect(self) }
}
struct DiscoverServices: DarwinCentralOperation {
let peripheral: DarwinCentral.Peripheral
let services: Set<BluetoothUUID>
let continuation: PeripheralContinuation<[DarwinCentral.Service], Error>
var operation: DarwinCentral.Operation { .discoverServices(self) }
}
struct DiscoverIncludedServices: DarwinCentralOperation {
let service: DarwinCentral.Service
let services: Set<BluetoothUUID>
let continuation: PeripheralContinuation<[DarwinCentral.Service], Error>
var operation: DarwinCentral.Operation { .discoverIncludedServices(self) }
}
struct DiscoverCharacteristics: DarwinCentralOperation {
let service: DarwinCentral.Service
let characteristics: Set<BluetoothUUID>
let continuation: PeripheralContinuation<[DarwinCentral.Characteristic], Error>
var operation: DarwinCentral.Operation { .discoverCharacteristics(self) }
}
struct ReadCharacteristic: DarwinCentralOperation {
let characteristic: DarwinCentral.Characteristic
let continuation: PeripheralContinuation<Data, Error>
var operation: DarwinCentral.Operation { .readCharacteristic(self) }
}
struct WriteCharacteristic: DarwinCentralOperation {
let characteristic: DarwinCentral.Characteristic
let data: Data
let withResponse: Bool
let continuation: PeripheralContinuation<(), Error>
var operation: DarwinCentral.Operation { .writeCharacteristic(self) }
}
struct DiscoverDescriptors: DarwinCentralOperation {
let characteristic: DarwinCentral.Characteristic
let continuation: PeripheralContinuation<[DarwinCentral.Descriptor], Error>
var operation: DarwinCentral.Operation { .discoverDescriptors(self) }
}
struct ReadDescriptor: DarwinCentralOperation {
let descriptor: DarwinCentral.Descriptor
let continuation: PeripheralContinuation<Data, Error>
var operation: DarwinCentral.Operation { .readDescriptor(self) }
}
struct WriteDescriptor: DarwinCentralOperation {
let descriptor: DarwinCentral.Descriptor
let data: Data
let continuation: PeripheralContinuation<(), Error>
var operation: DarwinCentral.Operation { .writeDescriptor(self) }
}
struct WriteWithoutResponseReady: DarwinCentralOperation {
let peripheral: DarwinCentral.Peripheral
let continuation: PeripheralContinuation<(), Error>
var operation: DarwinCentral.Operation { .isReadyToWriteWithoutResponse(self) }
}
struct NotificationState: DarwinCentralOperation {
let characteristic: DarwinCentral.Characteristic
let isEnabled: Bool
let continuation: PeripheralContinuation<(), Error>
var operation: DarwinCentral.Operation { .setNotification(self) }
}
struct ReadRSSI: DarwinCentralOperation {
let peripheral: DarwinCentral.Peripheral
let continuation: PeripheralContinuation<RSSI, Error>
var operation: DarwinCentral.Operation { .readRSSI(self) }
}
struct Scan {
let services: Set<BluetoothUUID>
let filterDuplicates: Bool
let continuation: AsyncIndefiniteStream<ScanData<DarwinCentral.Peripheral, DarwinCentral.Advertisement>>.Continuation
}
}
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal extension DarwinCentral {
/// Executes a queued operation and informs whether a continuation is pending.
func execute(_ operation: QueuedOperation) -> Bool {
return operation.isCancelled ? false : execute(operation.operation)
}
/// Executes an operation and informs whether a continuation is pending.
func execute(_ operation: DarwinCentral.Operation) -> Bool {
switch operation {
case let .connect(operation):
return execute(operation)
case let .disconnect(operation):
return execute(operation)
case let .discoverServices(operation):
return execute(operation)
case let .discoverIncludedServices(operation):
return execute(operation)
case let .discoverCharacteristics(operation):
return execute(operation)
case let .readCharacteristic(operation):
return execute(operation)
case let .writeCharacteristic(operation):
return execute(operation)
case let .discoverDescriptors(operation):
return execute(operation)
case let .readDescriptor(operation):
return execute(operation)
case let .writeDescriptor(operation):
return execute(operation)
case let .setNotification(operation):
return execute(operation)
case let .isReadyToWriteWithoutResponse(operation):
return execute(operation)
case let .readRSSI(operation):
return execute(operation)
}
}
func execute(_ operation: Operation.Connect) -> Bool {
log?("Will connect to \(operation.peripheral)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.peripheral, for: operation.continuation) else {
return false
}
// connect
self.centralManager.connect(peripheralObject, options: operation.options)
return true
}
func execute(_ operation: Operation.Disconnect) -> Bool {
log?("Will disconnect \(operation.peripheral)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.peripheral, for: operation.continuation) else {
return false
}
// disconnect
guard peripheralObject.state != .disconnected else {
operation.continuation.resume() // already disconnected
return false
}
self.centralManager.cancelPeripheralConnection(peripheralObject)
return true
}
func execute(_ operation: Operation.DiscoverServices) -> Bool {
log?("Peripheral \(operation.peripheral) will discover services")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// discover
let serviceUUIDs = operation.services.isEmpty ? nil : operation.services.map { CBUUID($0) }
peripheralObject.discoverServices(serviceUUIDs)
return true
}
func execute(_ operation: Operation.DiscoverIncludedServices) -> Bool {
log?("Peripheral \(operation.service.peripheral) will discover included services of service \(operation.service.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.service.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get service
guard let serviceObject = validateService(operation.service, for: operation.continuation) else {
return false
}
let serviceUUIDs = operation.services.isEmpty ? nil : operation.services.map { CBUUID($0) }
peripheralObject.discoverIncludedServices(serviceUUIDs, for: serviceObject)
return true
}
func execute(_ operation: Operation.DiscoverCharacteristics) -> Bool {
log?("Peripheral \(operation.service.peripheral) will discover characteristics of service \(operation.service.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.service.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get service
guard let serviceObject = validateService(operation.service, for: operation.continuation) else {
return false
}
// discover
let characteristicUUIDs = operation.characteristics.isEmpty ? nil : operation.characteristics.map { CBUUID($0) }
peripheralObject.discoverCharacteristics(characteristicUUIDs, for: serviceObject)
return true
}
func execute(_ operation: Operation.ReadCharacteristic) -> Bool {
log?("Peripheral \(operation.characteristic.peripheral) will read characteristic \(operation.characteristic.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.characteristic.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get characteristic
guard let characteristicObject = validateCharacteristic(operation.characteristic, for: operation.continuation) else {
return false
}
// read value
peripheralObject.readValue(for: characteristicObject)
return true
}
func execute(_ operation: Operation.WriteCharacteristic) -> Bool {
log?("Peripheral \(operation.characteristic.peripheral) will write characteristic \(operation.characteristic.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.characteristic.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get characteristic
guard let characteristicObject = validateCharacteristic(operation.characteristic, for: operation.continuation) else {
return false
}
assert(operation.withResponse || peripheralObject.canSendWriteWithoutResponse, "Cannot write without response")
// calls `peripheral:didWriteValueForCharacteristic:error:` only
// if you specified the write type as `.withResponse`.
let writeType: CBCharacteristicWriteType = operation.withResponse ? .withResponse : .withoutResponse
peripheralObject.writeValue(operation.data, for: characteristicObject, type: writeType)
guard operation.withResponse else {
operation.continuation.resume()
return false
}
return true
}
func execute(_ operation: Operation.DiscoverDescriptors) -> Bool {
log?("Peripheral \(operation.characteristic.peripheral) will discover descriptors of characteristic \(operation.characteristic.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.characteristic.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get characteristic
guard let characteristicObject = validateCharacteristic(operation.characteristic, for: operation.continuation) else {
return false
}
// discover
peripheralObject.discoverDescriptors(for: characteristicObject)
return true
}
func execute(_ operation: Operation.ReadDescriptor) -> Bool {
log?("Peripheral \(operation.descriptor.peripheral) will read descriptor \(operation.descriptor.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.descriptor.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get descriptor
guard let descriptorObject = validateDescriptor(operation.descriptor, for: operation.continuation) else {
return false
}
// write
peripheralObject.readValue(for: descriptorObject)
return true
}
func execute(_ operation: Operation.WriteDescriptor) -> Bool {
log?("Peripheral \(operation.descriptor.peripheral) will write descriptor \(operation.descriptor.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.descriptor.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get descriptor
guard let descriptorObject = validateDescriptor(operation.descriptor, for: operation.continuation) else {
return false
}
// write
peripheralObject.writeValue(operation.data, for: descriptorObject)
return true
}
func execute(_ operation: Operation.WriteWithoutResponseReady) -> Bool {
// get peripheral
guard let peripheralObject = validatePeripheral(operation.peripheral, for: operation.continuation) else {
return false
}
guard peripheralObject.canSendWriteWithoutResponse == false else {
operation.continuation.resume()
return false
}
// wait until delegate is called
return true
}
func execute(_ operation: Operation.NotificationState) -> Bool {
log?("Peripheral \(operation.characteristic.peripheral) will \(operation.isEnabled ? "enable" : "disable") notifications for characteristic \(operation.characteristic.uuid)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.characteristic.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// get characteristic
guard let characteristicObject = validateCharacteristic(operation.characteristic, for: operation.continuation) else {
return false
}
// notify
peripheralObject.setNotifyValue(operation.isEnabled, for: characteristicObject)
return true
}
func execute(_ operation: Operation.ReadRSSI) -> Bool {
self.log?("Will read RSSI for \(operation.peripheral)")
// check power on
guard validateState(.poweredOn, for: operation.continuation) else {
return false
}
// get peripheral
guard let peripheralObject = validatePeripheral(operation.peripheral, for: operation.continuation) else {
return false
}
// check connected
guard validateConnected(peripheralObject, for: operation.continuation) else {
return false
}
// read value
peripheralObject.readRSSI()
return true
}
func execute(_ operation: Operation.Scan) {
log?("Will scan for nearby devices")
let serviceUUIDs: [CBUUID]? = operation.services.isEmpty ? nil : operation.services.map { CBUUID($0) }
let options: [String: Any] = [
CBCentralManagerScanOptionAllowDuplicatesKey: NSNumber(value: operation.filterDuplicates == false)
]
// reset cache
self.cache = Cache()
// start scanning
//self.continuation.isScanning.yield(true)
self.centralManager.scanForPeripherals(
withServices: serviceUUIDs,
options: options
)
}
}
private extension DarwinCentral {
func validateState<T>(
_ state: DarwinBluetoothState,
for continuation: PeripheralContinuation<T, Error>
) -> Bool {
let state = self.centralManager._state
guard state == .poweredOn else {
continuation.resume(throwing: DarwinCentralError.invalidState(state))
return false
}
return true
}
func validatePeripheral<T>(
_ peripheral: Peripheral,
for continuation: PeripheralContinuation<T, Error>
) -> CBPeripheral? {
// get peripheral
guard let peripheralObject = self.cache.peripherals[peripheral] else {
continuation.resume(throwing: CentralError.unknownPeripheral)
return nil
}
assert(peripheralObject.delegate != nil)
return peripheralObject
}
func validateConnected<T>(
_ peripheral: CBPeripheral,
for continuation: PeripheralContinuation<T, Error>
) -> Bool {
guard peripheral.state == .connected else {
continuation.resume(throwing: CentralError.disconnected)
return false
}
return true
}
func validateService<T>(
_ service: Service,
for continuation: PeripheralContinuation<T, Error>
) -> CBService? {
guard let serviceObject = self.cache.services[service] else {
continuation.resume(throwing: CentralError.invalidAttribute(service.uuid))
return nil
}
return serviceObject
}
func validateCharacteristic<T>(
_ characteristic: Characteristic,
for continuation: PeripheralContinuation<T, Error>
) -> CBCharacteristic? {
guard let characteristicObject = self.cache.characteristics[characteristic] else {
continuation.resume(throwing: CentralError.invalidAttribute(characteristic.uuid))
return nil
}
return characteristicObject
}
func validateDescriptor<T>(
_ descriptor: Descriptor,
for continuation: PeripheralContinuation<T, Error>
) -> CBDescriptor? {
guard let descriptorObject = self.cache.descriptors[descriptor] else {
continuation.resume(throwing: CentralError.invalidAttribute(descriptor.uuid))
return nil
}
return descriptorObject
}
}
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal extension DarwinCentral {
@objc(GATTAsyncCentralManagerRestorableDelegate)
class RestorableDelegate: Delegate {
@objc
func centralManager(_ centralManager: CBCentralManager, willRestoreState state: [String : Any]) {
assert(self.central.centralManager === centralManager)
log("Will restore state: \(NSDictionary(dictionary: state).description)")
// An array of peripherals for use when restoring the state of a central manager.
if let peripherals = state[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral] {
for peripheralObject in peripherals {
self.central.cache.peripherals[Peripheral(peripheralObject)] = peripheralObject
}
}
}
}
@objc(GATTAsyncCentralManagerDelegate)
class Delegate: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
private(set) unowned var central: DarwinCentral
fileprivate init(_ central: DarwinCentral) {
self.central = central
super.init()
}
fileprivate func log(_ message: String) {
self.central.log?(message)
}
// MARK: - CBCentralManagerDelegate
@objc(centralManagerDidUpdateState:)
func centralManagerDidUpdateState(_ centralManager: CBCentralManager) {
assert(self.central.centralManager === centralManager)
let state = unsafeBitCast(centralManager.state, to: DarwinBluetoothState.self)
log("Did update state \(state)")
self.central.objectWillChange.send()
}
@objc(centralManager:didDiscoverPeripheral:advertisementData:RSSI:)
func centralManager(
_ centralManager: CBCentralManager,
didDiscover corePeripheral: CBPeripheral,
advertisementData: [String : Any],
rssi: NSNumber
) {
assert(self.central.centralManager === centralManager)
if corePeripheral.delegate == nil {
corePeripheral.delegate = self
}
let peripheral = Peripheral(corePeripheral)
let advertisement = Advertisement(advertisementData)
let scanResult = ScanData(
peripheral: peripheral,
date: Date(),
rssi: rssi.doubleValue,
advertisementData: advertisement,
isConnectable: advertisement.isConnectable ?? false
)
// cache value
self.central.cache.peripherals[peripheral] = corePeripheral
// yield value to stream
guard let operation = self.central.continuation.scan else {
assertionFailure("Not currently scanning")
return
}
operation.continuation.yield(scanResult)
}
#if os(iOS)
func centralManager(
_ central: CBCentralManager,
connectionEventDidOccur event: CBConnectionEvent,
for corePeripheral: CBPeripheral
) {
log("\(corePeripheral.id.uuidString) connection event")
}
#endif
@objc(centralManager:didConnectPeripheral:)
func centralManager(
_ centralManager: CBCentralManager,
didConnect corePeripheral: CBPeripheral
) {
log("Did connect to peripheral \(corePeripheral.id.uuidString)")
assert(corePeripheral.state != .disconnected, "Should be connected")
assert(self.central.centralManager === centralManager)
let peripheral = Peripheral(corePeripheral)
central.dequeue(for: peripheral, result: .success(()), filter: { (operation: DarwinCentral.Operation) -> (Operation.Connect?) in
guard case let .connect(operation) = operation else {
return nil
}
return operation
})
self.central.objectWillChange.send()
}
@objc(centralManager:didFailToConnectPeripheral:error:)
func centralManager(
_ centralManager: CBCentralManager,
didFailToConnect corePeripheral: CBPeripheral,
error: Swift.Error?
) {
log("Did fail to connect to peripheral \(corePeripheral.id.uuidString) (\(error!))")
assert(self.central.centralManager === centralManager)
assert(corePeripheral.state != .connected)
let peripheral = Peripheral(corePeripheral)
let error = error ?? CentralError.disconnected
central.dequeue(for: peripheral, result: .failure(error), filter: { (operation: DarwinCentral.Operation) -> (Operation.Connect?) in
guard case let .connect(operation) = operation else {
return nil
}
return operation
})
}
@objc(centralManager:didDisconnectPeripheral:error:)
func centralManager(
_ centralManager: CBCentralManager,
didDisconnectPeripheral corePeripheral: CBPeripheral,
error: Swift.Error?
) {
if let error = error {
log("Did disconnect peripheral \(corePeripheral.id.uuidString) due to error \(error.localizedDescription)")
} else {
log("Did disconnect peripheral \(corePeripheral.id.uuidString)")
}
let peripheral = Peripheral(corePeripheral)
guard let context = self.central.continuation.peripherals[peripheral] else {
assertionFailure("Missing context")
return
}
// user requested disconnection
if error == nil {
self.central.dequeue(for: peripheral, result: .success(()), filter: { (operation: DarwinCentral.Operation) -> (Operation.Disconnect?) in
guard case let .disconnect(disconnectOperation) = operation else {
return nil
}
return disconnectOperation
})
}
context.didDisconnect(error)
self.central.objectWillChange.send()
}
// MARK: - CBPeripheralDelegate
@objc(peripheral:didDiscoverServices:)
func peripheral(
_ corePeripheral: CBPeripheral,
didDiscoverServices error: Swift.Error?
) {
if let error = error {
log("Peripheral \(corePeripheral.id.uuidString) failed discovering services (\(error))")
} else {
log("Peripheral \(corePeripheral.id.uuidString) did discover \(corePeripheral.services?.count ?? 0) services")
}
let peripheral = Peripheral(corePeripheral)
let result: Result<[DarwinCentral.Service], Error>
if let error = error {
result = .failure(error)
} else {
let serviceObjects = corePeripheral.services ?? []
let services = serviceObjects.map { serviceObject in
Service(
service: serviceObject,
peripheral: corePeripheral
)
}
for (index, service) in services.enumerated() {
self.central.cache.services[service] = serviceObjects[index]
}
result = .success(services)
}
central.dequeue(for: peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.DiscoverServices?) in
guard case let .discoverServices(discoverServices) = operation else {
return nil
}
return discoverServices
})
}
@objc(peripheral:didDiscoverCharacteristicsForService:error:)
func peripheral(
_ peripheralObject: CBPeripheral,
didDiscoverCharacteristicsFor serviceObject: CBService,
error: Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed discovering characteristics (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did discover \(serviceObject.characteristics?.count ?? 0) characteristics for service \(serviceObject.uuid.uuidString)")
}
let service = Service(
service: serviceObject,
peripheral: peripheralObject
)
let result: Result<[DarwinCentral.Characteristic], Error>
if let error = error {
result = .failure(error)
} else {
let characteristicObjects = serviceObject.characteristics ?? []
let characteristics = characteristicObjects.map { characteristicObject in
Characteristic(
characteristic: characteristicObject,
peripheral: peripheralObject
)
}
for (index, characteristic) in characteristics.enumerated() {
self.central.cache.characteristics[characteristic] = characteristicObjects[index]
}
result = .success(characteristics)
}
central.dequeue(for: service.peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.DiscoverCharacteristics?) in
guard case let .discoverCharacteristics(discoverCharacteristics) = operation else {
return nil
}
return discoverCharacteristics
})
}
@objc(peripheral:didUpdateValueForCharacteristic:error:)
func peripheral(
_ peripheralObject: CBPeripheral,
didUpdateValueFor characteristicObject: CBCharacteristic,
error: Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed reading characteristic (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did update value for characteristic \(characteristicObject.uuid.uuidString)")
}
let characteristic = Characteristic(
characteristic: characteristicObject,
peripheral: peripheralObject
)
let data = characteristicObject.value ?? Data()
guard let context = self.central.continuation.peripherals[characteristic.peripheral] else {
assertionFailure("Missing context")
return
}
// either read operation or notification
if let queuedOperation = context.operations.current,
case let .readCharacteristic(operation) = queuedOperation.operation {
if queuedOperation.isCancelled {
return
}
if let error = error {
operation.continuation.resume(throwing: error)
} else {
operation.continuation.resume(returning: data)
}
context.operations.pop({ _ in }) // remove first
} else if characteristicObject.isNotifying {
guard let stream = context.notificationStream[characteristic.id] else {
assertionFailure("Missing notification stream")
return
}
assert(error == nil, "Notifications should never fail")
stream.yield(data)
} else {
assertionFailure("Missing continuation, not read or notification")
}
}
@objc(peripheral:didWriteValueForCharacteristic:error:)
func peripheral(
_ peripheralObject: CBPeripheral,
didWriteValueFor characteristicObject: CBCharacteristic,
error: Swift.Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed writing characteristic (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did write value for characteristic \(characteristicObject.uuid.uuidString)")
}
let characteristic = Characteristic(
characteristic: characteristicObject,
peripheral: peripheralObject
)
// should only be called for write with response
let result: Result<(), Error>
if let error = error {
result = .failure(error)
} else {
result = .success(())
}
central.dequeue(for: characteristic.peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.WriteCharacteristic?) in
guard case let .writeCharacteristic(operation) = operation else {
return nil
}
assert(operation.withResponse)
return operation
})
}
@objc
func peripheral(
_ peripheralObject: CBPeripheral,
didUpdateNotificationStateFor characteristicObject: CBCharacteristic,
error: Swift.Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed setting notifications for characteristic (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did update notification state for characteristic \(characteristicObject.uuid.uuidString)")
}
let characteristic = Characteristic(
characteristic: characteristicObject,
peripheral: peripheralObject
)
let result: Result<(), Error>
if let error = error {
result = .failure(error)
} else {
result = .success(())
}
central.dequeue(for: characteristic.peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.NotificationState?) in
guard case let .setNotification(notificationOperation) = operation else {
return nil
}
assert(characteristicObject.isNotifying == notificationOperation.isEnabled)
return notificationOperation
})
}
func peripheralIsReady(toSendWriteWithoutResponse peripheralObject: CBPeripheral) {
log("Peripheral \(peripheralObject.id.uuidString) is ready to send write without response")
let peripheral = Peripheral(peripheralObject)
central.dequeue(for: peripheral, result: .success(()), filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.WriteWithoutResponseReady?) in
guard case let .isReadyToWriteWithoutResponse(writeWithoutResponseReady) = operation else {
return nil
}
return writeWithoutResponseReady
})
}
func peripheralDidUpdateName(_ peripheralObject: CBPeripheral) {
log("Peripheral \(peripheralObject.id.uuidString) updated name \(peripheralObject.name ?? "")")
}
func peripheral(_ peripheralObject: CBPeripheral, didReadRSSI rssiObject: NSNumber, error: Error?) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed to read RSSI (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did read RSSI \(rssiObject.description)")
}
let peripheral = Peripheral(peripheralObject)
guard let context = self.central.continuation.peripherals[peripheral] else {
assertionFailure("Missing context")
return
}
guard let operation = context.readRSSI else {
assertionFailure("Invalid continuation")
return
}
if let error = error {
operation.continuation.resume(throwing: error)
} else {
guard let rssi = Bluetooth.RSSI(rawValue: rssiObject.int8Value) else {
assertionFailure("Invalid RSSI \(rssiObject)")
operation.continuation.resume(returning: RSSI(rawValue: -127)!)
return
}
operation.continuation.resume(returning: rssi)
}
}
func peripheral(
_ peripheralObject: CBPeripheral,
didDiscoverIncludedServicesFor serviceObject: CBService,
error: Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed discovering included services for service \(serviceObject.uuid.description) (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did discover \(serviceObject.includedServices?.count ?? 0) included services for service \(serviceObject.uuid.uuidString)")
}
let service = Service(
service: serviceObject,
peripheral: peripheralObject
)
let result: Result<[DarwinCentral.Service], Error>
if let error = error {
result = .failure(error)
} else {
let serviceObjects = (serviceObject.includedServices ?? [])
let services = serviceObjects.map { serviceObject in
Service(
service: serviceObject,
peripheral: peripheralObject
)
}
for (index, service) in services.enumerated() {
self.central.cache.services[service] = serviceObjects[index]
}
result = .success(services)
}
central.dequeue(for: service.peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.DiscoverIncludedServices?) in
guard case let .discoverIncludedServices(writeWithoutResponseReady) = operation else {
return nil
}
return writeWithoutResponseReady
})
}
@objc
func peripheral(_ peripheralObject: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
log("Peripheral \(peripheralObject.id.uuidString) did modify \(invalidatedServices.count) services")
// TODO: Try to rediscover services
}
@objc
func peripheral(
_ peripheralObject: CBPeripheral,
didDiscoverDescriptorsFor characteristicObject: CBCharacteristic,
error: Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed discovering descriptors for characteristic \(characteristicObject.uuid.uuidString) (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did discover \(characteristicObject.descriptors?.count ?? 0) descriptors for characteristic \(characteristicObject.uuid.uuidString)")
}
let peripheral = Peripheral(peripheralObject)
let result: Result<[DarwinCentral.Descriptor], Error>
if let error = error {
result = .failure(error)
} else {
let descriptorObjects = (characteristicObject.descriptors ?? [])
let descriptors = descriptorObjects.map { descriptorObject in
Descriptor(
descriptor: descriptorObject,
peripheral: peripheralObject
)
}
// store objects in cache
for (index, descriptor) in descriptors.enumerated() {
self.central.cache.descriptors[descriptor] = descriptorObjects[index]
}
// resume
result = .success(descriptors)
}
central.dequeue(for: peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.DiscoverDescriptors?) in
guard case let .discoverDescriptors(discoverDescriptors) = operation else {
return nil
}
return discoverDescriptors
})
}
func peripheral(
_ peripheralObject: CBPeripheral,
didWriteValueFor descriptorObject: CBDescriptor,
error: Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed writing descriptor \(descriptorObject.uuid.uuidString) (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did write value for descriptor \(descriptorObject.uuid.uuidString)")
}
let peripheral = Peripheral(peripheralObject)
let result: Result<(), Error>
if let error = error {
result = .failure(error)
} else {
result = .success(())
}
central.dequeue(for: peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.WriteDescriptor?) in
guard case let .writeDescriptor(writeDescriptor) = operation else {
return nil
}
return writeDescriptor
})
}
func peripheral(
_ peripheralObject: CBPeripheral,
didUpdateValueFor descriptorObject: CBDescriptor,
error: Error?
) {
if let error = error {
log("Peripheral \(peripheralObject.id.uuidString) failed updating value for descriptor \(descriptorObject.uuid.uuidString) (\(error))")
} else {
log("Peripheral \(peripheralObject.id.uuidString) did update value for descriptor \(descriptorObject.uuid.uuidString)")
}
let descriptor = Descriptor(
descriptor: descriptorObject,
peripheral: peripheralObject
)
let result: Result<Data, Error>
if let error = error {
result = .failure(error)
} else {
let data: Data
if let descriptor = DarwinDescriptor(descriptorObject) {
data = descriptor.data
} else if let dataObject = descriptorObject.value as? NSData {
data = dataObject as Data
} else {
data = Data()
}
result = .success(data)
}
central.dequeue(for: descriptor.peripheral, result: result, filter: { (operation: DarwinCentral.Operation) -> (DarwinCentral.Operation.ReadDescriptor?) in
guard case let .readDescriptor(readDescriptor) = operation else {
return nil
}
return readDescriptor
})
}
}
}
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal extension Service where ID == ObjectIdentifier, Peripheral == DarwinCentral.Peripheral {
init(
service serviceObject: CBService,
peripheral peripheralObject: CBPeripheral
) {
self.init(
id: ObjectIdentifier(serviceObject),
uuid: BluetoothUUID(serviceObject.uuid),
peripheral: DarwinCentral.Peripheral(peripheralObject),
isPrimary: serviceObject.isPrimary
)
}
}
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal extension Characteristic where ID == ObjectIdentifier, Peripheral == DarwinCentral.Peripheral {
init(
characteristic characteristicObject: CBCharacteristic,
peripheral peripheralObject: CBPeripheral
) {
self.init(
id: ObjectIdentifier(characteristicObject),
uuid: BluetoothUUID(characteristicObject.uuid),
peripheral: DarwinCentral.Peripheral(peripheralObject),
properties: .init(rawValue: numericCast(characteristicObject.properties.rawValue))
)
}
}
@available(macOS 10.5, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal extension Descriptor where ID == ObjectIdentifier, Peripheral == DarwinCentral.Peripheral {
init(
descriptor descriptorObject: CBDescriptor,
peripheral peripheralObject: CBPeripheral
) {
self.init(
id: ObjectIdentifier(descriptorObject),
uuid: BluetoothUUID(descriptorObject.uuid),
peripheral: DarwinCentral.Peripheral(peripheralObject)
)
}
}
#endif
| mit | c89c50d69f6907ec7328e0db04663704 | 38.53619 | 220 | 0.607786 | 6.027454 | false | false | false | false |
DopamineLabs/DopamineKit-iOS | BoundlessKit/Classes/Integration/HttpClients/Data/Storage/BKDatabase.swift | 1 | 1501 | //
// BKDatabase.swift
// BoundlessKit
//
// Created by Akash Desai on 3/8/18.
//
import Foundation
internal protocol BKData : NSCoding {}
internal protocol BKDatabase {
typealias Storage = (BKDatabase, String)
func archive<T: BKData>(_ value: T?, forKey key: String)
func unarchive<T: BKData>(_ key: String) -> T?
}
internal class BKUserDefaults : UserDefaults, BKDatabase {
private static let suiteName = "boundless.kit.db.1"
override class var standard: BKUserDefaults {
get {
return BKUserDefaults(suiteName: suiteName)!
}
}
func removePersistentDomain() {
removePersistentDomain(forName: BKUserDefaults.suiteName)
}
func archive<T: BKData>(_ value: T?, forKey key: String) {
if let value = value {
self.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)
} else {
self.set(nil, forKey: key)
}
}
func unarchive<T: BKData>(_ key: String) -> T? {
if let data = self.object(forKey: key) as? Data,
let t = NSKeyedUnarchiver.unarchiveObject(with: data) as? T {
return t
} else {
return nil
}
}
var initialBootDate: Date? {
get {
let date = object(forKey: "initialBootDate") as? Date
if date == nil {
set(Date(), forKey: "initialBootDate")
}
return date
}
}
}
| mit | 805bc99037b6036eb704367ae30bccb3 | 23.209677 | 86 | 0.568288 | 4.264205 | false | false | false | false |
ktatroe/MPA-Horatio | Horatio/Horatio/Classes/Operations/URLSessionTaskOperation.swift | 2 | 2062 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Shows how to lift operation-like objects in to the NSOperation world.
*/
import Foundation
private var URLSessionTaksOperationKVOContext = 0
/**
`URLSessionTaskOperation` is an `Operation` that lifts an `NSURLSessionTask`
into an operation.
Note that this operation does not participate in any of the delegate callbacks \
of an `NSURLSession`, but instead uses Key-Value-Observing to know when the
task has been completed. It also does not get notified about any errors that
occurred during execution of the task.
An example usage of `URLSessionTaskOperation` can be seen in the `DownloadEarthquakesOperation`.
*/
open class URLSessionTaskOperation: Operation {
let task: URLSessionTask
public init(task: URLSessionTask) {
assert(task.state == .suspended, "Tasks must be suspended.")
self.task = task
super.init()
let networkObserver = NetworkObserver()
self.addObserver(networkObserver)
}
override open func execute() {
assert(task.state == .suspended, "Task was resumed by something other than \(self).")
task.addObserver(self, forKeyPath: "state", options: [], context: &URLSessionTaksOperationKVOContext)
task.resume()
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard context == &URLSessionTaksOperationKVOContext else { return }
guard let object = object as? URLSessionTask else { return }
if object === task && keyPath == "state" && task.state == .completed {
task.removeObserver(self, forKeyPath: "state")
if let error = task.error {
finish([error as NSError])
} else {
finish()
}
}
}
override open func cancel() {
task.cancel()
super.cancel()
}
}
| mit | 2c9215ed9dc471947faec44e0d204ecf | 30.692308 | 156 | 0.667961 | 4.847059 | false | false | false | false |
abbeycode/Carthage | Source/CarthageKit/Resolver.swift | 1 | 14925 | //
// Resolver.swift
// Carthage
//
// Created by Justin Spahr-Summers on 2014-11-09.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
import Result
import ReactiveCocoa
/// Responsible for resolving acyclic dependency graphs.
public struct Resolver {
private let versionsForDependency: ProjectIdentifier -> SignalProducer<PinnedVersion, CarthageError>
private let resolvedGitReference: (ProjectIdentifier, String) -> SignalProducer<PinnedVersion, CarthageError>
private let cartfileForDependency: Dependency<PinnedVersion> -> SignalProducer<Cartfile, CarthageError>
/// Instantiates a dependency graph resolver with the given behaviors.
///
/// versionsForDependency - Sends a stream of available versions for a
/// dependency.
/// cartfileForDependency - Loads the Cartfile for a specific version of a
/// dependency.
/// resolvedGitReference - Resolves an arbitrary Git reference to the
/// latest object.
public init(versionsForDependency: ProjectIdentifier -> SignalProducer<PinnedVersion, CarthageError>, cartfileForDependency: Dependency<PinnedVersion> -> SignalProducer<Cartfile, CarthageError>, resolvedGitReference: (ProjectIdentifier, String) -> SignalProducer<PinnedVersion, CarthageError>) {
self.versionsForDependency = versionsForDependency
self.cartfileForDependency = cartfileForDependency
self.resolvedGitReference = resolvedGitReference
}
/// Attempts to determine the latest valid version to use for each dependency
/// specified in the given Cartfile, and all nested dependencies thereof.
///
/// Sends each recursive dependency with its resolved version, in the order
/// that they should be built.
public func resolveDependenciesInCartfile(cartfile: Cartfile) -> SignalProducer<Dependency<PinnedVersion>, CarthageError> {
return nodePermutationsForCartfile(cartfile)
|> flatMap(.Concat) { rootNodes -> SignalProducer<Event<DependencyGraph, CarthageError>, CarthageError> in
return self.graphPermutationsForEachNode(rootNodes, dependencyOf: nil, basedOnGraph: DependencyGraph())
|> promoteErrors(CarthageError.self)
}
// Pass through resolution errors only if we never got
// a valid graph.
|> dematerializeErrorsIfEmpty
|> take(1)
|> observeOn(QueueScheduler(name: "org.carthage.CarthageKit.Resolver.resolveDependencesInCartfile"))
|> flatMap(.Merge) { graph -> SignalProducer<Dependency<PinnedVersion>, CarthageError> in
return SignalProducer(values: graph.orderedNodes)
|> map { node in node.dependencyVersion }
}
}
/// Sends all permutations of valid DependencyNodes, corresponding to the
/// dependencies listed in the given Cartfile, in the order that they should
/// be tried.
///
/// In other words, this will always send arrays equal in length to
/// `cartfile.dependencies`. Each array represents one possible permutation
/// of those dependencies (chosen from among the versions that actually
/// exist for each).
private func nodePermutationsForCartfile(cartfile: Cartfile) -> SignalProducer<[DependencyNode], CarthageError> {
let scheduler = QueueScheduler(name: "org.carthage.CarthageKit.Resolver.nodePermutationsForCartfile")
return SignalProducer(values: cartfile.dependencies)
|> map { dependency -> SignalProducer<DependencyNode, CarthageError> in
let allowedVersions = SignalProducer<String?, CarthageError>.try {
switch dependency.version {
case let .GitReference(refName):
return .success(refName)
default:
return .success(nil)
}
}
|> flatMap(.Concat) { refName -> SignalProducer<PinnedVersion, CarthageError> in
if let refName = refName {
return self.resolvedGitReference(dependency.project, refName)
}
return self.versionsForDependency(dependency.project)
|> collect
|> flatMap(.Merge) { nodes -> SignalProducer<PinnedVersion, CarthageError> in
if nodes.isEmpty {
return SignalProducer(error: CarthageError.TaggedVersionNotFound(dependency.project))
} else {
return SignalProducer(values: nodes)
}
}
|> filter { dependency.version.satisfiedBy($0) }
}
return allowedVersions
|> startOn(scheduler)
|> observeOn(scheduler)
|> map { DependencyNode(project: dependency.project, proposedVersion: $0, versionSpecifier: dependency.version) }
|> collect
|> map(sorted)
|> flatMap(.Concat) { nodes -> SignalProducer<DependencyNode, CarthageError> in
if nodes.isEmpty {
return SignalProducer(error: CarthageError.RequiredVersionNotFound(dependency.project, dependency.version))
} else {
return SignalProducer(values: nodes)
}
}
}
|> collect
|> observeOn(scheduler)
|> flatMap(.Concat) { nodeProducers in permutations(nodeProducers) }
}
/// Sends all possible permutations of `inputGraph` oriented around the
/// dependencies of `node`.
///
/// In other words, this attempts to create one transformed graph for each
/// possible permutation of the dependencies for the given node (chosen from
/// among the verisons that actually exist for each).
private func graphPermutationsForDependenciesOfNode(node: DependencyNode, basedOnGraph inputGraph: DependencyGraph) -> SignalProducer<DependencyGraph, CarthageError> {
let scheduler = QueueScheduler(name: "org.carthage.CarthageKit.Resolver.graphPermutationsForDependenciesOfNode")
return cartfileForDependency(node.dependencyVersion)
|> startOn(scheduler)
|> concat(SignalProducer(value: Cartfile(dependencies: [])))
|> take(1)
|> observeOn(scheduler)
|> flatMap(.Merge) { self.nodePermutationsForCartfile($0) }
|> flatMap(.Concat) { dependencyNodes in
return self.graphPermutationsForEachNode(dependencyNodes, dependencyOf: node, basedOnGraph: inputGraph)
|> promoteErrors(CarthageError.self)
}
// Pass through resolution errors only if we never got
// a valid graph.
|> dematerializeErrorsIfEmpty
}
/// Recursively permutes each element in `nodes` and all dependencies
/// thereof, attaching each permutation to `inputGraph` as a dependency of
/// the specified node (or as a root otherwise).
///
/// This is a helper method, and not meant to be called from outside.
private func graphPermutationsForEachNode(nodes: [DependencyNode], dependencyOf: DependencyNode?, basedOnGraph inputGraph: DependencyGraph) -> SignalProducer<Event<DependencyGraph, CarthageError>, NoError> {
return SignalProducer<(DependencyGraph, [DependencyNode]), CarthageError> { observer, disposable in
var graph = inputGraph
var newNodes: [DependencyNode] = []
for node in nodes {
if disposable.disposed {
return
}
switch graph.addNode(node, dependencyOf: dependencyOf) {
case let .Success(newNode):
newNodes.append(newNode.value)
case let .Failure(error):
sendError(observer, error.value)
return
}
}
sendNext(observer, (graph, newNodes))
sendCompleted(observer)
}
|> flatMap(.Concat) { graph, nodes -> SignalProducer<DependencyGraph, CarthageError> in
return SignalProducer(values: nodes)
// Each producer represents all evaluations of one subtree.
|> map { node in self.graphPermutationsForDependenciesOfNode(node, basedOnGraph: graph) }
|> collect
|> observeOn(QueueScheduler(name: "org.carthage.CarthageKit.Resolver.graphPermutationsForEachNode"))
|> flatMap(.Concat) { graphProducers in permutations(graphProducers) }
|> flatMap(.Concat) { graphs -> SignalProducer<Event<DependencyGraph, CarthageError>, CarthageError> in
let mergedGraphs = SignalProducer(values: graphs)
|> scan(Result<DependencyGraph, CarthageError>.success(inputGraph)) { result, nextGraph in
return result.flatMap { previousGraph in mergeGraphs(previousGraph, nextGraph) }
}
|> tryMap { $0 }
return SignalProducer(value: inputGraph)
|> concat(mergedGraphs)
|> takeLast(1)
|> materialize
|> promoteErrors(CarthageError.self)
}
// Pass through resolution errors only if we never got
// a valid graph.
|> dematerializeErrorsIfEmpty
}
|> materialize
}
}
/// Represents an acyclic dependency graph in which each project appears at most
/// once.
///
/// Dependency graphs can exist in an incomplete state, but will never be
/// inconsistent (i.e., include versions that are known to be invalid given the
/// current graph).
private struct DependencyGraph: Equatable {
/// A full list of all nodes included in the graph.
var allNodes: Set<DependencyNode> = []
/// All nodes that have dependencies, associated with those lists of
/// dependencies themselves.
var edges: [DependencyNode: Set<DependencyNode>] = [:]
/// The root nodes of the graph (i.e., those dependencies that are listed
/// by the top-level project).
var roots: Set<DependencyNode> = []
/// Returns all of the graph nodes, in the order that they should be built.
var orderedNodes: [DependencyNode] {
return sorted(allNodes) { lhs, rhs in
let lhsDependencies = self.edges[lhs]
let rhsDependencies = self.edges[rhs]
if let rhsDependencies = rhsDependencies {
// If the right node has a dependency on the left node, the
// left node needs to be built first (and is thus ordered
// first).
if rhsDependencies.contains(lhs) {
return true
}
}
if let lhsDependencies = lhsDependencies {
// If the left node has a dependency on the right node, the
// right node needs to be built first.
if lhsDependencies.contains(rhs) {
return false
}
}
// If neither node depends on each other, sort the one with the
// fewer dependencies first.
let lhsCount = lhsDependencies?.count ?? 0
let rhsCount = rhsDependencies?.count ?? 0
if lhsCount < rhsCount {
return true
} else if lhsCount > rhsCount {
return false
} else {
// If all else fails, compare names.
return lhs.project.name < rhs.project.name
}
}
}
init() {}
/// Attempts to add the given node to the graph, optionally as a dependency
/// of another.
///
/// If the given node refers to a project which already exists in the graph,
/// this method will attempt to unify the version specifiers of both.
///
/// Returns the node as actually inserted into the graph (which may be
/// different from the node passed in), or an error if this addition would
/// make the graph inconsistent.
mutating func addNode(var node: DependencyNode, dependencyOf: DependencyNode?) -> Result<DependencyNode, CarthageError> {
if let index = allNodes.indexOf(node) {
let existingNode = allNodes[index]
if let newSpecifier = intersection(existingNode.versionSpecifier, node.versionSpecifier) {
if newSpecifier.satisfiedBy(existingNode.proposedVersion) {
node = existingNode
node.versionSpecifier = newSpecifier
} else {
return .failure(CarthageError.RequiredVersionNotFound(node.project, newSpecifier))
}
} else {
return .failure(CarthageError.IncompatibleRequirements(node.project, existingNode.versionSpecifier, node.versionSpecifier))
}
} else {
allNodes.insert(node)
}
if let dependencyOf = dependencyOf {
var nodeSet = edges[dependencyOf] ?? Set()
nodeSet.insert(node)
edges[dependencyOf] = nodeSet
} else {
roots.insert(node)
}
return .success(node)
}
}
private func ==(lhs: DependencyGraph, rhs: DependencyGraph) -> Bool {
if lhs.edges.count != rhs.edges.count || lhs.roots.count != rhs.roots.count {
return false
}
for (edge, leftDeps) in lhs.edges {
if let rightDeps = rhs.edges[edge] {
if leftDeps.count != rightDeps.count {
return false
}
for dep in leftDeps {
if !rightDeps.contains(dep) {
return false
}
}
} else {
return false
}
}
for root in lhs.roots {
if !rhs.roots.contains(root) {
return false
}
}
return true
}
extension DependencyGraph: Printable {
private var description: String {
var str = "Roots:"
for root in roots {
str += "\n\t\(root)"
}
str += "\n\nEdges:"
for (node, dependencies) in edges {
str += "\n\t\(node.project) ->"
for dep in dependencies {
str += "\n\t\t\(dep)"
}
}
return str
}
}
/// Attempts to unify two graphs.
///
/// Returns the new graph, or an error if the graphs specify inconsistent
/// versions for one or more dependencies.
private func mergeGraphs(lhs: DependencyGraph, rhs: DependencyGraph) -> Result<DependencyGraph, CarthageError> {
var result: Result<DependencyGraph, CarthageError> = .success(lhs)
for root in rhs.roots {
result = result.flatMap { (var graph) in
return graph.addNode(root, dependencyOf: nil).map { _ in graph }
}
}
for (node, dependencies) in rhs.edges {
for dependency in dependencies {
result = result.flatMap { (var graph) in
return graph.addNode(dependency, dependencyOf: node).map { _ in graph }
}
}
}
return result
}
/// A node in, or being considered for, an acyclic dependency graph.
private class DependencyNode: Comparable {
/// The project that this node refers to.
let project: ProjectIdentifier
/// The version of the dependency that this node represents.
///
/// This version is merely "proposed" because it depends on the final
/// resolution of the graph, as well as whether any "better" graphs exist.
let proposedVersion: PinnedVersion
/// The current requirements applied to this dependency.
///
/// This specifier may change as the graph is added to, and the requirements
/// become more stringent.
var versionSpecifier: VersionSpecifier
/// A Dependency equivalent to this node.
var dependencyVersion: Dependency<PinnedVersion> {
return Dependency(project: project, version: proposedVersion)
}
init(project: ProjectIdentifier, proposedVersion: PinnedVersion, versionSpecifier: VersionSpecifier) {
precondition(versionSpecifier.satisfiedBy(proposedVersion))
self.project = project
self.proposedVersion = proposedVersion
self.versionSpecifier = versionSpecifier
}
}
private func <(lhs: DependencyNode, rhs: DependencyNode) -> Bool {
let leftSemantic = SemanticVersion.fromPinnedVersion(lhs.proposedVersion).value ?? SemanticVersion(major: 0, minor: 0, patch: 0)
let rightSemantic = SemanticVersion.fromPinnedVersion(rhs.proposedVersion).value ?? SemanticVersion(major: 0, minor: 0, patch: 0)
// Try higher versions first.
return leftSemantic > rightSemantic
}
private func ==(lhs: DependencyNode, rhs: DependencyNode) -> Bool {
return lhs.project == rhs.project
}
extension DependencyNode: Hashable {
private var hashValue: Int {
return project.hashValue
}
}
extension DependencyNode: Printable {
private var description: String {
return "\(project) @ \(proposedVersion) (restricted to \(versionSpecifier))"
}
}
| mit | 8c28983291c2d886e6bdbb5bcbde6210 | 34.620525 | 296 | 0.717789 | 4.254561 | false | false | false | false |
curtisforrester/SwiftNonStandardLibrary | source/SwiftNonStandardLibrary/Atomic.swift | 1 | 1706 | ////
//// Atomic.swift
//// Swift Non-Standard Library
////
//// Created by Russ Bishop
//// http://github.com/xenadu/SwiftNonStandardLibrary
////
//// MIT licensed; see LICENSE for more information
////
//
//import Foundation
//
////WARNING: not yet tested, do not rely on this code
//@final class Atomic<T> {
// var _value:UnsafePointer<UnsafePointer<()>>
//
// init(_ initialValue:Box<T>) {
// //retain the object and get its pointer
// let ptr = Unmanaged.passRetained(initialValue).toUnsafePtr()
// //now store that object pointer indirectly (_value will be pointer-to-pointer)
// _value = UnsafePointer<UnsafePointer<()>>.alloc(1)
// _value.initialize(ptr)
// }
//
// deinit {
// let unmanaged = Unmanaged<Box<T>>.fromOpaque(_value.memory)
// unmanaged.release()
// _value.dealloc(1)
// }
//
// var value : Box<T> {
// get {
// return Unmanaged<Box<T>>.fromOpaque(_value.memory).takeUnretainedValue()
// }
// set {
// let unmanaged = Unmanaged.passRetained(newValue)
// let newPtr = unmanaged.toOpaque()
// let oldPtr = _value.memory
//
// let didUpdate = OSAtomicCompareAndSwapPtr(UnsafePointer<()>(oldPtr), UnsafePointer<()>(newPtr), _value)
//
// if didUpdate {
// //if swap was done, release old value
// Unmanaged<Box<T>>.fromOpaque(oldPtr).release()
// } else {
// //if swap was not done, we did an unbalanced retain that needs to be fixed
// unmanaged.release()
// }
// }
// }
//
// @conversion func __conversion() -> T {
// return value
// }
//
//}
| mit | 3fa8d45126e5ff2451e5f48232806770 | 29.464286 | 113 | 0.568581 | 3.766004 | false | false | false | false |
dmorenob/HermesFramework | Hermes/HermesDataHandling.swift | 1 | 17018 | //
// HermesDataHandling.swift
// Hermes
//
// Created by David Moreno Briz on 24/11/14.
// Copyright (c) 2014 David Moreno Briz. All rights reserved.
//
import Foundation
import UIKit
let EntityColor: UIColor = UIColor(red: 26/255, green: 188/255, blue: 156/255, alpha: 1.0)
// Old entity color. UIColor(red: 72/255, green: 124/255, blue: 144/255, alpha: 1)
extension Hermes {
// Func that generates a collection (array) of Tweet object from certain data. This data
// will contain an array of statuses. This func will be used inside get/post (as a handler) petitions.
func retrieveTweetFrom(data: NSData) -> Array<Tweet> {
// We create an empty array of tweets to populate it
var tweets: Array<Tweet> = Array<Tweet>()
// We serialice the retreived twees into an Array of NSDictionaries (We will retrive more that 1 tweet (array) and each tweet acts like a dictionary)
var serializationError: NSError?
let statuses = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &serializationError) as Array<NSDictionary>
// If there is a serialization error
if serializationError != nil {
NSLog(serializationError!.description)
} else { // If there is no serialization error.
// For each tweet, we add it to the timeline
for (idx, tweet) in enumerate(statuses) {
var finalStatus = self.retrieveTweetFrom(tweet)
// We add the generated Tweet
tweets.append(finalStatus)
}
}
// We return the array
return tweets
}
// Func that generate Tweets when the data comes from a search
func retrieveTweetFromSearch(data: NSData) -> Array<Tweet> {
// We create an empty array of tweets to populate it
var tweets: Array<Tweet> = Array<Tweet>()
// We serialice the retreived twees into an Array of NSDictionaries (We will retrive more that 1 tweet (array) and each tweet acts like a dictionary)
var serializationError: NSError?
let search = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &serializationError) as NSDictionary
// If there is a serialization error
if serializationError != nil {
NSLog(serializationError!.description)
} else { // If there is no serialization error.
let statuses = search.objectForKey("statuses") as Array<NSDictionary>
// For each tweet, we add it to the timeline
for (idx, tweet) in enumerate(statuses) {
// We create a generic Tweet object to populate it.
var finalStatus = self.retrieveTweetFrom(tweet)
// We add the generated Tweet
tweets.append(finalStatus)
}
}
// We return the array
return tweets
}
// Func that generates a single Tweet from a a Dictionary
func retrieveTweetFrom(tweet: NSDictionary) -> Tweet {
// We create a generic Tweet object to populate it.
var finalStatus: Tweet = Tweet(text: NSMutableAttributedString(string: ""), userName: "", id_str: "")
// If the status is a RETWEET
if let retweet = tweet.objectForKey("retweeted_status") as? NSDictionary {
// We get the params of the retweeted tweet
var text: NSMutableAttributedString = NSMutableAttributedString(string: retweet.objectForKey("text") as String)
var entities = retweet.objectForKey("entities") as NSDictionary
var extended_entities = retweet.objectForKey("extended_entities") as NSDictionary?
var userName: String = (retweet.objectForKey("user") as NSDictionary).objectForKey("name") as String
var id_str: String = retweet.objectForKey("id_str") as String
var status: Tweet = Tweet(text: text, userName: userName, id_str: id_str)
var profile_image_url: String = (retweet.objectForKey("user") as NSDictionary).objectForKey("profile_image_url") as String
profile_image_url = profile_image_url.stringByReplacingOccurrencesOfString("_normal", withString: "_bigger", options: NSStringCompareOptions.LiteralSearch, range: nil)
status.profile_image_url = profile_image_url
var created_at: String = retweet.objectForKey("created_at") as String
status.created_at = created_at
var screenName = (retweet.objectForKey("user") as NSDictionary).objectForKey("screen_name") as String
status.screen_name = "@\(screenName)"
status.entities = entities
status.extended_entities = extended_entities
var hashtags: Array<NSDictionary> = entities.objectForKey("hashtags") as Array<NSDictionary>
for (idx, hashtag) in enumerate(hashtags) {
status.hashtags.append(hashtag.objectForKey("text") as String)
}
var mentions: Array<NSDictionary> = entities.objectForKey("user_mentions") as Array<NSDictionary>
for (idx, mention) in enumerate(mentions) {
status.mentions.append(mention.objectForKey("screen_name") as String)
}
status.author_id = (retweet.objectForKey("user") as NSDictionary).objectForKey("id_str") as String
// And the params of the retweeter
var retweeterUserName: String = (tweet.objectForKey("user") as NSDictionary).objectForKey("name") as String
var rt_id_str: String = tweet.objectForKey("id_str") as String
var rt_screenName = (tweet.objectForKey("user") as NSDictionary).objectForKey("screen_name") as String
var rt_profile_image_url: String = (tweet.objectForKey("user") as NSDictionary).objectForKey("profile_image_url") as String
rt_profile_image_url = rt_profile_image_url.stringByReplacingOccurrencesOfString("_normal", withString: "_bigger", options: NSStringCompareOptions.LiteralSearch, range: nil)
status.retweeterName = retweeterUserName
status.retweeterScreenName = rt_screenName
status.retweeter_profile_image_url = rt_profile_image_url
status.idOfRetweet = rt_id_str
status.retweeterID = (tweet.objectForKey("user") as NSDictionary).objectForKey("id_str") as String!
// And create the final status to add to the array
finalStatus = status
// If it is not a RETWEET
} else {
// We get the params for the current tweet
var text: NSMutableAttributedString = NSMutableAttributedString(string: tweet.objectForKey("text") as String)
var entities = tweet.objectForKey("entities") as NSDictionary
var extended_entities = tweet.objectForKey("extended_entities") as NSDictionary?
var userName: String = (tweet.objectForKey("user") as NSDictionary).objectForKey("name") as String
var id_str: String = tweet.objectForKey("id_str") as String
var status: Tweet = Tweet(text: text, userName: userName, id_str: id_str)
var profile_image_url: String = (tweet.objectForKey("user") as NSDictionary).objectForKey("profile_image_url") as String
profile_image_url = profile_image_url.stringByReplacingOccurrencesOfString("_normal", withString: "_bigger", options: NSStringCompareOptions.LiteralSearch, range: nil)
status.profile_image_url = profile_image_url
var created_at: String = tweet.objectForKey("created_at") as String
status.created_at = created_at
var screenName = (tweet.objectForKey("user") as NSDictionary).objectForKey("screen_name") as String
status.screen_name = "@\(screenName)"
status.entities = entities
status.extended_entities = extended_entities
var hashtags: Array<NSDictionary> = entities.objectForKey("hashtags") as Array<NSDictionary>
for (idx, hashtag) in enumerate(hashtags) {
status.hashtags.append(hashtag.objectForKey("text") as String)
}
var mentions: Array<NSDictionary> = entities.objectForKey("user_mentions") as Array<NSDictionary>
for (idx, mention) in enumerate(mentions) {
status.mentions.append(mention.objectForKey("screen_name") as String)
}
status.author_id = (tweet.objectForKey("user") as NSDictionary).objectForKey("id_str") as String
// And create the final status to add to the array
finalStatus = status
}
return finalStatus
}
func retrieveUsersFrom(data: NSData) -> Array<User> {
// We create an empty array of users to populate it
var arrayOfUsers: Array<User> = Array<User>()
// We serialice the retreived users into an Array of NSDictionaries (We will retrive more that 1 user (array) and each user acts like a dictionary)
var serializationError: NSError?
let users = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &serializationError) as Array<NSDictionary>
// If there is a serialization error
if serializationError != nil {
NSLog(serializationError!.description)
} else { // If there is no serialization error.
for (idx, user) in enumerate(users) {
var tuitero = self.retrieveUserFrom(user)
arrayOfUsers.append(tuitero)
}
}
return arrayOfUsers
}
func retrieveUserFrom(data: NSData) -> User! {
// We create an empty array of users to populate it
var tuitero: User!
// We serialice the retreived users into an Array of NSDictionaries (We will retrive more that 1 user (array) and each user acts like a dictionary)
var serializationError: NSError?
let user = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &serializationError) as NSDictionary
// If there is a serialization error
if serializationError != nil {
NSLog(serializationError!.description)
} else { // If there is no serialization error.
tuitero = self.retrieveUserFrom(user)
}
return tuitero
}
func retrieveUsersAndCursorFrom(data: NSData) -> (String, Array<User>) {
// We create an empty array of users to populate it
var arrayOfUsers: Array<User> = Array<User>()
var nextCursor: String = "0"
// We serialice the retreived users into an Array of NSDictionaries (We will retrive more that 1 user (array) and each user acts like a dictionary)
var serializationError: NSError?
let users = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &serializationError) as NSDictionary
// If there is a serialization error
if serializationError != nil {
NSLog(serializationError!.description)
} else { // If there is no serialization error.
nextCursor = (users.objectForKey("next_cursor") as Int).description
var userDictionaries = users.objectForKey("users") as Array<NSDictionary>
for (idx, user) in enumerate(userDictionaries) {
var tuitero = self.retrieveUserFrom(user)
arrayOfUsers.append(tuitero)
}
}
return (nextCursor, arrayOfUsers)
}
func retrieveUserFrom(user: NSDictionary) -> User {
var tuitero = User(id_str: user.objectForKey("id_str") as String)
tuitero.name = user.objectForKey("name") as String
tuitero.screen_name = user.objectForKey("screen_name") as String
tuitero.profile_image_url = user.objectForKey("profile_image_url") as String
tuitero.location = user.objectForKey("location") as? String
tuitero.follow_request_sent = user.objectForKey("follow_request_sent") as? Bool
tuitero.favourites_count = user.objectForKey("favourites_count") as Int
tuitero.url = user.objectForKey("url") as? String
tuitero.listed_count = user.objectForKey("listed_count") as Int
tuitero.followers_count = user.objectForKey("followers_count") as Int
tuitero.protected = user.objectForKey("protected") as? Bool
tuitero.verified = user.objectForKey("verified") as? Bool
tuitero.description = user.objectForKey("description") as? String
tuitero.status_id_str = user.objectForKey("id_str") as? String
tuitero.statuses_count = user.objectForKey("statuses_count") as Int
tuitero.friends_count = user.objectForKey("friends_count") as Int
tuitero.following = user.objectForKey("following") as? Bool
tuitero.created_at = user.objectForKey("created_at") as String
return tuitero
}
func retrieveListFrom(data: NSData) -> List {
// We create an empty array of users to populate it
var lista: List = List(id_str: "0")
// We serialice the retreived users into an Array of NSDictionaries (We will retrive more that 1 user (array) and each user acts like a dictionary)
var serializationError: NSError?
let list_info = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &serializationError) as NSDictionary
// If there is a serialization error
if serializationError != nil {
NSLog(serializationError!.description)
} else { // If there is no serialization error.
lista = retrieveListFromDictionary(list_info)
}
return lista
}
func retrieveListsFrom(data: NSData) -> Array<List> {
// We create an empty array of users to populate it
var arrayOfLists: Array<List> = Array<List>()
// We serialice the retreived users into an Array of NSDictionaries (We will retrive more that 1 user (array) and each user acts like a dictionary)
var serializationError: NSError?
let lists = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &serializationError) as Array<NSDictionary>
// If there is a serialization error
if serializationError != nil {
NSLog(serializationError!.description)
} else { // If there is no serialization error.
for (idx, list_info) in enumerate(lists) {
var list = retrieveListFromDictionary(list_info)
arrayOfLists.append(list)
}
}
return arrayOfLists
}
func retrieveListsAndCursorFrom(data: NSData) -> (String, Array<List>) {
// We create an empty array of users to populate it
var arrayOfLists: Array<List> = Array<List>()
var nextCursor: String = "0"
// We serialice the retreived users into an Array of NSDictionaries (We will retrive more that 1 user (array) and each user acts like a dictionary)
var serializationError: NSError?
let lists = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &serializationError) as NSDictionary
// If there is a serialization error
if serializationError != nil {
NSLog(serializationError!.description)
} else { // If there is no serialization error.
nextCursor = (lists.objectForKey("next_cursor") as Int).description
var listDictionaries = lists.objectForKey("lists") as Array<NSDictionary>
for (idx, list) in enumerate(listDictionaries) {
var lista = self.retrieveListFromDictionary(list)
arrayOfLists.append(lista)
}
}
return (nextCursor, arrayOfLists)
}
func retrieveListFromDictionary(dictionary: NSDictionary) -> List {
var list = List(id_str: dictionary.objectForKey("id_str") as String)
list.name = dictionary.objectForKey("name") as String
list.description = dictionary.objectForKey("description") as String
list.member_count = dictionary.objectForKey("member_count") as Int
list.created_at = dictionary.objectForKey("created_at") as String
var user: NSDictionary = dictionary.objectForKey("user") as NSDictionary
list.author_id_str = user.objectForKey("id_str") as String
list.author_screen_name = user.objectForKey("screen_name") as String
list.author_profile_image_url = user.objectForKey("profile_image_url") as String
list.following = user.objectForKey("following") as? Bool
return list
}
} | mit | 3c0a26f14ce9ad3b7057c4715a88ff7f | 49.802985 | 185 | 0.636855 | 5.036401 | false | false | false | false |
blokadaorg/blokada | ios/App/UI/Settings/SettingsFormNoNavView.swift | 1 | 3290 | //
// This file is part of Blokada.
//
// 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 https://mozilla.org/MPL/2.0/.
//
// Copyright © 2020 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import SwiftUI
// Used in big screens mode, where we manage navigation ourselves.
struct SettingsFormNoNavView: View {
@ObservedObject var vm = ViewModels.account
@ObservedObject var tabVM = ViewModels.tab
@ObservedObject var contentVM = ViewModels.content
var body: some View {
Form {
SettingsHeaderView()
Section(header: Text(L10n.accountSectionHeaderPrimary)) {
Button(action: {
self.tabVM.setSection("manage")
}) {
SettingsItemView(
title: L10n.accountActionMyAccount,
image: Image.fAccount,
selected: self.tabVM.isSection("manage")
)
}
if (self.vm.type == .Plus) {
Button(action: {
self.tabVM.setSection("leases")
}) {
SettingsItemView(
title: L10n.webVpnDevicesHeader,
image: Image.fComputer,
selected: self.tabVM.isSection("leases")
)
}
}
Button(action: {
self.tabVM.setSection("logRetention")
}) {
SettingsItemView(
title: L10n.activitySectionHeader,
image: Image.fChart,
selected: self.tabVM.isSection("logRetention")
)
}
}
Section(header: Text(L10n.accountSectionHeaderOther)) {
Button(action: {
self.tabVM.setSection("changeaccount")
}) {
SettingsItemView(
title: L10n.accountActionLogout,
image: Image.fLogout,
selected: self.tabVM.isSection("changeaccount")
)
}
Button(action: {
self.contentVM.showSheet(.Help)
}) {
SettingsItemView(
title: L10n.universalActionSupport,
image: Image.fHelp,
selected: false
)
}
Button(action: {
self.contentVM.openLink(Link.Credits)
}) {
SettingsItemView(
title: L10n.accountActionAbout,
image: Image.fAbout,
selected: false
)
}
}
}
.navigationBarTitle(L10n.mainTabSettings)
.accentColor(Color.cAccent)
}
}
struct SettingsFormNoNavView_Previews: PreviewProvider {
static var previews: some View {
SettingsFormNoNavView()
}
}
| mpl-2.0 | ce05f07fd56d4a265261884dfdce51e9 | 31.564356 | 71 | 0.461538 | 5.418451 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.