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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Flows/OneTap/UI/Components/PXSummaryComposer.swift | 1 | 1671 | import UIKit
struct PXSummaryComposer {
// returns the composed summary items
var summaryItems: [PXOneTapSummaryRowData] {
return generateSummaryItems()
}
// MARK: constants
let isDefaultStatusBarStyle = ThemeManager.shared.statusBarStyle() == .default
let currency = SiteManager.shared.getCurrency()
let textTransparency: CGFloat = 1
// MARK: initialization properties
let amountHelper: PXAmountHelper
let additionalInfoSummary: PXAdditionalInfoSummary?
let selectedCard: PXCardSliderViewModel?
let shouldDisplayChargesHelp: Bool
init(amountHelper: PXAmountHelper,
additionalInfoSummary: PXAdditionalInfoSummary?,
selectedCard: PXCardSliderViewModel?,
shouldDisplayChargesHelp: Bool = false) {
self.amountHelper = amountHelper
self.additionalInfoSummary = additionalInfoSummary
self.selectedCard = selectedCard
self.shouldDisplayChargesHelp = shouldDisplayChargesHelp
}
private func generateSummaryItems() -> [PXOneTapSummaryRowData] {
if selectedCard == nil {
return [purchaseRow(haveDiscount: true)]
}
var internalSummary = [PXOneTapSummaryRowData]()
if shouldDisplayCharges() || shouldDisplayDiscount() {
internalSummary.append(purchaseRow(haveDiscount: false))
}
if shouldDisplayDiscount(), let discRow = discountRow() {
internalSummary.append(discRow)
}
if shouldDisplayCharges() {
internalSummary.append(chargesRow())
}
internalSummary.append(totalToPayRow())
return internalSummary
}
}
| mit | 621b1e9773e5cbe64b91a400062357d4 | 31.134615 | 82 | 0.688809 | 5.141538 | false | false | false | false |
xjmeplws/SapCore | SapCore/SapString.swift | 1 | 2271 | //
// SapString.swift
// SapcORE
//
// Created by huangyawei on 15/10/10.
// Copyright © 2015年 sapze. All rights reserved.
//
import Foundation
import CommonCrypto
public extension String {
//base64
public var base64Encoding: String {
let utf8Str = self.dataUsingEncoding(NSUTF8StringEncoding)
return utf8Str!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.init(rawValue: 0))
}
public var base64Decoding: String {
guard let data = NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions.init(rawValue: 0)) else {
return ""
}
return (NSString(data: data, encoding: NSUTF8StringEncoding) as! String)
}
//md5
public var md5Encoding: String{
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
let hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%x", result[i])
}
result.destroy()
return hash as String
}
//sha1
public var sha1Encoding: String {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)
var digest = [UInt8](count: Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA1(data!.bytes, CC_LONG(data!.length), &digest)
let output = NSMutableString(capacity: Int(CC_SHA1_DIGEST_LENGTH))
for byte in digest {
output.appendFormat("%02x", byte)
}
digest.removeAll()
return output as String
}
//sha256
public var sha256Encoding: String {
let data = self.dataUsingEncoding(NSUTF8StringEncoding)
var digest = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA256(data!.bytes, CC_LONG(data!.length), &digest)
let output = NSMutableString(capacity: Int(CC_SHA256_DIGEST_LENGTH))
for byte in digest {
output.appendFormat("%02x", byte)
}
digest.removeAll()
return output as String
}
} | apache-2.0 | b15827d6c9de093279df71b0238959f1 | 32.865672 | 121 | 0.636684 | 4.263158 | false | false | false | false |
lionheart/LionheartCurrencyTextField | Example/Pods/LionheartExtensions/Pod/Classes/Core/UIColor+LionheartExtensions.swift | 1 | 4439 | //
// Copyright 2016 Lionheart Software LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
import UIKit
/**
`UIColor` extension.
*/
public extension UIColor {
/**
Helper method to instantiate a `UIColor` object any number of ways. E.g.
With integer literals:
```
UIColor(0xF00)
UIColor(0xFF0000)
UIColor(0xFF0000FF)
```
Or string literals:
```
UIColor("f00")
UIColor("FF0000")
UIColor("rgb(255, 0, 0)")
UIColor("rgba(255, 0, 0, 0.15)")
```
Or (preferably), if you want to be a bit more explicit:
```
UIColor(.HEX(0xFF0000))
UIColor(.RGB(255, 0, 0))
UIColor(.RGBA(255, 0, 0, 0.5))
```
If a provided value is invalid, the color will be white with an alpha value of 0.
- parameter color: a `ColorRepresentation`
*/
convenience init(_ color: ColorRepresentation) {
switch color {
case .HEX(let value):
var r: CGFloat!
var g: CGFloat!
var b: CGFloat!
var a: CGFloat!
value.toRGBA(&r, &g, &b, &a)
self.init(red: r, green: g, blue: b, alpha: a)
case .RGB(let r, let g, let b):
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: 1)
case .RGBA(let r, let g, let b, let a):
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a))
case .invalid:
self.init(white: 0, alpha: 0)
}
}
/// Returns a `UIColor` with each color component of `self` lightened by `ratio`.
func lighten(byRatio ratio: CGFloat) -> UIColor {
var R: CGFloat = 0
var B: CGFloat = 0
var G: CGFloat = 0
var A: CGFloat = 0
getRed(&R, green: &G, blue: &B, alpha: &A)
let r = min(R * (1 + ratio), 1)
let g = min(G * (1 + ratio), 1)
let b = min(B * (1 + ratio), 1)
let a = min(A * (1 + ratio), 1)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
/// Returns a `UIColor` with each color component of `self` darkened by `ratio`.
func darken(byRatio ratio: CGFloat) -> UIColor {
var R: CGFloat = 0
var B: CGFloat = 0
var G: CGFloat = 0
var A: CGFloat = 0
getRed(&R, green: &G, blue: &B, alpha: &A)
let r = max(R * (1 - ratio), 0)
let g = max(G * (1 - ratio), 0)
let b = max(B * (1 - ratio), 0)
let a = max(A * (1 - ratio), 0)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
/**
A bool that indicates whether the color is dark.
- Note: Formula for brightness derived from [W3C Techniques For Accessibility Evaluation And Repair Tools](http://www.w3.org/WAI/ER/WD-AERT/#color-contrast), and formula for alpha-blending attributed to [StackOverflow](http://stackoverflow.com/a/746937/39155).
*/
var isDark: Bool {
var R1: CGFloat = 0
var B1: CGFloat = 0
var G1: CGFloat = 0
var A1: CGFloat = 0
let converted = getRed(&R1, green: &G1, blue: &B1, alpha: &A1)
guard converted else {
return false
}
let R = Float(R1)
let G = Float(G1)
let B = Float(B1)
let A = Float(A1)
// Formula derived from here:
// http://www.w3.org/WAI/ER/WD-AERT/#color-contrast
// Alpha blending:
// http://stackoverflow.com/a/746937/39155
let newR: Float = (255 * (1 - A) + 255 * R * A) / 255
let newG: Float = (255 * (1 - A) + 255 * G * A) / 255
let newB: Float = (255 * (1 - A) + 255 * B * A) / 255
let newR1: Float = (newR * 255 * 299)
let newG1: Float = (newG * 255 * 587)
let newB1: Float = (newB * 255 * 114)
return ((newR1 + newG1 + newB1) / 1000) < 200
}
}
| apache-2.0 | 00b1c9320683b4153988132e143046a3 | 30.260563 | 265 | 0.552377 | 3.425154 | false | false | false | false |
qmathe/Confetti | Geometry/GeometryUtilities.swift | 1 | 2831 | //
// Confetti
//
// Created by Quentin Mathé on 02/06/2016.
// Copyright © 2016 Quentin Mathé. All rights reserved.
//
import Foundation
import CoreGraphics
public typealias VectorFloat = CGFloat
/// Identical to CATransform3D
public struct Matrix4 {
public var m11: CGFloat = 0, m12: CGFloat = 0, m13: CGFloat = 0, m14: CGFloat = 0
public var m21: CGFloat = 0, m22: CGFloat = 0, m23: CGFloat = 0, m24: CGFloat = 0
public var m31: CGFloat = 0, m32: CGFloat = 0, m33: CGFloat = 0, m34: CGFloat = 0
public var m41: CGFloat = 0, m42: CGFloat = 0, m43: CGFloat = 0, m44: CGFloat = 0
// MARK: - Initialization
static func identity() -> Matrix4 {
var matrix = Matrix4()
matrix.m11 = 1
matrix.m22 = 1
matrix.m33 = 1
matrix.m44 = 1
return matrix
}
public init() { }
}
public struct Vector3 {
public var x: VectorFloat, y: VectorFloat, z: VectorFloat
// MARK: - Initialization
public init(x: VectorFloat, y: VectorFloat, z: VectorFloat) {
self.x = x
self.y = y
self.z = z
}
}
public struct Vector2: Equatable {
public var x: VectorFloat, y: VectorFloat
// MARK: - Initialization
public init(x: VectorFloat, y: VectorFloat) {
self.x = x
self.y = y
}
}
public struct Extent: Equatable {
public var width: VectorFloat, height: VectorFloat
// MARK: - Initialization
public static var zero: Extent { return Extent(width: 0, height: 0) }
public init(width: VectorFloat, height: VectorFloat) {
self.width = width
self.height = height
}
}
public struct Rect: Equatable {
public var origin: Point, extent: Extent
// MARK: - Initialization
public static var zero: Rect { return Rect(x: 0, y: 0, width: 0, height: 0) }
public init(origin: Point, extent: Extent) {
self.origin = origin
self.extent = extent
}
public init(x: VectorFloat, y: VectorFloat, width: VectorFloat, height: VectorFloat) {
origin = Point(x: x, y: y)
extent = Extent(width: width, height: height)
}
// MARK: - Conveniency
/// Returns whether the given point expressed in the receiver coordinate space is inside it.
public func contains(_ point: Point) -> Bool {
return point.x >= origin.x
&& point.y >= origin.y
&& point.x <= origin.x + extent.width
&& point.y <= origin.y + extent.height
}
}
public func == (lhs: Vector2, rhs: Vector2) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
public func == (lhs: Extent, rhs: Extent) -> Bool {
return lhs.width == rhs.width && lhs.height == rhs.height
}
public func == (lhs: Rect, rhs: Rect) -> Bool {
return lhs.origin == rhs.origin && lhs.extent == rhs.extent
}
public typealias Position = Vector3
public typealias Point = Vector2
public typealias Size = Vector3
public enum Orientation {
case vertical
case horizontal
case none
}
| mit | 239505f4009d65c622b0aac9c2d21c73 | 22.371901 | 93 | 0.653819 | 3.239404 | false | false | false | false |
SASAbus/SASAbus-ios | SASAbus/Controller/intro/IntroParentViewController.swift | 1 | 1171 | import UIKit
class IntroParentViewController: UIViewController, IntroPageViewControllerDelegate {
@IBOutlet weak var pageControl: UIPageControl!
var dataOnly: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
pageControl.currentPageIndicatorTintColor = Color.red
pageControl.pageIndicatorTintColor = UIColor.lightGray
pageControl.numberOfPages = 5
pageControl.currentPage = 0
if dataOnly {
pageControl.isHidden = true
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewController = segue.destination as? IntroViewController {
viewController.introDelegate = self
viewController.dataOnly = dataOnly
}
}
// MARK: - IntroPageViewControllerDelegate
func introPageViewController(didUpdatePageCount count: Int) {
pageControl.numberOfPages = count
}
func introPageViewController(didUpdatePageIndex index: Int, color: UIColor) {
pageControl.currentPage = index
pageControl.currentPageIndicatorTintColor = color
}
}
| gpl-3.0 | 2426f5ee4dc468174077c37bbc503949 | 27.560976 | 84 | 0.672929 | 6.163158 | false | false | false | false |
andresbrun/ABMCircularPieView | ABMCircularPieView/ABMCircularPieView/SurvivalCircularView/SurvivalCircularView.swift | 1 | 2691 | //
// SurvivalCircularView.swift
// DrummerBoy
//
// Created by AndresBrun on 13/09/14.
// Copyright (c) 2014 Brun's Software. All rights reserved.
//
import UIKit
@IBDesignable class SurvivalCircularView: CircularPieProgressView {
@IBInspectable var bgColorSafe: UIColor = UIColor.greenColor().colorWithAlphaComponent(0.5) {
didSet{
setupView()
}
}
@IBInspectable var trackColorSafe: UIColor = UIColor.greenColor() {
didSet{
setupView()
}
}
@IBInspectable var bgColorDanger: UIColor = UIColor.redColor().colorWithAlphaComponent(0.5) {
didSet{
setupView()
}
}
@IBInspectable var trackColorDanger: UIColor = UIColor.redColor() {
didSet{
setupView()
}
}
@IBInspectable var safeZone:CGFloat = 0.5 {
didSet{
setupView()
}
}
override func getPieAngles() -> NSArray
{
return [startAngle, getRelativeAngle(safeZone), endAngle]
}
override func getPieColors() -> NSArray
{
return [trackColorDanger, trackColorSafe]
}
override func getBgPieColors() -> NSArray
{
return [bgColorDanger, bgColorSafe]
}
override func startAngleForProgress (progress: CGFloat) -> CGFloat
{
var minMaskAngle = min(getRelativeAngle(progress),getRelativeAngle(safeZone))
var maxMaskAngle = max(getRelativeAngle(progress),getRelativeAngle(safeZone))
return clockWise ? maxMaskAngle : minMaskAngle
}
override func endAngleForProgress (progress: CGFloat) -> CGFloat
{
var minMaskAngle = min(getRelativeAngle(progress),getRelativeAngle(safeZone))
var maxMaskAngle = max(getRelativeAngle(progress),getRelativeAngle(safeZone))
return clockWise ? minMaskAngle : maxMaskAngle
}
override func createPathWithProgress (progress: CGFloat) -> CGPath
{
var minMaskAngle = min(getRelativeAngle(progress),getRelativeAngle(safeZone))
var maxMaskAngle = max(getRelativeAngle(progress),getRelativeAngle(safeZone))
var path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds))
CGPathAddArc(path,
nil,
CGRectGetMidX(self.bounds),
CGRectGetMidY(self.bounds),
CGRectGetMidX(self.bounds),
clockWise ? maxMaskAngle : minMaskAngle,
clockWise ? minMaskAngle : maxMaskAngle,
clockWise)
CGPathCloseSubpath(path)
return path
}
}
| mit | 5d83fe37ceac4382702d758fe3d85820 | 27.62766 | 97 | 0.625046 | 4.721053 | false | false | false | false |
DerrickQin2853/SinaWeibo-Swift | SinaWeibo/SinaWeibo/Classes/Tool/EmoticonKeyboard/DQEmoticonTools.swift | 1 | 4325 | //
// DQEmoticonTools.swift
// SinaWeibo
//
// Created by admin on 2016/10/8.
// Copyright © 2016年 Derrick_Qin. All rights reserved.
//
import UIKit
//通知key
let KsaveRecentEmoticon = "KsaveRecentEmoticon"
let KSelectEmoticon = "KSelectEmoticon"
//沙盒路径
private let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("recent.plist")
//每页最多有多少个表情
let emoticonPageMaxCount = 20
class DQEmoticonTools: NSObject {
static let sharedTools: DQEmoticonTools = DQEmoticonTools()
func saveRecentEmoticons(emoticon: DQEmoticon) {
// if recentEmoticons.contains(emoticon) {
// guard let index = recentEmoticons.index(of: emoticon) else {
// return
// }
// recentEmoticons.remove(at: index)
// }
for value in recentEmoticons.enumerated() {
if value.element.chs == emoticon.chs && emoticon.type == 0 {
recentEmoticons.remove(at: value.offset)
}
else if value.element.code == emoticon.code && emoticon.type == 1 {
recentEmoticons.remove(at: value.offset)
}
}
recentEmoticons.insert(emoticon, at: 0)
if recentEmoticons.count > 20 {
recentEmoticons.removeLast()
}
allEmoticon[0][0] = recentEmoticons
//存沙盒
NSKeyedArchiver.archiveRootObject(recentEmoticons, toFile: path)
//发通知
NotificationCenter.default.post(name: NSNotification.Name(KsaveRecentEmoticon), object: nil)
}
/// 将模型数组切割成二维数组
private func splitEmoticons(emoticons:[DQEmoticon]) -> [[DQEmoticon]] {
let cellPageCount = (emoticons.count - 1) / emoticonPageMaxCount + 1
var sectionEmoticons = [[DQEmoticon]]()
for i in 0..<cellPageCount {
let loc = i * emoticonPageMaxCount
var len = emoticonPageMaxCount
if loc + len > emoticons.count {
len = emoticons.count - loc
}
let splitedArray = (emoticons as NSArray).subarray(with: NSMakeRange(loc, len))
sectionEmoticons.append(splitedArray as! [DQEmoticon])
}
return sectionEmoticons
}
/// 根据不同的路径返回不同的表情模型数组
private func loadEmoticon(infoName: String) -> [DQEmoticon]{
let infoPath = emoticonBundle.path(forResource: infoName + "/info.plist", ofType: nil)
let dataArray = NSArray(contentsOfFile: infoPath!) as! [[String:Any]]
var emoticonArray = [DQEmoticon]()
for item in dataArray {
let temp = DQEmoticon()
temp.yy_modelSet(with: item)
if let img = temp.png {
temp.imagePath = infoName + "/" + img
}
emoticonArray.append(temp)
}
return emoticonArray
}
//所有的表情数组
lazy var allEmoticon: [[[DQEmoticon]]] = {
return [[self.recentEmoticons],
self.splitEmoticons(emoticons: self.defaultEmoticons),
self.splitEmoticons(emoticons: self.emojiEmoticons),
self.splitEmoticons(emoticons: self.lxhEmoticons)]
}()
//懒加载bundle对象
lazy var emoticonBundle: Bundle = {
let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)
let bundle = Bundle.init(path: path!)!
return bundle
}()
//最近表情数组
lazy var recentEmoticons: [DQEmoticon] = {
if let array = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? [DQEmoticon] {
return array
}
return [DQEmoticon]()
}()
//默认表情数组
lazy var defaultEmoticons: [DQEmoticon] = {
return self.loadEmoticon(infoName: "default")
}()
//emoji表情数组
lazy var emojiEmoticons: [DQEmoticon] = {
return self.loadEmoticon(infoName: "emoji")
}()
//浪小花表情数组
lazy var lxhEmoticons: [DQEmoticon] = {
return self.loadEmoticon(infoName: "lxh")
}()
}
| mit | aa1bf03e307ddc90550b4d5cb1c52154 | 30.18797 | 156 | 0.589682 | 4.513602 | false | false | false | false |
RoverPlatform/rover-ios-beta | Sources/Models/ImageBlock.swift | 2 | 1192 | //
// ImageBlock.swift
// Rover
//
// Created by Sean Rucker on 2018-04-24.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
public struct ImageBlock: Block {
public var background: Background
public var border: Border
public var id: String
public var name: String
public var image: Image
public var insets: Insets
public var opacity: Double
public var position: Position
public var tapBehavior: BlockTapBehavior
public var keys: [String: String]
public var tags: [String]
public var conversion: Conversion?
public init(background: Background, border: Border, id: String, name: String, image: Image, insets: Insets, opacity: Double, position: Position, tapBehavior: BlockTapBehavior, keys: [String: String], tags: [String], conversion: Conversion?) {
self.background = background
self.border = border
self.id = id
self.name = name
self.image = image
self.insets = insets
self.opacity = opacity
self.position = position
self.tapBehavior = tapBehavior
self.keys = keys
self.tags = tags
self.conversion = conversion
}
}
| mit | 0c3091a58906a46a1fdf518eaa64c488 | 30.342105 | 246 | 0.65995 | 4.346715 | false | false | false | false |
iOSTestApps/Typhoon-Swift-Example | PocketForecast/Model/CurrentConditions.swift | 3 | 2076 | ////////////////////////////////////////////////////////////////////////////////
//
// TYPHOON FRAMEWORK
// Copyright 2013, Typhoon Framework Contributors
// All Rights Reserved.
//
// NOTICE: The authors permit you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
public class CurrentConditions : NSObject, NSCoding {
private(set) var summary : String?
private(set) var temperature : Temperature?
private(set) var humidity : String?
private(set) var wind : String?
private(set) var imageUri : String?
public init(summary : String, temperature : Temperature, humidity : String, wind : String, imageUri : String) {
self.summary = summary
self.temperature = temperature
self.humidity = humidity
self.wind = wind
self.imageUri = imageUri
}
public required init(coder : NSCoder) {
self.summary = coder.decodeObjectForKey("summary") as? String
self.temperature = coder.decodeObjectForKey("temperature") as? Temperature
self.humidity = coder.decodeObjectForKey("humidity") as? String
self.wind = coder.decodeObjectForKey("wind") as? String
self.imageUri = coder.decodeObjectForKey("imageUri") as? String
}
public func longSummary() -> String {
return String(format: "%@. %@.", self.summary!, self.wind!)
}
public override var description: String {
return String(format: "Current Conditions: summary=%@, temperature=%@", self.summary!, self.temperature!)
}
public func encodeWithCoder(coder : NSCoder) {
coder.encodeObject(self.summary!, forKey:"summary")
coder.encodeObject(self.temperature!, forKey:"temperature")
coder.encodeObject(self.humidity!, forKey:"humidity")
coder.encodeObject(self.wind!, forKey:"wind")
coder.encodeObject(self.imageUri!, forKey:"imageUri")
}
} | apache-2.0 | 26fc2eca671ca4608bed1f7110e305b1 | 37.462963 | 115 | 0.615607 | 4.966507 | false | false | false | false |
Cin316/X-Schedule | X Schedule Widget/WidgetDataViewController.swift | 1 | 3656 | //
// WidgetDataViewController.swift
// X Schedule Widget
//
// Created by Nicholas Reichert on 4/8/15.
// Copyright (c) 2015 Nicholas Reichert.
//
import UIKit
import NotificationCenter
import XScheduleKit
class WidgetDataViewController: ScheduleViewController, NCWidgetProviding {
@IBOutlet weak var emptyLabel: UILabel!
var lastUpdated = Date()
override func viewDidLoad() {
super.viewDidLoad()
//Schedule date is 8 hours in the future so the schedule displays the next day's classes in the evenings.
scheduleDate = Date().addingTimeInterval(60*60*8)
if #available(iOSApplicationExtension 10.0, *) {
extensionContext?.widgetLargestAvailableDisplayMode = .expanded
}
}
override func refreshSchedule() {
// Download today's schedule from the St. X website.
XScheduleManager.getScheduleForDate(scheduleDate,
completionHandler: { (schedule: Schedule) in
//Execute code in main thread.
DispatchQueue.main.async {
self.handleCompletionOfDownload(schedule)
}
}
)
}
private func handleCompletionOfDownload(_ schedule: Schedule) {
displayScheduleInTable(schedule)
displayEmptyLabelForSchedule(schedule)
}
private func displayScheduleInTable(_ schedule: Schedule) {
//Display schedule items in table.
if let tableController = children[0] as? ScheduleTableController {
tableController.displaySchedule(schedule)
if #available(iOSApplicationExtension 10.0, *) {
} else {
correctlySizeWidget(tableController.tableView)
}
hideIfEmpty(tableController, schedule: schedule)
}
}
private func correctlySizeWidget(_ tableView: UITableView) {
if (tableView.contentSize.height > self.emptyLabel.frame.height){
self.preferredContentSize = tableView.contentSize
} else {
self.preferredContentSize = self.emptyLabel.frame.size
}
}
private func displayEmptyLabelForSchedule(_ schedule: Schedule) {
if (schedule.items.isEmpty) {
self.emptyLabel.text = "No classes"
} else {
self.emptyLabel.text = ""
}
}
private func hideIfEmpty(_ tableController: UIViewController, schedule: Schedule) {
//Hide schedule table lines if schedule is blank.
if (schedule.items.isEmpty) {
tableController.view.isHidden = true
}
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
//Update every 3 hours.
let secondsSinceLastUpdate = lastUpdated.timeIntervalSince(Date())
if (secondsSinceLastUpdate > 60*60*3){
completionHandler(NCUpdateResult.newData)
} else {
completionHandler(NCUpdateResult.noData)
}
}
func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsets.init(top: 0, left: 0, bottom: -1, right: 0)
}
@available(iOSApplicationExtension 10.0, *)
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
if let tableController = children[0] as? ScheduleTableController {
if (activeDisplayMode == .expanded) {
correctlySizeWidget(tableController.tableView)
} else {
self.preferredContentSize = maxSize
}
}
}
}
| mit | 4384c04f1fef12f52d43d8b2e7d835fb | 35.19802 | 118 | 0.638129 | 5.306241 | false | false | false | false |
LubosPlavucha/CocoaGlue | CocoaGlue/classes/BLabel.swift | 1 | 1759 | // Created by lubos plavucha on 02/12/14.
// Copyright (c) 2014 Acepricot. All rights reserved.
//
import Foundation
import UIKit
open class BLabel: UILabel, BControl {
fileprivate weak var object: NSObject!
fileprivate var keyPath: String!
fileprivate var bounded = false;
open var validationFailed = false
open var delegates: [BControlDelegate] = []
deinit {
delegates.removeAll()
}
open func bind(_ object: NSObject, keyPath: String) -> BLabel {
if bounded {
return self
}
self.object = object
self.keyPath = keyPath
self.object.addObserver(self, forKeyPath: keyPath, options: [.new, .old], context: nil)
// set value immediately when being bound
setValueFromModel(self.object.value(forKeyPath: keyPath) as? String)
self.bounded = true
return self
}
open func unbind() {
// ui component needs to be unbound before managed object becomes invalid
if bounded {
self.object.removeObserver(self, forKeyPath: keyPath)
bounded = false
}
}
func setValueFromModel(_ value: String?) {
self.text = value != nil ? value : ""
}
// func setValueFromComponent(value: String?) {
//
// }
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if self.object.isEqual(object) {
setValueFromModel(change?[NSKeyValueChangeKey.newKey] as? String)
}
}
public func validate() {
}
}
| mit | 9f1e5358da8891bafc3b531cc2e7dbb7 | 22.453333 | 156 | 0.581012 | 4.859116 | false | false | false | false |
things-nyc/mapthethings-ios | MapTheThings/Bluetooth.swift | 1 | 25518 | //
// Bluetooth.swift
// MapTheThings
//
// Created by Frank on 2016/7/13.
// Copyright © 2016 The Things Network New York. All rights reserved.
//
import Foundation
import CoreBluetooth
import ReactiveSwift
/*
Every bluetooth peripheral has a UUID.
The Bluetooth singleton object maintains a dictionary of nodes indexed by UUID. The values
are instances of LoraNode, which (currently) may be either a BluetoothNode or a FakeBluetoothNode.
When Bluetooth starts, it uses either a list of known peripherals or starts a scan of peripherals.
When a peripheral is discovered, it gets added to the Bluetooth.nodes dictionary and a Device object
representing its state is added to AppState.bluetooth dictionary (also indexed by same UUID).
At this point, we have not established a bluetooth connection to any device.
When AppState.connectToDevice is assigned a NSUUID, an observer on Bluetooth object initiates
a connect operation on the peripheral identified by state.activeDeviceID.
*/
/*
"Device Name" type="org.bluetooth.characteristic.gap.device_name" uuid="2A00"
"Name": utf8s
"org.bluetooth.characteristic.manufacturer_name_string" uuid="2A29" name="Manufacturer Name String"
"Manufacturer Name": utf8s
type="org.bluetooth.characteristic.firmware_revision_string" uuid="2A26" name="Firmware Revision String"
"Firmware Revision": utf8s
*/
let loraService = CBUUID(string: "00001830-0000-1000-8000-00805F9B34FB")
let deviceInfoService = CBUUID(string: "0000180A-0000-1000-8000-00805F9B34FB")
let batteryService = CBUUID(string: "0000180F-0000-1000-8000-00805F9B34FB")
let logService = CBUUID(string: "00001831-0000-1000-8000-00805F9B34FB")
let nodeServices : [CBUUID]? = [loraService, deviceInfoService, batteryService, logService]
let batteryLevelCharacteristic = CBUUID(string: "00002A19-0000-1000-8000-00805F9B34FB")
let logStringCharacteristic = CBUUID(string: "00002AD6-0000-1000-8000-00805F9B34FB")
let loraCommandCharacteristic = CBUUID(string: "00002AD0-0000-1000-8000-00805F9B34FB")
let loraWritePacketCharacteristic = CBUUID(string: "00002AD1-0000-1000-8000-00805F9B34FB")
let loraWritePacketWithAckCharacteristic =
CBUUID(string: "00002ADB-0000-1000-8000-00805F9B34FB")
let loraDevAddrCharacteristic = CBUUID(string: "00002AD2-0000-1000-8000-00805F9B34FB")
let loraNwkSKeyCharacteristic = CBUUID(string: "00002AD3-0000-1000-8000-00805F9B34FB")
let loraAppSKeyCharacteristic = CBUUID(string: "00002AD4-0000-1000-8000-00805F9B34FB")
let loraAppKeyCharacteristic = CBUUID(string: "00002AD7-0000-1000-8000-00805F9B34FB")
let loraAppEUICharacteristic = CBUUID(string: "00002AD8-0000-1000-8000-00805F9B34FB")
let loraDevEUICharacteristic = CBUUID(string: "00002AD9-0000-1000-8000-00805F9B34FB")
let loraSpreadingFactorCharacteristic =
CBUUID(string: "00002AD5-0000-1000-8000-00805F9B34FB")
let transmitResultCharacteristic = CBUUID(string: "00002ADA-0000-1000-8000-00805F9B34FB")
let loraNodeCharacteristics : [CBUUID]? = [
loraCommandCharacteristic,
loraWritePacketCharacteristic,
loraWritePacketWithAckCharacteristic,
loraDevAddrCharacteristic,
loraNwkSKeyCharacteristic,
loraAppSKeyCharacteristic,
loraSpreadingFactorCharacteristic,
transmitResultCharacteristic,
loraAppKeyCharacteristic,
loraAppEUICharacteristic,
loraDevEUICharacteristic,
]
extension UInt16 {
var data: Data {
var int: UInt16 = self
let buffer = UnsafeBufferPointer(start: &int, count: 1)
return Data(buffer: buffer)
}
}
extension UInt8 {
var data: Data {
var int: UInt8 = self
let buffer = UnsafeBufferPointer(start: &int, count: 1)
return Data(buffer: buffer)
}
}
extension CBCharacteristic {
var nsUUID : UUID {
var s = self.uuid.uuidString
if s.lengthOfBytes(using: String.Encoding.utf8)==4 {
s = "0000\(s)-0000-1000-8000-00805F9B34FB"
}
return UUID(uuidString: s)!
}
}
func readInteger<T : Integer>(_ data : Data, start : Int) -> T {
var d : T = 0
(data as NSData).getBytes(&d, range: NSRange(location: start, length: MemoryLayout<T>.size))
return d
}
func storeLoraSeq(_ old_state: AppState, device: UUID, ble_seq: UInt8, lora_seq: UInt32) -> AppState {
debugPrint("storeLoraSeq \(lora_seq) for ble: \(ble_seq)")
var state = old_state
// Find transmission with this device+ble_seq
for (index, tx) in state.map.transmissions.enumerated() {
if let tx_ble_seq = tx.ble_seq,
let tx_dev = tx.device, (ble_seq==tx_ble_seq && device==tx_dev as UUID && tx.lora_seq==nil) {
// There could be the same device+ble with lora_seq already set
// - because BLE seq numbers repeat - hence lora_seq nil check.
// TODO: Not good enough - could have failed to receive lora seq.
// We should assume most recent is the one we just got.
state.map.transmissions[index].lora_seq = lora_seq
if let objID = state.map.transmissions[index].objectID {
state.syncState.recordLoraToObject.append((objID, lora_seq))
}
else {
debugPrint("No object ID to record lora seq no")
}
}
}
return state
}
func setAppStateDeviceAttribute(_ id: UUID, name: String?, characteristic: CBCharacteristic, value: Data, error: NSError?) {
let s = String(data: value, encoding: String.Encoding.utf8)
debugPrint("peripheral didUpdateValueForCharacteristic", name ?? "-", characteristic, s?.description ?? "-", error?.description ?? "-")
updateAppState { (old) -> AppState in
if var dev = old.bluetooth[id] {
var state = old
switch characteristic.uuid {
case loraDevAddrCharacteristic:
dev.devAddr = value
case loraNwkSKeyCharacteristic:
dev.nwkSKey = value
case loraAppSKeyCharacteristic:
dev.appSKey = value
case loraAppKeyCharacteristic:
dev.appKey = value
case loraAppEUICharacteristic:
dev.appEUI = value
case loraDevEUICharacteristic:
dev.devEUI = value
case transmitResultCharacteristic:
// format ble_seq error lora_seq
assert(value.count==(MemoryLayout<UInt8>.size+MemoryLayout<UInt8>.size+MemoryLayout<UInt16>.size+MemoryLayout<UInt32>.size))
debugPrint("TX result: \(value)")
let result_format:UInt8 = readInteger(value, start: 0)
if result_format==1 {
let ble_seq:UInt8 = readInteger(value, start: MemoryLayout<UInt8>.size)
let error:UInt16 = readInteger(value, start: 2*MemoryLayout<UInt8>.size)
let lora_seq:UInt32 = readInteger(value, start: 2*MemoryLayout<UInt8>.size+MemoryLayout<UInt16>.size)
if error==0 {
state = storeLoraSeq(state, device: id, ble_seq: ble_seq, lora_seq: lora_seq)
}
else {
debugPrint("Received tx error result: \(error)")
}
}
else {
debugPrint("Received unknown result format: \(result_format)")
}
case batteryLevelCharacteristic:
dev.battery = readInteger(value, start: 0)
case logStringCharacteristic:
let msg = String(data: value, encoding: String.Encoding.utf8)!
dev.log.append(msg)
case loraSpreadingFactorCharacteristic:
let sf:UInt8 = readInteger(value, start: 0)
dev.spreadingFactor = sf
default:
return old // No changes
}
state.bluetooth[id] = dev
return state
}
else {
debugPrint("Should find \(id) in device list")
return old
}
}
}
public protocol LoraNode {
var identifier : UUID { get }
func requestConnection(_ central: CBCentralManager)
func onConnect()
func requestDisconnect(_ central: CBCentralManager)
func onDisconnect()
func sendPacket(_ data : Data) -> Bool
func sendPacketWithAck(_ data : Data) -> UInt8? // ble sequence number, or null on failure or unavailable
func setSpreadingFactor(_ sf: UInt8) -> Bool
func assignOTAA(_ appKey: Data, appEUI: Data, devEUI: Data)
}
func markConnectStatus(_ id: UUID, connected: Bool) {
updateAppState { (old) -> AppState in
// assert(dev.identifier.isEqual(peripheral.identifier), "Device id should be same as peripheral id")
var state = old
state.bluetooth[id]?.connected = connected
return state
}
}
func observeSpreadingFactor(_ device: LoraNode) -> Disposable? {
return appStateObservable.observeValues { update in
let oldDev = update.old.bluetooth[device.identifier]
if let dev = update.new.bluetooth[device.identifier],
let sf = dev.spreadingFactor,
oldDev==nil || oldDev!.spreadingFactor==nil || sf != oldDev!.spreadingFactor! {
_ = device.setSpreadingFactor(sf)
}
}
}
open class FakeBluetoothNode : NSObject, LoraNode {
let uuid: UUID
var lora_seq: UInt32 = 100;
var ble_seq: UInt8 = 1 // Rolling sequence number that lets us link ack messages to sends
var sfDisposer: Disposable?
override public init() {
self.uuid = UUID()
super.init()
self.sfDisposer = observeSpreadingFactor(self)
}
open var identifier : UUID {
return self.uuid
}
open func requestConnection(_ central: CBCentralManager) {
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).asyncAfter(deadline: DispatchTime.now() + Double(Int64(2 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {
self.onConnect()
});
}
open func onConnect() {
markConnectStatus(self.identifier, connected: true)
}
open func requestDisconnect(_ central: CBCentralManager) {
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).asyncAfter(deadline: DispatchTime.now() + Double(Int64(2 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {
self.onDisconnect()
});
}
open func onDisconnect() {
markConnectStatus(self.identifier, connected: false)
}
open func setSpreadingFactor(_ sf: UInt8) -> Bool {
debugPrint("Set spreading factor: \(sf)")
return true
}
open func assignOTAA(_ appKey: Data, appEUI: Data, devEUI: Data) {
debugPrint("Assigning OTAA")
}
open func sendPacket(_ data : Data) -> Bool {
debugPrint("Sending fake packet: \(data)")
return true
}
open func sendPacketWithAck(_ data: Data) -> UInt8? {
let ble_seq = self.ble_seq
self.ble_seq += 1
let lora_seq = self.lora_seq
self.lora_seq += 1
var tracked = NSData(data: ble_seq.data) as Data
tracked.append(data)
_ = sendPacket(tracked)
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).asyncAfter(deadline: DispatchTime.now() + Double(Int64(10 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {
debugPrint("Writing response sequence no \(self.ble_seq)")
updateAppState { (old) -> AppState in
return storeLoraSeq(old, device: self.uuid, ble_seq: ble_seq, lora_seq: lora_seq)
}
});
return ble_seq
}
}
open class BluetoothNode : NSObject, LoraNode, CBPeripheralDelegate {
let peripheral : CBPeripheral
var characteristics : [String: CBCharacteristic] = [:]
var ble_seq: UInt8 = 1
var sfDisposer: Disposable?
public init(peripheral : CBPeripheral) {
self.peripheral = peripheral
super.init()
self.peripheral.delegate = self
self.sfDisposer = observeSpreadingFactor(self)
}
open var identifier : UUID {
return self.peripheral.identifier
}
open func requestConnection(_ central: CBCentralManager) {
central.connect(self.peripheral, options: nil)
}
open func onConnect() {
self.peripheral.discoverServices(nodeServices)
markConnectStatus(self.identifier, connected: true)
}
open func requestDisconnect(_ central: CBCentralManager) {
central.cancelPeripheralConnection(self.peripheral)
}
open func onDisconnect() {
self.characteristics = [:]
self.ble_seq = 1
markConnectStatus(self.identifier, connected: false)
}
open func sendPacket(_ data : Data) -> Bool {
if let characteristic = self.characteristics[loraWritePacketCharacteristic.uuidString] {
debugPrint("Sending packet", data)
peripheral.writeValue(data, for: characteristic, type: CBCharacteristicWriteType.withResponse)
return true
}
else {
debugPrint("Unable to send packet - Write Packet characteristic unavailable.")
return false
}
}
open func sendPacketWithAck(_ data: Data) -> UInt8? {
if let characteristic = self.characteristics[loraWritePacketWithAckCharacteristic.uuidString] {
debugPrint("Sending packet with ack", data)
let ble_seq = self.ble_seq
self.ble_seq += 1
// Prepend ble_seq to actual data. ble_seq will be included in tx result report.
var tracked = NSData(data: ble_seq.data) as Data
tracked.append(data)
peripheral.writeValue(tracked, for: characteristic,
type: CBCharacteristicWriteType.withResponse)
return ble_seq
}
else {
debugPrint("Write Packet with ack characteristic unavailable.")
return nil
}
}
open func assignOTAA(_ appKey: Data, appEUI: Data, devEUI: Data) {
if let charAppKey = self.characteristics[loraAppKeyCharacteristic.uuidString],
let charAppEUI = self.characteristics[loraAppEUICharacteristic.uuidString],
let charDevEUI = self.characteristics[loraDevEUICharacteristic.uuidString] {
peripheral.writeValue(appKey, for: charAppKey, type: CBCharacteristicWriteType.withResponse)
peripheral.writeValue(appEUI, for: charAppEUI, type: CBCharacteristicWriteType.withResponse)
peripheral.writeValue(devEUI, for: charDevEUI, type: CBCharacteristicWriteType.withResponse)
}
}
open func setSpreadingFactor(_ sf : UInt8) -> Bool {
if let characteristic = self.characteristics[loraSpreadingFactorCharacteristic.uuidString] {
debugPrint("Setting SF", sf)
peripheral.writeValue(sf.data, for: characteristic, type: CBCharacteristicWriteType.withResponse)
return true
}
else {
debugPrint("Unable to set SF - Spreading Factor characteristic unavailable.")
return false
}
}
@objc open func peripheralDidUpdateName(_ peripheral: CBPeripheral) {
debugPrint("peripheralDidUpdateName", peripheral.name ?? "-")
}
@objc open func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
debugPrint("peripheral didModifyServices", peripheral.name ?? "-", invalidatedServices)
}
@objc open func peripheralDidUpdateRSSI(_ peripheral: CBPeripheral, error: Error?) {
debugPrint("peripheralDidUpdateRSSI", peripheral.name ?? "-", error ?? "-")
}
@objc open func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
debugPrint("peripheral didReadRSSI", peripheral.name ?? "-", RSSI, error ?? "-")
}
@objc open func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
debugPrint("peripheral didDiscoverServices", peripheral.name ?? "-", peripheral.services ?? "-", error ?? "-")
peripheral.services?.forEach({ (service) in
switch service.uuid {
case loraService:
peripheral.discoverCharacteristics(loraNodeCharacteristics, for: service)
case logService:
peripheral.discoverCharacteristics([logStringCharacteristic], for: service)
default:
peripheral.discoverCharacteristics(nil, for: service)
}
})
}
@objc open func peripheral(_ peripheral: CBPeripheral, didDiscoverIncludedServicesFor service: CBService, error: Error?) {
debugPrint("peripheral didDiscoverIncludedServicesForService", peripheral.name ?? "-", service, error ?? "-")
}
@objc open func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
debugPrint("peripheral didDiscoverCharacteristicsForService", peripheral.name ?? "-", service, service.characteristics ?? "-", error ?? "-")
service.characteristics!.forEach { (characteristic) in
debugPrint("Set characteristic: ", characteristic.nsUUID.uuidString)
self.characteristics[characteristic.nsUUID.uuidString] = characteristic
switch characteristic.uuid {
case loraDevAddrCharacteristic,
loraAppSKeyCharacteristic,
loraNwkSKeyCharacteristic,
loraAppKeyCharacteristic,
loraAppEUICharacteristic,
loraDevEUICharacteristic,
loraSpreadingFactorCharacteristic:
peripheral.readValue(for: characteristic)
case batteryLevelCharacteristic,
transmitResultCharacteristic,
logStringCharacteristic:
debugPrint("Subscribing to characteristic", characteristic)
peripheral.setNotifyValue(true, for: characteristic)
// case loraCommandCharacteristic:
// let command : UInt16 = 500
// debugPrint("Writing to characteristic", characteristic, command)
// peripheral.writeValue(command.data, forCharacteristic: characteristic,
// type:CBCharacteristicWriteType.WithResponse)
default:
peripheral.readValue(for: characteristic)
}
}
}
@objc open func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if let value = characteristic.value {
setAppStateDeviceAttribute(peripheral.identifier, name: peripheral.name, characteristic: characteristic, value: value, error: error as NSError?)
}
}
@objc open func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
debugPrint("peripheral didWriteValueForCharacteristic", peripheral.name ?? "-", characteristic, error ?? "-")
}
@objc open func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
debugPrint("peripheral didUpdateNotificationStateForCharacteristic", peripheral.name ?? "-", characteristic, error ?? "-")
}
@objc open func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) {
debugPrint("peripheral didDiscoverDescriptorsForCharacteristic", peripheral.name ?? "-", characteristic, error ?? "-")
}
@objc open func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) {
debugPrint("peripheral didUpdateValueForDescriptor", peripheral.name ?? "-", descriptor, error ?? "-")
}
@objc open func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
debugPrint("peripheral didWriteValueForDescriptor", peripheral.name ?? "-", descriptor, error ?? "-")
}
}
open class Bluetooth : NSObject, CBCentralManagerDelegate {
let queue = DispatchQueue(label: "Bluetooth", attributes: [])
var central : CBCentralManager!
var nodes : [UUID: LoraNode] = [:]
var disposeObserver: Disposable?
public init(savedIdentifiers: [UUID]) {
super.init()
self.central = CBCentralManager.init(delegate: self, queue: self.queue,
options: [CBCentralManagerOptionRestoreIdentifierKey: "MapTheThingsManager"])
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double((Int64)(5 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {
let knownPeripherals =
self.central.retrievePeripherals(withIdentifiers: savedIdentifiers)
if !knownPeripherals.isEmpty {
knownPeripherals.forEach({ (p) in
// self.central!.connectPeripheral(p, options: nil)
self.centralManager(self.central, didDiscover: p, advertisementData: [:], rssi: 0)
})
}
else {
self.rescan()
}
})
self.disposeObserver = appStateObservable.observeValues({ update in
if let activeID = update.new.viewDetailDeviceID,
let node = self.nodes[activeID] {
if stateValChanged(update, access: {$0.connectToDevice}) {
node.requestConnection(self.central)
}
if stateValChanged(update, access: {$0.disconnectDevice}) {
node.requestDisconnect(self.central)
}
}
if stateValChanged(update, access: {$0.assignProvisioning}) {
if let (_, deviceID) = update.new.assignProvisioning,
let node = self.nodes[deviceID],
let device = update.new.bluetooth[deviceID],
let appKey = device.appKey,
let appEUI = device.appEUI,
let devEUI = device.devEUI {
node.assignOTAA(appKey, appEUI: appEUI, devEUI: devEUI)
}
}
})
}
open func addFakeNode() -> Void {
let fake = FakeBluetoothNode()
discoveredNode(fake, name: fake.identifier.uuidString)
}
open func rescan() {
self.central.scanForPeripherals(withServices: nodeServices, options: nil)
}
var nodeIdentifiers : [UUID] {
return Array(nodes.keys)
}
open func node(_ id: UUID) -> LoraNode? {
return nodes[id]
}
@objc open func centralManagerDidUpdateState(_ central: CBCentralManager) {
debugPrint("centralManagerDidUpdateState", central.state)
}
@objc open func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
debugPrint("centralManager willRestoreState")
}
@objc open func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
debugPrint("centralManager didDiscoverPeripheral", peripheral.name ?? "-", advertisementData, RSSI)
if nodes[peripheral.identifier]==nil {
let node = BluetoothNode(peripheral: peripheral)
discoveredNode(node, name: peripheral.name)
}
else {
debugPrint("Repeated call to didDiscoverPeripheral ignored.")
}
}
@objc open func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
debugPrint("centralManager didConnectPeripheral", peripheral.name ?? "-")
if let node = nodes[peripheral.identifier] {
node.onConnect()
}
}
open func discoveredNode(_ node: LoraNode, name: String?) {
self.nodes[node.identifier] = node
updateAppState { (old) -> AppState in
var state = old
let devName = name==nil ? "<UnknownDevice>" : name!
var dev = Device(uuid: node.identifier, name: devName)
if let known = state.bluetooth[node.identifier] {
dev = known
assert(dev.identifier == node.identifier, "Device id should be same as peripheral id")
}
dev.connected = false // Just discovered, not yet connected
state.bluetooth[node.identifier] = dev
return state
}
}
@objc open func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
debugPrint("centralManager didFailToConnectPeripheral", peripheral.name ?? "-", error ?? "-")
}
@objc open func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
// Ensure that when bluetooth device is disconnected, the device.connected = false
debugPrint("centralManager didDisconnectPeripheral", peripheral.name ?? "-", error ?? "-")
if let node = self.nodes[peripheral.identifier] {
node.onDisconnect()
}
}
}
| mit | 070adf057d9a78e9763159b52e15f71f | 42.544369 | 176 | 0.638907 | 4.636083 | false | false | false | false |
sun409377708/swiftDemo | SinaSwiftPractice/SinaSwiftPractice/Classes/View/Discover/View/JQSearchTextView.swift | 1 | 2274 | //
// JQSearchTextView.swift
// SinaSwiftPractice
//
// Created by maoge on 16/11/12.
// Copyright © 2016年 maoge. All rights reserved.
//
import UIKit
class JQSearchTextView: UIView {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var cancelBtn: UIButton!
@IBOutlet weak var layoutConstant: NSLayoutConstraint!
class func loadSearchText() -> JQSearchTextView {
return UINib.init(nibName: "SearchTextView", bundle: nil).instantiate(withOwner: nil, options: nil).last as! JQSearchTextView
}
override func awakeFromNib() {
// 1. 设置view自身大小
self.bounds.size.width = UIScreen.main.bounds.size.width
// 2. 设置背景色为透明色, 避免button的视图显示白色
self.backgroundColor = UIColor.clear
// 3. 设置textField背景色
textField.borderStyle = .none
textField.backgroundColor = UIColor.lightGray
// 4. 设置左视图
self.leftview.frame = CGRect(x: 0, y: 0, width: self.bounds.height, height: self.bounds.height)
textField.leftView = leftview
textField.leftViewMode = .always
// 5. 设置圆角
textField.layer.cornerRadius = 10
textField.layer.masksToBounds = true
// textField.layer.borderWidth = 1
// textField.layer.borderColor = UIColor.red.cgColor
}
@IBAction func textBeginChange(_ sender: UITextField) {
layoutConstant.constant = cancelBtn.bounds.width + 5
UIView.animate(withDuration: 0.5) {
self.layoutIfNeeded()
}
}
@IBAction func cancelBtnClick(_ sender: UIButton) {
layoutConstant.constant = 0
UIView.animate(withDuration: 0.25) {
self.layoutIfNeeded()
}
self.textField.resignFirstResponder()
}
// MARK: - 懒加载控件
private lazy var leftview: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
imageView.contentMode = .center
return imageView
}()
}
| mit | 391dbaeb0b6160bf2f9879c4b416b5e7 | 23.829545 | 133 | 0.589474 | 4.739696 | false | false | false | false |
habr/ChatTaskAPI | Session.swift | 1 | 2809 | //
// AppDelegate.swift
// Chat
//
// Created by Kobalt on 12.01.16.
// Copyright © 2016 Kobalt. All rights reserved.
//
import Foundation
class Session: NSObject {
// MARK: - Types
typealias Success = (NSData?) -> Void
typealias Failure = (ErrorType) -> Void
// MARK: - Class Properties
static let instance = Session()
// MARK: - Properties
private let baseURL = NSURL(string: "http://52.192.101.131")!
private let token = "5694cde0-d2dc-4cc4-b2d5-7506ac1f0216"
private var session = NSURLSession(configuration: .defaultSessionConfiguration())
// MARK: - Initialization
private override init() {
super.init()
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Requests GET
func GET(path: String, parameters: [String: String]?, success: Success?,
failure: Failure?) -> NSURLSessionDataTask {
let request = requestWithPath(path, method: "GET", parameters: parameters)
return GET(request, success: success, failure: failure)
}
func GET(URL: NSURL, parameters: [String: String]?, success: Success?,
failure: Failure?) -> NSURLSessionDataTask {
let request = requestWithURL(URL, method: "GET", parameters: parameters)
return GET(request, success: success, failure: failure)
}
private func GET(request: NSURLRequest, success: Success?, failure: Failure?) -> NSURLSessionDataTask {
let task = session.dataTaskWithRequest(request) { (data, _, error) -> Void in
guard error == nil else {
failure?(error!)
return
}
success?(data)
}
task.resume()
return task
}
// MARK: - Creating Request
private func requestWithPath(path: String, method: String,
parameters: [String: String]?) -> NSURLRequest {
let URL = baseURL.URLByAppendingPathComponent(path)
return requestWithURL(URL, method: method, parameters: parameters)
}
private func requestWithURL(var URL: NSURL, method: String,
parameters: [String: String]?) -> NSURLRequest {
if var actualParameters = parameters {
var parametersString = "?"
actualParameters["session"] = token
for (parameter, value) in actualParameters {
parametersString += parameter + "=" + value + "&"
}
parametersString.removeAtIndex(parametersString.endIndex.predecessor())
if let newURL = NSURL(string: URL.absoluteString + parametersString) {
URL = newURL
}
}
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = method
return request
}
}
| mit | e906ff70bf9308521564f5a3955106f6 | 30.550562 | 107 | 0.60114 | 4.833046 | false | false | false | false |
eaheckert/Tournament | Tournament/Tournament/ViewControllers/TTournamentListVC.swift | 1 | 7715 | //
// TTournamentListVC.swift
// Tournament
//
// Created by Eugene Heckert on 8/5/15.
// Copyright (c) 2015 Eugene Heckert. All rights reserved.
//
import Foundation
import Parse
class TTournamentListVC: UIViewController, UITableViewDataSource, UITableViewDelegate
{
//MARK: Variables
@IBOutlet weak var tableView: UITableView!
private var shouldRefreshOnReturn: Bool = false
private var respondingToTouch: Bool = false
private var firstTime: Bool = true
private var tournaments: NSMutableArray = NSMutableArray()
private var selectedTournament: Tournament = Tournament()
//MARK: View Controller Method
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
let plusImage = UIImage(named: "white_plus")?.imageWithRenderingMode(.AlwaysOriginal)
let barButton = UIBarButtonItem(image: plusImage, style: UIBarButtonItemStyle.Plain, target: self, action: "onCreateTournamentAction")
self.parentViewController?.navigationItem.rightBarButtonItem = barButton
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
//Check to see if LoginVC was displayed if so refreash data
if self.shouldRefreshOnReturn || firstTime
{
self.shouldRefreshOnReturn = false
self.firstTime = false
self.getTournamentList()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "To Single Elimination Bracket Segue"
{
print("Segue")
if let vc = segue.destinationViewController as? TBracketVC
{
vc.selectedTournament = selectedTournament
}
}
}
override func viewDidDisappear(animated: Bool)
{
super.viewDidDisappear(animated)
respondingToTouch = false
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Custom Methods
func getTournamentList()
{
//Check to see if the user has a username
//If not load loginVC
let currentUser = User.currentUser()
if currentUser != nil
{
tournaments.removeAllObjects()
let query = PFQuery(className: "Tournament")
let username = currentUser?.username
query.whereKey("createdBy", equalTo:username!)
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil
{
print("objects: ", objects)
for var i = 0; i < objects?.count; i++
{
if let tempTour = objects?[i] as? Tournament
{
self.tournaments.addObject(tempTour)
}
}
self.tableView.reloadData()
}
else
{
print("Error: \(error!) \(error!.userInfo)")
}
}
}
else
{
print("No userName")
//If there is no user name we know there is no user.
//So we present the login view controller.
//It is presented as a Model since the user can't use the app without
//being a regisited user.
let storyboard = UIStoryboard(name: "Login", bundle: nil)
let loginVC = storyboard.instantiateViewControllerWithIdentifier("TLoginVC") as! TLoginVC
self.navigationController?.presentViewController(loginVC, animated: true, completion: { () -> Void in
//mark that the LoginVC is going to be displayed so that when we return the data gets refreshed.
self.shouldRefreshOnReturn = true
})
}
}
func onCreateTournamentAction()
{
let createVC = self.storyboard!.instantiateViewControllerWithIdentifier("TCreateTournamentVC") as! TCreateTournamentVC
//Since we might be adding a new tournament we need to refresh the list when the user returns to this view.
self.shouldRefreshOnReturn = true
self.navigationController?.pushViewController(createVC, animated: true)
}
//MARK: UITableView Delegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return tournaments.count
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
return 31.0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let header = tableView.dequeueReusableCellWithIdentifier("sectionHeaderCell") as! UIView
let titleLabel = header.viewWithTag(1) as! UILabel
if tournaments.count == 1
{
titleLabel.text = String(format: "%i Tournament", tournaments.count)
}
else
{
titleLabel.text = String(format: "%i Tournaments", tournaments.count)
}
return header
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 63.0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var tempTour: Tournament = Tournament()
if indexPath.row >= tournaments.count
{
return UITableViewCell()
}
else
{
tempTour = tournaments[indexPath.row] as! Tournament
}
let cell = tableView.dequeueReusableCellWithIdentifier("TTournamentCell") as! TTournamentCell
cell.loadTournament(tempTour)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if respondingToTouch
{
return
}
respondingToTouch = true
var tempTour: Tournament = Tournament()
if indexPath.row >= tournaments.count
{
return
}
else
{
tempTour = tournaments[indexPath.row] as! Tournament
}
self.selectedTournament = tempTour
if !Bool(self.selectedTournament.tournamentParticipants.count)
{
self.selectedTournament.tournamentParticipants = Participant.parseParticipantFromJson(self.selectedTournament.tournamentParticipantsDictAr)
}
if !Bool(self.selectedTournament.tournamentMatches.count)
{
self.selectedTournament.tournamentMatches = Match.parseParticipantFromJson(self.selectedTournament.tournamentMatchesDictAr)
}
self.performSegueWithIdentifier("To Single Elimination Bracket Segue", sender: self)
}
}
| mit | 6a43914a0d32dd5505a1d68af08063a9 | 29.254902 | 151 | 0.578743 | 5.526504 | false | false | false | false |
khizkhiz/swift | test/SILGen/witness_tables.swift | 2 | 39146 | // RUN: %target-swift-frontend -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module > %t.sil
// RUN: FileCheck -check-prefix=TABLE -check-prefix=TABLE-ALL %s < %t.sil
// RUN: FileCheck -check-prefix=SYMBOL %s < %t.sil
// RUN: %target-swift-frontend -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module -enable-testing > %t.testable.sil
// RUN: FileCheck -check-prefix=TABLE-TESTABLE -check-prefix=TABLE-ALL %s < %t.testable.sil
// RUN: FileCheck -check-prefix=SYMBOL-TESTABLE %s < %t.testable.sil
import witness_tables_b
struct Arg {}
@objc class ObjCClass {}
infix operator <~> {}
protocol AssocReqt {
func requiredMethod()
}
protocol ArchetypeReqt {
func requiredMethod()
}
protocol AnyProtocol {
associatedtype AssocType
associatedtype AssocWithReqt: AssocReqt
func method(x x: Arg, y: Self)
func generic<A: ArchetypeReqt>(x x: A, y: Self)
func assocTypesMethod(x x: AssocType, y: AssocWithReqt)
static func staticMethod(x x: Self)
func <~>(x: Self, y: Self)
}
protocol ClassProtocol : class {
associatedtype AssocType
associatedtype AssocWithReqt: AssocReqt
func method(x x: Arg, y: Self)
func generic<B: ArchetypeReqt>(x x: B, y: Self)
func assocTypesMethod(x x: AssocType, y: AssocWithReqt)
static func staticMethod(x x: Self)
func <~>(x: Self, y: Self)
}
@objc protocol ObjCProtocol {
func method(x x: ObjCClass)
static func staticMethod(y y: ObjCClass)
}
class SomeAssoc {}
struct ConformingAssoc : AssocReqt {
func requiredMethod() {}
}
// TABLE-LABEL: sil_witness_table hidden ConformingAssoc: AssocReqt module witness_tables {
// TABLE-TESTABLE-LABEL: sil_witness_table ConformingAssoc: AssocReqt module witness_tables {
// TABLE-ALL-NEXT: method #AssocReqt.requiredMethod!1: @_TTWV14witness_tables15ConformingAssocS_9AssocReqtS_FS1_14requiredMethod{{.*}}
// TABLE-ALL-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables15ConformingAssocS_9AssocReqtS_FS1_14requiredMethod{{.*}} : $@convention(witness_method) (@in_guaranteed ConformingAssoc) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables15ConformingAssocS_9AssocReqtS_FS1_14requiredMethod{{.*}} : $@convention(witness_method) (@in_guaranteed ConformingAssoc) -> ()
struct ConformingStruct : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformingStruct) {}
func generic<D: ArchetypeReqt>(x x: D, y: ConformingStruct) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: ConformingStruct) {}
}
func <~>(x: ConformingStruct, y: ConformingStruct) {}
// TABLE-LABEL: sil_witness_table hidden ConformingStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_7generic{{.*}}: ArchetypeReqt> (@in A, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <A where A : ArchetypeReqt> (@in A, @in ConformingStruct, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingStruct) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformingStruct, @thick ConformingStruct.Type) -> ()
// SYMBOL-TESTABLE: sil [transparent] [thunk] @_TTWV14witness_tables16ConformingStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> ()
protocol AddressOnly {}
struct ConformingAddressOnlyStruct : AnyProtocol {
var p: AddressOnly // force address-only layout with a protocol-type field
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformingAddressOnlyStruct) {}
func generic<E: ArchetypeReqt>(x x: E, y: ConformingAddressOnlyStruct) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: ConformingAddressOnlyStruct) {}
}
func <~>(x: ConformingAddressOnlyStruct, y: ConformingAddressOnlyStruct) {}
// TABLE-LABEL: sil_witness_table hidden ConformingAddressOnlyStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <A where A : ArchetypeReqt> (@in A, @in ConformingAddressOnlyStruct, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingAddressOnlyStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables27ConformingAddressOnlyStructS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingAddressOnlyStruct, @in ConformingAddressOnlyStruct, @thick ConformingAddressOnlyStruct.Type) -> ()
class ConformingClass : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformingClass) {}
func generic<F: ArchetypeReqt>(x x: F, y: ConformingClass) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x x: ConformingClass) {}
}
func <~>(x: ConformingClass, y: ConformingClass) {}
// TABLE-LABEL: sil_witness_table hidden ConformingClass: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformingClass, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <A where A : ArchetypeReqt> (@in A, @in ConformingClass, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformingClass) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformingClass, @thick ConformingClass.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables15ConformingClassS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformingClass, @in ConformingClass, @thick ConformingClass.Type) -> ()
struct ConformsByExtension {}
extension ConformsByExtension : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformsByExtension) {}
func generic<G: ArchetypeReqt>(x x: G, y: ConformsByExtension) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: ConformsByExtension) {}
}
func <~>(x: ConformsByExtension, y: ConformsByExtension) {}
// TABLE-LABEL: sil_witness_table hidden ConformsByExtension: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformsByExtension, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <A where A : ArchetypeReqt> (@in A, @in ConformsByExtension, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformsByExtension) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformsByExtension, @thick ConformsByExtension.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables19ConformsByExtensionS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformsByExtension, @in ConformsByExtension, @thick ConformsByExtension.Type) -> ()
extension OtherModuleStruct : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: OtherModuleStruct) {}
func generic<H: ArchetypeReqt>(x x: H, y: OtherModuleStruct) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: OtherModuleStruct) {}
}
func <~>(x: OtherModuleStruct, y: OtherModuleStruct) {}
// TABLE-LABEL: sil_witness_table hidden OtherModuleStruct: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_ZFS2_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_ZFS2_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_6method{{.*}} : $@convention(witness_method) (Arg, @in OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_7generic{{.*}} : $@convention(witness_method) <A where A : ArchetypeReqt> (@in A, @in OtherModuleStruct, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_FS2_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed OtherModuleStruct) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_ZFS2_12staticMethod{{.*}} : $@convention(witness_method) (@in OtherModuleStruct, @thick OtherModuleStruct.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV16witness_tables_b17OtherModuleStruct14witness_tables11AnyProtocolS1_ZFS2_oi3ltg{{.*}} : $@convention(witness_method) (@in OtherModuleStruct, @in OtherModuleStruct, @thick OtherModuleStruct.Type) -> ()
protocol OtherProtocol {}
struct ConformsWithMoreGenericWitnesses : AnyProtocol, OtherProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method<I, J>(x x: I, y: J) {}
func generic<K, L>(x x: K, y: L) {}
func assocTypesMethod<M, N>(x x: M, y: N) {}
static func staticMethod<O>(x x: O) {}
}
func <~> <P: OtherProtocol>(x: P, y: P) {}
// TABLE-LABEL: sil_witness_table hidden ConformsWithMoreGenericWitnesses: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <A where A : ArchetypeReqt> (@in A, @in ConformsWithMoreGenericWitnesses, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @in_guaranteed ConformsWithMoreGenericWitnesses) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@in ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables32ConformsWithMoreGenericWitnessesS_11AnyProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@in ConformsWithMoreGenericWitnesses, @in ConformsWithMoreGenericWitnesses, @thick ConformsWithMoreGenericWitnesses.Type) -> ()
class ConformingClassToClassProtocol : ClassProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ConformingClassToClassProtocol) {}
func generic<Q: ArchetypeReqt>(x x: Q, y: ConformingClassToClassProtocol) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x x: ConformingClassToClassProtocol) {}
}
func <~>(x: ConformingClassToClassProtocol,
y: ConformingClassToClassProtocol) {}
// TABLE-LABEL: sil_witness_table hidden ConformingClassToClassProtocol: ClassProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #ClassProtocol.method!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #ClassProtocol.generic!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #ClassProtocol.assocTypesMethod!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #ClassProtocol.staticMethod!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #ClassProtocol."<~>"!1: @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @owned ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_7generic{{.*}} : $@convention(witness_method) <B where B : ArchetypeReqt> (@in B, @owned ConformingClassToClassProtocol, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_FS1_16assocTypesMethod{{.*}} : $@convention(witness_method) (@in SomeAssoc, @in ConformingAssoc, @guaranteed ConformingClassToClassProtocol) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_ZFS1_12staticMethod{{.*}} : $@convention(witness_method) (@owned ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables30ConformingClassToClassProtocolS_13ClassProtocolS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@owned ConformingClassToClassProtocol, @owned ConformingClassToClassProtocol, @thick ConformingClassToClassProtocol.Type) -> ()
class ConformingClassToObjCProtocol : ObjCProtocol {
@objc func method(x x: ObjCClass) {}
@objc class func staticMethod(y y: ObjCClass) {}
}
// TABLE-NOT: sil_witness_table hidden ConformingClassToObjCProtocol
struct ConformingGeneric<R: AssocReqt> : AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = R
func method(x x: Arg, y: ConformingGeneric) {}
func generic<Q: ArchetypeReqt>(x x: Q, y: ConformingGeneric) {}
func assocTypesMethod(x x: SomeAssoc, y: R) {}
static func staticMethod(x x: ConformingGeneric) {}
}
func <~> <R: AssocReqt>(x: ConformingGeneric<R>, y: ConformingGeneric<R>) {}
// TABLE-LABEL: sil_witness_table hidden <R where R : AssocReqt> ConformingGeneric<R>: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: R
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_FS2_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_FS2_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_FS2_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_ZFS2_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWuRx14witness_tables9AssocReqtrGVS_17ConformingGenericx_S_11AnyProtocolS_ZFS2_oi3ltg{{.*}}
// TABLE-NEXT: }
protocol AnotherProtocol {}
struct ConformingGenericWithMoreGenericWitnesses<S: AssocReqt>
: AnyProtocol, AnotherProtocol
{
typealias AssocType = SomeAssoc
typealias AssocWithReqt = S
func method<T, U>(x x: T, y: U) {}
func generic<V, W>(x x: V, y: W) {}
func assocTypesMethod<X, Y>(x x: X, y: Y) {}
static func staticMethod<Z>(x x: Z) {}
}
func <~> <AA: AnotherProtocol, BB: AnotherProtocol>(x: AA, y: BB) {}
// TABLE-LABEL: sil_witness_table hidden <S where S : AssocReqt> ConformingGenericWithMoreGenericWitnesses<S>: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: S
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): dependent
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_FS2_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_FS2_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_FS2_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_ZFS2_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWuRx14witness_tables9AssocReqtrGVS_41ConformingGenericWithMoreGenericWitnessesx_S_11AnyProtocolS_ZFS2_oi3ltg{{.*}}
// TABLE-NEXT: }
protocol InheritedProtocol1 : AnyProtocol {
func inheritedMethod()
}
protocol InheritedProtocol2 : AnyProtocol {
func inheritedMethod()
}
protocol InheritedClassProtocol : class, AnyProtocol {
func inheritedMethod()
}
struct InheritedConformance : InheritedProtocol1 {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: InheritedConformance) {}
func generic<H: ArchetypeReqt>(x x: H, y: InheritedConformance) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: InheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: InheritedConformance, y: InheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden InheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: InheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: @_TTWV14witness_tables20InheritedConformanceS_18InheritedProtocol1S_FS1_15inheritedMethod{{.*}}
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden InheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables20InheritedConformanceS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
struct RedundantInheritedConformance : InheritedProtocol1, AnyProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: RedundantInheritedConformance) {}
func generic<H: ArchetypeReqt>(x x: H, y: RedundantInheritedConformance) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: RedundantInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: RedundantInheritedConformance, y: RedundantInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: RedundantInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_18InheritedProtocol1S_FS1_15inheritedMethod{{.*}}
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden RedundantInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables29RedundantInheritedConformanceS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
struct DiamondInheritedConformance : InheritedProtocol1, InheritedProtocol2 {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: DiamondInheritedConformance) {}
func generic<H: ArchetypeReqt>(x x: H, y: DiamondInheritedConformance) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
static func staticMethod(x x: DiamondInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: DiamondInheritedConformance, y: DiamondInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol1 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol1.inheritedMethod!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_18InheritedProtocol1S_FS1_15inheritedMethod{{.*}}
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: InheritedProtocol2 module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: DiamondInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedProtocol2.inheritedMethod!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_18InheritedProtocol2S_FS1_15inheritedMethod{{.*}}
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden DiamondInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWV14witness_tables27DiamondInheritedConformanceS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
class ClassInheritedConformance : InheritedClassProtocol {
typealias AssocType = SomeAssoc
typealias AssocWithReqt = ConformingAssoc
func method(x x: Arg, y: ClassInheritedConformance) {}
func generic<H: ArchetypeReqt>(x x: H, y: ClassInheritedConformance) {}
func assocTypesMethod(x x: SomeAssoc, y: ConformingAssoc) {}
class func staticMethod(x x: ClassInheritedConformance) {}
func inheritedMethod() {}
}
func <~>(x: ClassInheritedConformance, y: ClassInheritedConformance) {}
// TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: InheritedClassProtocol module witness_tables {
// TABLE-NEXT: base_protocol AnyProtocol: ClassInheritedConformance: AnyProtocol module witness_tables
// TABLE-NEXT: method #InheritedClassProtocol.inheritedMethod!1: @_TTWC14witness_tables25ClassInheritedConformanceS_22InheritedClassProtocolS_FS1_15inheritedMethod{{.*}}
// TABLE-NEXT: }
// TABLE-LABEL: sil_witness_table hidden ClassInheritedConformance: AnyProtocol module witness_tables {
// TABLE-NEXT: associated_type AssocType: SomeAssoc
// TABLE-NEXT: associated_type AssocWithReqt: ConformingAssoc
// TABLE-NEXT: associated_type_protocol (AssocWithReqt: AssocReqt): ConformingAssoc: AssocReqt module witness_tables
// TABLE-NEXT: method #AnyProtocol.method!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}}
// TABLE-NEXT: method #AnyProtocol.generic!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_FS1_7generic{{.*}}
// TABLE-NEXT: method #AnyProtocol.assocTypesMethod!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_FS1_16assocTypesMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol.staticMethod!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_ZFS1_12staticMethod{{.*}}
// TABLE-NEXT: method #AnyProtocol."<~>"!1: @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_ZFS1_oi3ltg{{.*}}
// TABLE-NEXT: }
// -- Witnesses have the 'self' abstraction level of their protocol.
// AnyProtocol has no class bound, so its witnesses treat Self as opaque.
// InheritedClassProtocol has a class bound, so its witnesses treat Self as
// a reference value.
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables25ClassInheritedConformanceS_22InheritedClassProtocolS_FS1_15inheritedMethod{{.*}} : $@convention(witness_method) (@guaranteed ClassInheritedConformance) -> ()
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables25ClassInheritedConformanceS_11AnyProtocolS_FS1_6method{{.*}} : $@convention(witness_method) (Arg, @in ClassInheritedConformance, @in_guaranteed ClassInheritedConformance) -> ()
struct GenericAssocType<T> : AssocReqt {
func requiredMethod() {}
}
protocol AssocTypeWithReqt {
associatedtype AssocType : AssocReqt
}
struct ConformsWithDependentAssocType1<CC: AssocReqt> : AssocTypeWithReqt {
typealias AssocType = CC
}
// TABLE-LABEL: sil_witness_table hidden <CC where CC : AssocReqt> ConformsWithDependentAssocType1<CC>: AssocTypeWithReqt module witness_tables {
// TABLE-NEXT: associated_type AssocType: CC
// TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): dependent
// TABLE-NEXT: }
struct ConformsWithDependentAssocType2<DD> : AssocTypeWithReqt {
typealias AssocType = GenericAssocType<DD>
}
// TABLE-LABEL: sil_witness_table hidden <DD> ConformsWithDependentAssocType2<DD>: AssocTypeWithReqt module witness_tables {
// TABLE-NEXT: associated_type AssocType: GenericAssocType<DD>
// TABLE-NEXT: associated_type_protocol (AssocType: AssocReqt): GenericAssocType<DD>: specialize <DD> (<T> GenericAssocType<T>: AssocReqt module witness_tables)
// TABLE-NEXT: }
protocol InheritedFromObjC : ObjCProtocol {
func inheritedMethod()
}
class ConformsInheritedFromObjC : InheritedFromObjC {
@objc func method(x x: ObjCClass) {}
@objc class func staticMethod(y y: ObjCClass) {}
func inheritedMethod() {}
}
// TABLE-LABEL: sil_witness_table hidden ConformsInheritedFromObjC: InheritedFromObjC module witness_tables {
// TABLE-NEXT: method #InheritedFromObjC.inheritedMethod!1: @_TTWC14witness_tables25ConformsInheritedFromObjCS_17InheritedFromObjCS_FS1_15inheritedMethod{{.*}}
// TABLE-NEXT: }
protocol ObjCAssoc {
associatedtype AssocType : ObjCProtocol
}
struct HasObjCAssoc : ObjCAssoc {
typealias AssocType = ConformsInheritedFromObjC
}
// TABLE-LABEL: sil_witness_table hidden HasObjCAssoc: ObjCAssoc module witness_tables {
// TABLE-NEXT: associated_type AssocType: ConformsInheritedFromObjC
// TABLE-NEXT: }
protocol Initializer {
init(arg: Arg)
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerStruct: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: @_TTWV14witness_tables20HasInitializerStructS_11InitializerS_FS1_C{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWV14witness_tables20HasInitializerStructS_11InitializerS_FS1_C{{.*}} : $@convention(witness_method) (Arg, @thick HasInitializerStruct.Type) -> @out HasInitializerStruct
struct HasInitializerStruct : Initializer {
init(arg: Arg) { }
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerClass: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: @_TTWC14witness_tables19HasInitializerClassS_11InitializerS_FS1_C{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWC14witness_tables19HasInitializerClassS_11InitializerS_FS1_C{{.*}} : $@convention(witness_method) (Arg, @thick HasInitializerClass.Type) -> @out HasInitializerClass
class HasInitializerClass : Initializer {
required init(arg: Arg) { }
}
// TABLE-LABEL: sil_witness_table hidden HasInitializerEnum: Initializer module witness_tables {
// TABLE-NEXT: method #Initializer.init!allocator.1: @_TTWO14witness_tables18HasInitializerEnumS_11InitializerS_FS1_C{{.*}}
// TABLE-NEXT: }
// SYMBOL: sil hidden [transparent] [thunk] @_TTWO14witness_tables18HasInitializerEnumS_11InitializerS_FS1_C{{.*}} : $@convention(witness_method) (Arg, @thick HasInitializerEnum.Type) -> @out HasInitializerEnum
enum HasInitializerEnum : Initializer {
case A
init(arg: Arg) { self = .A }
}
| apache-2.0 | 33713596215870966426e4637c180f4d | 70.174545 | 300 | 0.771394 | 3.779301 | false | false | false | false |
Heisenbean/Won-t-Starve | Won't Starve/Won't Starve/MenuDetalViewController.swift | 1 | 2690 | //
// MenuDetalViewController.swift
// Won't Starve
//
// Created by Heisenbean on 17/1/10.
// Copyright © 2017年 Heisenbean. All rights reserved.
//
import UIKit
class MenuDetalViewController: UIViewController {
// MARK: Properties
@IBOutlet weak var detaliLabel: UILabel!
@IBOutlet weak var nameLabel:UILabel!
@IBOutlet weak var foodIcon: UIImageView!
@IBOutlet weak var healthNum: UILabel!
@IBOutlet weak var hungryNum: UILabel!
@IBOutlet weak var santiNum: UILabel!
@IBOutlet weak var timeNum: UILabel!
@IBOutlet weak var badTimeNum: UILabel!
@IBOutlet weak var limitNum: UILabel!
@IBOutlet weak var generateCode: UILabel!
@IBOutlet weak var tableview: UITableView!
@IBOutlet weak var exampleTopConst: NSLayoutConstraint!
var datas = [String:AnyObject]()
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
detaliLabel.preferredMaxLayoutWidth = UIScreen.main.bounds.size.width * 0.5
configData()
}
func configData() {
detaliLabel.text = datas["desc"] as? String
foodIcon.image = UIImage.init(named: (datas["icon"] as? String)!)
nameLabel.text = datas["name"] as? String
healthNum.text = datas["health"] as? String
hungryNum.text = datas["hungry"] as? String
santiNum.text = datas["sanity"] as? String
badTimeNum.text = datas["badTime"] as? String
limitNum.text = datas["max"] as? String
limitNum.text = datas["max"] as? String
generateCode.text = "\"" + (datas["code"] as! String) + "\""
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if detaliLabel.frame.height > 274 {
exampleTopConst.constant += detaliLabel.frame.height - 274
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension MenuDetalViewController: UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let examples = datas["example"] as! [String]
return examples.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ExampleCell
let examples = datas["example"] as! [String]
cell.datas = examples[indexPath.row]
cell.result.image = UIImage.init(named: (datas["icon"] as? String)!)
return cell
}
}
| mit | c27e581b51e4a5eaaa46df636eb07a90 | 32.17284 | 104 | 0.654633 | 4.433993 | false | false | false | false |
coreymason/LAHacks2017 | ios/DreamWell/DreamWell/Services.swift | 1 | 2226 | //
// Services.swift
// DreamWell
//
// Created by Rohin Bhushan on 4/1/17.
// Copyright © 2017 rohin. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
struct Services {
static var delegate : ServicesDelegate?
static let userID = "SwFaJKpAMIaKhIz4vS4FCnYvTj33"
static let root = "http://projectscale.me"
static func postSleepLogs(text: String, stars: Int) {
let endpoint: String = "\(root)/dreamLog/\(userID)"
let newTodo: [String: Any] = ["text" : text, "quality" : stars]
Alamofire.request(endpoint, method: .post, parameters: newTodo,
encoding: JSONEncoding.default).responseString { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling POST on dreamlog")
print(response.result.error!)
return
}
print("SUCCESS SENDING SLEEP LOGS")
}
}
static func getDailyStat(dayOffset : Int = 0) {
let endpoint = "\(root)/pastDayStats/\(userID)/\(dayOffset)"
Alamofire.request(endpoint).responseJSON { response in
// check for errors
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling GET on /todos/1")
print(response.result.error!)
return
}
guard let json = response.result.value as? [String: Any] else {
print("didn't get todo object as JSON from API")
print("Error: \(response.result.error)")
return
}
DispatchQueue.main.async {
delegate?.dailyStatsReceived(json: json)
}
}
}
static func getSuggestions() {
/*let endpoint = "\(root)/suggestions/\(userID)"
Alamofire.request(endpoint).responseJSON { response in
// check for errors
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling GET on suggestions")
print(response.result.error!)
return
}
guard let json = response.result.value as? [String: Any] else {
print("didn't get todo object as JSON from API")
print("Error: \(response.result.error)")
return
}
}*/
}
}
protocol ServicesDelegate {
func dailyStatsReceived(json: [String: Any])
}
| mit | fa54ef58b4abcf9b5462af4533cddf06 | 24.284091 | 80 | 0.671461 | 3.498428 | false | false | false | false |
tkremenek/swift | test/SILOptimizer/Inputs/BaseProblem.swift | 76 | 406 | public class BaseProblem
{
func run() -> Int
{
return 0
}
}
class Evaluator
{
var map: [Int: () -> Int] = [:]
init()
{
map[1] = { Problem1().run() }
map[2] = { Problem2().run() }
}
func evaluate(_ n: Int)
{
if let problemBlock = map[n]
{
let foo = problemBlock()
print("foo = \(foo)")
}
}
}
| apache-2.0 | 80474f2c0adc81d5e5001253c21de505 | 14.037037 | 37 | 0.406404 | 3.470085 | false | false | false | false |
mmisesin/particle | Particle/ArticleContent.swift | 1 | 804 | //
// ArticleContent.swift
// Particle
//
// Created by Artem Misesin on 7/20/17.
// Copyright © 2017 Artem Misesin. All rights reserved.
//
import Foundation
enum Tag: String {
case p = "p"
case h1 = "h1"
case h2 = "h2"
case h3 = "h3"
case h4 = "h4"
case blockquote = "blockquote"
case img = "img"
case figure = "figure"
case unknown = "_"
}
struct ArticleContent {
var id: Double?
var title: String?
var contentString: [String] = []
var tags: [Tag] = []
func getTag(from tagName: String) -> Tag {
if let tag = Tag(rawValue: tagName) {
return tag
} else {
return Tag.unknown
}
}
}
struct ArticleParagraph {
var content: String = ""
var styleTag: Tag = .unknown
}
| mit | 533968e122f68dc6710fed5719daf192 | 17.674419 | 56 | 0.555417 | 3.417021 | false | false | false | false |
PurpleSweetPotatoes/customControl | SwiftKit/extension/UIButton+extension.swift | 1 | 3186 | //
// UIButton+extension.swift
// HJLBusiness
//
// Created by MrBai on 2017/5/16.
// Copyright © 2017年 baiqiang. All rights reserved.
//
import UIKit
enum BtnSubViewAdjust {
case none
case left
case right
case imgTopTitleBottom
}
extension UIButton {
class func mainColorBtn(frame:CGRect, title:String?) -> UIButton {
let btn = UIButton(frame: frame)
btn.backgroundColor = UIColor.mainColor
btn.setTitleColor(UIColor.white, for: .normal)
btn.setCorner(readius: 5)
btn.setTitle(title, for: .normal)
return btn
}
class func borderBtn(frame:CGRect, title:String?) -> UIButton {
let btn = UIButton(frame: frame)
btn.backgroundColor = UIColor.white
btn.setTitleColor(UIColor.mainColor, for: .normal)
btn.setTitle(title, for: .normal)
btn.setCorner(readius: 5)
btn.setBordColor(color: UIColor.mainColor)
return btn
}
class func createCornerBtn(frame:CGRect, color:UIColor, title:String) -> UIButton {
let btn = UIButton(type: .custom)
btn.frame = frame
btn.setCorner(readius: btn.width * 0.5)
btn.setBordColor(color: color)
btn.setTitle(title, for: .normal)
btn.setTitleColor(color, for: .normal)
return btn
}
/// 调整btn视图和文字位置()
///
/// - Parameters:
/// - spacing: 调整后的间距
/// - type: 调整方式BtnSubViewAdjust
func adjustImageTitle(spacing: CGFloat, type: BtnSubViewAdjust) {
//重置内间距、防止获取视图位置出错
self.imageEdgeInsets = UIEdgeInsets.zero
self.titleEdgeInsets = UIEdgeInsets.zero
if type == .none {
return
}
guard let imgView = self.imageView, let titleLab = self.titleLabel else {
print("check you btn have image and text!")
return
}
let width = self.frame.width
var imageLeft: CGFloat = 0
var imageTop: CGFloat = 0
var titleLeft: CGFloat = 0
var titleTop: CGFloat = 0
var titleRift: CGFloat = 0
if type == .imgTopTitleBottom {
imageLeft = (width - imgView.frame.width) * 0.5 - imgView.frame.origin.x
imageTop = spacing - imgView.frame.origin.y
titleLeft = (width - titleLab.frame.width) * 0.5 - titleLab.frame.origin.x - titleLab.frame.origin.x
titleTop = spacing * 2 + imgView.frame.height - titleLab.frame.origin.y
titleRift = -titleLeft - titleLab.frame.origin.x * 2
}else if type == .left {
imageLeft = spacing - imgView.frame.origin.x
titleLeft = spacing * 2 + imgView.frame.width - titleLab.frame.origin.x
titleRift = -titleLeft
}else {
titleLeft = width - titleLab.frame.maxX - spacing
titleRift = -titleLeft
imageLeft = width - imgView.right - spacing * 2 - titleLab.frame.width
}
self.imageEdgeInsets = UIEdgeInsetsMake(imageTop, imageLeft, -imageTop, -imageLeft)
self.titleEdgeInsets = UIEdgeInsetsMake(titleTop, titleLeft, -titleTop, titleRift)
}
}
| apache-2.0 | 9ac49644539b3924ca58b6a37522847b | 35.623529 | 112 | 0.616447 | 4.101449 | false | false | false | false |
shorlander/firefox-ios | Client/Frontend/Menu/MenuPresentationAnimator.swift | 4 | 6762 | /* 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
class MenuPresentationAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var presenting: Bool = false
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let screens = (from: transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!, to: transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!)
guard let menuViewController = !self.presenting ? screens.from as? MenuViewController : screens.to as? MenuViewController else {
return
}
var bottomViewController = !self.presenting ? screens.to as UIViewController : screens.from as UIViewController
// don't do anything special if it's a popover presentation
if menuViewController.presentationStyle == .popover {
return
}
if let navController = bottomViewController as? UINavigationController {
bottomViewController = navController.viewControllers.last ?? bottomViewController
}
if bottomViewController.isKind(of: BrowserViewController.self) {
animateWithMenu(menuViewController, browserViewController: bottomViewController as! BrowserViewController, transitionContext: transitionContext)
} else if bottomViewController.isKind(of: TabTrayController.self) {
animateWithMenu(menuViewController, tabTrayController: bottomViewController as! TabTrayController, transitionContext: transitionContext)
}
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return presenting ? 0.4 : 0.2
}
}
extension MenuPresentationAnimator: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
return self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = false
return self
}
}
extension MenuPresentationAnimator {
fileprivate func animateWithMenu(_ menu: MenuViewController, browserViewController bvc: BrowserViewController, transitionContext: UIViewControllerContextTransitioning) {
let leftViews: [UIView]?
let rightViews: [UIView]?
let sourceView: UIView?
if let toolbar = bvc.toolbar {
leftViews = [toolbar.backButton, toolbar.forwardButton]
rightViews = [toolbar.stopReloadButton, toolbar.shareButton, toolbar.homePageButton]
sourceView = toolbar.menuButton
} else {
sourceView = nil
leftViews = nil
rightViews = nil
}
self.animateWithMenu(menu, baseController: bvc, viewsToAnimateLeft: leftViews, viewsToAnimateRight: rightViews, sourceView: sourceView, withTransitionContext: transitionContext)
}
fileprivate func animateWithMenu(_ menu: MenuViewController, tabTrayController ttc: TabTrayController, transitionContext: UIViewControllerContextTransitioning) {
animateWithMenu(menu, baseController: ttc, viewsToAnimateLeft: ttc.leftToolbarButtons, viewsToAnimateRight: ttc.rightToolbarButtons, sourceView: ttc.toolbar.menuButton, withTransitionContext: transitionContext)
}
fileprivate func animateWithMenu(_ menuController: MenuViewController, baseController: UIViewController, viewsToAnimateLeft: [UIView]?, viewsToAnimateRight: [UIView]?, sourceView: UIView?, withTransitionContext transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
// If we don't have any views abort the animation since there isn't anything to animate.
guard let menuView = menuController.view, let bottomView = baseController.view else {
transitionContext.completeTransition(true)
return
}
menuView.frame = container.bounds
let bgView = UIView()
bgView.frame = container.bounds
if presenting {
container.addSubview(menuView)
container.insertSubview(bgView, belowSubview: menuView)
menuView.layoutSubviews()
}
let vanishingPoint = CGPoint(x: menuView.frame.origin.x, y: menuView.frame.size.height)
let minimisedFrame = CGRect(origin: vanishingPoint, size: menuView.frame.size)
if presenting {
menuView.frame = minimisedFrame
}
let offstageValue = bottomView.bounds.size.width / 2
let offstageLeft = CGAffineTransform(translationX: -offstageValue, y: 0)
let offstageRight = CGAffineTransform(translationX: offstageValue, y: 0)
if presenting {
bgView.backgroundColor = menuView.backgroundColor?.withAlphaComponent(0.0)
} else {
bgView.backgroundColor = menuView.backgroundColor?.withAlphaComponent(0.4)
// move the buttons to their offstage positions
viewsToAnimateLeft?.forEach { $0.transform = offstageLeft }
viewsToAnimateRight?.forEach { $0.transform = offstageRight }
}
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: [], animations: {
if self.presenting {
menuView.frame = container.bounds
bgView.backgroundColor = menuView.backgroundColor?.withAlphaComponent(0.4)
// animate back and forward buttons off to the left
viewsToAnimateLeft?.forEach { $0.transform = offstageLeft }
// animate reload and share buttons off to the right
viewsToAnimateRight?.forEach { $0.transform = offstageRight }
} else {
menuView.frame = minimisedFrame
bgView.backgroundColor = menuView.backgroundColor?.withAlphaComponent(0.0)
// animate back and forward buttons in from the left
viewsToAnimateLeft?.forEach { $0.transform = CGAffineTransform.identity }
// animate reload and share buttons in from the right
viewsToAnimateRight?.forEach { $0.transform = CGAffineTransform.identity }
}
}, completion: { finished in
bgView.removeFromSuperview()
transitionContext.completeTransition(true)
})
}
}
| mpl-2.0 | 572a752574da0aea15224f8fd3c7ff8a | 48 | 273 | 0.702899 | 5.789384 | false | false | false | false |
danielallsopp/Charts | Source/Charts/Renderers/ChartRendererBase.swift | 12 | 1473 | //
// ChartRendererBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
public class ChartRendererBase: NSObject
{
/// the component that handles the drawing area of the chart and it's offsets
public var viewPortHandler: ChartViewPortHandler!
/// the minimum value on the x-axis that should be plotted
public var minX: Int = 0
/// the maximum value on the x-axis that should be plotted
public var maxX: Int = 0
public override init()
{
super.init()
}
public init(viewPortHandler: ChartViewPortHandler)
{
super.init()
self.viewPortHandler = viewPortHandler
}
/// Calculates the minimum and maximum x-value the chart can currently display (with the given zoom level).
public func calcXBounds(chart chart: BarLineScatterCandleBubbleChartDataProvider, xAxisModulus: Int)
{
let low = chart.lowestVisibleXIndex
let high = chart.highestVisibleXIndex
let subLow = (low % xAxisModulus == 0) ? xAxisModulus : 0
minX = max((low / xAxisModulus) * (xAxisModulus) - subLow, 0)
maxX = min((high / xAxisModulus) * (xAxisModulus) + xAxisModulus, Int(chart.chartXMax))
}
}
| apache-2.0 | 25117a6cc8e4df5cf96b29c320bc7861 | 27.901961 | 111 | 0.662593 | 4.646688 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Models/Search/Response/SearchResponse/Auxiliary/Facet/FacetsStorage.swift | 1 | 712 | //
// FacetsStorage.swift
//
//
// Created by Vladislav Fitc on 13/04/2020.
//
import Foundation
struct FacetsStorage: Codable {
var storage: [Attribute: [Facet]]
public init(storage: [Attribute: [Facet]]) {
self.storage = storage
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let rawFacetsForAttribute = try container.decode([String: [String: Int]].self)
let output = [Attribute: [Facet]](rawFacetsForAttribute)
self.storage = output
}
func encode(to encoder: Encoder) throws {
let rawFacets = [String: [String: Int]](storage)
var container = encoder.singleValueContainer()
try container.encode(rawFacets)
}
}
| mit | 111b16ee97bdfe94ec746b48e20af0be | 21.967742 | 82 | 0.686798 | 3.787234 | false | false | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Idiomatic/UnavailableFunctionRule.swift | 1 | 5913 | import SwiftSyntax
struct UnavailableFunctionRule: SwiftSyntaxRule, ConfigurationProviderRule, OptInRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static let description = RuleDescription(
identifier: "unavailable_function",
name: "Unavailable Function",
description: "Unimplemented functions should be marked as unavailable.",
kind: .idiomatic,
nonTriggeringExamples: [
Example("""
class ViewController: UIViewController {
@available(*, unavailable)
public required init?(coder aDecoder: NSCoder) {
preconditionFailure("init(coder:) has not been implemented")
}
}
"""),
Example("""
func jsonValue(_ jsonString: String) -> NSObject {
let data = jsonString.data(using: .utf8)!
let result = try! JSONSerialization.jsonObject(with: data, options: [])
if let dict = (result as? [String: Any])?.bridge() {
return dict
} else if let array = (result as? [Any])?.bridge() {
return array
}
fatalError()
}
"""),
Example("""
func resetOnboardingStateAndCrash() -> Never {
resetUserDefaults()
// Crash the app to re-start the onboarding flow.
fatalError("Onboarding re-start crash.")
}
""")
],
triggeringExamples: [
Example("""
class ViewController: UIViewController {
public required ↓init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
"""),
Example("""
class ViewController: UIViewController {
public required ↓init?(coder aDecoder: NSCoder) {
let reason = "init(coder:) has not been implemented"
fatalError(reason)
}
}
"""),
Example("""
class ViewController: UIViewController {
public required ↓init?(coder aDecoder: NSCoder) {
preconditionFailure("init(coder:) has not been implemented")
}
}
"""),
Example("""
↓func resetOnboardingStateAndCrash() {
resetUserDefaults()
// Crash the app to re-start the onboarding flow.
fatalError("Onboarding re-start crash.")
}
""")
]
)
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(viewMode: .sourceAccurate)
}
}
private extension UnavailableFunctionRule {
final class Visitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: FunctionDeclSyntax) {
guard !node.returnsNever,
!node.attributes.hasUnavailableAttribute,
node.body.containsTerminatingCall,
!node.body.containsReturn else {
return
}
violations.append(node.funcKeyword.positionAfterSkippingLeadingTrivia)
}
override func visitPost(_ node: InitializerDeclSyntax) {
guard !node.attributes.hasUnavailableAttribute,
node.body.containsTerminatingCall,
!node.body.containsReturn else {
return
}
violations.append(node.initKeyword.positionAfterSkippingLeadingTrivia)
}
}
}
private extension FunctionDeclSyntax {
var returnsNever: Bool {
if let expr = signature.output?.returnType.as(SimpleTypeIdentifierSyntax.self) {
return expr.name.withoutTrivia().text == "Never"
}
return false
}
}
private extension AttributeListSyntax? {
var hasUnavailableAttribute: Bool {
guard let attrs = self else {
return false
}
return attrs.contains { elem in
guard let attr = elem.as(AttributeSyntax.self),
let arguments = attr.argument?.as(AvailabilitySpecListSyntax.self) else {
return false
}
return attr.attributeName.tokenKind == .contextualKeyword("available") && arguments.contains { arg in
arg.entry.as(TokenSyntax.self)?.tokenKind == .contextualKeyword("unavailable")
}
}
}
}
private extension CodeBlockSyntax? {
var containsTerminatingCall: Bool {
guard let statements = self?.statements else {
return false
}
let terminatingFunctions: Set = [
"abort",
"fatalError",
"preconditionFailure"
]
return statements.contains { item in
guard let function = item.item.as(FunctionCallExprSyntax.self),
let identifierExpr = function.calledExpression.as(IdentifierExprSyntax.self) else {
return false
}
return terminatingFunctions.contains(identifierExpr.identifier.withoutTrivia().text)
}
}
var containsReturn: Bool {
guard let statements = self?.statements else {
return false
}
return ReturnFinderVisitor(viewMode: .sourceAccurate)
.walk(tree: statements, handler: \.containsReturn)
}
}
private final class ReturnFinderVisitor: SyntaxVisitor {
private(set) var containsReturn = false
override func visitPost(_ node: ReturnStmtSyntax) {
containsReturn = true
}
override func visit(_ node: ClosureExprSyntax) -> SyntaxVisitorContinueKind {
.skipChildren
}
override func visit(_ node: FunctionCallExprSyntax) -> SyntaxVisitorContinueKind {
.skipChildren
}
}
| mit | 067559b13b505a99ff8cd479394b1a61 | 31.988827 | 113 | 0.567993 | 5.721899 | false | false | false | false |
cforlando/orlando-walking-tours-ios | Orlando Walking Tours/Controllers/CurrentTourVC.swift | 1 | 5232 | //
// CurrentTourVC.swift
// Orlando Walking Tours
//
// Created by Keli'i Martin on 7/9/16.
// Copyright © 2016 Code for Orlando. All rights reserved.
//
import UIKit
import MapKit
class CurrentTourVC: UIViewController
{
////////////////////////////////////////////////////////////
// MARK: - IBOutlets
////////////////////////////////////////////////////////////
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var tableView: UITableView!
////////////////////////////////////////////////////////////
// MARK: - Properties
////////////////////////////////////////////////////////////
var tour: Tour?
lazy var locations = [HistoricLocation]()
lazy var modelService: ModelService = MagicalRecordModelService()
var userLocation: CLLocation?
// Exchange Building
let simulatedLocation = CLLocation(latitude: 28.540951, longitude: -81.381265)
////////////////////////////////////////////////////////////
// MARK: - View Controller Life Cycle
////////////////////////////////////////////////////////////
override func viewDidLoad()
{
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.navigationItem.title = self.tour?.title
self.loadLocations()
let zoomLevel = 1.0.asMeters
let mapRegion = MKCoordinateRegionMakeWithDistance(self.simulatedLocation.coordinate, zoomLevel, zoomLevel)
self.mapView.setRegion(mapRegion, animated: true) // animate the zoom
let locationAnnotations = self.locations.map
{
return LocationAnnotation(location: $0)
}
self.mapView.addAnnotations(locationAnnotations)
}
////////////////////////////////////////////////////////////
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
self.loadLocations()
}
////////////////////////////////////////////////////////////
// MARK: - IBActions
////////////////////////////////////////////////////////////
@IBAction func addMoreLocationsTapped(sender: UIBarButtonItem)
{
performSegue(withIdentifier: "AddMoreLocationsSegue", sender: nil)
}
////////////////////////////////////////////////////////////
@IBAction func homeTapped(_ sender: UIBarButtonItem)
{
performSegue(withIdentifier: "unwindToDashboard", sender: nil)
}
////////////////////////////////////////////////////////////
// MARK: - Navigation
////////////////////////////////////////////////////////////
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
super.prepare(for: segue, sender: sender)
if let navController = segue.destination as? UINavigationController
{
if let vc = navController.topViewController as? LocationListVC,
segue.identifier == "AddMoreLocationsSegue"
{
vc.tour = self.tour
}
else if let vc = navController.topViewController as? LocationDetailVC,
segue.identifier == "ShowLocationDetailsSegue"
{
if let indexPath = sender as? NSIndexPath
{
vc.location = locations[indexPath.row]
}
}
}
}
////////////////////////////////////////////////////////////
func loadLocations()
{
if let tour = self.tour,
let locations = modelService.loadLocations(fromTour: tour)
{
self.locations = locations
self.tableView.reloadData()
}
}
}
////////////////////////////////////////////////////////////
extension CurrentTourVC: UITableViewDelegate, UITableViewDataSource
{
func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
////////////////////////////////////////////////////////////
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.tour?.historicLocations?.count ?? 0
}
////////////////////////////////////////////////////////////
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat
{
return 70
}
////////////////////////////////////////////////////////////
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let location = self.locations[indexPath.row]
guard let cell = tableView.dequeueReusableCell(withIdentifier: CurrentLocationTableViewCell.reuseIdentifier, for: indexPath) as? CurrentLocationTableViewCell else
{
return UITableViewCell()
}
cell.configureImage(frame: cell.locationThumbnail.frame)
cell.locationLabel.text = location.locationTitle
cell.addressLabel.text = location.address
return cell
}
////////////////////////////////////////////////////////////
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
performSegue(withIdentifier: "ShowLocationDetailsSegue", sender: indexPath)
}
}
| mit | 668e63b6619acadd22e42d837ac74d08 | 30.323353 | 170 | 0.500478 | 6.183215 | false | false | false | false |
iSapozhnik/FamilyPocket | FamilyPocket/ViewControllers/TestTableViewController.swift | 1 | 3140 | //
// TestTableViewController.swift
// FamilyPocket
//
// Created by Ivan Sapozhnik on 5/17/17.
// Copyright © 2017 Ivan Sapozhnik. All rights reserved.
//
import UIKit
class TestTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
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 | adad72744c29efab802ace27bc921974 | 32.042105 | 136 | 0.671551 | 5.338435 | false | false | false | false |
nessBautista/iOSBackup | RxSwift_02/RxTables/Pods/PKHUD/PKHUD/PKHUD.swift | 4 | 4484 | //
// HUD.swift
// PKHUD
//
// Created by Philip Kluz on 6/13/14.
// Copyright (c) 2016 NSExceptional. All rights reserved.
// Licensed under the MIT license.
//
import UIKit
/// The PKHUD object controls showing and hiding of the HUD, as well as its contents and touch response behavior.
open class PKHUD: NSObject {
fileprivate struct Constants {
static let sharedHUD = PKHUD()
}
fileprivate let window = Window()
fileprivate var hideTimer: Timer?
public typealias TimerAction = (Bool) -> Void
fileprivate var timerActions = [String: TimerAction]()
// MARK: Public
open class var sharedHUD: PKHUD {
return Constants.sharedHUD
}
public override init () {
super.init()
NotificationCenter.default.addObserver(self,
selector: #selector(PKHUD.willEnterForeground(_:)),
name: NSNotification.Name.UIApplicationWillEnterForeground,
object: nil)
userInteractionOnUnderlyingViewsEnabled = false
window.frameView.autoresizingMask = [ .flexibleLeftMargin,
.flexibleRightMargin,
.flexibleTopMargin,
.flexibleBottomMargin ]
}
deinit {
NotificationCenter.default.removeObserver(self)
}
open var dimsBackground = true
open var userInteractionOnUnderlyingViewsEnabled: Bool {
get {
return !window.isUserInteractionEnabled
}
set {
window.isUserInteractionEnabled = !newValue
}
}
open var isVisible: Bool {
return !window.isHidden
}
open var contentView: UIView {
get {
return window.frameView.content
}
set {
window.frameView.content = newValue
startAnimatingContentView()
}
}
open var effect: UIVisualEffect? {
get {
return window.frameView.effect
}
set {
window.frameView.effect = effect
}
}
open func show() {
window.showFrameView()
if dimsBackground {
window.showBackground(animated: true)
}
startAnimatingContentView()
}
open func hide(animated anim: Bool = true, completion: TimerAction? = nil) {
window.hideFrameView(animated: anim, completion: completion)
stopAnimatingContentView()
}
open func hide(_ animated: Bool, completion: TimerAction? = nil) {
hide(animated: animated, completion: completion)
}
open func hide(afterDelay delay: TimeInterval, completion: TimerAction? = nil) {
let key = UUID().uuidString
let userInfo = ["timerActionKey": key]
if let completion = completion {
timerActions[key] = completion
}
hideTimer?.invalidate()
hideTimer = Timer.scheduledTimer(timeInterval: delay,
target: self,
selector: #selector(PKHUD.performDelayedHide(_:)),
userInfo: userInfo,
repeats: false)
}
// MARK: Internal
internal func willEnterForeground(_ notification: Notification?) {
self.startAnimatingContentView()
}
internal func performDelayedHide(_ timer: Timer? = nil) {
let userInfo = timer?.userInfo as? NSDictionary
let key = userInfo?["timerActionKey"] as? String
var completion: TimerAction?
if let key = key, let action = timerActions[key] {
completion = action
timerActions[key] = nil
}
hide(animated: true, completion: completion);
}
internal func startAnimatingContentView() {
if isVisible && contentView.conforms(to: PKHUDAnimating.self) {
let animatingContentView = contentView as! PKHUDAnimating
animatingContentView.startAnimation()
}
}
internal func stopAnimatingContentView() {
if contentView.conforms(to: PKHUDAnimating.self) {
let animatingContentView = contentView as! PKHUDAnimating
animatingContentView.stopAnimation?()
}
}
}
| cc0-1.0 | 7ab66b025b3dafa0bb8dbf8f25006a3e | 29.712329 | 113 | 0.564674 | 5.697586 | false | false | false | false |
meteochu/Alamofire | Source/ResponseSerialization.swift | 1 | 14563 | //
// ResponseSerialization.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// MARK: ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`.
associatedtype SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
associatedtype ErrorObject: ErrorProtocol
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
var serializeResponse: (NSURLRequest?, HTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
}
// MARK: -
/**
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
*/
public struct ResponseSerializer<Value, Error: ErrorProtocol>: ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = Value
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
public typealias ErrorObject = Error
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
public var serializeResponse: (NSURLRequest?, HTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
/**
Initializes the `ResponseSerializer` instance with the given serialize response closure.
- parameter serializeResponse: The closure used to serialize the response.
- returns: The new generic response serializer instance.
*/
public init(serializeResponse: (NSURLRequest?, HTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response(
queue: DispatchQueue? = nil,
completionHandler: (NSURLRequest?, HTTPURLResponse?, NSData?, NSError?) -> Void)
-> Self
{
delegate.queue.addOperation {
(queue ?? DispatchQueue.main).async {
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
}
}
return self
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response<T: ResponseSerializerType>(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: (Response<T.SerializedObject, T.ErrorObject>) -> Void)
-> Self
{
delegate.queue.addOperation {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
let timeline = Timeline(
requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
initialResponseTime: initialResponseTime,
requestCompletedTime: requestCompletedTime,
serializationCompletedTime: CFAbsoluteTimeGetCurrent()
)
let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result,
timeline: timeline
)
(queue ?? DispatchQueue.main).async { completionHandler(response) }
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSData()) }
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.error(code: .DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
return .Success(validData)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(
queue: DispatchQueue? = nil,
completionHandler: (Response<NSData, NSError>) -> Void)
-> Self
{
return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public static func stringResponseSerializer(
encoding: String.Encoding? = nil)
-> ResponseSerializer<String, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success("") }
guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil."
let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
var convertedEncoding = encoding
if let encodingName = response?.textEncodingName where convertedEncoding == nil {
convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
))
}
let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1
if let string = String(data: validData as Data, encoding: actualEncoding) {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.error(code: .StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseString(
queue: DispatchQueue? = nil,
encoding: String.Encoding? = nil,
completionHandler: (Response<String, NSError>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(
options: JSONSerialization.ReadingOptions = .allowFragments)
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "JSON could not be serialized. Input data was nil or zero length."
let error = Error.error(code: .JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let JSON = try JSONSerialization.jsonObject(with: validData as Data, options: options)
return .Success(JSON)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: (Response<AnyObject, NSError>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
- returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(
options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions())
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "Property list could not be serialized. Input data was nil or zero length."
let error = Error.error(code: .PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let plist = try PropertyListSerialization.propertyList(from: validData as Data, options: options, format: nil)
return .Success(plist)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response, the server data and the result
produced while creating the property list.
- returns: The request.
*/
public func responsePropertyList(
queue: DispatchQueue? = nil,
options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions(),
completionHandler: (Response<AnyObject, NSError>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| mit | d78a5680aa47ef9d659880fb2941c053 | 37.526455 | 129 | 0.640184 | 5.594698 | false | false | false | false |
accatyyc/Buildasaur | Buildasaur/EmptyBuildTemplateViewController.swift | 1 | 4126 | //
// EmptyBuildTemplateViewController.swift
// Buildasaur
//
// Created by Honza Dvorsky on 10/6/15.
// Copyright © 2015 Honza Dvorsky. All rights reserved.
//
import Cocoa
import BuildaKit
import BuildaUtils
import XcodeServerSDK
import ReactiveCocoa
protocol EmptyBuildTemplateViewControllerDelegate: class {
func didSelectBuildTemplate(buildTemplate: BuildTemplate)
}
class EmptyBuildTemplateViewController: EditableViewController {
//for cases when we're editing an existing syncer - show the
//right preference.
var existingTemplateId: RefType?
//for requesting just the right build templates
var projectName: String!
weak var emptyTemplateDelegate: EmptyBuildTemplateViewControllerDelegate?
@IBOutlet weak var existingBuildTemplatesPopup: NSPopUpButton!
private var buildTemplates: [BuildTemplate] = []
private var selectedTemplate = MutableProperty<BuildTemplate?>(nil)
override func viewDidLoad() {
super.viewDidLoad()
precondition(self.projectName != nil)
self.setupDataSource()
self.setupPopupAction()
self.setupEditableStates()
//select if existing template is being edited
//TODO: also the actual index in the popup must be selected!
let index: Int
if let configId = self.existingTemplateId {
let ids = self.buildTemplates.map { $0.id }
index = ids.indexOf(configId) ?? 0
} else {
index = 0
}
self.selectItemAtIndex(index)
self.existingBuildTemplatesPopup.selectItemAtIndex(index)
}
func addNewString() -> String {
return "Add new build template..."
}
func newTemplate() -> BuildTemplate {
return BuildTemplate() //TODO: pass the project name!
}
override func shouldGoNext() -> Bool {
self.didSelectBuildTemplate(self.selectedTemplate.value!)
return super.shouldGoNext()
}
private func setupEditableStates() {
self.nextAllowed <~ self.selectedTemplate.producer.map { $0 != nil }
}
private func selectItemAtIndex(index: Int) {
let templates = self.buildTemplates
// last item is "add new"
let template = (index == templates.count) ? self.newTemplate() : templates[index]
self.selectedTemplate.value = template
}
private func setupPopupAction() {
let handler = SignalProducer<AnyObject, NoError> { [weak self] sink, _ in
if let sself = self {
let index = sself.existingBuildTemplatesPopup.indexOfSelectedItem
sself.selectItemAtIndex(index)
}
sink.sendCompleted()
}
let action = Action { (_: AnyObject?) in handler }
self.existingBuildTemplatesPopup.rac_command = toRACCommand(action)
}
private func setupDataSource() {
let templatesProducer = self.storageManager
.buildTemplatesForProjectName(self.projectName)
let allTemplatesProducer = templatesProducer
.map { templates in templates.sort { $0.name < $1.name } }
allTemplatesProducer.startWithNext { [weak self] newTemplates in
guard let sself = self else { return }
sself.buildTemplates = newTemplates
let popup = sself.existingBuildTemplatesPopup
popup.removeAllItems()
let unnamed = "Untitled template"
var configDisplayNames = newTemplates.map { template -> String in
let project = template.projectName ?? ""
return "\(template.name ?? unnamed) (\(project))"
}
configDisplayNames.append(self?.addNewString() ?? ":(")
popup.addItemsWithTitles(configDisplayNames)
}
}
private func didSelectBuildTemplate(template: BuildTemplate) {
Log.verbose("Selected \(template.name)")
self.emptyTemplateDelegate?.didSelectBuildTemplate(template)
}
}
| mit | 4c69343cabdbf0b5fdced0a9c37ae622 | 32.536585 | 89 | 0.632242 | 5.288462 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKitUI/helper/Trip+Titles.swift | 1 | 1957 | //
// Trip+Titles.swift
// TripKitUI-iOS
//
// Created by Adrian Schönig on 04.09.19.
// Copyright © 2019 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import TripKit
extension Trip {
func timeTitles(capitalize: Bool) -> (title: String, subtitle: String)? {
guard let departureTime = departureTime, let arrivalTime = arrivalTime else {
return nil // This can happen during KVO
}
return Self.timeTitles(
departure: departureTime,
arrival: arrivalTime,
departureTimeZone: departureTimeZone,
arrivalTimeZone: arrivalTimeZone ?? departureTimeZone,
focusOnDuration: !departureTimeIsFixed,
hideExactTimes: hideExactTimes,
isArriveBefore: request.type == .arriveBefore,
capitalize: true
)
}
static func timeTitles(departure: Date, arrival: Date, departureTimeZone: TimeZone, arrivalTimeZone: TimeZone, focusOnDuration: Bool, hideExactTimes: Bool, isArriveBefore: Bool, capitalize: Bool = false) -> (title: String, subtitle: String) {
guard !hideExactTimes else { return ("", "") }
let duration = arrival.durationSince(departure)
if focusOnDuration {
let subtitle: String
if isArriveBefore {
let timeText = TKStyleManager.timeString(departure, for: departureTimeZone, relativeTo: arrivalTimeZone)
subtitle = Loc.Departs(atTime: timeText, capitalize: capitalize)
} else {
let timeText = TKStyleManager.timeString(arrival, for: arrivalTimeZone, relativeTo: departureTimeZone)
subtitle = Loc.Arrives(atTime: timeText, capitalize: capitalize)
}
return (duration, subtitle)
} else {
var title = TKStyleManager.timeString(departure, for: departureTimeZone, relativeTo: arrivalTimeZone)
title += " - "
title += TKStyleManager.timeString(arrival, for: arrivalTimeZone, relativeTo: departureTimeZone)
return (title, duration)
}
}
}
| apache-2.0 | 6058834d04451162df87a8bfc5940200 | 32.706897 | 244 | 0.692583 | 4.494253 | false | false | false | false |
Incipia/IncipiaKit | IncipiaKit/UIKit-Extensions/UIView+Extensions.swift | 1 | 3974 | //
// UIView+Extensions.swift
// IncipiaKit
//
// Created by Gregory Klein on 7/20/16.
// Copyright © 2016 Incipia. All rights reserved.
//
import UIKit
public extension UIView {
public func addAndFill(subview subview: UIView) {
addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
subview.topAnchor.constraintEqualToAnchor(topAnchor).active = true
subview.bottomAnchor.constraintEqualToAnchor(bottomAnchor).active = true
subview.leadingAnchor.constraintEqualToAnchor(leadingAnchor).active = true
subview.trailingAnchor.constraintEqualToAnchor(trailingAnchor).active = true
}
public func addBorder(withSize size: CGFloat, toEdge edge: UIRectEdge, padding: CGFloat = 0.0) -> UIView? {
switch edge {
case UIRectEdge.Top: return _addTopBorder(withSize: size, padding: padding)
case UIRectEdge.Left: return _addLeftBorder(withSize: size, padding: padding)
case UIRectEdge.Bottom: return _addBottomBorder(withSize: size, padding: padding)
case UIRectEdge.Right: return _addRightBorder(withSize: size, padding: padding)
default: return nil
}
}
public func addBorders(withSize size: CGFloat, toEdges edges: UIRectEdge, padding: CGFloat = 0.0) -> [UIView] {
var borders: [UIView] = []
if edges.contains(.Top) {
borders.append(_addTopBorder(withSize: size, padding: padding))
}
if edges.contains(.Left) {
borders.append(_addLeftBorder(withSize: size, padding: padding))
}
if edges.contains(.Bottom) {
borders.append(_addBottomBorder(withSize: size, padding: padding))
}
if edges.contains(.Right) {
borders.append(_addRightBorder(withSize: size, padding: padding))
}
return borders
}
public func addBordersToAllEdges(borderSize size: CGFloat) -> [UIView] {
return addBorders(withSize: size, toEdges: [.Top, .Right, .Bottom, .Left])
}
private func _addTopBorder(withSize size: CGFloat, padding: CGFloat) -> UIView {
let border = UIView()
addSubview(border)
border.translatesAutoresizingMaskIntoConstraints = false
border.topAnchor.constraintEqualToAnchor(topAnchor).active = true
border.leftAnchor.constraintEqualToAnchor(leftAnchor, constant: padding).active = true
border.rightAnchor.constraintEqualToAnchor(rightAnchor, constant: -padding).active = true
border.heightAnchor.constraintEqualToConstant(size).active = true
return border
}
private func _addBottomBorder(withSize size: CGFloat, padding: CGFloat) -> UIView {
let border = UIView()
addSubview(border)
border.translatesAutoresizingMaskIntoConstraints = false
border.bottomAnchor.constraintEqualToAnchor(bottomAnchor).active = true
border.leftAnchor.constraintEqualToAnchor(leftAnchor, constant: padding).active = true
border.rightAnchor.constraintEqualToAnchor(rightAnchor, constant: -padding).active = true
border.heightAnchor.constraintEqualToConstant(size).active = true
return border
}
private func _addLeftBorder(withSize size: CGFloat, padding: CGFloat) -> UIView {
let border = UIView()
addSubview(border)
border.translatesAutoresizingMaskIntoConstraints = false
border.leftAnchor.constraintEqualToAnchor(leftAnchor).active = true
border.topAnchor.constraintEqualToAnchor(topAnchor, constant: padding).active = true
border.bottomAnchor.constraintEqualToAnchor(bottomAnchor, constant: -padding).active = true
border.widthAnchor.constraintEqualToConstant(size).active = true
return border
}
private func _addRightBorder(withSize size: CGFloat, padding: CGFloat) -> UIView {
let border = UIView()
addSubview(border)
border.translatesAutoresizingMaskIntoConstraints = false
border.rightAnchor.constraintEqualToAnchor(rightAnchor).active = true
border.topAnchor.constraintEqualToAnchor(topAnchor, constant: padding).active = true
border.bottomAnchor.constraintEqualToAnchor(bottomAnchor, constant: -padding).active = true
border.widthAnchor.constraintEqualToConstant(size).active = true
return border
}
}
| apache-2.0 | 898d4b842f7decf0e797f488c76e836a | 36.838095 | 112 | 0.771709 | 4.361142 | false | false | false | false |
RevenueCat/purchases-ios | Tests/UnitTests/Mocks/MockSubscriberAttributesManager.swift | 1 | 15664 | //
// Created by RevenueCat on 3/2/20.
// Copyright (c) 2020 Purchases. All rights reserved.
//
@testable import RevenueCat
// swiftlint:disable identifier_name
// swiftlint:disable line_length
class MockSubscriberAttributesManager: SubscriberAttributesManager {
var invokedSetAttributes = false
var invokedSetAttributesCount = 0
var invokedSetAttributesParameters: (attributes: [String: String], appUserID: String)?
var invokedSetAttributesParametersList = [(attributes: [String: String], appUserID: String)]()
override func setAttributes(_ attributes: [String: String], appUserID: String) {
invokedSetAttributes = true
invokedSetAttributesCount += 1
invokedSetAttributesParameters = (attributes, appUserID)
invokedSetAttributesParametersList.append((attributes, appUserID))
}
var invokedSetEmail = false
var invokedSetEmailCount = 0
var invokedSetEmailParameters: (email: String?, appUserID: String)?
var invokedSetEmailParametersList = [(email: String?, appUserID: String)]()
override func setEmail(_ email: String?, appUserID: String) {
invokedSetEmail = true
invokedSetEmailCount += 1
invokedSetEmailParameters = (email, appUserID)
invokedSetEmailParametersList.append((email, appUserID))
}
var invokedSetPhoneNumber = false
var invokedSetPhoneNumberCount = 0
var invokedSetPhoneNumberParameters: (phoneNumber: String?, appUserID: String)?
var invokedSetPhoneNumberParametersList = [(phoneNumber: String?, appUserID: String)]()
override func setPhoneNumber(_ phoneNumber: String?, appUserID: String) {
invokedSetPhoneNumber = true
invokedSetPhoneNumberCount += 1
invokedSetPhoneNumberParameters = (phoneNumber, appUserID)
invokedSetPhoneNumberParametersList.append((phoneNumber, appUserID))
}
var invokedSetDisplayName = false
var invokedSetDisplayNameCount = 0
var invokedSetDisplayNameParameters: (displayName: String?, appUserID: String)?
var invokedSetDisplayNameParametersList = [(displayName: String?, appUserID: String)]()
override func setDisplayName(_ displayName: String?, appUserID: String) {
invokedSetDisplayName = true
invokedSetDisplayNameCount += 1
invokedSetDisplayNameParameters = (displayName, appUserID)
invokedSetDisplayNameParametersList.append((displayName, appUserID))
}
var invokedSetPushToken = false
var invokedSetPushTokenCount = 0
var invokedSetPushTokenParameters: (pushToken: Data?, appUserID: String)?
var invokedSetPushTokenParametersList = [(pushToken: Data?, appUserID: String)]()
override func setPushToken(_ pushToken: Data?, appUserID: String) {
invokedSetPushToken = true
invokedSetPushTokenCount += 1
invokedSetPushTokenParameters = (pushToken, appUserID)
invokedSetPushTokenParametersList.append((pushToken, appUserID))
}
var invokedSetPushTokenString = false
var invokedSetPushTokenStringCount = 0
var invokedSetPushTokenStringParameters: (pushToken: String?, appUserID: String?)?
var invokedSetPushTokenStringParametersList = [(pushToken: String?, appUserID: String?)]()
override func setPushTokenString(_ pushToken: String?, appUserID: String?) {
invokedSetPushTokenString = true
invokedSetPushTokenStringCount += 1
invokedSetPushTokenStringParameters = (pushToken, appUserID)
invokedSetPushTokenStringParametersList.append((pushToken, appUserID))
}
var invokedSetAdjustID = false
var invokedSetAdjustIDCount = 0
var invokedSetAdjustIDParameters: (adjustID: String?, appUserID: String?)?
var invokedSetAdjustIDParametersList = [(pushToken: String?, appUserID: String?)]()
override func setAdjustID(_ adjustID: String?, appUserID: String) {
invokedSetAdjustID = true
invokedSetAdjustIDCount += 1
invokedSetAdjustIDParameters = (adjustID, appUserID)
invokedSetAdjustIDParametersList.append((adjustID, appUserID))
}
var invokedSetAppsflyerID = false
var invokedSetAppsflyerIDCount = 0
var invokedSetAppsflyerIDParameters: (appsflyerID: String?, appUserID: String?)?
var invokedSetAppsflyerIDParametersList = [(appsflyerID: String?, appUserID: String?)]()
override func setAppsflyerID(_ appsflyerID: String?, appUserID: String) {
invokedSetAppsflyerID = true
invokedSetAppsflyerIDCount += 1
invokedSetAppsflyerIDParameters = (appsflyerID, appUserID)
invokedSetAppsflyerIDParametersList.append((appsflyerID, appUserID))
}
var invokedSetFBAnonymousID = false
var invokedSetFBAnonymousIDCount = 0
var invokedSetFBAnonymousIDParameters: (fbAnonymousID: String?, appUserID: String?)?
var invokedSetFBAnonymousIDParametersList = [(fbAnonymousID: String?, appUserID: String?)]()
override func setFBAnonymousID(_ fbAnonymousID: String?, appUserID: String) {
invokedSetFBAnonymousID = true
invokedSetFBAnonymousIDCount += 1
invokedSetFBAnonymousIDParameters = (fbAnonymousID, appUserID)
invokedSetFBAnonymousIDParametersList.append((fbAnonymousID, appUserID))
}
var invokedSetMparticleID = false
var invokedSetMparticleIDCount = 0
var invokedSetMparticleIDParameters: (mparticleID: String?, appUserID: String?)?
var invokedSetMparticleIDParametersList = [(mparticleID: String?, appUserID: String?)]()
override func setMparticleID(_ mparticleID: String?, appUserID: String) {
invokedSetMparticleID = true
invokedSetMparticleIDCount += 1
invokedSetMparticleIDParameters = (mparticleID, appUserID)
invokedSetMparticleIDParametersList.append((mparticleID, appUserID))
}
var invokedSetOnesignalID = false
var invokedSetOnesignalIDCount = 0
var invokedSetOnesignalIDParameters: (onesignalID: String?, appUserID: String?)?
var invokedSetOnesignalIDParametersList = [(onesignalID: String?, appUserID: String?)]()
override func setOnesignalID(_ onesignalID: String?, appUserID: String) {
invokedSetOnesignalID = true
invokedSetOnesignalIDCount += 1
invokedSetOnesignalIDParameters = (onesignalID, appUserID)
invokedSetOnesignalIDParametersList.append((onesignalID, appUserID))
}
var invokedSetAirshipChannelID = false
var invokedSetAirshipChannelIDCount = 0
var invokedSetAirshipChannelIDParameters: (airshipChannelID: String?, appUserID: String?)?
var invokedSetAirshipChannelIDParametersList = [(airshipChannelID: String?, appUserID: String?)]()
override func setAirshipChannelID(_ airshipChannelID: String?, appUserID: String) {
invokedSetAirshipChannelID = true
invokedSetAirshipChannelIDCount += 1
invokedSetAirshipChannelIDParameters = (airshipChannelID, appUserID)
invokedSetAirshipChannelIDParametersList.append((airshipChannelID, appUserID))
}
var invokedSetCleverTapID = false
var invokedSetCleverTapIDCount = 0
var invokedSetCleverTapIDParameters: (CleverTapID: String?, appUserID: String?)?
var invokedSetCleverTapIDParametersList = [(CleverTapID: String?, appUserID: String?)]()
override func setCleverTapID(_ cleverTapID: String?, appUserID: String) {
invokedSetCleverTapID = true
invokedSetCleverTapIDCount += 1
invokedSetCleverTapIDParameters = (cleverTapID, appUserID)
invokedSetCleverTapIDParametersList.append((cleverTapID, appUserID))
}
var invokedSetMixpanelDistinctID = false
var invokedSetMixpanelDistinctIDCount = 0
var invokedSetMixpanelDistinctIDParameters: (mixpanelDistinctID: String?, appUserID: String?)?
var invokedSetMixpanelDistinctIDParametersList = [(mixpanelDistinctID: String?, appUserID: String?)]()
override func setMixpanelDistinctID(_ mixpanelDistinctID: String?, appUserID: String) {
invokedSetMixpanelDistinctID = true
invokedSetMixpanelDistinctIDCount += 1
invokedSetMixpanelDistinctIDParameters = (mixpanelDistinctID, appUserID)
invokedSetMixpanelDistinctIDParametersList.append((mixpanelDistinctID, appUserID))
}
var invokedSetFirebaseAppInstanceID = false
var invokedSetFirebaseAppInstanceIDCount = 0
var invokedSetFirebaseAppInstanceIDParameters: (firebaseAppInstanceID: String?, appUserID: String?)?
var invokedSetFirebaseAppInstanceIDParametersList = [(firebaseAppInstanceID: String?, appUserID: String?)]()
override func setFirebaseAppInstanceID(_ firebaseAppInstanceID: String?, appUserID: String) {
invokedSetFirebaseAppInstanceID = true
invokedSetFirebaseAppInstanceIDCount += 1
invokedSetFirebaseAppInstanceIDParameters = (firebaseAppInstanceID, appUserID)
invokedSetFirebaseAppInstanceIDParametersList.append((firebaseAppInstanceID, appUserID))
}
var invokedSetMediaSource = false
var invokedSetMediaSourceCount = 0
var invokedSetMediaSourceParameters: (mediaSource: String?, appUserID: String?)?
var invokedSetMediaSourceParametersList = [(mediaSource: String?, appUserID: String?)]()
override func setMediaSource(_ mediaSource: String?, appUserID: String) {
invokedSetMediaSource = true
invokedSetMediaSourceCount += 1
invokedSetMediaSourceParameters = (mediaSource, appUserID)
invokedSetMediaSourceParametersList.append((mediaSource, appUserID))
}
var invokedSetCampaign = false
var invokedSetCampaignCount = 0
var invokedSetCampaignParameters: (campaign: String?, appUserID: String?)?
var invokedSetCampaignParametersList = [(campaign: String?, appUserID: String?)]()
override func setCampaign(_ campaign: String?, appUserID: String) {
invokedSetCampaign = true
invokedSetCampaignCount += 1
invokedSetCampaignParameters = (campaign, appUserID)
invokedSetCampaignParametersList.append((campaign, appUserID))
}
var invokedSetAdGroup = false
var invokedSetAdGroupCount = 0
var invokedSetAdGroupParameters: (adGroup: String?, appUserID: String?)?
var invokedSetAdGroupParametersList = [(adGroup: String?, appUserID: String?)]()
override func setAdGroup(_ adGroup: String?, appUserID: String) {
invokedSetAdGroup = true
invokedSetAdGroupCount += 1
invokedSetAdGroupParameters = (adGroup, appUserID)
invokedSetAdGroupParametersList.append((adGroup, appUserID))
}
var invokedSetAd = false
var invokedSetAdCount = 0
var invokedSetAdParameters: (ad: String?, appUserID: String?)?
var invokedSetAdParametersList = [(ad: String?, appUserID: String?)]()
override func setAd(_ ad: String?, appUserID: String) {
invokedSetAd = true
invokedSetAdCount += 1
invokedSetAdParameters = (ad, appUserID)
invokedSetAdParametersList.append((ad, appUserID))
}
var invokedSetKeyword = false
var invokedSetKeywordCount = 0
var invokedSetKeywordParameters: (keyword: String?, appUserID: String?)?
var invokedSetKeywordParametersList = [(keyword: String?, appUserID: String?)]()
override func setKeyword(_ keyword: String?, appUserID: String) {
invokedSetKeyword = true
invokedSetKeywordCount += 1
invokedSetKeywordParameters = (keyword, appUserID)
invokedSetKeywordParametersList.append((keyword, appUserID))
}
var invokedSetCreative = false
var invokedSetCreativeCount = 0
var invokedSetCreativeParameters: (creative: String?, appUserID: String?)?
var invokedSetCreativeParametersList = [(creative: String?, appUserID: String?)]()
override func setCreative(_ creative: String?, appUserID: String) {
invokedSetCreative = true
invokedSetCreativeCount += 1
invokedSetCreativeParameters = (creative, appUserID)
invokedSetCreativeParametersList.append((creative, appUserID))
}
var invokedUnsyncedAttributesByKey = false
var invokedUnsyncedAttributesByKeyCount = 0
var invokedUnsyncedAttributesByKeyParameters: (appUserID: String, Void)?
var invokedUnsyncedAttributesByKeyParametersList = [(appUserID: String, Void)]()
var stubbedUnsyncedAttributesByKeyResult: [String: SubscriberAttribute]! = [:]
override func unsyncedAttributesByKey(appUserID: String) -> [String: SubscriberAttribute] {
invokedUnsyncedAttributesByKey = true
invokedUnsyncedAttributesByKeyCount += 1
invokedUnsyncedAttributesByKeyParameters = (appUserID, ())
invokedUnsyncedAttributesByKeyParametersList.append((appUserID, ()))
return stubbedUnsyncedAttributesByKeyResult
}
var invokedMarkAttributes = false
var invokedMarkAttributesCount = 0
var invokedMarkAttributesParameters: (syncedAttributes: [String: SubscriberAttribute]?, appUserID: String)?
var invokedMarkAttributesParametersList = [(syncedAttributes: [String: SubscriberAttribute]?, appUserID: String)]()
override func markAttributesAsSynced(_ syncedAttributes: [String: SubscriberAttribute]?,
appUserID: String) {
invokedMarkAttributes = true
invokedMarkAttributesCount += 1
invokedMarkAttributesParameters = (syncedAttributes, appUserID)
invokedMarkAttributesParametersList.append((syncedAttributes, appUserID))
}
var invokedSyncAttributesForAllUsers = false
var invokedSyncAttributesForAllUsersCount = 0
var invokedSyncAttributesForAllUsersParameters: (currentAppUserID: String?, Void)?
var invokedSyncAttributesForAllUsersParametersList = [(currentAppUserID: String?, Void)]()
override func syncAttributesForAllUsers(
currentAppUserID: String,
syncedAttribute: (@Sendable (PurchasesError?) -> Void)? = nil,
completion: (@Sendable () -> Void)? = nil
) -> Int {
invokedSyncAttributesForAllUsers = true
invokedSyncAttributesForAllUsersCount += 1
invokedSyncAttributesForAllUsersParameters = (currentAppUserID, ())
invokedSyncAttributesForAllUsersParametersList.append((currentAppUserID, ()))
return -1
}
var invokedCollectDeviceIdentifiers = false
var invokedCollectDeviceIdentifiersCount = 0
var invokedCollectDeviceIdentifiersParameters: (appUserID: String?, Void)?
var invokedCollectDeviceIdentifiersParametersList = [(appUserID: String?, Void)]()
override func collectDeviceIdentifiers(forAppUserID appUserID: String) {
invokedCollectDeviceIdentifiers = true
invokedCollectDeviceIdentifiersCount += 1
invokedCollectDeviceIdentifiersParameters = (appUserID, ())
invokedCollectDeviceIdentifiersParametersList.append((appUserID, ()))
}
var invokedConvertAttributionDataAndSet = false
var invokedConvertAttributionDataAndSetCount = 0
var invokedConvertAttributionDataAndSetParameters: (attributionData: [String: Any], network: AttributionNetwork, appUserID: String)?
var invokedConvertAttributionDataAndSetParametersList = [(attributionData: [String: Any], network: AttributionNetwork, appUserID: String)]()
override func setAttributes(fromAttributionData attributionData: [String: Any],
network: AttributionNetwork,
appUserID: String) {
invokedConvertAttributionDataAndSet = true
invokedConvertAttributionDataAndSetCount += 1
invokedConvertAttributionDataAndSetParameters = (attributionData, network, appUserID)
invokedConvertAttributionDataAndSetParametersList.append((attributionData, network, appUserID))
}
}
| mit | 07b415487776abce3451809e2cb79e57 | 45.758209 | 144 | 0.740871 | 5.039897 | false | false | false | false |
ZeeQL/ZeeQL3 | Sources/ZeeQL/Control/Key.swift | 1 | 2369 | //
// Key.swift
// ZeeQL
//
// Created by Helge Hess on 15/02/2017.
// Copyright © 2017-2019 ZeeZide GmbH. All rights reserved.
//
public protocol Key : Expression, ExpressionEvaluation, EquatableType,
CustomStringConvertible
{
var key : String { get }
// MARK: - building keys
func append(_ key: Key) -> Key
}
public extension Key {
// MARK: - value
func rawValue(in object: Any?) -> Any? {
guard let object = object else { return nil }
return KeyValueCoding.value(forKeyPath: key, inObject: object)
}
func valueFor(object: Any?) -> Any? {
return rawValue(in: object)
}
// TODO: Add convenience methods
// MARK: - Equality
func isEqual(to object: Any?) -> Bool {
guard let other = object as? Key else { return false }
return self.key == other.key // Hm.
}
// MARK: - building keys
func append(_ key: Key) -> Key { return KeyPath(self, key) }
func append(_ key: String) -> Key { return append(StringKey(key)) }
func dot (_ key: Key) -> Key { return KeyPath(self, key) }
func dot(_ key: String) -> Key { // Key("persons").dot("name")
return append(StringKey(key))
}
}
public struct StringKey : Key, Equatable {
public let key : String
public init(_ key: String) { self.key = key }
public static func ==(lhs: StringKey, rhs: StringKey) -> Bool {
return lhs.key == rhs.key
}
}
public struct KeyPath : Key, Equatable {
public var keys : [ Key ]
public var key : String { return keys.map { $0.key }.joined(separator: ".") }
public init(_ keys: Key...) { self.keys = keys }
public init(keys: Key...) { self.keys = keys }
public static func ==(lhs: KeyPath, rhs: KeyPath) -> Bool {
// TODO: just compare the arrays
guard lhs.keys.count == rhs.keys.count else { return false }
return lhs.key == rhs.key
}
public var description : String {
return "<KeyPath: \(key)>"
}
}
public extension Key {
var description : String { return "<Key: \(key)>" }
}
extension StringKey : ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.key = value
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.key = value
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.key = value
}
}
| apache-2.0 | f8b93447cfe4eb3b0dc00e854515b789 | 21.990291 | 80 | 0.619932 | 3.837925 | false | false | false | false |
amarantine308/OneDayOneDemo_Swift | Day8_生成二维码,扫一扫/QRCode/UIImage+QRCode.swift | 2 | 2244 | //
// UIImage+QRCode.swift
// QRCode
//
// Created by gaofu on 16/9/9.
// Copyright © 2016年 gaofu. All rights reserved.
//
import UIKit
import CoreImage
extension UIImage
{
/**
1.识别图片二维码
- returns: 二维码内容
*/
func recognizeQRCode() -> String?
{
let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy : CIDetectorAccuracyHigh])
let features = detector?.features(in: CoreImage.CIImage(cgImage: self.cgImage!))
guard (features?.count)! > 0 else { return nil }
let feature = features?.first as? CIQRCodeFeature
return feature?.messageString
}
//2.获取圆角图片
func getRoundRectImage(size:CGFloat,radius:CGFloat) -> UIImage
{
return getRoundRectImage(size: size, radius: radius, borderWidth: nil, borderColor: nil)
}
//3.获取圆角图片(带边框)
func getRoundRectImage(size:CGFloat,radius:CGFloat,borderWidth:CGFloat?,borderColor:UIColor?) -> UIImage
{
let scale = self.size.width / size ;
//初始值
var defaultBorderWidth : CGFloat = 0
var defaultBorderColor = UIColor.clear
if let borderWidth = borderWidth { defaultBorderWidth = borderWidth * scale }
if let borderColor = borderColor { defaultBorderColor = borderColor }
let radius = radius * scale
let react = CGRect(x: defaultBorderWidth, y: defaultBorderWidth, width: self.size.width - 2 * defaultBorderWidth, height: self.size.height - 2 * defaultBorderWidth)
//绘制图片设置
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
let path = UIBezierPath(roundedRect:react , cornerRadius: radius)
//绘制边框
path.lineWidth = defaultBorderWidth
defaultBorderColor.setStroke()
path.stroke()
path.addClip()
//画图片
draw(in: react)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!;
}
}
| gpl-3.0 | 1ff414eff4273d4b9cdfe8c301415392 | 26.278481 | 172 | 0.617169 | 4.810268 | false | false | false | false |
iosliutingxin/DYVeideoVideo | DYZB/DYZB/Classes/Main/View/PageTitleView.swift | 1 | 5427 | //
// PageTitleView.swift
// DYZB
//
// Created by 北京时代华擎 on 17/5/1.
// Copyright © 2017年 iOS _Liu. All rights reserved.
//
import UIKit
//定义一个协议传递头部导航栏的信息到
protocol pageTitleDelegate : class
{
func pageTitleView(_ titleView : PageTitleView,selectedIndex index:Int)
}
private let scrollLineH :CGFloat=2
class PageTitleView: UIView {
//定义属性
fileprivate var titles :[String]
public var currentIndex : Int = 0
weak var delegate : pageTitleDelegate?
//懒加载属性
fileprivate lazy var scrollView:UIScrollView={
let scrollView=UIScrollView()
scrollView.showsHorizontalScrollIndicator=false
scrollView.scrollsToTop=false
scrollView.bounces=false
return scrollView
}()
fileprivate lazy var titleLables : [UILabel] = [UILabel]()
fileprivate lazy var scrollerLine:UIView = {
let scrollerLine=UIView()
scrollerLine.backgroundColor=UIColor.orange
return scrollerLine
}()
//自定义构造函数
init(frame: CGRect,titles:[String]) {
self.titles=titles
super.init(frame:frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//监听lable的点击
extension PageTitleView{
@objc fileprivate func titleLableClick(_ tagGes : UITapGestureRecognizer){
//1、获取当前lable
guard let currentLable = tagGes.view as? UILabel else { return }
//2、获取之前lable
let oldLable = titleLables[currentIndex]
//3、保存最新lable下标值
currentIndex = currentLable.tag
//4、切换颜色
currentLable.textColor = UIColor.orange
oldLable.textColor = UIColor.darkGray
//5、设置滚动条颜色
let scollerlineX = CGFloat(currentIndex) * scrollerLine.frame.width
UIView.animate(withDuration: 0.15, animations: {
self.scrollerLine.frame.origin.x = scollerlineX
})
//6.通知代理
delegate?.pageTitleView(self, selectedIndex: currentIndex)
}
}
extension PageTitleView{
fileprivate func setupUI(){
// 1、添加UISCollerView
addSubview(scrollView)
scrollView.frame=bounds
//2、添加title对应的Lable
setupTitleLables()
//3、设置底线和滚动滑块
setupBottonLineAndScollLine()
}
fileprivate func setupBottonLineAndScollLine(){
let botton=UIView()
botton.backgroundColor=UIColor.red
let lineH:CGFloat = 0.5
botton.frame=CGRect(x: 0, y: frame.height-lineH, width: frame.width, height: lineH)
// scrollView.addSubview(botton)
addSubview(botton)
//1、获取第一个label
guard let firstLabel = titleLables.first else {return}
firstLabel.textColor = UIColor.orange
//2、设置scrollerLine的属性
scrollView.addSubview(scrollerLine)
scrollerLine.frame=CGRect(x: firstLabel.frame.origin.x, y: frame.height - scrollLineH, width: firstLabel.frame.width, height: scrollLineH)
}
fileprivate func setupTitleLables(){
for (index,title) in titles.enumerated(){
//1、创建UILable
let lable=UILabel()
lable.text=title
lable.tag=index
lable.textAlignment = .center
lable.textColor=UIColor.darkGray
lable.font=UIFont.systemFont(ofSize: 16.0)
let lableW:CGFloat=frame.width / CGFloat(titles.count)
let lableH:CGFloat=frame.height - scrollLineH
let lableX:CGFloat=lableW * CGFloat(index)
let lableY:CGFloat=0
lable.frame=CGRect(x: lableX, y: lableY, width: lableW, height: lableH)
//2、将uilable添加到scrollerview中
scrollView.addSubview(lable)
titleLables.append(lable)
//3、给lable添加手势,应许交互
lable.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action:#selector(PageTitleView.titleLableClick(_:)))
lable.addGestureRecognizer(tapGes)
}
}
}
//对外暴露的方法
/**
1、通过typealie传递滚动的页面信息,然后传给主控制器的currentIndex、通过didset监听其变换,然后调用当前控制器对外暴露的方法实现标题随内容的滚动而滚动
*/
extension PageTitleView{
func setCurrentId(_ currentIndex:Int){
//2、获取lable
let oldLable = titleLables[self.currentIndex]
let currentLable = titleLables[currentIndex]
//3、保存最新lable下标值
self.currentIndex = currentIndex
//4、切换颜色
currentLable.textColor = UIColor.orange
oldLable.textColor = UIColor.darkGray
//5、设置滚动条颜色
let scollerlineX = CGFloat(currentIndex) * scrollerLine.frame.width
UIView.animate(withDuration: 0.15, animations: {
self.scrollerLine.frame.origin.x = scollerlineX
})
}
}
| mit | 6a6681757ab779b0409dc2a2bb9e3a89 | 23.416667 | 146 | 0.613933 | 4.447321 | false | false | false | false |
practicalswift/swift | test/Constraints/ErrorBridging.swift | 41 | 1954 | // RUN: %target-swift-frontend %clang-importer-sdk -typecheck %s -verify
// REQUIRES: objc_interop
import Foundation
enum FooError: HairyError, Runcible {
case A
var hairiness: Int { return 0 }
func runce() {}
}
protocol HairyError : Error {
var hairiness: Int { get }
}
protocol Runcible {
func runce()
}
let foo = FooError.A
let error: Error = foo
let subError: HairyError = foo
let compo: HairyError & Runcible = foo
// Error-conforming concrete or existential types can be coerced explicitly
// to NSError.
let ns1 = foo as NSError
let ns2 = error as NSError
let ns3 = subError as NSError
var ns4 = compo as NSError
// NSError conversion must be explicit.
// TODO: fixit to insert 'as NSError'
ns4 = compo // expected-error{{cannot assign value of type 'HairyError & Runcible' to type 'NSError'}}
let e1 = ns1 as? FooError
let e1fix = ns1 as FooError // expected-error{{did you mean to use 'as!'}} {{17-19=as!}}
let esub = ns1 as Error
let esub2 = ns1 as? Error // expected-warning{{conditional cast from 'NSError' to 'Error' always succeeds}}
// SR-1562 / rdar://problem/26370984
enum MyError : Error {
case failed
}
func concrete1(myError: MyError) -> NSError {
return myError as NSError
}
func concrete2(myError: MyError) -> NSError {
return myError // expected-error{{cannot convert return expression of type 'MyError' to return type 'NSError'}}
}
func generic<T : Error>(error: T) -> NSError {
return error as NSError
}
extension Error {
var asNSError: NSError {
return self as NSError
}
var asNSError2: NSError {
return self // expected-error{{cannot convert return expression of type 'Self' to return type 'NSError'}}
}
}
// rdar://problem/27543121
func throwErrorCode() throws {
throw FictionalServerError.meltedDown // expected-error{{thrown error code type 'FictionalServerError.Code' does not conform to 'Error'; construct an 'FictionalServerError' instance}}{{29-29=(}}{{40-40=)}}
}
| apache-2.0 | e26a69752f8ebb37fc2d8222bc58d1ba | 25.053333 | 207 | 0.71392 | 3.591912 | false | false | false | false |
huonw/swift | stdlib/public/SDK/Intents/INNotebookItemTypeResolutionResult.swift | 25 | 982 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Intents
import Foundation
#if os(iOS) || os(watchOS)
@available(iOS 11.0, watchOS 4.0, *)
extension INNotebookItemTypeResolutionResult {
@nonobjc public
static func disambiguation(with notebookItemTypesToDisambiguate: [INNotebookItemType]) -> Self {
let numbers = notebookItemTypesToDisambiguate.map { NSNumber(value: $0.rawValue) }
return __disambiguationWithNotebookItemTypes(toDisambiguate: numbers)
}
}
#endif
| apache-2.0 | a3a3124418c6d1e289653d89093d9668 | 36.769231 | 100 | 0.624236 | 4.76699 | false | false | false | false |
huonw/swift | validation-test/compiler_crashers_fixed/00062-ioctl.swift | 65 | 1096 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol A {
typealias override func d() -> String {
return ""
}
func c() -> String {
return ""
}
}
func e<T where T: A, T: B>(t: T) {
t.c()
}
protocol b {
claealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
typealias g
}
protocol a {
class func c(dynamicType.c()
var x1 = 1
var f1: Int -> Int = {
return $0
}
let succeeds: Int = { (x: Int, f: Int -> Int) -> Int in
return f(x)
}(x1, f1)
let crashes: Int = { x, f in
return f(x)
}(x1, f1)
b
protocol c : b { func b
import Foundation
class Foo<T>: NSObject {
var foo: T
init(foo: T) {
self.foo = foo
su
var b: ((T,}
}
| apache-2.0 | 26378534a5d9a4ae5df7886076af901a | 20.490196 | 79 | 0.595803 | 3.044444 | false | false | false | false |
markedwardmurray/Precipitate | Pods/SwiftyDate/SwiftyDate.swift | 1 | 4873 |
/**
The MIT License (MIT)
Copyright (c) 2015 Eddie Kaiger
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
/**
This class is used as the middleman for easily constructing a relative date
based on extensions from Swift number types. It is not intended to be used
independently. Instead, use SwiftyDate's extensions to construct statements
such as `12.days.ago()`.
*/
public struct SwiftyDate {
private let seconds: NSTimeInterval
/**
Initializes a new SwiftyDate object.
:param: seconds The total number of seconds to be used as a relative timestamp.
*/
public init(seconds: NSTimeInterval) {
self.seconds = seconds
}
/**
Returns an `NSDate` that represents the specified amount of time ahead of the current date.
*/
public func fromNow() -> NSDate {
return NSDate(timeIntervalSinceNow: seconds)
}
/**
Returns an `NSDate` that represents the specified amount of time before the current date.
*/
public func ago() -> NSDate {
return before(NSDate())
}
/**
Returns an `NSDate` that represents the specified amount of time after a certain date.
:param: date The date of comparison.
*/
public func after(date: NSDate) -> NSDate {
return NSDate(timeInterval: seconds, sinceDate: date)
}
/**
Returns an `NSDate` that represents the specified amount of time before a certain date.
:param: date The date of comparison.
*/
public func before(date: NSDate) -> NSDate {
return NSDate(timeInterval: -seconds, sinceDate: date)
}
}
/** Constants */
private let secondsInMinute: NSTimeInterval = 60
private let secondsInHour: NSTimeInterval = 3600
private let secondsInDay: NSTimeInterval = 86400
private let secondsInWeek: NSTimeInterval = 604800
extension NSTimeInterval {
private func swiftDate(secondsInUnit: NSTimeInterval) -> SwiftyDate {
return SwiftyDate(seconds: self * secondsInUnit)
}
public var seconds: SwiftyDate { return swiftDate(1) }
public var minutes: SwiftyDate { return swiftDate(secondsInMinute) }
public var hours: SwiftyDate { return swiftDate(secondsInHour) }
public var days: SwiftyDate { return swiftDate(secondsInDay) }
public var weeks: SwiftyDate { return swiftDate(secondsInWeek) }
}
extension Int {
public var seconds: SwiftyDate { return NSTimeInterval(self).seconds }
public var minutes: SwiftyDate { return NSTimeInterval(self).minutes }
public var hours: SwiftyDate { return NSTimeInterval(self).hours }
public var days: SwiftyDate { return NSTimeInterval(self).days }
public var weeks: SwiftyDate { return NSTimeInterval(self).weeks }
}
extension CGFloat {
public var seconds: SwiftyDate { return NSTimeInterval(self).seconds }
public var minutes: SwiftyDate { return NSTimeInterval(self).minutes }
public var hours: SwiftyDate { return NSTimeInterval(self).hours }
public var days: SwiftyDate { return NSTimeInterval(self).days }
public var weeks: SwiftyDate { return NSTimeInterval(self).weeks }
}
extension Float {
public var seconds: SwiftyDate { return NSTimeInterval(self).seconds }
public var minutes: SwiftyDate { return NSTimeInterval(self).minutes }
public var hours: SwiftyDate { return NSTimeInterval(self).hours }
public var days: SwiftyDate { return NSTimeInterval(self).days }
public var weeks: SwiftyDate { return NSTimeInterval(self).weeks }
}
extension NSNumber {
public var seconds: SwiftyDate { return doubleValue.seconds }
public var minutes: SwiftyDate { return doubleValue.minutes }
public var hours: SwiftyDate { return doubleValue.hours }
public var days: SwiftyDate { return doubleValue.days }
public var weeks: SwiftyDate { return doubleValue.weeks }
}
| mit | b75461e0f9617ebdf1d523b66e797466 | 36.198473 | 99 | 0.723579 | 4.708213 | false | false | false | false |
mattgallagher/CwlPreconditionTesting | Sources/CwlPreconditionTesting/CwlBadInstructionException.swift | 1 | 3595 | //
// CwlBadInstructionException.swift
// CwlPreconditionTesting
//
// Created by Matt Gallagher on 2016/01/10.
// Copyright © 2016 Matt Gallagher ( https://www.cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#if (os(macOS) || os(iOS)) && (arch(x86_64) || arch(arm64))
import Foundation
#if SWIFT_PACKAGE || COCOAPODS
import CwlMachBadInstructionHandler
#endif
var raiseBadInstructionException = {
BadInstructionException().raise()
} as @convention(c) () -> Void
/// A simple NSException subclass. It's not required to subclass NSException (since the exception type is represented in the name) but this helps for identifying the exception through runtime type.
@objc(BadInstructionException)
public class BadInstructionException: NSException {
static var name: String = "com.cocoawithlove.BadInstruction"
init() {
super.init(name: NSExceptionName(rawValue: BadInstructionException.name), reason: nil, userInfo: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// An Objective-C callable function, invoked from the `mach_exc_server` callback function `catch_mach_exception_raise_state` to push the `raiseBadInstructionException` function onto the stack.
@objc(receiveReply:)
public class func receiveReply(_ reply: bad_instruction_exception_reply_t) -> CInt {
let old_state = UnsafeRawPointer(reply.old_state!).bindMemory(to: NativeThreadState.self, capacity: 1)
let old_stateCnt: mach_msg_type_number_t = reply.old_stateCnt
let new_state = UnsafeMutableRawPointer(reply.new_state!).bindMemory(to: NativeThreadState.self, capacity: 1)
let new_stateCnt: UnsafeMutablePointer<mach_msg_type_number_t> = reply.new_stateCnt!
// Make sure we've been given enough memory
guard
old_stateCnt == nativeThreadStateCount,
new_stateCnt.pointee >= nativeThreadStateCount
else {
return KERN_INVALID_ARGUMENT
}
// 0. Copy over the state.
new_state.pointee = old_state.pointee
#if arch(x86_64)
// 1. Decrement the stack pointer
new_state.pointee.__rsp -= UInt64(MemoryLayout<Int>.size)
// 2. Save the old Instruction Pointer to the stack.
guard let pointer = UnsafeMutablePointer<UInt64>(bitPattern: UInt(new_state.pointee.__rsp)) else {
return KERN_INVALID_ARGUMENT
}
pointer.pointee = old_state.pointee.__rip
// 3. Set the Instruction Pointer to the new function's address
new_state.pointee.__rip = unsafeBitCast(raiseBadInstructionException, to: UInt64.self)
#elseif arch(arm64)
// 1. Set the link register to the current address.
new_state.pointee.__lr = old_state.pointee.__pc
// 2. Set the Instruction Pointer to the new function's address.
new_state.pointee.__pc = unsafeBitCast(raiseBadInstructionException, to: UInt64.self)
#endif
new_stateCnt.pointee = nativeThreadStateCount
return KERN_SUCCESS
}
}
#endif
| isc | 53374c7bd0298e80430d9c742f475376 | 38.065217 | 197 | 0.74847 | 3.839744 | false | false | false | false |
JohnnyDevMode/Hoard | HoardTests/ComplexKeyTests.swift | 1 | 1794 | //
// ComplexKeyTests.swift
// Hoard
//
// Created by John Bailey on 4/9/17.
// Copyright © 2017 DevMode Studios. All rights reserved.
//
import XCTest
@testable import Hoard
class ComplexKeyTests : XCTestCase {
func testNoSegmentsInvalid() {
let key = ComplexKey(segments: [])
XCTAssertEqual("INVALID", key.head)
XCTAssertEqual(Key.Invalid, key.tail)
}
func testSingleSegmentInvalidTail() {
let key = ComplexKey(segments: ["key"])
XCTAssertEqual("key", key.head)
XCTAssertEqual(Key.Invalid, key.tail)
}
func testTwoSegment() {
let key = ComplexKey(segments: ["root", "leaf"])
XCTAssertEqual("root", key.head)
XCTAssertNotNil(key.tail as? SimpleKey)
if let tail = key.tail as? SimpleKey {
XCTAssertEqual("leaf", tail.key)
}
}
func testMultiSegment() {
let key = ComplexKey(segments: ["root", "mid", "leaf"])
XCTAssertEqual("root", key.head)
XCTAssertNotNil(key.tail as? ComplexKey)
if let mid = key.tail as? ComplexKey {
XCTAssertEqual("mid", mid.head)
XCTAssertNotNil(mid.tail as? SimpleKey)
if let leaf = mid.tail as? SimpleKey {
XCTAssertEqual("leaf", leaf.key)
}
}
}
func testCrazySegment() {
let key = ComplexKey(segments: ["root", "mid", "nextmid", "leaf"])
XCTAssertEqual("root", key.head)
XCTAssertNotNil(key.tail as? ComplexKey)
if let mid = key.tail as? ComplexKey {
XCTAssertEqual("mid", mid.head)
XCTAssertNotNil(mid.tail as? ComplexKey)
if let nextmid = mid.tail as? ComplexKey {
XCTAssertEqual("nextmid", nextmid.head)
XCTAssertNotNil(nextmid.tail as? SimpleKey)
if let leaf = nextmid.tail as? SimpleKey {
XCTAssertEqual("leaf", leaf.key)
}
}
}
}
}
| mit | 713fbf612b38daca3a16a26b54d1e6eb | 26.584615 | 70 | 0.640825 | 4.011186 | false | true | false | false |
mro/ShaarliOS | swift4/ShaarliOS/3rd/KeychainPasswordItem.swift | 1 | 7949 | /*
https://developer.apple.com/library/archive/samplecode/GenericKeychain/Listings/GenericKeychain_KeychainPasswordItem_swift.html#//apple_ref/doc/uid/DTS40007797-GenericKeychain_KeychainPasswordItem_swift-DontLinkElementID_7
via https://developer.apple.com/library/archive/samplecode/GenericKeychain/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007797
via https://l.mro.name/o/p/a8b2sa5/
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A struct for accessing generic password keychain items.
*/
import Foundation
struct KeychainPasswordItem {
// MARK: Types
enum KeychainError: Error {
case noPassword
case unexpectedPasswordData
case unexpectedItemData
case unhandledError(status: OSStatus)
}
// MARK: Properties
let service: String
private(set) var account: String
let accessGroup: String?
// MARK: Intialization
init(service: String, account: String, accessGroup: String? = nil) {
self.service = service
self.account = account
self.accessGroup = accessGroup
}
// MARK: Keychain access
func readPassword() throws -> String {
/*
Build a query to find the item that matches the service, account and
access group.
*/
var query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
query[kSecMatchLimit as String] = kSecMatchLimitOne
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecReturnData as String] = kCFBooleanTrue
// Try to fetch the existing keychain item that matches the query.
var queryResult: AnyObject?
let status = withUnsafeMutablePointer(to: &queryResult) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
// Check the return status and throw an error if appropriate.
guard status != errSecItemNotFound else { throw KeychainError.noPassword }
guard status == noErr else { throw KeychainError.unhandledError(status: status) }
// Parse the password string from the query result.
guard let existingItem = queryResult as? [String : AnyObject],
let passwordData = existingItem[kSecValueData as String] as? Data,
let password = String(data: passwordData, encoding: String.Encoding.utf8)
else {
throw KeychainError.unexpectedPasswordData
}
return password
}
func savePassword(_ password: String) throws {
// Encode the password into an Data object.
let encodedPassword = password.data(using: String.Encoding.utf8)!
do {
// Check for an existing item in the keychain.
try _ = readPassword()
// Update the existing item with the new password.
var attributesToUpdate = [String : AnyObject]()
attributesToUpdate[kSecValueData as String] = encodedPassword as AnyObject?
let query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr else { throw KeychainError.unhandledError(status: status) }
}
catch KeychainError.noPassword {
/*
No password was found in the keychain. Create a dictionary to save
as a new keychain item.
*/
var newItem = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
newItem[kSecValueData as String] = encodedPassword as AnyObject?
// Add a the new item to the keychain.
let status = SecItemAdd(newItem as CFDictionary, nil)
// Throw an error if an unexpected status was returned.
guard status == noErr else { throw KeychainError.unhandledError(status: status) }
}
}
mutating func renameAccount(_ newAccountName: String) throws {
// Try to update an existing item with the new account name.
var attributesToUpdate = [String : AnyObject]()
attributesToUpdate[kSecAttrAccount as String] = newAccountName as AnyObject?
let query = KeychainPasswordItem.keychainQuery(withService: service, account: self.account, accessGroup: accessGroup)
let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr || status == errSecItemNotFound else { throw KeychainError.unhandledError(status: status) }
self.account = newAccountName
}
func deleteItem() throws {
// Delete the existing item from the keychain.
let query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
let status = SecItemDelete(query as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr || status == errSecItemNotFound else { throw KeychainError.unhandledError(status: status) }
}
static func passwordItems(forService service: String, accessGroup: String? = nil) throws -> [KeychainPasswordItem] {
// Build a query for all items that match the service and access group.
var query = KeychainPasswordItem.keychainQuery(withService: service, accessGroup: accessGroup)
query[kSecMatchLimit as String] = kSecMatchLimitAll
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecReturnData as String] = kCFBooleanFalse
// Fetch matching items from the keychain.
var queryResult: AnyObject?
let status = withUnsafeMutablePointer(to: &queryResult) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
// If no items were found, return an empty array.
guard status != errSecItemNotFound else { return [] }
// Throw an error if an unexpected status was returned.
guard status == noErr else { throw KeychainError.unhandledError(status: status) }
// Cast the query result to an array of dictionaries.
guard let resultData = queryResult as? [[String : AnyObject]] else { throw KeychainError.unexpectedItemData }
// Create a `KeychainPasswordItem` for each dictionary in the query result.
var passwordItems = [KeychainPasswordItem]()
for result in resultData {
guard let account = result[kSecAttrAccount as String] as? String else { throw KeychainError.unexpectedItemData }
let passwordItem = KeychainPasswordItem(service: service, account: account, accessGroup: accessGroup)
passwordItems.append(passwordItem)
}
return passwordItems
}
// MARK: Convenience
private static func keychainQuery(withService service: String, account: String? = nil, accessGroup: String? = nil) -> [String : AnyObject] {
var query = [String : AnyObject]()
query[kSecClass as String] = kSecClassGenericPassword
query[kSecAttrService as String] = service as AnyObject?
if let account = account {
query[kSecAttrAccount as String] = account as AnyObject?
}
if let accessGroup = accessGroup {
query[kSecAttrAccessGroup as String] = accessGroup as AnyObject?
}
return query
}
}
| gpl-3.0 | 3e94f9136d16a5b64886a8e5e478a3af | 42.664835 | 223 | 0.657984 | 5.454358 | false | false | false | false |
ashikahmad/SlideMenuControllerSwift | SlideMenuControllerSwift/AppDelegate.swift | 2 | 7855 | //
// AppDelegate.swift
// test11
//
// Created by Yuji Hato on 4/20/15.
// Copyright (c) 2015 Yuji Hato. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
fileprivate func createMenuView() {
// create viewController code...
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainViewController = storyboard.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController
let leftViewController = storyboard.instantiateViewController(withIdentifier: "LeftViewController") as! LeftViewController
let rightViewController = storyboard.instantiateViewController(withIdentifier: "RightViewController") as! RightViewController
let nvc: UINavigationController = UINavigationController(rootViewController: mainViewController)
UINavigationBar.appearance().tintColor = UIColor(hex: "689F38")
leftViewController.mainViewController = nvc
let slideMenuController = ExSlideMenuController(mainViewController:nvc, leftMenuViewController: leftViewController, rightMenuViewController: rightViewController)
slideMenuController.automaticallyAdjustsScrollViewInsets = true
slideMenuController.delegate = mainViewController
self.window?.backgroundColor = UIColor(red: 236.0, green: 238.0, blue: 241.0, alpha: 1.0)
self.window?.rootViewController = slideMenuController
self.window?.makeKeyAndVisible()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.createMenuView()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "dekatotoro.test11" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var 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: "test11", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// 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
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("test11.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// 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
error = 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 \(error?.debugDescription ?? ""), \(error?.userInfo.debugDescription ?? "")")
abort()
} catch {
fatalError()
}
return coordinator
}()
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
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error?.debugDescription ?? ""), \(error?.userInfo.debugDescription ?? "")")
abort()
}
}
}
}
}
| mit | d709050556acb7df59bf8e5a4c13f061 | 53.172414 | 290 | 0.692934 | 5.991609 | false | false | false | false |
Antondomashnev/Sourcery | Pods/SourceKittenFramework/Source/SourceKittenFramework/SwiftDocKey.swift | 2 | 8912 | //
// SwiftDocKey.swift
// SourceKitten
//
// Created by JP Simard on 2015-01-05.
// Copyright (c) 2015 SourceKitten. All rights reserved.
//
import Foundation
/// SourceKit response dictionary keys.
public enum SwiftDocKey: String {
// MARK: SourceKit Keys
/// Annotated declaration (String).
case annotatedDeclaration = "key.annotated_decl"
/// Body length (Int64).
case bodyLength = "key.bodylength"
/// Body offset (Int64).
case bodyOffset = "key.bodyoffset"
/// Diagnostic stage (String).
case diagnosticStage = "key.diagnostic_stage"
/// File path (String).
case filePath = "key.filepath"
/// Full XML docs (String).
case fullXMLDocs = "key.doc.full_as_xml"
/// Kind (String).
case kind = "key.kind"
/// Length (Int64).
case length = "key.length"
/// Name (String).
case name = "key.name"
/// Name length (Int64).
case nameLength = "key.namelength"
/// Name offset (Int64).
case nameOffset = "key.nameoffset"
/// Offset (Int64).
case offset = "key.offset"
/// Substructure ([SourceKitRepresentable]).
case substructure = "key.substructure"
/// Syntax map (NSData).
case syntaxMap = "key.syntaxmap"
/// Type name (String).
case typeName = "key.typename"
/// Inheritedtype ([SourceKitRepresentable])
case inheritedtypes = "key.inheritedtypes"
// MARK: Custom Keys
/// Column where the token's declaration begins (Int64).
case docColumn = "key.doc.column"
/// Documentation comment (String).
case documentationComment = "key.doc.comment"
/// Declaration of documented token (String).
case docDeclaration = "key.doc.declaration"
/// Discussion documentation of documented token ([SourceKitRepresentable]).
case docDiscussion = "key.doc.discussion"
/// File where the documented token is located (String).
case docFile = "key.doc.file"
/// Line where the token's declaration begins (Int64).
case docLine = "key.doc.line"
/// Name of documented token (String).
case docName = "key.doc.name"
/// Parameters of documented token ([SourceKitRepresentable]).
case docParameters = "key.doc.parameters"
/// Parsed declaration (String).
case docResultDiscussion = "key.doc.result_discussion"
/// Parsed scope start (Int64).
case docType = "key.doc.type"
/// Parsed scope start end (Int64).
case usr = "key.usr"
/// Result discussion documentation of documented token ([SourceKitRepresentable]).
case parsedDeclaration = "key.parsed_declaration"
/// Type of documented token (String).
case parsedScopeEnd = "key.parsed_scope.end"
/// USR of documented token (String).
case parsedScopeStart = "key.parsed_scope.start"
/// Swift Declaration (String).
case swiftDeclaration = "key.swift_declaration"
/// Always deprecated (Bool).
case alwaysDeprecated = "key.always_deprecated"
/// Always unavailable (Bool).
case alwaysUnavailable = "key.always_unavailable"
/// Always deprecated (String).
case deprecationMessage = "key.deprecation_message"
/// Always unavailable (String).
case unavailableMessage = "key.unavailable_message"
// MARK: Typed SwiftDocKey Getters
/**
Returns the typed value of a dictionary key.
- parameter key: SwiftDoctKey to get from the dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Typed value of a dictionary key.
*/
private static func get<T>(_ key: SwiftDocKey, _ dictionary: [String: SourceKitRepresentable]) -> T? {
return dictionary[key.rawValue] as! T?
}
/**
Get kind string from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Kind string if successful.
*/
internal static func getKind(_ dictionary: [String: SourceKitRepresentable]) -> String? {
return get(.kind, dictionary)
}
/**
Get syntax map data from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Syntax map data if successful.
*/
internal static func getSyntaxMap(_ dictionary: [String: SourceKitRepresentable]) -> [SourceKitRepresentable]? {
return get(.syntaxMap, dictionary)
}
/**
Get offset int from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Offset int if successful.
*/
internal static func getOffset(_ dictionary: [String: SourceKitRepresentable]) -> Int64? {
return get(.offset, dictionary)
}
/**
Get length int from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Length int if successful.
*/
internal static func getLength(_ dictionary: [String: SourceKitRepresentable]) -> Int64? {
return get(.length, dictionary)
}
/**
Get name string from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Name string if successful.
*/
internal static func getName(_ dictionary: [String: SourceKitRepresentable]) -> String? {
return get(.name, dictionary)
}
/**
Get type name string from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Type name string if successful.
*/
internal static func getTypeName(_ dictionary: [String: SourceKitRepresentable]) -> String? {
return get(.typeName, dictionary)
}
/**
Get annotated declaration string from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Annotated declaration string if successful.
*/
internal static func getAnnotatedDeclaration(_ dictionary: [String: SourceKitRepresentable]) -> String? {
return get(.annotatedDeclaration, dictionary)
}
/**
Get substructure array from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Substructure array if successful.
*/
internal static func getSubstructure(_ dictionary: [String: SourceKitRepresentable]) -> [SourceKitRepresentable]? {
return get(.substructure, dictionary)
}
/**
Get name offset int from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Name offset int if successful.
*/
internal static func getNameOffset(_ dictionary: [String: SourceKitRepresentable]) -> Int64? {
return get(.nameOffset, dictionary)
}
/**
Get length int from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Length int if successful.
*/
internal static func getNameLength(_ dictionary: [String: SourceKitRepresentable]) -> Int64? {
return get(.nameLength, dictionary)
}
/**
Get body offset int from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Body offset int if successful.
*/
internal static func getBodyOffset(_ dictionary: [String: SourceKitRepresentable]) -> Int64? {
return get(.bodyOffset, dictionary)
}
/**
Get body length int from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Body length int if successful.
*/
internal static func getBodyLength(_ dictionary: [String: SourceKitRepresentable]) -> Int64? {
return get(.bodyLength, dictionary)
}
/**
Get file path string from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: File path string if successful.
*/
internal static func getFilePath(_ dictionary: [String: SourceKitRepresentable]) -> String? {
return get(.filePath, dictionary)
}
/**
Get full xml docs string from dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Full xml docs string if successful.
*/
internal static func getFullXMLDocs(_ dictionary: [String: SourceKitRepresentable]) -> String? {
return get(.fullXMLDocs, dictionary)
}
}
// MARK: - higher-level helpers
extension SwiftDocKey {
/**
Get the best offset from the dictionary.
- parameter dictionary: Dictionary to get value from.
- returns: Best 'offset' for the declaration. Name offset normally preferable,
but some eg. enumcase have invalid 0 here.
*/
internal static func getBestOffset(_ dictionary: [String: SourceKitRepresentable]) -> Int64? {
if let nameOffset = getNameOffset(dictionary), nameOffset > 0 {
return nameOffset
}
return getOffset(dictionary)
}
}
| mit | 2b4cdb9a77211efaf1c36a2ef6b669b9 | 31.525547 | 119 | 0.645085 | 4.727851 | false | false | false | false |
MartinOSix/DemoKit | dSwift/SwiftSyntaxDemo/SwiftSyntaxDemo/ViewController_ViewA.swift | 1 | 1252 | //
// ViewController_ViewA.swift
// SwiftSyntaxDemo
//
// Created by runo on 16/12/22.
// Copyright © 2016年 com.runo. All rights reserved.
//
import UIKit
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
class ViewController_ViewA: UIViewController,ViewController_ViewB_Delegate {
let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
label.frame = CGRect.init(x: 0, y: 20, width: screenWidth, height: 30)
self.view.addSubview(label)
label.backgroundColor = UIColor.red
self.edgesForExtendedLayout = UIRectEdge.init(rawValue: 0);
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let viewB = ViewController_ViewB()
viewB.block = {
(txt :String)->Void in {
self.label.text = txt
}()
}
viewB.delegate = self
self.navigationController?.pushViewController(viewB, animated: true)
}
func getInfo(info: UIColor) {
self.view.backgroundColor = info
}
}
| apache-2.0 | f3bf6d83c2c22e798c43a0f0c17107e1 | 22.12963 | 79 | 0.60048 | 4.460714 | false | false | false | false |
Darkkrye/DKDetailsParallax | DKDetailsParallax/Cells/RoundedTheme/RoundedDetailsProfileCell.swift | 1 | 6706 | //
// RoundedDetailsProfile.swift
// DKDetailsParallax
//
// Created by Pierre on 26/03/2016.
// Copyright © 2016 Pierre. All rights reserved.
//
import UIKit
/// RoundedDetailsProfileCell class
open class RoundedDetailsProfileCell: UITableViewCell {
/// MARK: - Private Constants
/// Cell default height
public static let defaultHeight: CGFloat = 105
/// MARK: - Private Variables
/// Cell primary color
public var primaryColor = UIColor.black
/// Cell secondary color
public var secondaryColor = UIColor.gray
/// Cell delegate
public var delegate: DKDetailsParallaxCellDelegate?
/// MARK: - IBOutlets
/// Square ImageView
@IBOutlet public weak var squareImageView: UIImageView!
/// Title Label
@IBOutlet public weak var titleLabel: UILabel!
/// Subtitle Label
@IBOutlet public weak var subtitleLabel: UILabel!
/// Circle Button
@IBOutlet public weak var circleButton: UIButton!
/// Outlined Button
@IBOutlet public weak var outlinedButton: UIButton!
/// Plain Button
@IBOutlet public weak var plainButton: UIButton!
/// MARK: - IBActions
/// IBAction for plain button
///
/// - Parameter sender: Any - The button
@IBAction func plainButtonTapped(_ sender: Any) {
/* Execute when plain button is tapped */
if let d = self.delegate {
d.roundedDetailsProfileCellCallback!(cell: self, forPlainButton: self.plainButton)
}
}
/// IBAction for outlined button
///
/// - Parameter sender: Any - The button
@IBAction func outlinedButtonTapped(_ sender: Any) {
/* Execute when outlined button is tapped */
if let d = self.delegate {
d.roundedDetailsProfileCellCallback!(cell: self, forOutlinedButton: self.outlinedButton)
}
}
/// IBAction for circle button
///
/// - Parameter sender: Any - The button
@IBAction func circleButtonTapped(_ sender: Any) {
/* Execute when circle button is tapped */
if let d = self.delegate {
d.roundedDetailsProfileCellCallback!(cell: self, forCircleButton: self.circleButton)
}
}
/// MARK: - "Default" Methods
/// Override function awakeFromNib
override open func awakeFromNib() {
super.awakeFromNib()
}
/// MARK: - Delegates
/// MARK: - Personnal Delegates
/// MARK: - Personnal Methods
/// Default constructor for the cell
///
/// - Parameters:
/// - withPrimaryColor: UIColor? - The primary color
/// - andSecondaryColor: UIColor ? - The secondary color
/// - Returns: RoundedDetailsProfileCell - The created cell
open static func detailsProfile(withPrimaryColor: UIColor?, andSecondaryColor: UIColor?) -> RoundedDetailsProfileCell {
/* Call other constructor with default value */
return detailsProfile(withPrimaryColor: withPrimaryColor, andSecondaryColor: andSecondaryColor, exceptSquareImage: false, exceptTitleLabel: false, exceptSubtitleLabel: false, exceptCircleButton: false, exceptOutlinedButton: false, exceptPlainButton: false)
}
/// Complex constructor for the cell
///
/// - Parameters:
/// - withPrimaryColor: UIColor? - The primary color
/// - andSecondaryColor: UIColor? - The secondary color
/// - exceptSquareImage: Bool - If you don't want this item
/// - exceptTitleLabel: Bool - If you don't want this item
/// - exceptSubtitleLabel: Bool - If you don't want this item
/// - exceptCircleButton: Bool - If you don't want this item
/// - exceptOutlinedButton: Bool - If you don't want this item
/// - exceptPlainButton: Bool - If you don't want this item
/// - Returns: RoundedDetailsProfileCell - The created cell
open static func detailsProfile(withPrimaryColor: UIColor?, andSecondaryColor: UIColor?, exceptSquareImage: Bool, exceptTitleLabel: Bool, exceptSubtitleLabel: Bool, exceptCircleButton: Bool, exceptOutlinedButton: Bool, exceptPlainButton: Bool) -> RoundedDetailsProfileCell {
/* Retrieve cell */
let nibs = DKDetailsParallax.bundle()?.loadNibNamed("RoundedDetailsProfileCell", owner: self, options: nil)
let cell: RoundedDetailsProfileCell = nibs![0] as! RoundedDetailsProfileCell
cell.selectionStyle = .none
if exceptSquareImage {
/* Hide square image */
cell.squareImageView.isHidden = true
}
if exceptTitleLabel {
/* Hide title label */
cell.titleLabel.isHidden = true
}
if exceptSubtitleLabel {
/* Hide subtitle label */
cell.subtitleLabel.isHidden = true
}
if exceptCircleButton {
/* Hide circle button */
cell.circleButton.isHidden = true
}
if exceptOutlinedButton {
/* Hide outlined button */
cell.outlinedButton.isHidden = true
}
if exceptPlainButton {
/* Hide plain button */
cell.plainButton.isHidden = true
}
/* Set colors */
if let p = withPrimaryColor {
cell.primaryColor = p
}
if let s = andSecondaryColor {
cell.secondaryColor = s
}
/* Call initialize function */
initialize(cell: cell)
return cell
}
/// Initialize function
///
/// - Parameter cell: RoundedDetailsProfileCell - The cell
private static func initialize(cell: RoundedDetailsProfileCell) {
/* Set cell properties for variables */
cell.titleLabel.textColor = cell.primaryColor
cell.subtitleLabel.textColor = cell.secondaryColor
/* Set cell square image properties */
cell.squareImageView.layer.cornerRadius = cell.squareImageView.frame.size.width/2
cell.squareImageView.layer.masksToBounds = true
/* Set plain button properties */
cell.plainButton.layer.borderColor = cell.primaryColor.cgColor
cell.plainButton.backgroundColor = cell.primaryColor
cell.plainButton.layer.cornerRadius = 15.0
cell.plainButton.setTitleColor(UIColor.white, for: .normal)
/* Set outlined button properties */
cell.outlinedButton.layer.borderColor = cell.primaryColor.cgColor
cell.outlinedButton.setTitleColor(cell.primaryColor, for: .normal)
cell.outlinedButton.layer.borderWidth = 1.0
cell.outlinedButton.layer.cornerRadius = 15.0
}
}
| bsd-3-clause | a0f3bf8fa2ee143cba7e3c64f60eead9 | 35.048387 | 278 | 0.634899 | 5.045147 | false | false | false | false |
stripe/stripe-ios | StripePayments/StripePayments/API Bindings/Models/Sources/STPSourceVerification.swift | 1 | 3316 | //
// STPSourceVerification.swift
// StripePayments
//
// Created by Ben Guo on 1/25/17.
// Copyright © 2017 Stripe, Inc. All rights reserved.
//
import Foundation
/// Verification status types for a Source.
@objc
public enum STPSourceVerificationStatus: Int {
/// The verification is pending.
case pending
/// The verification has succeeeded.
case succeeded
/// The verification has failed.
case failed
/// The state of the verification is unknown.
case unknown
}
/// Information related to a source's verification flow.
public class STPSourceVerification: NSObject, STPAPIResponseDecodable {
/// The number of attempts remaining to authenticate the source object with a
/// verification code.
@objc public private(set) var attemptsRemaining: NSNumber?
/// The status of the verification.
@objc public private(set) var status: STPSourceVerificationStatus = .unknown
@objc public private(set) var allResponseFields: [AnyHashable: Any] = [:]
// MARK: - STPSourceVerificationStatus
class func stringToStatusMapping() -> [String: NSNumber] {
return [
"pending": NSNumber(value: STPSourceVerificationStatus.pending.rawValue),
"succeeded": NSNumber(value: STPSourceVerificationStatus.succeeded.rawValue),
"failed": NSNumber(value: STPSourceVerificationStatus.failed.rawValue),
]
}
@objc(statusFromString:)
class func status(from string: String) -> STPSourceVerificationStatus {
let key = string.lowercased()
let statusNumber = self.stringToStatusMapping()[key]
if let statusNumber = statusNumber {
return (STPSourceVerificationStatus(rawValue: statusNumber.intValue))!
}
return .unknown
}
@objc(stringFromStatus:)
class func string(from status: STPSourceVerificationStatus) -> String? {
return
(self.stringToStatusMapping() as NSDictionary).allKeys(
for: NSNumber(value: status.rawValue)
)
.first as? String
}
// MARK: - Description
/// :nodoc:
@objc public override var description: String {
let props = [
// Object
String(format: "%@: %p", NSStringFromClass(STPSourceVerification.self), self),
// Details (alphabetical)
"attemptsRemaining = \(attemptsRemaining ?? 0)",
"status = \((STPSourceVerification.string(from: status)) ?? "unknown")",
]
return "<\(props.joined(separator: "; "))>"
}
// MARK: - STPAPIResponseDecodable
override required init() {
super.init()
}
public class func decodedObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? {
guard let response = response else {
return nil
}
let dict = response.stp_dictionaryByRemovingNulls()
// required fields
let rawStatus = dict.stp_string(forKey: "status")
if rawStatus == nil {
return nil
}
let verification = self.init()
verification.attemptsRemaining = dict.stp_number(forKey: "attempts_remaining")
verification.status = self.status(from: rawStatus ?? "")
verification.allResponseFields = response
return verification
}
}
| mit | 188bb7e4bf9a7f4959ec6085c099385f | 32.15 | 93 | 0.644646 | 4.790462 | false | false | false | false |
wangyaqing/LeetCode-swift | Solutions/35. Search Insert Position.playground/Contents.swift | 1 | 711 | import UIKit
class Solution {
func searchInsert(_ nums: [Int], _ target: Int) -> Int {
var left = 0
var right = nums.count - 1
while left <= right {
if target <= nums[left] {
return left
} else if target >= nums[right] {
return right
} else {
let mid = (right + left) / 2
if nums[mid] > target {
right = mid - 1
} else if nums[mid] < target {
left = mid + 1
} else {
return mid
}
}
}
return 0
}
}
print(Solution().searchInsert([1,3,5,6], 2))
| mit | 75952135593ccc065addba34c5f18d68 | 26.346154 | 60 | 0.390999 | 4.528662 | false | false | false | false |
ello/ello-ios | Specs/Extensions/ArraySpec.swift | 1 | 7452 | ////
/// ArraySpec.swift
//
@testable import Ello
import Quick
import Nimble
class ArraySpec: QuickSpec {
override func spec() {
describe("Array") {
describe("safeValue(_:Int)->T") {
let subject = [1, 2, 3]
it("should return Some<Int> when valid") {
let val1 = subject.safeValue(0)
expect(val1) == 1
let val2 = subject.safeValue(2)
expect(val2) == 3
}
it("should return None when invalid") {
let val1 = subject.safeValue(3)
expect(val1).to(beNil())
let val2 = subject.safeValue(100)
expect(val2).to(beNil())
}
}
describe("find(test:(T) -> Bool) -> Bool") {
let subject = [1, 2, 3]
it("should return 2 if test passes") {
expect(subject.find { $0 == 2 }) == 2
}
it("should return 1 when first test passes") {
expect(subject.find { $0 < 4 }) == 1
}
it("should return nil if no tests pass") {
expect(subject.find { $0 < 0 }).to(beNil())
}
}
describe("any(test:(T) -> Bool) -> Bool") {
let subject = [1, 2, 3]
it("should return true if any pass") {
expect(subject.any { $0 == 2 }) == true
}
it("should return true if all pass") {
expect(subject.any { $0 < 4 }) == true
}
it("should return false if none pass") {
expect(subject.any { $0 < 0 }) == false
}
}
describe("all(test:(T) -> Bool) -> Bool") {
let subject = [1, 2, 3]
it("should return false if only one pass") {
expect(subject.all { $0 == 2 }) == false
}
it("should return true if all pass") {
expect(subject.all { $0 < 4 }) == true
}
it("should return false if none pass") {
expect(subject.all { $0 < 0 }) == false
}
}
describe("eachPair arity 2") {
var a: Int?, b: Int?, count: Int = 0
beforeEach {
(a, b) = (nil, nil)
count = 0
}
it("should work with zero items") {
let subject: [Int] = []
subject.eachPair { prev, curr in
(a, b) = (prev, curr)
count += 1
}
expect(a).to(beNil())
expect(b).to(beNil())
expect(count) == subject.count
}
it("should work with one item") {
let subject = [1]
subject.eachPair { prev, curr in
(a, b) = (prev, curr)
count += 1
}
expect(a).to(beNil())
expect(b) == 1
expect(count) == subject.count
}
it("should work with two items") {
let subject = [1, 2]
subject.eachPair { prev, curr in
(a, b) = (prev, curr)
count += 1
}
expect(a) == 1
expect(b) == 2
expect(count) == subject.count
}
it("should work with more items") {
let subject = [1, 2, 3]
subject.eachPair { prev, curr in
switch count {
case 0:
expect(prev).to(beNil())
expect(curr) == 1
case 1:
expect(prev) == 1
expect(curr) == 2
case 2:
expect(prev) == 2
expect(curr) == 3
default:
fail()
}
count += 1
}
}
}
describe("eachPair arity 3") {
var a: Int?, b: Int?, expectedIsLast: Bool?, count: Int = 0
beforeEach {
(a, b, expectedIsLast) = (nil, nil, nil)
count = 0
}
it("should work with zero items") {
let subject: [Int] = []
subject.eachPair { prev, curr, isLast in
(a, b, expectedIsLast) = (prev, curr, isLast)
count += 1
}
expect(a).to(beNil())
expect(b).to(beNil())
expect(count) == subject.count
}
it("should work with one item") {
let subject = [1]
subject.eachPair { prev, curr, isLast in
(a, b, expectedIsLast) = (prev, curr, isLast)
count += 1
}
expect(a).to(beNil())
expect(b) == 1
expect(expectedIsLast) == true
expect(count) == subject.count
}
it("should work with two items") {
let subject = [1, 2]
var wasLast: Bool?
subject.eachPair { prev, curr, isLast in
wasLast = expectedIsLast
(a, b, expectedIsLast) = (prev, curr, isLast)
count += 1
}
expect(a) == 1
expect(b) == 2
expect(wasLast) == false
expect(expectedIsLast) == true
expect(count) == subject.count
}
it("should work with more items") {
let subject = [1, 2, 3]
subject.eachPair { prev, curr, isLast in
switch count {
case 0:
expect(prev).to(beNil())
expect(curr) == 1
expect(isLast) == false
case 1:
expect(prev) == 1
expect(curr) == 2
expect(isLast) == false
case 2:
expect(prev) == 2
expect(curr) == 3
expect(isLast) == true
default:
fail()
}
count += 1
}
}
}
describe("unique() -> []") {
it("should remove duplicates and preserve order") {
let subject = [1, 2, 3, 3, 2, 4, 1, 5]
expect(subject.unique()) == [1, 2, 3, 4, 5]
}
}
}
}
}
| mit | f273cfa13c35234d9fc29c1a9485664c | 37.412371 | 75 | 0.337493 | 5.214836 | false | false | false | false |
argent-os/argent-ios | app-ios/SupportCategoryTableViewController.swift | 1 | 923 | //
// SupportCategoryTableViewController.swift
// app-ios
//
// Created by Sinan Ulkuatam on 5/27/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import Foundation
class SupportCategoryTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Send the subject with the segue
_ = self.tableView.indexPathForSelectedRow!.row
let indexPath = tableView.indexPathForSelectedRow
self.tableView.deselectRowAtIndexPath(indexPath!, animated: true)
let currentCell = tableView.cellForRowAtIndexPath(indexPath!)! as UITableViewCell
let destination = segue.destinationViewController as! SupportMessageViewController
destination.subject = (currentCell.textLabel!.text)!
}
} | mit | 471e56f73d07152928007961910f9961 | 27.84375 | 90 | 0.701735 | 5.587879 | false | false | false | false |
CatchChat/Yep | Yep/Helpers/YepHUD.swift | 1 | 4779 | //
// YepHUD.swift
// Yep
//
// Created by NIX on 15/4/27.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
final class YepHUD: NSObject {
static let sharedInstance = YepHUD()
var isShowing = false
var dismissTimer: NSTimer?
lazy var containerView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5)
return view
}()
lazy var activityIndicator: UIActivityIndicatorView = {
let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
return view
}()
class func showActivityIndicator() {
showActivityIndicatorWhileBlockingUI(true)
}
class func showActivityIndicatorWhileBlockingUI(blockingUI: Bool) {
if sharedInstance.isShowing {
return // TODO: 或者用新的取代旧的
}
SafeDispatch.async {
if
let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate,
let window = appDelegate.window {
sharedInstance.isShowing = true
sharedInstance.containerView.userInteractionEnabled = blockingUI
sharedInstance.containerView.alpha = 0
window.addSubview(sharedInstance.containerView)
sharedInstance.containerView.frame = window.bounds
UIView.animateWithDuration(0.1, delay: 0.0, options: UIViewAnimationOptions(rawValue: 0), animations: {
sharedInstance.containerView.alpha = 1
}, completion: { _ in
sharedInstance.containerView.addSubview(sharedInstance.activityIndicator)
sharedInstance.activityIndicator.center = sharedInstance.containerView.center
sharedInstance.activityIndicator.startAnimating()
sharedInstance.activityIndicator.alpha = 0
sharedInstance.activityIndicator.transform = CGAffineTransformMakeScale(0.0001, 0.0001)
UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions(rawValue: 0), animations: {
sharedInstance.activityIndicator.transform = CGAffineTransformMakeScale(1.0, 1.0)
sharedInstance.activityIndicator.alpha = 1
}, completion: { _ in
sharedInstance.activityIndicator.transform = CGAffineTransformIdentity
if let dismissTimer = sharedInstance.dismissTimer {
dismissTimer.invalidate()
}
sharedInstance.dismissTimer = NSTimer.scheduledTimerWithTimeInterval(YepConfig.forcedHideActivityIndicatorTimeInterval, target: self, selector: #selector(YepHUD.forcedHideActivityIndicator), userInfo: nil, repeats: false)
})
})
}
}
}
class func forcedHideActivityIndicator() {
hideActivityIndicator() {
if
let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate,
let viewController = appDelegate.window?.rootViewController {
YepAlert.alertSorry(message: NSLocalizedString("Wait too long, the operation may not be completed.", comment: ""), inViewController: viewController)
}
}
}
class func hideActivityIndicator() {
hideActivityIndicator() {
}
}
class func hideActivityIndicator(completion: () -> Void) {
SafeDispatch.async {
if sharedInstance.isShowing {
sharedInstance.activityIndicator.transform = CGAffineTransformIdentity
UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions(rawValue: 0), animations: {
sharedInstance.activityIndicator.transform = CGAffineTransformMakeScale(0.0001, 0.0001)
sharedInstance.activityIndicator.alpha = 0
}, completion: { _ in
sharedInstance.activityIndicator.removeFromSuperview()
UIView.animateWithDuration(0.1, delay: 0.0, options: UIViewAnimationOptions(rawValue: 0), animations: {
sharedInstance.containerView.alpha = 0
}, completion: { _ in
sharedInstance.containerView.removeFromSuperview()
completion()
})
})
}
sharedInstance.isShowing = false
}
}
}
| mit | d26f92b3b36bb5d87124522db54b97e4 | 36.179688 | 249 | 0.598025 | 6.387919 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/Register/RegisterVerifyMobileViewController.swift | 1 | 7597 | //
// RegisterVerifyMobileViewController.swift
// Yep
//
// Created by NIX on 15/3/17.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
import YepNetworking
import Ruler
import RxSwift
import RxCocoa
final class RegisterVerifyMobileViewController: SegueViewController {
var mobile: String!
var areaCode: String!
private lazy var disposeBag = DisposeBag()
@IBOutlet private weak var verifyMobileNumberPromptLabel: UILabel!
@IBOutlet private weak var verifyMobileNumberPromptLabelTopConstraint: NSLayoutConstraint!
@IBOutlet private weak var phoneNumberLabel: UILabel!
@IBOutlet private weak var verifyCodeTextField: BorderTextField!
@IBOutlet private weak var verifyCodeTextFieldTopConstraint: NSLayoutConstraint!
@IBOutlet private weak var callMePromptLabel: UILabel!
@IBOutlet private weak var callMeButton: UIButton!
@IBOutlet private weak var callMeButtonTopConstraint: NSLayoutConstraint!
private lazy var nextButton: UIBarButtonItem = {
let button = UIBarButtonItem()
button.title = NSLocalizedString("Next", comment: "")
button.rx_tap
.subscribeNext({ [weak self] in self?.verifyRegisterMobile() })
.addDisposableTo(self.disposeBag)
return button
}()
private lazy var callMeTimer: NSTimer = {
let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(RegisterVerifyMobileViewController.tryCallMe(_:)), userInfo: nil, repeats: true)
return timer
}()
private var haveAppropriateInput = false {
didSet {
nextButton.enabled = haveAppropriateInput
if (oldValue != haveAppropriateInput) && haveAppropriateInput {
verifyRegisterMobile()
}
}
}
private var callMeInSeconds = YepConfig.callMeInSeconds()
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
println("deinit RegisterVerifyMobile")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.yepViewBackgroundColor()
navigationItem.titleView = NavigationTitleLabel(title: NSLocalizedString("Sign Up", comment: ""))
navigationItem.rightBarButtonItem = nextButton
NSNotificationCenter.defaultCenter()
.rx_notification(AppDelegate.Notification.applicationDidBecomeActive)
.subscribeNext({ [weak self] _ in self?.verifyCodeTextField.becomeFirstResponder() })
.addDisposableTo(disposeBag)
verifyMobileNumberPromptLabel.text = NSLocalizedString("Input verification code sent to", comment: "")
phoneNumberLabel.text = "+" + areaCode + " " + mobile
verifyCodeTextField.placeholder = " "
verifyCodeTextField.backgroundColor = UIColor.whiteColor()
verifyCodeTextField.textColor = UIColor.yepInputTextColor()
verifyCodeTextField.rx_text
.map({ $0.characters.count == YepConfig.verifyCodeLength() })
.subscribeNext({ [weak self] in self?.haveAppropriateInput = $0 })
.addDisposableTo(disposeBag)
callMePromptLabel.text = NSLocalizedString("Didn't get it?", comment: "")
callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal)
verifyMobileNumberPromptLabelTopConstraint.constant = Ruler.iPhoneVertical(30, 50, 60, 60).value
verifyCodeTextFieldTopConstraint.constant = Ruler.iPhoneVertical(30, 40, 50, 50).value
callMeButtonTopConstraint.constant = Ruler.iPhoneVertical(10, 20, 40, 40).value
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
nextButton.enabled = false
callMeButton.enabled = false
verifyCodeTextField.text = nil
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
verifyCodeTextField.becomeFirstResponder()
callMeTimer.fire()
}
// MARK: Actions
@objc private func tryCallMe(timer: NSTimer) {
if !haveAppropriateInput {
if callMeInSeconds > 1 {
let callMeInSecondsString = String.trans_buttonCallMe + " (\(callMeInSeconds))"
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(callMeInSecondsString, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
}
} else {
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
}
callMeButton.enabled = true
}
}
if (callMeInSeconds > 1) {
callMeInSeconds -= 1
}
}
@IBAction private func callMe(sender: UIButton) {
callMeTimer.invalidate()
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(String.trans_buttonCalling, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
self?.callMeButton.enabled = false
}
delay(10) {
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
self?.callMeButton.enabled = true
}
}
sendVerifyCodeOfMobile(mobile, withAreaCode: areaCode, useMethod: .Call, failureHandler: { (reason, errorMessage) in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
if let errorMessage = errorMessage {
SafeDispatch.async { [weak self] in
YepAlert.alertSorry(message: errorMessage, inViewController: self)
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
}
}
}
}, completion: { success in
println("resendVoiceVerifyCode \(success)")
})
}
private func verifyRegisterMobile() {
view.endEditing(true)
guard let verifyCode = verifyCodeTextField.text else {
return
}
YepHUD.showActivityIndicator()
verifyMobile(mobile, withAreaCode: areaCode, verifyCode: verifyCode, failureHandler: { (reason, errorMessage) in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
YepHUD.hideActivityIndicator()
if let errorMessage = errorMessage {
SafeDispatch.async { [weak self] in
self?.nextButton.enabled = false
YepAlert.alertSorry(message: errorMessage, inViewController: self, withDismissAction: { [weak self] in
self?.verifyCodeTextField.text = nil
self?.verifyCodeTextField.becomeFirstResponder()
})
}
}
}, completion: { loginUser in
println("\(loginUser)")
YepHUD.hideActivityIndicator()
SafeDispatch.async { [weak self] in
saveTokenAndUserInfoOfLoginUser(loginUser)
self?.performSegueWithIdentifier("showRegisterPickAvatar", sender: nil)
}
})
}
}
| mit | 85c6054a6addc49ec25e5afbd05d8dd8 | 33.366516 | 178 | 0.638578 | 5.405694 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | byuSuite/Apps/Galleries/controller/GalleriesArtworkViewController.swift | 1 | 3301 | //
// GalleriesArtworkViewController.swift
// byuSuite
//
// Created by Alex Boswell on 2/9/18.
// Copyright © 2018 Brigham Young University. All rights reserved.
//
import UIKit
private let NUM_OF_COLUMNS = 3
class GalleriesArtworkViewController: ByuViewController2, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
//MARK: Outlets
@IBOutlet private weak var collectionView: UICollectionView!
@IBOutlet private weak var noDataLabel: UILabel!
@IBOutlet private weak var spinner: UIActivityIndicatorView!
//MARK: Public Properties
var galleryId: String!
var albumId: String!
//MARK: Static Properties
static var artwork = [GalleryArtwork]()
//MARK: View controller lifecycle
override func viewDidLoad() {
super.viewDidLoad()
//Clear out previous artwork so that the collection view is empty when it first appears
GalleriesArtworkViewController.artwork = [GalleryArtwork]()
collectionView.reloadData()
loadArtwork()
}
override func viewWillAppear(_ animated: Bool) {
super.viewDidAppear(animated)
collectionView.deselectSelectedItems()
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? GalleriesArtworkPageViewController, let cell = sender as? UICollectionViewCell {
vc.selectedIndex = self.collectionView.indexPath(for: cell)?.row
}
}
//MARK: UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return GalleriesArtworkViewController.artwork.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "artworkCell", for: indexPath) as? GalleriesArtworkCollectionViewCell else {
return UICollectionViewCell()
}
cell.artwork = GalleriesArtworkViewController.artwork[indexPath.row]
return cell
}
//MARK: UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//UICollectionViewLayout is an abstract base class for Apple's default UICollectionViewFlowLayout
let minInterimSpacing = (collectionViewLayout as? UICollectionViewFlowLayout)?.minimumInteritemSpacing ?? 0
let totalSpaceBetweenItemsInRow = Int(CGFloat(NUM_OF_COLUMNS - 1) * minInterimSpacing) //sum of all space between items in a single row
let itemWidth = (collectionView.frame.size.width - CGFloat(totalSpaceBetweenItemsInRow)) / CGFloat(NUM_OF_COLUMNS)
//Returns an item size that ensures that there will only ever be 3 columns (i.e.; 3 items per row)
return CGSize(width: itemWidth, height: itemWidth)
}
//MARK: Custom Methods
func loadArtwork() {
GalleriesClient.getArtwork(galleryId: galleryId, albumId: albumId) { (artwork, error) in
self.spinner.stopAnimating()
if let artwork = artwork {
GalleriesArtworkViewController.artwork = artwork
if artwork.count > 0 {
self.collectionView.reloadData()
} else {
self.noDataLabel.isHidden = false
self.collectionView.isHidden = true
}
} else {
super.displayAlert(error: error)
}
}
}
}
| apache-2.0 | 00b96269abe00db034e4397bb1d95353 | 35.666667 | 157 | 0.767576 | 4.447439 | false | false | false | false |
nerdyc/SwiftEmoji | Sources/Emoji.swift | 2 | 3888 | import Foundation
///
/// Useful things for working with Emoji.
///
public final class Emoji : EmojiData {
///
/// Pattern that matches a single Emoji character, including combining marks and sequences.
///
public static var SingleEmojiPattern:String = {
// The "emoji" group needs to be followed by a special character to be rendered like emoji.
let emojiVariants = "(?:(?:\(EmojiPatterns.joined(separator: "|")))\\uFE0F)"
// Emoji can be followed by optional combining marks. The standard says only keycaps and
// backslash are likely to be supported.
let combiningMarks = "[\\u20E3\\u20E0]"
// "Presentation" characters are rendered as emoji by default and need no variant.
let emojiPresentation = "\(EmojiPresentationPatterns.joined(separator: "|"))"
// Some other emoji are sequences of characters, joined with 'Zero Width Joiner' characters.
// We want the longest match, so we sort these in reverse order.
let zwjSequences = ZWJSequencePatterns.reversed().joined(separator: "|")
let otherSequences = SequencePatterns.joined(separator: "|")
return "(?:(?:\(zwjSequences)|\(otherSequences)|\(emojiVariants)|\(emojiPresentation))\(combiningMarks)?)"
}()
/// A regular expression that matches any emoji character. Useful for plucking individual emoji
/// out of a string.
public static var SingleEmojiRegex:NSRegularExpression = {
return try! NSRegularExpression(pattern:SingleEmojiPattern, options:[])
}()
/// Pattern that matches one or more emoji characters in a row.
public static var MultiEmojiPattern:String = {
return "(?:\(SingleEmojiPattern)+)"
}()
/// Matches one or more emoji characters in a row.
public static var MultiEmojiRegex:NSRegularExpression = {
return try! NSRegularExpression(pattern:MultiEmojiPattern, options:[])
}()
///
/// Pattern that matches one or more Emoji or whitespace characters in a row. At least one emoji
/// character is required; empty or blank strings will not be matched. Leading and trailing
/// whitespace will be included in the match range.
///
public static var MultiEmojiAndWhitespacePattern:String = {
return "(?:(?:\\s*\(MultiEmojiPattern))+\\s*)"
}()
///
/// Matches one or more Emoji or whitespace characters in a row. At least one emoji character is
/// required; empty or blank strings will not be matched. Leading and trailing whitespace will
/// be included in the match range.
///
public static var MultiEmojiAndWhitespaceRegex:NSRegularExpression = {
return try! NSRegularExpression(pattern:MultiEmojiAndWhitespacePattern, options:[])
}()
///
/// Pattern that matches any string composed solely of emoji and (optional) whitespace. Empty or
/// blank strings will not match.
///
public static var PureEmojiAndWhitespacePattern:String = {
return "^\(MultiEmojiAndWhitespacePattern)$"
}()
///
/// Matches any string composed solely of emoji and (optional) whitespace. Empty or blank
/// strings will not match.
///
public static var PureEmojiAndWhitespaceRegex:NSRegularExpression = {
return try! NSRegularExpression(pattern:PureEmojiAndWhitespacePattern, options:[])
}()
///
/// Returns `true` if the given string is composed solely of emoji and (optional) whitespace.
/// Empty or blank strings will not match.
///
public static func isPureEmojiString(_ string:String) -> Bool {
let range = NSRange(location: 0, length: string.utf16.count)
let firstMatch = PureEmojiAndWhitespaceRegex.rangeOfFirstMatch(in: string, options:[], range:range)
return firstMatch.location != NSNotFound
}
}
| mit | 0a789c4d1961236b77b1de6a88fd34ad | 42.2 | 114 | 0.671553 | 4.959184 | false | false | false | false |
ios-archy/Sinaweibo_swift | SinaWeibo_swift/SinaWeibo_swift/Classess/Tools/Emotion/Model/Emoticon.swift | 1 | 1796 | //
// Emoticon.swift
// Emotion
//
// Created by archy on 16/11/18.
// Copyright © 2016年 archy. All rights reserved.
//
import UIKit
class Emoticon: NSObject {
//MARK: --定义属性
var code : String?{ //emoji的code
didSet {
guard let code = code else {
return
}
//1.创建扫描器
let scanner = NSScanner(string: code)
//2.调用方法,扫描出code中的值
var value : UInt32 = 0
scanner.scanHexInt(&value)
//3.将value转成字符
let c = Character(UnicodeScalar(value))
//4.将字符转成字符串
emojiCode = String(c)
}
}
var png : String? { //普通表情对应的图片名称
didSet {
guard let png = png else {
return
}
pngPath = NSBundle.mainBundle().bundlePath + "/Emoticons.bundle/" + png
}
}
var chs : String? //普通表情对应的文字
// //MARK: --数据处理
var pngPath : String?
var emojiCode : String?
var isRemove : Bool = false
var isEmpty : Bool = false
//MARK: --自定义构造函数
init(dict: [String : String]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
init(isRemove : Bool) {
self.isRemove = isRemove
}
init(isEmpty : Bool) {
self.isEmpty = isEmpty
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
override var description : String {
return dictionaryWithValuesForKeys(["emojiCode","pngPath" ,"chs"]).description
}
}
| mit | 56cabad629a58d7317705a4a0bd432ee | 20.597403 | 86 | 0.497294 | 4.543716 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Maps/Set min-max scale/SetMinMaxScaleViewController.swift | 1 | 1661 | //
// Copyright © 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import ArcGIS
/// A view controller that manages the interface of the Set Min/Max Scale
/// sample.
class SetMinMaxScaleViewController: UIViewController {
/// The map view managed by the view controller.
@IBOutlet weak var mapView: AGSMapView! {
didSet {
mapView.map = makeMap()
mapView.setViewpoint(AGSViewpoint(center: AGSPoint(x: -355_453, y: 7_548_720, spatialReference: .webMercator()), scale: 3_000))
}
}
/// Creates a map with the min and max scale set.
///
/// - Returns: A new `AGSMap` object.
func makeMap() -> AGSMap {
let map = AGSMap(basemapStyle: .arcGISStreets)
map.minScale = 8_000
map.maxScale = 2_000
return map
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as? SourceCodeBarButtonItem)?.filenames = ["SetMinMaxScaleViewController"]
}
}
| apache-2.0 | 6a6a5d22a048d1bd47f86bb52e500cbf | 32.877551 | 139 | 0.671084 | 4.311688 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/permutations.swift | 2 | 2019 | /**
* https://leetcode.com/problems/permutations/
*
*
*/
class Solution {
func permute(_ nums: [Int]) -> [[Int]] {
var nums = nums
var ret: [[Int]] = []
process(&ret, [], &nums)
return ret
}
/// Try out all the possible choice for the next element in this `solution` (permutation)
/// If we have none choice left in candidate, it means we have all choices in current `solution` (permutation), then it's a valid solution.
///
///
/// - Parameters:
/// - result: final result, which contains all the solutions (possible permutations.)
/// - solution: current working partial solution, could be one of possible permutation.
/// - candidate: all the possible choices left to choose for the rest of current permutation.
///
fileprivate func process(_ result: inout [[Int]], _ solution: [Int], _ candidate: inout [Int]) {
if candidate.isEmpty {
result.append(solution)
return
}
for index in 0 ..< candidate.count {
let tmp = candidate[index]
candidate.remove(at: index)
process(&result, solution + [tmp], &candidate)
candidate.insert(tmp, at: index)
}
}
}
/**
* https://leetcode.com/problems/permutations/
*
*
*/
class Solution {
func permute(_ nums: [Int]) -> [[Int]] {
var cand: [Int : Int] = [:]
for n in nums {
cand[n] = 1 + cand[n, default: 0]
}
var ret: [[Int]] = []
process(&ret, [], &cand)
return ret
}
fileprivate func process(_ result: inout [[Int]], _ solution: [Int], _ candidate: inout [Int : Int]) {
if candidate.isEmpty {
result.append(solution)
return
}
for (key, value) in candidate {
candidate[key] = value == 1 ? nil : value - 1
process(&result, solution + [key], &candidate)
candidate[key] = value
}
}
}
| mit | 2ea1d65e7a74b05f5ce66b36d3b8acc6 | 30.546875 | 143 | 0.538881 | 4.20625 | false | false | false | false |
kar1m/firefox-ios | Storage/Bookmarks.swift | 11 | 10198 | /* 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
public struct ShareItem {
public let url: String
public let title: String?
public let favicon: Favicon?
public init(url: String, title: String?, favicon: Favicon?) {
self.url = url
self.title = title
self.favicon = favicon
}
}
public protocol ShareToDestination {
func shareItem(item: ShareItem)
}
public protocol SearchableBookmarks {
func bookmarksByURL(url: NSURL) -> Deferred<Result<Cursor<BookmarkItem>>>
}
public struct BookmarkRoots {
// These match Places on desktop.
public static let RootGUID = "root________"
public static let MobileFolderGUID = "mobile______"
public static let MenuFolderGUID = "menu________"
public static let ToolbarFolderGUID = "toolbar_____"
public static let UnfiledFolderGUID = "unfiled_____"
/*
public static let TagsFolderGUID = "tags________"
public static let PinnedFolderGUID = "pinned______"
public static let FakeDesktopFolderGUID = "desktop_____"
*/
static let RootID = 0
static let MobileID = 1
static let MenuID = 2
static let ToolbarID = 3
static let UnfiledID = 4
}
/**
* This matches Places's nsINavBookmarksService, just for sanity.
* These are only used at the DB layer.
*/
public enum BookmarkNodeType: Int {
case Bookmark = 1
case Folder = 2
case Separator = 3
case DynamicContainer = 4
}
/**
* The immutable base interface for bookmarks and folders.
*/
public class BookmarkNode {
public var id: Int? = nil
public var guid: String
public var title: String
public var favicon: Favicon? = nil
init(guid: String, title: String) {
self.guid = guid
self.title = title
}
}
/**
* An immutable item representing a bookmark.
*
* To modify this, issue changes against the backing store and get an updated model.
*/
public class BookmarkItem: BookmarkNode {
public let url: String!
public init(guid: String, title: String, url: String) {
self.url = url
super.init(guid: guid, title: title)
}
}
/**
* A folder is an immutable abstraction over a named
* thing that can return its child nodes by index.
*/
public class BookmarkFolder: BookmarkNode {
public var count: Int { return 0 }
public subscript(index: Int) -> BookmarkNode? { return nil }
}
/**
* A model is a snapshot of the bookmarks store, suitable for backing a table view.
*
* Navigation through the folder hierarchy produces a sequence of models.
*
* Changes to the backing store implicitly invalidates a subset of models.
*
* 'Refresh' means requesting a new model from the store.
*/
public class BookmarksModel {
let modelFactory: BookmarksModelFactory
public let current: BookmarkFolder
public init(modelFactory: BookmarksModelFactory, root: BookmarkFolder) {
self.modelFactory = modelFactory
self.current = root
}
/**
* Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist.
*/
public func selectFolder(folder: BookmarkFolder, success: BookmarksModel -> (), failure: Any -> ()) {
modelFactory.modelForFolder(folder, success: success, failure: failure)
}
/**
* Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist.
*/
public func selectFolder(guid: String, success: BookmarksModel -> (), failure: Any -> ()) {
modelFactory.modelForFolder(guid, success: success, failure: failure)
}
/**
* Produce a new model rooted at the base of the hierarchy. Should never fail.
*/
public func selectRoot(success: BookmarksModel -> (), failure: Any -> ()) {
modelFactory.modelForRoot(success, failure: failure)
}
/**
* Produce a new model rooted at the same place as this model. Can fail if
* the folder has been deleted from the backing store.
*/
public func reloadData(success: BookmarksModel -> (), failure: Any -> ()) {
modelFactory.modelForFolder(current, success: success, failure: failure)
}
}
public protocol BookmarksModelFactory {
func modelForFolder(folder: BookmarkFolder, success: BookmarksModel -> (), failure: Any -> ())
func modelForFolder(guid: String, success: BookmarksModel -> (), failure: Any -> ())
func modelForRoot(success: BookmarksModel -> (), failure: Any -> ())
// Whenever async construction is necessary, we fall into a pattern of needing
// a placeholder that behaves correctly for the period between kickoff and set.
var nullModel: BookmarksModel { get }
func isBookmarked(url: String, success: Bool -> (), failure: Any -> ())
func remove(bookmark: BookmarkNode) -> Success
func removeByURL(url: String) -> Success
func clearBookmarks() -> Success
}
/*
* A folder that contains an array of children.
*/
public class MemoryBookmarkFolder: BookmarkFolder, SequenceType {
let children: [BookmarkNode]
public init(guid: String, title: String, children: [BookmarkNode]) {
self.children = children
super.init(guid: guid, title: title)
}
public struct BookmarkNodeGenerator: GeneratorType {
typealias Element = BookmarkNode
let children: [BookmarkNode]
var index: Int = 0
init(children: [BookmarkNode]) {
self.children = children
}
public mutating func next() -> BookmarkNode? {
return index < children.count ? children[index++] : nil
}
}
override public var favicon: Favicon? {
get {
if let path = NSBundle.mainBundle().pathForResource("bookmark_folder_closed", ofType: "png") {
if let url = NSURL(fileURLWithPath: path) {
return Favicon(url: url.absoluteString!, date: NSDate(), type: IconType.Local)
}
}
return nil
}
set {
}
}
override public var count: Int {
return children.count
}
override public subscript(index: Int) -> BookmarkNode {
get {
return children[index]
}
}
public func generate() -> BookmarkNodeGenerator {
return BookmarkNodeGenerator(children: self.children)
}
/**
* Return a new immutable folder that's just like this one,
* but also contains the new items.
*/
func append(items: [BookmarkNode]) -> MemoryBookmarkFolder {
if (items.isEmpty) {
return self
}
return MemoryBookmarkFolder(guid: self.guid, title: self.title, children: self.children + items)
}
}
public class MemoryBookmarksSink: ShareToDestination {
var queue: [BookmarkNode] = []
public init() { }
public func shareItem(item: ShareItem) {
let title = item.title == nil ? "Untitled" : item.title!
func exists(e: BookmarkNode) -> Bool {
if let bookmark = e as? BookmarkItem {
return bookmark.url == item.url;
}
return false;
}
// Don't create duplicates.
if (!contains(queue, exists)) {
queue.append(BookmarkItem(guid: Bytes.generateGUID(), title: title, url: item.url))
}
}
}
/**
* A trivial offline model factory that represents a simple hierarchy.
*/
public class MockMemoryBookmarksStore: BookmarksModelFactory, ShareToDestination {
let mobile: MemoryBookmarkFolder
let root: MemoryBookmarkFolder
var unsorted: MemoryBookmarkFolder
let sink: MemoryBookmarksSink
public init() {
var res = [BookmarkItem]()
mobile = MemoryBookmarkFolder(guid: BookmarkRoots.MobileFolderGUID, title: "Mobile Bookmarks", children: res)
unsorted = MemoryBookmarkFolder(guid: BookmarkRoots.UnfiledFolderGUID, title: "Unsorted Bookmarks", children: [])
sink = MemoryBookmarksSink()
root = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: [mobile, unsorted])
}
public func modelForFolder(folder: BookmarkFolder, success: (BookmarksModel) -> (), failure: (Any) -> ()) {
self.modelForFolder(folder.guid, success: success, failure: failure)
}
public func modelForFolder(guid: String, success: (BookmarksModel) -> (), failure: (Any) -> ()) {
var m: BookmarkFolder
switch (guid) {
case BookmarkRoots.MobileFolderGUID:
// Transparently merges in any queued items.
m = self.mobile.append(self.sink.queue)
break;
case BookmarkRoots.RootGUID:
m = self.root
break;
case BookmarkRoots.UnfiledFolderGUID:
m = self.unsorted
break;
default:
failure("No such folder.")
return
}
success(BookmarksModel(modelFactory: self, root: m))
}
public func modelForRoot(success: (BookmarksModel) -> (), failure: (Any) -> ()) {
success(BookmarksModel(modelFactory: self, root: self.root))
}
/**
* This class could return the full data immediately. We don't, because real DB-backed code won't.
*/
public var nullModel: BookmarksModel {
let f = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: [])
return BookmarksModel(modelFactory: self, root: f)
}
public func shareItem(item: ShareItem) {
self.sink.shareItem(item)
}
public func isBookmarked(url: String, success: (Bool) -> (), failure: (Any) -> ()) {
failure("Not implemented")
}
public func remove(bookmark: BookmarkNode) -> Success {
return deferResult(DatabaseError(description: "Not implemented"))
}
public func removeByURL(url: String) -> Success {
return deferResult(DatabaseError(description: "Not implemented"))
}
public func clearBookmarks() -> Success {
return succeed()
}
} | mpl-2.0 | edfd98824efc3c8576002448c61fcf2d | 30.478395 | 121 | 0.640812 | 4.581312 | false | false | false | false |
Rapid-SDK/ios | Examples/RapiChat - Chat client/RapiChat macOS/ChannelCellView.swift | 1 | 2540 | //
// ChannelCell.swift
// RapiChat
//
// Created by Jan on 28/06/2017.
// Copyright © 2017 Rapid. All rights reserved.
//
import Cocoa
class ChannelCellView: NSTableCellView {
@IBOutlet weak var nameLabel: NSTextField!
@IBOutlet weak var timeLabel: NSTextField!
@IBOutlet weak var messageTextLabel: NSTextField!
@IBOutlet weak var unreadView: NSView! {
didSet {
unreadView.wantsLayer = true
unreadView.layer?.backgroundColor = NSColor.appRed.cgColor
unreadView.layer?.cornerRadius = 7.5
}
}
@IBOutlet weak var nameLeading: NSLayoutConstraint!
fileprivate let nameFont = NSFont.boldSystemFont(ofSize: 16)
fileprivate let nameFontUnread = NSFont.boldSystemFont(ofSize: 16)
fileprivate let textFont = NSFont.systemFont(ofSize: 12)
fileprivate let textFontUnread = NSFont.boldSystemFont(ofSize: 12)
fileprivate let dateFont = NSFont.systemFont(ofSize: 10)
fileprivate let dateFontUnread = NSFont.boldSystemFont(ofSize: 10)
func configure(withChannel channel: Channel, selected: Bool) {
nameLabel.stringValue = channel.name
if let lastMessage = channel.lastMessage {
messageTextLabel.stringValue = "\(lastMessage.sender): \(lastMessage.text ?? "")"
let nsDate = NSDate(timeIntervalSince1970: lastMessage.sentDate.timeIntervalSince1970)
timeLabel.stringValue = nsDate.timeAgoSinceNow()
}
else {
messageTextLabel.stringValue = ""
timeLabel.stringValue = ""
}
let unread = isUnread(channel: channel)
nameLabel.font = unread ? nameFontUnread : nameFont
messageTextLabel.font = unread ? textFontUnread : textFont
timeLabel.font = unread ? dateFontUnread : dateFont
unreadView.isHidden = !unread
nameLeading.constant = unread ? 30 : 15
nameLabel.textColor = selected ? NSColor.white : .textColor
messageTextLabel.textColor = selected ? NSColor.white : .textColor
timeLabel.textColor = selected ? NSColor.white : .textColor
wantsLayer = true
layer?.backgroundColor = selected ? NSColor.appRed.cgColor : NSColor.clear.cgColor
}
private func isUnread(channel: Channel) -> Bool {
if let messageID = channel.lastMessage?.id {
return messageID != UserDefaultsManager.lastReadMessage(inChannel: channel.name)
}
else {
return false
}
}
}
| mit | c387ef645168afc7891a9e2981785771 | 35.797101 | 98 | 0.658921 | 4.998031 | false | false | false | false |
LoveAlwaysYoung/EnjoyUniversity | EnjoyUniversity/EnjoyUniversity/Classes/Tools/SwiftyControl/SwiftySpinner.swift | 1 | 5296 | //
// SwiftySpinner.swift
// EnjoyUniversity
//
// Created by lip on 17/4/15.
// Copyright © 2017年 lip. All rights reserved.
//
import UIKit
protocol SwiftySpinnerDelegate {
/// 选中
func swiftySpinnerDidSelectRowAt(cell:SwiftySpinnerCell,row:Int)
/// 显示状态变化
func swiftySpinnerDidChangeStatus(isOnView:Bool)
}
class SwiftySpinner: UIView {
/// 下拉选择列表
lazy var spinnertableview = UITableView()
/// 下拉选择数组
var datalist = [String]()
/// 是否显示
var isOnView: Bool = false{
didSet{
delegate?.swiftySpinnerDidChangeStatus(isOnView: isOnView)
}
}
/// 代理
var delegate:SwiftySpinnerDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.6)
spinnertableview.layer.masksToBounds = true
spinnertableview.layer.cornerRadius = 10
spinnertableview.separatorStyle = .none
spinnertableview.delegate = self
spinnertableview.dataSource = self
spinnertableview.backgroundColor = UIColor.white
addSubview(spinnertableview)
let tapgesture = UITapGestureRecognizer(target: self, action: #selector(removeSpinner))
tapgesture.delegate = self
addGestureRecognizer(tapgesture)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func reloadData(){
let tbheight:CGFloat = CGFloat(datalist.count > 3 ? 4 : datalist.count)*44.0
spinnertableview.frame = CGRect(x: 10, y: -tbheight , width: UIScreen.main.bounds.width - 20, height: tbheight)
spinnertableview.reloadData()
}
}
// MARK: - 动画方法
extension SwiftySpinner{
func showSpinner(){
isOnView = true
self.alpha = 1
UIView.animate(withDuration: 0.5) {
self.spinnertableview.frame.origin = CGPoint(x: 10, y: 64 + 10)
}
}
func removeSpinner(){
isOnView = false
UIView.animate(withDuration: 0.5, animations: {
self.alpha = 0
self.spinnertableview.frame.origin = CGPoint(x: 5, y: -self.spinnertableview.frame.height)
}) { (_) in
self.removeFromSuperview()
}
}
}
// MARK: - 代理方法
extension SwiftySpinner:UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datalist.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = SwiftySpinnerCell(title: datalist[indexPath.row], font: 15, textcolor: UIColor.darkText)
if indexPath.row == 0{
cell.textlabel.textColor = UIColor.init(red: 18/255, green: 150/255, blue: 219/255, alpha: 1)
cell.indicatorview.isHidden = false
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
for cell in tableView.visibleCells{
let cell = cell as? SwiftySpinnerCell
cell?.textlabel.textColor = UIColor.darkText
cell?.indicatorview.isHidden = true
}
guard let cell = tableView.cellForRow(at: indexPath) as? SwiftySpinnerCell else{
return
}
cell.textlabel.textColor = UIColor.init(red: 18/255, green: 150/255, blue: 219/255, alpha: 1)
cell.indicatorview.isHidden = false
removeSpinner()
delegate?.swiftySpinnerDidSelectRowAt(cell: cell, row: indexPath.row)
}
// 解决手势和 tableview 响应冲突
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if NSStringFromClass((touch.view?.classForCoder)!) == "UITableViewCellContentView"{
return false
}
return true
}
}
/// 自定义 Cell
class SwiftySpinnerCell:UITableViewCell{
let textlabel = UILabel()
let indicatorview = UIImageView(image: UIImage(named: "community_select"))
init(title:String,font:CGFloat = 15,textcolor:UIColor = UIColor.darkText) {
super.init(style: .default, reuseIdentifier: nil)
selectionStyle = .none
textlabel.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 20, height: self.frame.height)
textlabel.text = title
textlabel.textAlignment = .center
textlabel.font = UIFont.boldSystemFont(ofSize: font)
textlabel.textColor = textcolor
textlabel.backgroundColor = UIColor.clear
addSubview(textlabel)
indicatorview.frame = CGRect(x: 5, y: 5, width: 5, height: frame.height - 10)
indicatorview.isHidden = true
addSubview(indicatorview)
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 3f4dc5a57d298230d5cab695474ca5f0 | 28.384181 | 119 | 0.620265 | 4.542358 | false | false | false | false |
NJUiosproject/AnyWay | happy_map/ViewController_chats.swift | 1 | 28167 | //
// ViewController_chats.swift
// happy_map
//
// Created by XiaoPeng on 16/5/1.
// Copyright © 2016年 XiaoPeng. All rights reserved.
//
import UIKit
class ViewController_chats: UIViewController,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var Danmu:NSArray?
// var data:NSArray?
var Index:Int?
var ID:Int?
@IBOutlet weak var myinput: UITextField!
@IBOutlet weak var titileimage: UIImageView!
@IBAction func returntomap(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
var selectedImage:UIImage?
@IBAction func pickimage(sender: AnyObject) {
//判断设置是否支持图片库
if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
//初始化图片控制器
let picker = UIImagePickerController()
//设置代理
picker.delegate = self
//指定图片控制器类型
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
//设置是否允许编辑
picker.allowsEditing = false
//弹出控制器,显示界面
self.presentViewController(picker, animated: true, completion: {
() -> Void in
})
}else{
print("读取相册错误")
}
}
@IBOutlet weak var mybottom: UIImageView!
@IBOutlet weak var mytest: UILabel!
@IBOutlet weak var myintroduction: UILabel!
var _renderer : BarrageRenderer!;
var _timer :NSTimer!;
var _index :NSInteger!;
func walkTextSpriteDescriptorWithDirection(direction:NSInteger)->BarrageDescriptor
{
let descriptor = BarrageDescriptor.init();
descriptor.spriteName = NSStringFromClass(BarrageWalkTextSprite);
_index = _index + 1
let data = Danmu?[ID!]
if Index == -1
{
Index = data!.count - 1
}
descriptor.params["textColor"] = UIColor.whiteColor();
var rand = random();
rand=100*rand/NSInteger.init(RAND_MAX);
rand=rand+50;
descriptor.params["speed"] = rand;
descriptor.params["direction"] = 2;
descriptor.params["backgroundColor"] = UIColor.init(colorLiteralRed: 76/255, green: 175/255, blue: 80/255, alpha: 0.7);
let myimagetext = NSTextAttachment.init()
let image = UIImage.init(named: "[email protected]")
let newSize = CGSizeMake(25.0, 25.0)
UIGraphicsBeginImageContext(newSize);
// 绘制改变大小的图片
image!.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
// 从当前context中创建一个改变大小后的图片
let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
myimagetext.image = scaledImage;
let newimagetext = NSMutableAttributedString.init(string: data![Index!]["url"] as! String)
Index = Index! - 1
newimagetext.insertAttributedString(NSAttributedString.init(attachment: myimagetext), atIndex: 0)
descriptor.params["attributedText"] = newimagetext
return descriptor;
}
func walkSelectedimageSpriteDescriptorWithDirection(direction:NSInteger)->BarrageDescriptor
{
let descriptor = BarrageDescriptor.init();
descriptor.spriteName = NSStringFromClass(BarrageWalkTextSprite);
_index = _index + 1
let data = Danmu?[ID!]
if Index == -1
{
Index = data!.count - 1
}
descriptor.params["textColor"] = UIColor.whiteColor();
var rand = random();
rand=100*rand/NSInteger.init(RAND_MAX);
rand=rand+50;
descriptor.params["speed"] = rand;
descriptor.params["direction"] = 2;
//descriptor.params["backgroundColor"] = UIColor.init(colorLiteralRed: 76/255, green: 175/255, blue: 80/255, alpha: 0.7);
let myimagetext = NSTextAttachment.init()
let image = selectedImage;
let rate = (selectedImage?.size.height)! / (selectedImage?.size.width)!
let newSize = CGSizeMake(75, 95)
//let new2size = selectedImage?.size
UIGraphicsBeginImageContext(newSize);
// 绘制改变大小的图片
image!.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
// 从当前context中创建一个改变大小后的图片
let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
myimagetext.image = scaledImage;
let spark = String(" ");
let newimagetext = NSMutableAttributedString.init(string:spark)
Index = Index! - 1
newimagetext.insertAttributedString(NSAttributedString.init(attachment: myimagetext), atIndex: 0)
descriptor.params["attributedText"] = newimagetext
return descriptor;
}
func imagePickerController(picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : AnyObject]) {
//查看info对象
print(info)
//获取选择的原图
selectedImage = (info[UIImagePickerControllerOriginalImage] as! UIImage)
_renderer.receive(self.walkSelectedimageSpriteDescriptorWithDirection(NSInteger.init(BarrageWalkDirection.L2R.rawValue)));
//图片控制器退出
picker.dismissViewControllerAnimated(true, completion: {
() -> Void in
})
}
func walkTextimageSpriteDescriptorWithDirection(direction:NSInteger)->BarrageDescriptor
{
let descriptor = BarrageDescriptor.init();
descriptor.spriteName = NSStringFromClass(BarrageWalkTextSprite);
_index = _index + 1
let data = Danmu?[ID!]
if Index == -1
{
Index = data!.count - 1
}
descriptor.params["textColor"] = UIColor.whiteColor();
var rand = random();
rand=100*rand/NSInteger.init(RAND_MAX);
rand=rand+50;
descriptor.params["speed"] = rand;
descriptor.params["direction"] = 2;
descriptor.params["backgroundColor"] = UIColor.init(colorLiteralRed: 76/255, green: 175/255, blue: 80/255, alpha: 0);
descriptor.params["cornerRadius"] = 5
descriptor.params["shadowColor"] = UIColor.blackColor()
descriptor.params["textFont"] = UIFont.italicSystemFontOfSize(20)
var mystring:String = data![Index!]["url"] as! String;
var find = 0
var iffind = Bool.init(false)
for i in mystring.characters
{
if i == "/"
{
iffind = true
}
if iffind == true
{
switch i {
case "1":
find = 1;break;
case "2":
find = 2;break;
case "3":
find = 3;break;
case "4":
find = 4;break;
default:
break;
}
}
}
print(find)
switch find {
case 0:
let newimagetext = NSMutableAttributedString.init(string: mystring)
Index = Index! - 1
descriptor.params["attributedText"] = newimagetext
return descriptor;
case 1:
let rangeOf=Range(start: mystring.startIndex, end: mystring.startIndex.advancedBy(2));
mystring.removeRange(rangeOf)
print(mystring)
let newimagetext = NSMutableAttributedString.init(string: mystring)
let myimagetext = NSTextAttachment.init()
let image = UIImage.init(named: "[email protected]")
let newSize = CGSizeMake(25.0, 25.0)
UIGraphicsBeginImageContext(newSize);
// 绘制改变大小的图片
image!.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
// 从当前context中创建一个改变大小后的图片
let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
myimagetext.image = scaledImage;
Index = Index! - 1
newimagetext.insertAttributedString(NSAttributedString.init(attachment: myimagetext), atIndex: 0)
descriptor.params["attributedText"] = newimagetext
case 2:
let rangeOf=Range(start: mystring.startIndex, end: mystring.startIndex.advancedBy(2));
mystring.removeRange(rangeOf)
print(mystring)
let newimagetext = NSMutableAttributedString.init(string: mystring)
let myimagetext = NSTextAttachment.init()
let image = UIImage.init(named: "[email protected]")
let newSize = CGSizeMake(25.0, 25.0)
UIGraphicsBeginImageContext(newSize);
// 绘制改变大小的图片
image!.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
// 从当前context中创建一个改变大小后的图片
let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
myimagetext.image = scaledImage;
Index = Index! - 1
newimagetext.insertAttributedString(NSAttributedString.init(attachment: myimagetext), atIndex: 0)
descriptor.params["attributedText"] = newimagetext
case 3:
let rangeOf=Range(start: mystring.startIndex, end: mystring.startIndex.advancedBy(2));
mystring.removeRange(rangeOf)
print(mystring)
let newimagetext = NSMutableAttributedString.init(string: mystring)
let myimagetext = NSTextAttachment.init()
let image = UIImage.init(named: "[email protected]")
let newSize = CGSizeMake(25.0, 25.0)
UIGraphicsBeginImageContext(newSize);
// 绘制改变大小的图片
image!.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
// 从当前context中创建一个改变大小后的图片
let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
myimagetext.image = scaledImage;
Index = Index! - 1
newimagetext.insertAttributedString(NSAttributedString.init(attachment: myimagetext), atIndex: 0)
descriptor.params["attributedText"] = newimagetext
case 4:
let rangeOf=Range(start: mystring.startIndex, end: mystring.startIndex.advancedBy(2));
mystring.removeRange(rangeOf)
print(mystring)
let newimagetext = NSMutableAttributedString.init(string: mystring)
let myimagetext = NSTextAttachment.init()
let image = UIImage.init(named: "[email protected]")
let newSize = CGSizeMake(25.0, 25.0)
UIGraphicsBeginImageContext(newSize);
// 绘制改变大小的图片
image!.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
// 从当前context中创建一个改变大小后的图片
let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
myimagetext.image = scaledImage;
Index = Index! - 1
newimagetext.insertAttributedString(NSAttributedString.init(attachment: myimagetext), atIndex: 0)
descriptor.params["attributedText"] = newimagetext
// return descriptor
default:break;
}
/* let newimagetext = NSMutableAttributedString.init(string: data![Index!]["url"] as! String)
let myimagetext = NSTextAttachment.init()
let image = UIImage.init(named: "[email protected]")
let newSize = CGSizeMake(25.0, 25.0)
UIGraphicsBeginImageContext(newSize);
// 绘制改变大小的图片
image!.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
// 从当前context中创建一个改变大小后的图片
let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
myimagetext.image = scaledImage;
Index = Index! - 1
newimagetext.insertAttributedString(NSAttributedString.init(attachment: myimagetext), atIndex: 0)
descriptor.params["attributedText"] = newimagetext*/
return descriptor;
}
func selfwalkTextimageSpriteDescriptorWithDirection(direction:NSInteger,test:NSString)->BarrageDescriptor
{
let descriptor = BarrageDescriptor.init();
descriptor.spriteName = NSStringFromClass(BarrageWalkTextSprite);
descriptor.params["textColor"] = UIColor.whiteColor();
var rand = random();
rand=100*rand/NSInteger.init(RAND_MAX);
rand=rand+50;
descriptor.params["speed"] = rand;
descriptor.params["direction"] = 2;
descriptor.params["backgroundColor"] = UIColor.init(colorLiteralRed: 190/255, green: 190/255, blue: 190/255, alpha: 0.5);
descriptor.params["cornerRadius"] = 5
descriptor.params["shadowColor"] = UIColor.blackColor()
var mystring:String = test as String;
var find = 0
var iffind = Bool.init(false)
for i in mystring.characters
{
if i == "/"
{
iffind = true
}
if iffind == true
{
switch i {
case "1":
find = 1;break;
case "2":
find = 2;break;
case "3":
find = 3;break;
case "4":
find = 4;break;
default:
break;
}
}
}
print(find)
switch find {
case 0:
let newimagetext = NSMutableAttributedString.init(string: mystring)
descriptor.params["attributedText"] = newimagetext
return descriptor;
case 1:
let rangeOf=Range(start: mystring.startIndex, end: mystring.startIndex.advancedBy(2));
mystring.removeRange(rangeOf)
print(mystring)
let newimagetext = NSMutableAttributedString.init(string: mystring)
let myimagetext = NSTextAttachment.init()
let image = UIImage.init(named: "[email protected]")
let newSize = CGSizeMake(25.0, 25.0)
UIGraphicsBeginImageContext(newSize);
// 绘制改变大小的图片
image!.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
// 从当前context中创建一个改变大小后的图片
let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
myimagetext.image = scaledImage;
newimagetext.insertAttributedString(NSAttributedString.init(attachment: myimagetext), atIndex: 0)
descriptor.params["attributedText"] = newimagetext
case 2:
let rangeOf=Range(start: mystring.startIndex, end: mystring.startIndex.advancedBy(2));
mystring.removeRange(rangeOf)
print(mystring)
let newimagetext = NSMutableAttributedString.init(string: mystring)
let myimagetext = NSTextAttachment.init()
let image = UIImage.init(named: "[email protected]")
let newSize = CGSizeMake(25.0, 25.0)
UIGraphicsBeginImageContext(newSize);
// 绘制改变大小的图片
image!.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
// 从当前context中创建一个改变大小后的图片
let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
myimagetext.image = scaledImage;
newimagetext.insertAttributedString(NSAttributedString.init(attachment: myimagetext), atIndex: 0)
descriptor.params["attributedText"] = newimagetext
case 3:
let rangeOf=Range(start: mystring.startIndex, end: mystring.startIndex.advancedBy(2));
mystring.removeRange(rangeOf)
print(mystring)
let newimagetext = NSMutableAttributedString.init(string: mystring)
let myimagetext = NSTextAttachment.init()
let image = UIImage.init(named: "[email protected]")
let newSize = CGSizeMake(25.0, 25.0)
UIGraphicsBeginImageContext(newSize);
// 绘制改变大小的图片
image!.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
// 从当前context中创建一个改变大小后的图片
let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
myimagetext.image = scaledImage;
newimagetext.insertAttributedString(NSAttributedString.init(attachment: myimagetext), atIndex: 0)
descriptor.params["attributedText"] = newimagetext
case 4:
let rangeOf=Range(start: mystring.startIndex, end: mystring.startIndex.advancedBy(2));
mystring.removeRange(rangeOf)
print(mystring)
let newimagetext = NSMutableAttributedString.init(string: mystring)
let myimagetext = NSTextAttachment.init()
let image = UIImage.init(named: "[email protected]")
let newSize = CGSizeMake(25.0, 25.0)
UIGraphicsBeginImageContext(newSize);
// 绘制改变大小的图片
image!.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
// 从当前context中创建一个改变大小后的图片
let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
myimagetext.image = scaledImage;
newimagetext.insertAttributedString(NSAttributedString.init(attachment: myimagetext), atIndex: 0)
descriptor.params["attributedText"] = newimagetext
// return descriptor
default:break;
}
/* let newimagetext = NSMutableAttributedString.init(string: data![Index!]["url"] as! String)
let myimagetext = NSTextAttachment.init()
let image = UIImage.init(named: "[email protected]")
let newSize = CGSizeMake(25.0, 25.0)
UIGraphicsBeginImageContext(newSize);
// 绘制改变大小的图片
image!.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height));
// 从当前context中创建一个改变大小后的图片
let scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
myimagetext.image = scaledImage;
Index = Index! - 1
newimagetext.insertAttributedString(NSAttributedString.init(attachment: myimagetext), atIndex: 0)
descriptor.params["attributedText"] = newimagetext*/
return descriptor;
}
func selfwalkTextSpriteDescriptorWithDirection(direction:NSInteger,test:NSString)->BarrageDescriptor
{
let descriptor = BarrageDescriptor.init();
descriptor.spriteName = NSStringFromClass(BarrageWalkImageTextSprite);
_index = _index + 1
descriptor.params["text"] = NSString.localizedStringWithFormat(test);
descriptor.params["textColor"] = UIColor.redColor();
var rand = random();
rand=100*rand/NSInteger.init(RAND_MAX);
rand=rand+50;
descriptor.params["speed"] = rand;
descriptor.params["direction"] = direction;
descriptor.params["trackNumber"]=20;
descriptor.params["duration"]=3;
return descriptor;
}
func autorSendBarrage() {
let spriteNumber = _renderer.spritesNumberWithName(nil);
if(spriteNumber<50){
//Direction default set 1
let dir = BarrageWalkDirection.L2R.rawValue;
print(dir);
//_renderer.receive(self.walkTextSpriteDescriptorWithDirection(NSInteger.init(dir)));
_renderer.receive(self.walkTextimageSpriteDescriptorWithDirection(NSInteger.init(dir)));
}
}
func handleSwipeFrom(recognizer:UISwipeGestureRecognizer) {
// 触发手勢事件后,在这里作些事情
// 底下是刪除手势的方法
self.dismissViewControllerAnimated(true, completion: nil)
self.view.removeGestureRecognizer(recognizer)
}
override func viewDidLoad() {
// self.view.frame = CGRectMake(10, 10, 300, 500);
super.viewDidLoad()
//let filepath:NSString = NSBundle.mainBundle().pathForResource("danmaku", ofType: "plist")!
let filepath:NSString = NSBundle.mainBundle().pathForResource("danmaku", ofType: "plist")!
//let filepath:String = NSHomeDirectory() + "/Documents/danmaku.plist"
Danmu = NSArray(contentsOfFile: filepath as String)
self.modalPresentationStyle = .Custom
myinput.delegate = self
//myintroduction.lineBreakMode=NSLineBreakMode.ByWordWrapping
//myintroduction.numberOfLines = 0;
//mytest.backgroundColor=UIColor.grayColor()
//mytest.font=UIFont.systemFontOfSize(10)//调整文字大小
// mytest.font=UIFont.boldSystemFontOfSize(20)
//mytest.font=UIFont.italicSystemFontOfSize(20)
//mytest.font=UIFont(name: "Bobz Type", size: 40)
// self.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
// self.view.frame = CGRectMake(10, 10, 300, 600);
//self.view.superview?.frame = CGRectMake(0, 0, 300,300);
// Do any additional setup after loading the view.
_index = 0
_renderer = BarrageRenderer.init();
mybottom.addSubview(_renderer.view);
//_renderer.canvasMargin=UIEdgeInsetsMake(100, 100,100,100);
mybottom.sendSubviewToBack(_renderer.view);
let safeObj=NSSafeObject.init(object: self, withSelector:#selector(ViewController_chats.autorSendBarrage));
_timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target:safeObj, selector:#selector(NSSafeObject.excute), userInfo: nil, repeats: true)
let recognizer = UISwipeGestureRecognizer.init(target: self, action:#selector(handleSwipeFrom))
// 不同的 Recognizer 有不同的实体变数
// 例如 SwipeGesture 可以指定方向
// 而 TapGesture 則可以指定次數
recognizer.direction = UISwipeGestureRecognizerDirection.Down
self.view.addGestureRecognizer(recognizer)
}
override func viewDidLayoutSubviews() {
self.view.frame = CGRectMake(10, 30, 300, 520);
// self.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
// self.view.superview?.frame = CGRectMake(0, 0, 300, 300);
//self.view.frame = CGRectMake(10, 10, 300, 600);
super.viewWillAppear(animated)
titileimage.layer.cornerRadius = 8;
titileimage.layer.masksToBounds = true
switch ID! {
case 0:
let img = UIImage(named:"DSC_0751.jpg") //初始化图片
let img2 = UIImage(named:"DSC_0741.jpg")
titileimage.image = img2
mybottom.image = img
break
case 1:
let img2 = UIImage(named:"IMG_1140.jpg") //初始化图片
let img = UIImage(named:"IMG_1947.jpg")
titileimage.image = img2
mybottom.image = img
break
case 2:
let img = UIImage(named:"食堂1.jpg") //初始化图片
let img2 = UIImage(named:"食堂2.jpg")
titileimage.image = img2
mybottom.image = img
break
case 3:
let img = UIImage(named:"IMG_1159.JPG") //初始化图片
let img2 = UIImage(named:"教学楼2.jpg")
titileimage.image = img2
mybottom.image = img
break
case 4:
let img = UIImage(named:"IMG_1155.jpg") //初始化图片
let img2 = UIImage(named:"系楼1.jpg")
titileimage.image = img2
mybottom.image = img
break
case 5:
let img = UIImage(named:"IMG_1718.jpg") //初始化图片
let img2 = UIImage(named:"图书馆2.jpg")
titileimage.image = img2
mybottom.image = img
break
default:
let img = UIImage(named:"DSC_0751.jpg") //初始化图片
let img2 = UIImage(named:"DSC_0741.jpg")
titileimage.image = img2
mybottom.image = img
}
_renderer.start()
let data = Danmu?[ID!]
Index = data!.count-1
// mytest.font=UIFont(name: "Bobz Type", size: 40)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func animateTextField(textField: UITextField, up: Bool) {
let movementDistance:CGFloat = -210
let movementDuration: Double = 0.3
var movement:CGFloat = 0
if up {
movement = movementDistance
}
else {
movement = -movementDistance
}
UIView.beginAnimations("animateTextField", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration)
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
func textFieldDidBeginEditing(textField: UITextField) {
self.animateTextField(textField, up:true)
textField.text = ""
}
func textFieldDidEndEditing(textField: UITextField) {
self.animateTextField(textField, up:false)
}
func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore.
{
textField.resignFirstResponder()
_renderer.receive(selfwalkTextimageSpriteDescriptorWithDirection(2, test: myinput.text!))
modifiymap(ID!, text: myinput.text! as String)
textField.text = "一起来吐槽吧~"
return true;
}
func modifiymap(index : Int,text : String) -> Bool {
let tempArray = NSMutableArray.init(array:Danmu!)
let tempDictionaryArray=NSMutableArray.init(array:tempArray[index] as! NSArray)
let addedEntry=["time":"1", "url":text];
tempDictionaryArray.addObject(addedEntry);
tempArray.replaceObjectAtIndex(index, withObject: tempDictionaryArray)
Danmu = tempArray;
let filepath:NSString = NSBundle.mainBundle().pathForResource("danmaku", ofType: "plist")!
//let filepath:String = NSHomeDirectory() + "/Documents/danmaku.plist"
NSArray(array: Danmu!).writeToFile(filepath as String, atomically: true)
return true;
}
}
| mit | f754640350fd152174a61c2bc5816531 | 41.29108 | 147 | 0.616008 | 4.709655 | false | false | false | false |
kevintulod/CascadeKit-iOS | CascadeKit/CascadeKit/Cascade Controller/CascadeController+Animations.swift | 1 | 5161 | //
// CascadeController+Animations.swift
// CascadeKit
//
// Created by Kevin Tulod on 1/14/17.
// Copyright © 2017 Kevin Tulod. All rights reserved.
//
import UIKit
extension CascadeController {
typealias AnimationStageHandler = () -> Void
/// Performs a cascade animation in the forward direction
internal func animate(withForwardCascadeController cascadeController: UIViewController, preAnimation: AnimationStageHandler?, postAnimation: AnimationStageHandler?, completion: AnimationStageHandler?) {
// Add images of the current state
let imageViews = imageViewsForCurrentState()
view.addSubviews([imageViews.left, imageViews.right])
// Add cascading view image
var cascadeFrame = rightViewContainer.frame
cascadeFrame.origin.x += cascadeFrame.width
let cascadeImageView = imageView(for: cascadeController.view, targetFrame: cascadeFrame)
view.addSubview(cascadeImageView)
// Calculate target frames
let rightImageViewTargetFrame = leftViewContainer.frame
let cascadeImageViewTargetFrame = rightViewContainer.frame
var leftImageViewTargetFrame = leftViewContainer.frame
leftImageViewTargetFrame.origin.x = -leftImageViewTargetFrame.width
// Set alphas
leftViewContainer.alpha = 0
rightViewContainer.alpha = 0
preAnimation?()
UIView.animate(withDuration: animationDuration, delay: 0, options: [.curveEaseOut],
animations: {
imageViews.left.frame = leftImageViewTargetFrame
imageViews.right.frame = rightImageViewTargetFrame
cascadeImageView.frame = cascadeImageViewTargetFrame
imageViews.right.alpha = 0.5
self.leftViewContainer.alpha = 1
self.rightViewContainer.alpha = 1
}, completion: { success in
postAnimation?()
imageViews.left.removeFromSuperview()
imageViews.right.removeFromSuperview()
cascadeImageView.removeFromSuperview()
completion?()
})
}
/// Performs a cascade animation in the backward direction
internal func animate(withBackwardCascadeController cascadeController: UIViewController, preAnimation: AnimationStageHandler?, postAnimation: AnimationStageHandler?, completion: AnimationStageHandler?) {
// Add images of the current state
let imageViews = imageViewsForCurrentState()
view.addSubviews([imageViews.left, imageViews.right])
// Add cascading view image
var cascadeFrame = leftViewContainer.frame
cascadeFrame.origin.x += cascadeFrame.width
let cascadeImageView = imageView(for: cascadeController.view, targetFrame: cascadeFrame)
view.addSubview(cascadeImageView)
// Calculate target frames
let leftImageViewTargetFrame = rightViewContainer.frame
let cascadeImageViewTargetFrame = leftViewContainer.frame
var rightImageViewTargetFrame = rightViewContainer.frame
rightImageViewTargetFrame.origin.x += rightImageViewTargetFrame.width
// Set alphas
leftViewContainer.alpha = 0
rightViewContainer.alpha = 0
preAnimation?()
UIView.animate(withDuration: animationDuration,
delay: 0,
options: [.curveEaseOut],
animations: {
imageViews.left.frame = leftImageViewTargetFrame
imageViews.right.frame = rightImageViewTargetFrame
cascadeImageView.frame = cascadeImageViewTargetFrame
imageViews.left.alpha = 0.5
self.leftViewContainer.alpha = 1
self.rightViewContainer.alpha = 1
}, completion: { success in
postAnimation?()
imageViews.left.removeFromSuperview()
imageViews.right.removeFromSuperview()
cascadeImageView.removeFromSuperview()
completion?()
})
}
/// Returns the image view representations for the left and right views
fileprivate func imageViewsForCurrentState() -> (left: UIImageView, right: UIImageView) {
let leftImageView = UIImageView(frame: leftViewContainer.frame)
leftImageView.image = UIImage.image(from: leftController?.view)
let rightImageView = UIImageView(frame: rightViewContainer.frame)
rightImageView.image = UIImage.image(from: rightController?.view)
return (leftImageView, rightImageView)
}
/// Returns an image view representation of the passed-in view in the target frame
fileprivate func imageView(for pendingView: UIView, targetFrame: CGRect) -> UIImageView {
let tempView = UIView(frame: targetFrame)
tempView.fill(with: pendingView)
let pendingViewImageView = UIImageView(frame: targetFrame)
pendingViewImageView.image = UIImage.image(from: tempView)
return pendingViewImageView
}
}
| mit | 0ffe07e43b91c6f52fec0f1505a736c3 | 38.389313 | 207 | 0.661822 | 5.701657 | false | false | false | false |
suzuki-0000/SKPhotoBrowser | SKPhotoBrowser/SKCaptionView.swift | 3 | 2646 | //
// SKCaptionView.swift
// SKPhotoBrowser
//
// Created by suzuki_keishi on 2015/10/07.
// Copyright © 2015 suzuki_keishi. All rights reserved.
//
import UIKit
open class SKCaptionView: UIView {
fileprivate var photo: SKPhotoProtocol?
fileprivate var photoLabel: UILabel!
fileprivate var photoLabelPadding: CGFloat = 10
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public convenience init(photo: SKPhotoProtocol) {
self.init(frame: CGRect(x: 0, y: 0, width: SKMesurement.screenWidth, height: SKMesurement.screenHeight))
self.photo = photo
setup()
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
guard let text = photoLabel.text, text.count > 0 else {
return CGSize.zero
}
let font: UIFont = photoLabel.font
let width: CGFloat = size.width - photoLabelPadding * 2
let height: CGFloat = photoLabel.font.lineHeight * CGFloat(photoLabel.numberOfLines)
let attributedText = NSAttributedString(string: text, attributes: [NSAttributedString.Key.font: font])
let textSize = attributedText.boundingRect(with: CGSize(width: width, height: height), options: .usesLineFragmentOrigin, context: nil).size
return CGSize(width: textSize.width, height: textSize.height + photoLabelPadding * 2)
}
}
private extension SKCaptionView {
func setup() {
isOpaque = false
autoresizingMask = [.flexibleWidth, .flexibleTopMargin, .flexibleRightMargin, .flexibleLeftMargin]
// setup photoLabel
setupPhotoLabel()
}
func setupPhotoLabel() {
photoLabel = UILabel(frame: CGRect(x: photoLabelPadding, y: 0, width: bounds.size.width - (photoLabelPadding * 2), height: bounds.size.height))
photoLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight]
photoLabel.isOpaque = false
photoLabel.backgroundColor = SKCaptionOptions.backgroundColor
photoLabel.textColor = SKCaptionOptions.textColor
photoLabel.textAlignment = SKCaptionOptions.textAlignment
photoLabel.lineBreakMode = SKCaptionOptions.lineBreakMode
photoLabel.numberOfLines = SKCaptionOptions.numberOfLine
photoLabel.font = SKCaptionOptions.font
photoLabel.shadowColor = UIColor(white: 0.0, alpha: 0.5)
photoLabel.shadowOffset = CGSize(width: 0.0, height: 1.0)
photoLabel.text = photo?.caption
addSubview(photoLabel)
}
}
| mit | 4cf6f51ce5544b5b409c21f0bfd2dc69 | 35.736111 | 151 | 0.675992 | 4.576125 | false | false | false | false |
zhuhaow/soca | soca/ProxyServer.swift | 1 | 2651 | //
// ProxyServer.swift
// Soca
//
// Created by Zhuhao Wang on 2/16/15.
// Copyright (c) 2015 Zhuhao Wang. All rights reserved.
//
import Foundation
import CocoaLumberjack
//import CocoaLumberjackSwift
class ProxyServer : NSObject {
let listeningPort :UInt16
let ruleManager :RuleManager
var activeSockets :[ProxySocket]!
var listeningSocket :GCDAsyncSocket!
let listeningQueue :dispatch_queue_t = dispatch_queue_create("com.Soca.ProxyServer.listenQueue", DISPATCH_QUEUE_SERIAL)
required init(listenPort port: UInt16, ruleManager: RuleManager) {
self.listeningPort = port
self.ruleManager = ruleManager
super.init()
}
func startProxy() {
self.disconnect()
self.listeningSocket = GCDAsyncSocket(delegate: self, delegateQueue: self.listeningQueue)
self.activeSockets = [ProxySocket]()
var error :NSError?
self.listeningSocket.acceptOnPort(self.listeningPort, error: &error)
if let userInfo = error?.userInfo {
DDLogError("Error listening on port \(self.listeningPort): \(userInfo)")
}
DDLogInfo("Listening on port \(self.listeningPort)")
}
func socket(sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {}
func disconnect() {
self.activeSockets = nil
self.listeningSocket?.disconnect()
self.listeningSocket?.delegate = nil
self.listeningSocket = nil
}
func socketDidDisconnect(socket: ProxySocket) {
dispatch_async(self.listeningQueue) {
let index = (self.activeSockets as NSArray).indexOfObject(socket)
self.activeSockets.removeAtIndex(index)
DDLogVerbose("Removed a closed proxy socket, current sockets: \(self.activeSockets.count)")
}
}
func matchRule(request :ConnectMessage) -> AdapterFactory {
return ruleManager.match(request)
}
}
class SOCKS5ProxyServer : ProxyServer {
override func socket(sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {
DDLogVerbose("SOCKS5 proxy server accepted new socket")
let proxySocket = SOCKS5ProxySocket(socket: newSocket, proxy:self)
self.activeSockets.append(proxySocket)
}
}
class HTTPProxyServer : ProxyServer {
override func socket(sock: GCDAsyncSocket, didAcceptNewSocket newSocket: GCDAsyncSocket) {
DDLogVerbose("HTTP proxy server accepted new socket")
let proxySocket = HTTPProxySocket(socket: newSocket, proxy: self)
self.activeSockets.append(proxySocket)
proxySocket.openSocket()
}
} | mit | 59cc1521137013db7c2e81ffad2b3c1f | 33.441558 | 123 | 0.683893 | 4.578584 | false | false | false | false |
WickedColdfront/Slide-iOS | Pods/PagingMenuController/Pod/Classes/PagingMenuController.swift | 1 | 22096 | //
// PagingMenuController.swift
// PagingMenuController
//
// Created by Yusuke Kita on 3/18/15.
// Copyright (c) 2015 kitasuke. All rights reserved.
//
import UIKit
@available(*, unavailable, message: "Please use `onMove` property instead")
public protocol PagingMenuControllerDelegate: class {}
public enum MenuMoveState {
case willMoveController(to: UIViewController, from: UIViewController)
case didMoveController(to: UIViewController, from: UIViewController)
case willMoveItem(to: MenuItemView, from: MenuItemView)
case didMoveItem(to: MenuItemView, from: MenuItemView)
case didScrollStart
case didScrollEnd
}
internal let MinimumSupportedViewCount = 1
internal let VisiblePagingViewNumber = 3
open class PagingMenuController: UIViewController {
public fileprivate(set) var menuView: MenuView? {
didSet {
guard let menuView = menuView else { return }
menuView.delegate = self
menuView.onMove = onMove
menuView.update(currentPage: options.defaultPage)
view.addSubview(menuView)
}
}
public fileprivate(set) var pagingViewController: PagingViewController? {
didSet {
guard let pagingViewController = pagingViewController else { return }
pagingViewController.contentScrollView.delegate = self
view.addSubview(pagingViewController.view)
addChildViewController(pagingViewController)
pagingViewController.didMove(toParentViewController: self)
}
}
public var onMove: ((MenuMoveState) -> Void)? {
didSet {
guard let menuView = menuView else { return }
menuView.onMove = onMove
}
}
fileprivate var options: PagingMenuControllerCustomizable! {
didSet {
cleanup()
validate(options)
}
}
fileprivate var menuOptions: MenuViewCustomizable?
// MARK: - Lifecycle
public init(options: PagingMenuControllerCustomizable) {
super.init(nibName: nil, bundle: nil)
setup(options)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// fix unnecessary inset for menu view when implemented by programmatically
menuView?.contentInset.top = 0
}
override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if let menuView = menuView, let menuOptions = menuOptions {
menuView.updateMenuViewConstraints(size)
coordinator.animate(alongsideTransition: { [unowned self] (_) -> Void in
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
// reset selected menu item view position
switch menuOptions.displayMode {
case .standard, .infinite:
self.move(toPage: menuView.currentPage)
default: break
}
}, completion: nil)
}
}
// MARK: - Public
open func setup(_ options: PagingMenuControllerCustomizable) {
self.options = options
switch options.componentType {
case .all(let menuOptions, _):
self.menuOptions = menuOptions
case .menuView(let menuOptions):
self.menuOptions = menuOptions
default: break
}
setupMenuView()
setupMenuController()
move(toPage: currentPage, animated: false)
}
fileprivate func setupMenuView() {
switch options.componentType {
case .pagingController: return
default: break
}
constructMenuView()
layoutMenuView()
}
fileprivate func setupMenuController() {
switch options.componentType {
case .menuView: return
default: break
}
constructPagingViewController()
layoutPagingViewController()
}
open func move(toPage page: Int, animated: Bool = true) {
switch options.componentType {
case .menuView, .all:
// ignore an unexpected page number
guard let menuView = menuView , page < menuView.menuItemCount else { return }
let lastPage = menuView.currentPage
guard page != lastPage else {
// place views on appropriate position
menuView.move(toPage: page, animated: animated)
pagingViewController?.positionMenuController()
return
}
switch options.componentType {
case .all: break
default:
menuView.move(toPage: page, animated: animated)
return
}
case .pagingController:
guard let pagingViewController = pagingViewController , page < pagingViewController.controllers.count else { return }
guard page != pagingViewController.currentPage else { return }
}
guard let pagingViewController = pagingViewController,
let previousPagingViewController = pagingViewController.currentViewController else { return }
// hide paging views if it's moving to far away
hidePagingMenuControllers(page)
let nextPage = page % pagingViewController.controllers.count
let nextPagingViewController = pagingViewController.controllers[nextPage]
onMove?(.willMoveController(to: nextPagingViewController, from: previousPagingViewController))
menuView?.move(toPage: page)
pagingViewController.update(currentPage: nextPage)
pagingViewController.currentViewController = nextPagingViewController
let duration = animated ? options.animationDuration : 0
let animationClosure = {
pagingViewController.positionMenuController()
}
let completionClosure = { [weak self] (_: Bool) -> Void in
pagingViewController.relayoutPagingViewControllers()
// show paging views
self?.showPagingMenuControllers()
self?.onMove?(.didMoveController(to: nextPagingViewController, from: previousPagingViewController))
}
if duration > 0 {
UIView.animate(withDuration: duration, animations: animationClosure, completion: completionClosure)
} else {
animationClosure()
completionClosure(true)
}
}
// MARK: - Constructor
fileprivate func constructMenuView() {
guard let menuOptions = self.menuOptions else { return }
menuView = MenuView(menuOptions: menuOptions)
addTapGestureHandler()
addSwipeGestureHandler()
}
fileprivate func layoutMenuView() {
guard let menuView = menuView else { return }
let height: CGFloat
switch options.componentType {
case .all(let menuOptions, _):
height = menuOptions.height
switch menuOptions.menuPosition {
case .top:
// V:|[menuView]
menuView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
case .bottom:
// V:[menuView]|
menuView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
case .menuView(let menuOptions):
height = menuOptions.height
// V:|[menuView]
menuView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
default: return
}
// H:|[menuView]|
// V:[menuView(height)]
NSLayoutConstraint.activate([
menuView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
menuView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
menuView.heightAnchor.constraint(equalToConstant: height + (menuOptions?.marginTop)!)
])
menuView.setNeedsLayout()
menuView.layoutIfNeeded()
}
fileprivate func constructPagingViewController() {
let viewControllers: [UIViewController]
switch options.componentType {
case .pagingController(let pagingControllers): viewControllers = pagingControllers
case .all(_, let pagingControllers): viewControllers = pagingControllers
default: return
}
pagingViewController = PagingViewController(viewControllers: viewControllers, options: options)
}
fileprivate func layoutPagingViewController() {
guard let pagingViewController = pagingViewController else { return }
// H:|[pagingView]|
NSLayoutConstraint.activate([
pagingViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
pagingViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
switch options.componentType {
case .pagingController:
// V:|[pagingView]|
NSLayoutConstraint.activate([
pagingViewController.view.topAnchor.constraint(equalTo: view.topAnchor),
pagingViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
case .all(let menuOptions, _):
guard let menuView = menuView else { return }
switch menuOptions.menuPosition {
case .top:
// V:[menuView][pagingView]|
NSLayoutConstraint.activate([
menuView.bottomAnchor.constraint(equalTo: pagingViewController.view.topAnchor, constant: 0),
pagingViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
case .bottom:
// V:|[pagingView][menuView]
NSLayoutConstraint.activate([
pagingViewController.view.topAnchor.constraint(equalTo: view.topAnchor),
pagingViewController.view.bottomAnchor.constraint(equalTo: menuView.topAnchor, constant: 0),
])
}
default: return
}
}
// MARK: - Private
fileprivate func hidePagingMenuControllers(_ page: Int) {
guard let menuOptions = menuOptions else { return }
switch (options.lazyLoadingPage, menuOptions.displayMode, page) {
case (.three, .infinite, menuView?.previousPage ?? previousPage),
(.three, .infinite, menuView?.nextPage ?? nextPage): break
case (.three, .infinite, _):
pagingViewController?.visibleControllers.forEach { $0.view.alpha = 0 }
default: break
}
}
fileprivate func showPagingMenuControllers() {
pagingViewController?.visibleControllers.forEach { $0.view.alpha = 1 }
}
}
extension PagingMenuController: UIScrollViewDelegate {
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
onMove?(.didScrollEnd)
guard let menuOptions = menuOptions else { return }
let nextPage: Int
switch (scrollView, pagingViewController, menuView, menuOptions.isAutoSelectAtScrollEnd) {
case let (scrollView, pagingViewController?, _, _) where scrollView.isEqual(pagingViewController.contentScrollView):
nextPage = nextPageFromCurrentPosition
case let (scrollView, _, menuView?, autoSelect) where scrollView.isEqual(menuView) && autoSelect:
nextPage = nextPageFromCurrentPoint
default: return
}
move(toPage: nextPage)
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
onMove?(.didScrollStart)
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
guard let menuOptions = menuOptions else { return }
switch (scrollView, decelerate, menuOptions.isAutoSelectAtScrollEnd) {
case (let scrollView, false, true) where scrollView.isEqual(menuView): break
default: return
}
let nextPage = nextPageFromCurrentPoint
move(toPage: nextPage)
}
}
extension PagingMenuController: Pagable {
public var currentPage: Int {
switch (menuView, pagingViewController) {
case (let menuView?, _):
return menuView.currentPage
case (_, let pagingViewController?):
return pagingViewController.currentPage
default:
return 0
}
}
var previousPage: Int {
guard let menuOptions = menuOptions,
case .infinite = menuOptions.displayMode,
let controllers = pagingViewController?.controllers else { return currentPage - 1 }
return currentPage - 1 < 0 ? controllers.count - 1 : currentPage - 1
}
var nextPage: Int {
guard let menuOptions = menuOptions,
case .infinite = menuOptions.displayMode,
let controllers = pagingViewController?.controllers else { return currentPage + 1 }
return currentPage + 1 > controllers.count - 1 ? 0 : currentPage + 1
}
}
// MARK: Page Control
extension PagingMenuController {
fileprivate enum PagingViewPosition {
case left, center, right, unknown
init(order: Int) {
switch order {
case 0: self = .left
case 1: self = .center
case 2: self = .right
default: self = .unknown
}
}
}
fileprivate var currentPagingViewPosition: PagingViewPosition {
guard let pagingViewController = pagingViewController else { return .unknown }
let pageWidth = pagingViewController.contentScrollView.frame.width
let order = Int(ceil((pagingViewController.contentScrollView.contentOffset.x - pageWidth / 2) / pageWidth))
if let menuOptions = menuOptions,
case .infinite = menuOptions.displayMode {
return PagingViewPosition(order: order)
}
// consider left edge menu as center position
guard pagingViewController.currentPage == 0 && pagingViewController.contentScrollView.contentSize.width < (pageWidth * CGFloat(VisiblePagingViewNumber)) else { return PagingViewPosition(order: order) }
return PagingViewPosition(order: order + 1)
}
fileprivate var nextPageFromCurrentPosition: Int {
// set new page number according to current moving direction
let page: Int
switch options.lazyLoadingPage {
case .all:
guard let scrollView = pagingViewController?.contentScrollView else { return currentPage }
page = Int(scrollView.contentOffset.x) / Int(scrollView.frame.width)
default:
switch (currentPagingViewPosition, options.componentType) {
case (.left, .pagingController):
page = previousPage
case (.left, _):
page = menuView?.previousPage ?? previousPage
case (.right, .pagingController):
page = nextPage
case (.right, _):
page = menuView?.nextPage ?? nextPage
default:
page = currentPage
}
}
return page
}
fileprivate var nextPageFromCurrentPoint: Int {
guard let menuView = menuView else { return 0 }
let point = CGPoint(x: menuView.contentOffset.x + menuView.frame.width / 2, y: 0)
for (index, menuItemView) in menuView.menuItemViews.enumerated() {
guard menuItemView.frame.contains(point) else { continue }
return index
}
return menuView.currentPage
}
}
// MARK: - GestureRecognizer
extension PagingMenuController {
fileprivate var tapGestureRecognizer: UITapGestureRecognizer {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
gestureRecognizer.numberOfTapsRequired = 1
return gestureRecognizer
}
fileprivate var leftSwipeGestureRecognizer: UISwipeGestureRecognizer {
let gestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeGesture))
gestureRecognizer.direction = .left
return gestureRecognizer
}
fileprivate var rightSwipeGestureRecognizer: UISwipeGestureRecognizer {
let gestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeGesture))
gestureRecognizer.direction = .right
return gestureRecognizer
}
fileprivate func addTapGestureHandler() {
menuView?.menuItemViews.forEach {
$0.addGestureRecognizer(tapGestureRecognizer)
}
}
fileprivate func addSwipeGestureHandler() {
guard let menuOptions = menuOptions else { return }
switch menuOptions.displayMode {
case .standard(_, _, .pagingEnabled): break
case .infinite(_, .pagingEnabled): break
default: return
}
menuView?.panGestureRecognizer.require(toFail: leftSwipeGestureRecognizer)
menuView?.addGestureRecognizer(leftSwipeGestureRecognizer)
menuView?.panGestureRecognizer.require(toFail: rightSwipeGestureRecognizer)
menuView?.addGestureRecognizer(rightSwipeGestureRecognizer)
}
internal func handleTapGesture(_ recognizer: UITapGestureRecognizer) {
guard let menuItemView = recognizer.view as? MenuItemView,
let menuView = menuView,
let page = menuView.menuItemViews.index(of: menuItemView),
page != menuView.currentPage,
let menuOptions = menuOptions else { return }
let newPage: Int
switch menuOptions.displayMode {
case .standard(_, _, .pagingEnabled):
newPage = page < currentPage ? menuView.currentPage - 1 : menuView.currentPage + 1
case .infinite(_, .pagingEnabled):
if menuItemView.frame.midX > menuView.currentMenuItemView.frame.midX {
newPage = menuView.nextPage
} else {
newPage = menuView.previousPage
}
case .infinite: fallthrough
default:
newPage = page
}
move(toPage: newPage)
}
internal func handleSwipeGesture(_ recognizer: UISwipeGestureRecognizer) {
guard let menuView = recognizer.view as? MenuView,
let menuOptions = menuOptions else { return }
let newPage: Int
switch (recognizer.direction, menuOptions.displayMode) {
case (UISwipeGestureRecognizerDirection.left, .infinite):
newPage = menuView.nextPage
case (UISwipeGestureRecognizerDirection.left, _):
newPage = min(nextPage, menuOptions.itemsOptions.count - 1)
case (UISwipeGestureRecognizerDirection.right, .infinite):
newPage = menuView.previousPage
case (UISwipeGestureRecognizerDirection.right, _):
newPage = max(previousPage, 0)
default: return
}
move(toPage: newPage)
}
}
extension PagingMenuController {
func cleanup() {
if let menuView = self.menuView {
menuView.cleanup()
menuView.removeFromSuperview()
}
if let pagingViewController = self.pagingViewController {
pagingViewController.cleanup()
pagingViewController.view.removeFromSuperview()
pagingViewController.removeFromParentViewController()
pagingViewController.willMove(toParentViewController: nil)
}
}
}
// MARK: Validator
extension PagingMenuController {
fileprivate func validate(_ options: PagingMenuControllerCustomizable) {
validateDefaultPage(options)
validateContentsCount(options)
validateInfiniteMenuItemNumbers(options)
}
fileprivate func validateContentsCount(_ options: PagingMenuControllerCustomizable) {
switch options.componentType {
case .all(let menuOptions, let pagingControllers):
guard menuOptions.itemsOptions.count == pagingControllers.count else {
raise("number of menu items and view controllers doesn't match")
return
}
default: break
}
}
fileprivate func validateDefaultPage(_ options: PagingMenuControllerCustomizable) {
let maxCount: Int
switch options.componentType {
case .pagingController(let pagingControllers):
maxCount = pagingControllers.count
case .all(_, let pagingControllers):
maxCount = pagingControllers.count
case .menuView(let menuOptions):
maxCount = menuOptions.itemsOptions.count
}
guard options.defaultPage >= maxCount || options.defaultPage < 0 else { return }
raise("default page is invalid")
}
fileprivate func validateInfiniteMenuItemNumbers(_ options: PagingMenuControllerCustomizable) {
guard case .all(let menuOptions, _) = options.componentType,
case .infinite = menuOptions.displayMode else { return }
guard menuOptions.itemsOptions.count < VisiblePagingViewNumber else { return }
raise("number of view controllers should be more than three with Infinite display mode")
}
fileprivate var exceptionName: String {
return "PMCException"
}
fileprivate func raise(_ reason: String) {
NSException(name: NSExceptionName(rawValue: exceptionName), reason: reason, userInfo: nil).raise()
}
}
| apache-2.0 | 7ba738d7e62efdc75be59954bb823d8a | 36.073826 | 209 | 0.629118 | 5.851695 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/Types.swift | 1 | 1157 | //
// Types.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 30.11.2016.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// A section is basically a collection of paragraphs
typealias Section = [Paragraph]
// A chapter is a collection of sections
typealias Chapter = [Section]
// These functions are used for finding existing book data for
// a project, a certain language, code and identifier
// Returns nil if no such book exists
typealias FindBook = (String, String, String, String) -> Book?
// This function / algorithm matches paragraphs with each other
// Multiple matches can be formed from / to a single paragraph
// Returns nil if the matching couldn't be done
// The left side is always an existing paragraph, while the right side is always a new paragraph
typealias MatchParagraphs = ([Paragraph], [Paragraph]) -> [(Paragraph, Paragraph)]?
// This function merges the properties of multiple conflicting revisions into a single revision
// Input: Document id string, Conflicting revision properties
// Output: Merged revision properties
// typealias Merge = (String, [PropertySet]) throws -> PropertySet
| mit | 284b30b217ec82b08735fb8a096f9783 | 36.290323 | 96 | 0.754325 | 4.498054 | false | false | false | false |
Alienson/Bc | source-code/Parketovanie/RotatePad.swift | 1 | 1181 | //
// RotatePad.swift
// Parketovanie
//
// Created by Adam Turna on 18.2.2016.
// Copyright © 2016 Adam Turna. All rights reserved.
//
import Foundation
import SpriteKit
class RotatePad: FrameController {
var catchedParquet = Parquet()
var isPadEmpty = true
var level = Level()
init(size: CGSize, level: Int, parent: SKSpriteNode) {
let color = self.level.value(level).color
let position = CGPoint(x: 40, y: 500)
super.init(size: size, name: "rotatePad", position: position, parent: parent, color: color)
//self.inputAccessoryViewController
self.isPadEmpty = true
super.position = CGPoint(x: 40, y: 500)
//super.alpha = CGFloat(0.5)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func pinParquetToPad(parquet: Parquet) {
self.catchedParquet = parquet
self.catchedParquet.rotatable = true
self.isPadEmpty = false
}
func unpinParquetFromPad() {
self.catchedParquet.rotatable = false
self.catchedParquet = Parquet()
self.isPadEmpty = true
}
}
| apache-2.0 | 81d9630004d145eb0e952655c4e17408 | 25.818182 | 99 | 0.631356 | 3.757962 | false | false | false | false |
kumabook/StickyNotesiOS | StickyNotes/Sticky.swift | 1 | 1529 | //
// Sticky.swift
// StickyNotes
//
// Created by Hiroki Kumamoto on 8/6/16.
// Copyright © 2016 kumabook. All rights reserved.
//
import Foundation
import Himotoki
import RealmSwift
struct Sticky: Decodable {
fileprivate static var onceToken : Int = 0
enum State: Int {
case normal = 0
case deleted = 1
case minimized = 2
static func fromRawValue(_ rawValue: Int) -> State {
if let s = State(rawValue: rawValue) {
return s
} else {
return .normal
}
}
}
var id: Int
var uuid: String
var left: Int
var top: Int
var width: Int
var height: Int
var content: String
var color: String
var state: State
var createdAt: Date
var updatedAt: Date
var userId: Int
var page: Page
var tags: [String]
static func decode(_ e: Extractor) throws -> Sticky {
return try Sticky(
id: e <| "id",
uuid: e <| "uuid",
left: e <| "left",
top: e <| "top",
width: e <| "width",
height: e <| "height",
content: e <| "content",
color: e <| "color",
state: State.fromRawValue(e <| "state"),
createdAt: DateFormatter.shared.date(from: e <| "created_at")!,
updatedAt: DateFormatter.shared.date(from: e <| "updated_at")!,
userId: e <| "user_id",
page: e <| "page",
tags: e <|| "tags")
}
}
| mit | 1e7371241bd1cc26dd521188de18b48f | 24.898305 | 75 | 0.513089 | 4.140921 | false | false | false | false |
NestedWorld/NestedWorld-iOS | nestedworld/nestedworld/APIUserRequestManager.swift | 1 | 3940 | //
// APIUserRequestManager.swift
// nestedworld
//
// Created by Jean-Antoine Dupont on 25/04/2016.
// Copyright © 2016 NestedWorld. All rights reserved.
//
import UIKit
class APIUserRequestManager
{
private var httpRequestManager: HttpRequestManagerProtocol
private var requestRoot: String = ""
private var authenticationManager: APIUserAuthenticationRequestManager
// MARK: ...
init(httpRequestManager: HttpRequestManagerProtocol, apiRootURL: String)
{
self.httpRequestManager = httpRequestManager
self.requestRoot = apiRootURL + "/users"
self.authenticationManager = APIUserAuthenticationRequestManager(httpRequestManager: self.httpRequestManager, apiRootURL: self.requestRoot)
}
// MARK: ...
func getAuthenticationManager() -> APIUserAuthenticationRequestManager
{
return self.authenticationManager
}
// MARK: ...
func profile(token: String, success: (response: AnyObject?) -> Void, failure: (error: NSError?, response: AnyObject?) -> Void)
{
let url: String = self.requestRoot + "/"
let headers: Dictionary<String, String> = [
"Authorization": token
]
self.httpRequestManager.get(url, headers: headers, success: { (response) -> Void in
success(response: response)
}) { (error, response) -> Void in
failure(error: error, response: response)
}
}
func updateProfile(token: String,
email: String, nickname: String,
city: String, gender: User.GENDER, birthDate: NSDate,
avatar: UIImage, background: UIImage,
isActive: Bool,
success: (response: AnyObject?) -> Void, failure: (error: NSError?, response: AnyObject?) -> Void)
{
let url: String = self.requestRoot + "/"
let params: Dictionary<String, AnyObject> = [
"email": email,
"pseudo": nickname,
"city": city,
"gender": gender.toString(),
"birth_date": birthDate.toString("yyyy-MM-dd'T'HH:mm:ss.SSSZ"),
"avatar": avatar,
"background": background,
"is_active": isActive
]
let headers: Dictionary<String, String> = [
"Authorization": token
]
self.httpRequestManager.put(url, params: params, headers: headers, success: { (response) -> Void in
success(response: response)
}) { (error, response) -> Void in
failure(error: error, response: response)
}
}
func addMonster()
{
}
func getFriends(token: String, success: (response: AnyObject?) -> Void, failure: (error: NSError?, response: AnyObject?) -> Void)
{
let url: String = self.requestRoot + "/friends/"
let headers: Dictionary<String, String> = [
"Authorization": token
]
self.httpRequestManager.get(url, headers: headers, success: { (response) -> Void in
success(response: response)
}) { (error, response) -> Void in
failure(error: error, response: response)
}
}
func addFriend(token: String, success: (response: AnyObject?) -> Void, failure: (error: NSError?, response: AnyObject?) -> Void)
{
let url: String = self.requestRoot + "/friends"
let params: Dictionary<String, AnyObject> = [
"": ""
]
let headers: Dictionary<String, String> = [
"Authorization": token
]
self.httpRequestManager.post(url, params: params, headers: headers, success: { (response) -> Void in
success(response: response)
}) { (error, response) -> Void in
failure(error: error, response: response)
}
}
} | mit | 8d39ad72d4b815a033d5574cecffafe7 | 31.561983 | 147 | 0.575781 | 4.694875 | false | false | false | false |
huangboju/Moots | Examples/undo-manager-practice-master/UndoAppExample/FigureSettingsViewController.swift | 1 | 5931 | //
// FigureSettingsViewController.swift
// UndoAppExample
//
// Created by Tomasz Szulc on 13/09/15.
// Copyright © 2015 Tomasz Szulc. All rights reserved.
//
import UIKit
extension FigureView {
func recordBeginChanges() {
self.changesRecorder.setValue(for: "backgroundColor", value: self.backgroundColor)
self.changesRecorder.setValue(for: "cornerRadius", value: self.cornerRadius)
}
func revertChanges() {
self.backgroundColor = self.changesRecorder.value(for: "backgroundColor") as? UIColor
self.cornerRadius = self.changesRecorder.value(for: "cornerRadius") as! CGFloat
}
@objc func registerUndoChange() {
let changes = changesRecorder.dictionary
let beginBackgroundColor = changes["backgroundColor"] as! UIColor
let beginCornerRadius = changes["cornerRadius"] as! CGFloat
let colorModified = self.backgroundColor! != beginBackgroundColor
let cornerRadiusModified = self.cornerRadius != beginCornerRadius
undoManager.beginUndoGrouping()
(undoManager.prepare(withInvocationTarget: self) as AnyObject).registerUndoChange()
undoManager.registerUndo(withTarget: self, selector: #selector(registerUndoChange), object: nil)
undoManager.registerUndo(withTarget: self, selector: #selector(setter: backgroundColor), object: beginBackgroundColor)
undoManager.registerUndo(withTarget: self, selector: #selector(setter: cornerRadius), object: beginCornerRadius)
if colorModified && cornerRadiusModified {
undoManager.setActionName("Change Color and Radius")
} else if colorModified {
undoManager.setActionName("Change Color")
} else if cornerRadiusModified {
undoManager.setActionName("Change Radius")
}
undoManager.endUndoGrouping()
}
}
class FigureSettingsViewController: UIViewController {
@IBOutlet var colorButtons: [UIButton]!
@IBOutlet var cornerRadiusSlider: UISlider!
@IBOutlet var undoButton: UIButton!
@IBOutlet var redoButton: UIButton!
@IBOutlet var saveButton: UIButton!
var figure: FigureView!
var lockUndo: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
observeUndoManager()
updateUndoAndRedoButtons()
setupUI()
updateBeginChanges()
figure.addObserver(self, forKeyPath: "cornerRadius", options: [.new, .initial], context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "cornerRadius" {
cornerRadiusSlider.value = (change![NSKeyValueChangeKey.newKey] as! NSNumber).floatValue
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
figure.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
revertChanges()
figure.removeObserver(self, forKeyPath: "cornerRadius")
figure.resignFirstResponder()
}
private func setupUI() {
colorButtons[0].backgroundColor = UIColor.red
colorButtons[1].backgroundColor = UIColor.blue
colorButtons[2].backgroundColor = UIColor.purple
colorButtons[3].backgroundColor = UIColor(white: 0.7, alpha: 1)
cornerRadiusSlider.value = Float(figure.layer.cornerRadius)
}
private func updateBeginChanges() {
figure.recordBeginChanges()
}
private func revertChanges() {
figure.revertChanges()
}
private func updateButtons() {
saveButton.isEnabled = true
if lockUndo {
self.undoButton.isEnabled = false
self.redoButton.isEnabled = false
}
}
@IBAction func savePressed(sender: AnyObject) {
figure.registerUndoChange()
updateBeginChanges()
self.dismiss(animated: true, completion: nil)
}
@IBAction func changeColor(sender: UIButton) {
lockUndo = true
figure.backgroundColor = sender.backgroundColor
updateButtons()
}
@IBAction func cornerRadiusValueChanged(sender: UISlider) {
lockUndo = true
figure.layer.cornerRadius = CGFloat(sender.value)
updateButtons()
}
/// MARK: Undo Manager
private func observeUndoManager() {
NotificationCenter.default.addObserver(self, selector: #selector(undoManagerDidUndoNotification), name: .NSUndoManagerDidUndoChange, object: figure.undoManager)
NotificationCenter.default.addObserver(self, selector: #selector(undoManagerDidRedoNotification), name: .NSUndoManagerDidRedoChange, object: figure.undoManager)
}
@objc func undoManagerDidUndoNotification() {
updateUndoAndRedoButtons()
figure.recordBeginChanges()
}
@objc func undoManagerDidRedoNotification() {
updateUndoAndRedoButtons()
figure.recordBeginChanges()
}
private func updateUndoAndRedoButtons() {
undoButton.isEnabled = figure.undoManager.canUndo == true
if figure.undoManager.canUndo {
undoButton.setTitle(figure.undoManager.undoMenuTitle(forUndoActionName: figure.undoManager.undoActionName), for: .normal)
} else {
undoButton.setTitle(figure.undoManager.undoMenuItemTitle, for: .normal)
}
redoButton.isEnabled = figure.undoManager.canRedo == true
if figure.undoManager.canRedo {
redoButton.setTitle(figure.undoManager.redoMenuTitle(forUndoActionName: figure.undoManager.redoActionName), for: .normal)
} else {
redoButton.setTitle(figure.undoManager.redoMenuItemTitle, for: .normal)
}
}
}
| mit | 70f24c39f969da5eda343219c7ac4b7a | 35.380368 | 168 | 0.673019 | 5.10327 | false | false | false | false |
Anvics/Amber | Amber/Classes/AmberStore.swift | 1 | 7320 | //
// AmberStore.swift
// TrainBrain
//
// Created by Nikita Arkhipov on 09.10.2017.
// Copyright © 2017 Nikita Arkhipov. All rights reserved.
//
import Foundation
import ReactiveKit
public final class AmberStore<Reducer: AmberReducer>{
var state: Signal<Reducer.State, NoError> { return _state.toSignal().ignoreNil() }
public let action = Subject<Reducer.Action, NoError>()
public let outputAction = Subject<Reducer.OutputAction, NoError>()
public let transition = Subject<Reducer.Transition, NoError>()
fileprivate var outputListener: ((Reducer.OutputAction) -> Void)?
fileprivate var routePerformer: AmberRoutePerformer!
fileprivate let _state = Property<Reducer.State?>(nil)
fileprivate let reducer: Reducer
private let router: AmberRouterBlock<Reducer>
private var isInitialized = false
typealias ActionBlock = (Reducer.Action) -> Void
typealias OutputActionBlock = (Reducer.OutputAction) -> Void
typealias TransitionBlock = (Reducer.Transition) -> Void
public init<R: AmberRouter>(reducer: Reducer, router: R) where R.Reducer == Reducer{
self.reducer = reducer
self.router = router.perform
subscribe()
}
///Use only for tests
// public init<R: AmberRouter>(reducer: Reducer, router: R, requiredData: Reducer.State.RequiredData) where R.Reducer == Reducer{
// self.reducer = reducer
// self.router = router.perform
// subscribe()
// routePerformer = FakeAmberRoutePerformer()
// sharedInitialize(data: requiredData)
// }
public func initialize(with data: Reducer.State.RequiredData, routePerformer: AmberRoutePerformer){
if isInitialized { return }
isInitialized = true
self.routePerformer = routePerformer
sharedInitialize(data: data)
}
public func currentState() -> Reducer.State{
guard let state = _state.value else {
fatalError("Не удалось получить текущее состояние. Если ошибка произошла при запуске приложения, убедитесь в том что в начальном контроллере в самом начале viewDidLoad есть строчка store.initialize(on: self)")
}
return state
}
public func perform(action: Reducer.Action){
initiateChangeState(action: action) { (state, router, actionPerf, outActionPerf, transitionPerf) in
self.reducer.reduce(action: action, state: state, performTransition: transitionPerf, performAction: actionPerf, performOutputAction: outActionPerf)
}
}
public func performInput(action: Reducer.InputAction){
initiateChangeState(action: action) { (state, router, actionPerf, outActionPerf, _) in
self.reducer.reduceInput(action: action, state: state, performAction: actionPerf, performOutputAction: outActionPerf)
}
}
public func performOutput(action: Reducer.OutputAction){
processAction(action) {
self.outputListener?(action)
}
}
public func perform(transition: Reducer.Transition){
processAction(transition) {
self.router(transition, self.routePerformer, self.reducer, self.perform)
}
}
}
extension AmberStore{
fileprivate func subscribe(){
let _ = action.observeNext { [weak self] in self?.perform(action: $0) }
let _ = outputAction.observeNext { [weak self] in self?.performOutput(action: $0) }
let _ = transition.observeNext { [weak self] in self?.perform(transition: $0) }
}
fileprivate func processAction(_ action: Any, actionBlock: @escaping () -> Void){
Amber.main.process(state: currentState(), beforeEvent: action)
Amber.main.perform(event: action, onState: currentState(), route: routePerformer) {
actionBlock()
Amber.main.process(state: self.currentState(), afterEvent: action, route: self.routePerformer)
}
}
fileprivate func initiateChangeState(action: AmberAction, newState: @escaping (Reducer.State, AmberRoutePerformer, @escaping ActionBlock, @escaping OutputActionBlock, @escaping TransitionBlock) -> Reducer.State){
processAction(action) { self.changeState(action: action, newState: newState) }
}
fileprivate func changeState(action: AmberAction, newState: (Reducer.State, AmberRoutePerformer, @escaping ActionBlock, @escaping OutputActionBlock, @escaping TransitionBlock) -> Reducer.State){
let stateToUse = currentState()
var isPerformed = false
var delayedActions: [Reducer.Action] = []
var delayedOutputActions: [Reducer.OutputAction] = []
var delayedTransitions: [Reducer.Transition] = []
let ns = newState(stateToUse, routePerformer, { a in
if isPerformed{ self.perform(action: a) }
else { delayedActions.append(a) }
}, { a in
if isPerformed{ self.performOutput(action: a) }
else { delayedOutputActions.append(a) }
}, { t in
if isPerformed { self.perform(transition: t) }
else{ delayedTransitions.append(t) }
})
_state.value = ns
isPerformed = true
delayedActions.forEach(perform)
delayedOutputActions.forEach(performOutput)
delayedTransitions.forEach(perform)
}
fileprivate func sharedInitialize(data: Reducer.State.RequiredData){
_state.value = Reducer.State(data: data)
reducer.initialize(state: currentState(), performAction: perform, performOutputAction: performOutput)
}
}
public class AmberControllerHelper{
public static func create<Module: AmberController>(module: Module.Type, data: Module.Reducer.State.RequiredData, outputListener: Module.OutputActionListener? = nil) -> (UIViewController, Module.InputActionListener){
return create(module: module, data: data, outputListener: outputListener, router: { $0 })
}
public static func create<Module: AmberController, Route: AmberController>(module: Module.Type, data: Module.Reducer.State.RequiredData, route: Route, outputListener: Module.OutputActionListener? = nil) -> (UIViewController, Module.InputActionListener){
return create(module: module, data: data, outputListener: outputListener, router: { _ in route })
}
private static func create<Module: AmberController, Route: AmberController>(module: Module.Type, data: Module.Reducer.State.RequiredData, outputListener: Module.OutputActionListener? = nil, router: (Module) -> Route) -> (UIViewController, Module.InputActionListener){
let vc = Module.instantiate()
vc.store.initialize(with: data, routePerformer: AmberRoutePerformerImplementation(controller: router(vc), embedder: vc))
vc.store.outputListener = outputListener
guard let uivc = vc as? UIViewController else {
fatalError("На текущий момент возможно произвести переход/встроить только UIViewController. Попытались создать \(type(of: vc))")
}
return (uivc, vc.store.performInput)
}
}
| mit | 2b0d3b0d9a3c9bc7f633f8c120616bb0 | 43.475 | 271 | 0.681984 | 4.3049 | false | false | false | false |
Adlai-Holler/RACReddit | RACReddit/RedditModel.swift | 1 | 597 |
import SwiftyJSON
struct RedditPost {
var id: String
var title: String
var url: NSURL
/** Attempt to parse the provided JSON into a RedditPost.
* NOTE: This is actually quite expensive due to Swift casts being slow
* so in production, cache these by ID.
*/
init?(json: JSON) {
let data = json["data"]
guard let title = data["title"].string,
url = data["url"].string.flatMap({ NSURL(string: $0) }),
id = data["id"].string else {
NSLog("Failed to parse JSON into Reddit post: \(json)")
return nil
}
self.title = title
self.url = url
self.id = id
}
}
| mit | 9b62752f623ad11c74d1b0fe804736d6 | 19.586207 | 71 | 0.644891 | 3.262295 | false | false | false | false |
jam891/Luna | Luna/LunarViewModel.swift | 1 | 1317 | //
// LunarViewModel.swift
// Luna
//
// Created by Andrew Shepard on 3/1/15.
// Copyright (c) 2015 Andrew Shepard. All rights reserved.
//
import Foundation
struct LunarViewModel {
private let moon: Moon
init(moon: Moon) {
self.moon = moon
}
var icon: String {
return moon.percent.symbolForMoon()
}
var phase: String {
return moon.phase.capitalizedString
}
var rise: String {
return self.formatter.stringFromDate(moon.rise)
}
var set: String {
return self.formatter.stringFromDate(moon.set)
}
var age: String {
let length = 27.3
let age = ((moon.percent * 0.01) * length) * 100.0
switch age {
case 1:
let day = String(format: "%.1f", age)
return "\(day) day old"
default:
let days = String(format: "%.1f", age)
return "\(days) days old"
}
}
var illumination: String {
return "\(moon.percent * 100)% complete"
}
private var formatter: NSDateFormatter {
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.timeStyle = NSDateFormatterStyle.LongStyle
return formatter
}
} | mit | d17c0d97c58e438075be568bd4788a76 | 21.338983 | 60 | 0.562642 | 4.375415 | false | false | false | false |
pselle/macvimspeak | MacVimSpeak/Utils.swift | 1 | 973 | //
// Utils.swift
// MacVimSpeak
//
// Created by Pam Selle on 3/16/15.
// Copyright (c) 2015 The Webivore. All rights reserved.
//
import Foundation
func mapDict<S, T, U>(myDict:[S:T], f: T -> U) -> [S:U] {
var newDict = [S: U]()
for (key, val) in myDict {
newDict[key] = f(val)
}
return newDict
}
// Takes 2 dictionaries and combines them with an optional separator for the keys
func combineDictionaries(dict1: [String:String], dict2: [String:String], separator: String?) -> [String:String] {
var combinedDictionary = [String:String]()
var combinedKey: String, combinedVal:String
for i in dict1 {
for j in dict2 {
if((separator) != nil) {
combinedKey = i.0 + separator! + j.0
} else {
combinedKey = i.0 + j.0
}
combinedVal = i.1 + j.1
combinedDictionary[combinedKey] = combinedVal
}
}
return combinedDictionary
} | mit | d2a13be98d6a8fcf6fdfad77cc8dd7d0 | 26.828571 | 113 | 0.579651 | 3.538182 | false | false | false | false |
brentdax/swift | test/expr/capture/dynamic_self.swift | 4 | 342 | // RUN: %target-swift-frontend -dump-ast %s 2>&1 | %FileCheck %s
// CHECK: func_decl{{.*}}"clone()" interface type='(Android) -> () -> Self'
class Android {
func clone() -> Self {
// CHECK: closure_expr type='() -> Self' {{.*}} discriminator=0 captures=(<dynamic_self> self<direct>)
let fn = { return self }
return fn()
}
}
| apache-2.0 | fac9d3a5542b60aea08a8bac96c4cb6b | 30.090909 | 106 | 0.581871 | 3.386139 | false | false | false | false |
tungvoduc/DTPagerController | Example/DTPagerController/PagerControllers/CustomPagerController.swift | 1 | 2887 | //
// CustomPagerController.swift
// DTPagerController_Example
//
// Created by tungvoduc on 25/02/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import DTPagerController
import HMSegmentedControl
import UIKit
class CustomPagerController: DTPagerController {
init() {
let viewController1 = CityListViewController(cellType: .light)
viewController1.title = "One"
let viewController2 = CityListViewController(cellType: .dark)
viewController2.title = "Two"
let viewController3 = CityListViewController(cellType: .light)
viewController3.title = "Three"
// swiftlint:disable line_length
guard let segmentedControl = HMSegmentedControl(sectionTitles: ["Cities", "So many cities", "Many many many .......... cities"]) else {
fatalError("HMSegmentedControl cannot be created")
}
super.init(viewControllers: [viewController1, viewController2, viewController3], pageSegmentedControl: segmentedControl)
// swiftlint:enable line_length
title = "CustomPagerController"
}
override func viewDidLoad() {
super.viewDidLoad()
if let segmentedControl = pageSegmentedControl as? HMSegmentedControl {
segmentedControl.segmentWidthStyle = .dynamic
segmentedControl.segmentEdgeInset = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 30)
segmentedControl.setTitleTextAttributes([.foregroundColor: UIColor.appDefault], for: .selected)
segmentedControl.selectionIndicatorColor = UIColor.appDefault
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setUpSegmentedControl(viewControllers: [UIViewController]) {
super.setUpSegmentedControl(viewControllers: viewControllers)
perferredScrollIndicatorHeight = 0
if let segmentedControl = pageSegmentedControl as? HMSegmentedControl {
segmentedControl.selectionIndicatorColor = UIColor.blue
}
}
override func updateAppearanceForSegmentedItem(at index: Int) {
// Does not do anything since custom page control does not support title/image update
}
}
extension HMSegmentedControl: DTSegmentedControlProtocol {
public func setImage(_ image: UIImage?, forSegmentAt segment: Int) {
// Custom page control does not support
}
public func setTitle(_ title: String?, forSegmentAt segment: Int) {
// Custom page control does not support
}
public func setTitleTextAttributes(_ attributes: [NSAttributedString.Key: Any]?, for state: UIControl.State) {
if state == UIControl.State.normal {
titleTextAttributes = attributes
} else if state == UIControl.State.selected {
selectedTitleTextAttributes = attributes
}
}
}
| mit | f8f4e8bd3a5704ac67f5b52e839d006f | 35.075 | 143 | 0.694733 | 5.394393 | false | false | false | false |
cuappdev/tcat-ios | TCAT/Controllers/RouteOptionsViewController+Extensions.swift | 1 | 16629 | //
// RouteOptionsViewController+Extensions.swift
// TCAT
//
// Created by Omar Rasheed on 5/25/19.
// Copyright © 2019 cuappdev. All rights reserved.
//
import UIKit
import CoreLocation
import DZNEmptyDataSet
// MARK: - Previewing Delegate
extension RouteOptionsViewController: UIViewControllerPreviewingDelegate {
@objc func handleLongPressGesture(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
let point = sender.location(in: routeResults)
if let indexPath = routeResults.indexPathForRow(at: point), let cell = routeResults.cellForRow(at: indexPath) {
let route = routes[indexPath.section][indexPath.row]
presentShareSheet(from: view, for: route, with: cell.getImage())
}
}
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
let point = view.convert(location, to: routeResults)
guard
let indexPath = routeResults.indexPathForRow(at: point),
let cell = routeResults.cellForRow(at: indexPath) as? RouteTableViewCell,
let routeDetailViewController = createRouteDetailViewController(from: indexPath)
else {
return nil
}
routeDetailViewController.preferredContentSize = .zero
cell.transform = .identity
previewingContext.sourceRect = routeResults.convert(cell.frame, to: view)
let payload = RouteResultsCellPeekedPayload()
Analytics.shared.log(payload)
return routeDetailViewController
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
navigationController?.pushViewController(viewControllerToCommit, animated: true)
}
}
// MARK: - SearchBarCancelDelegate
extension RouteOptionsViewController: SearchBarCancelDelegate {
func didCancel() {
hideSearchBar()
}
}
// MARK: - Destination Delegate
extension RouteOptionsViewController: DestinationDelegate {
func didSelectPlace(place: Place) {
switch searchType {
case .from:
searchFrom = place
case .to:
searchTo = place
}
if place.name != Constants.General.currentLocation && place.name != Constants.General.firstFavorite {
Global.shared.insertPlace(for: Constants.UserDefaults.recentSearch, place: place)
}
hideSearchBar()
dismissSearchBar()
searchForRoutes()
let payload: Payload = PlaceSelectedPayload(name: place.name, type: place.type)
Analytics.shared.log(payload)
}
}
// MARK: - DatePickerViewDelegate
extension RouteOptionsViewController: DatePickerViewDelegate {
@objc func dismissDatePicker() {
UIView.animate(withDuration: 0.5, animations: {
self.setupConstraintsForHiddenDatePickerView()
self.datePickerOverlay.alpha = 0.0
self.view.layoutIfNeeded()
}, completion: { (_) in
self.view.sendSubviewToBack(self.datePickerOverlay)
self.view.sendSubviewToBack(self.datePickerView)
})
}
func saveDatePickerDate(for date: Date, searchType: SearchType) {
searchTime = date
searchTimeType = searchType
routeSelection.setDatepickerTitle(withDate: date, withSearchTimeType: searchTimeType)
var buttonTapped = ""
switch searchType {
case .arriveBy: buttonTapped = "Arrive By Tapped"
case .leaveAt: buttonTapped = "Leave At Tapped"
case .leaveNow: buttonTapped = "Leave Now Tapped"
}
dismissDatePicker()
searchForRoutes()
let payload = RouteOptionsSettingsPayload(description: buttonTapped)
Analytics.shared.log(payload)
}
}
// MARK: - Location Manager Delegate
extension RouteOptionsViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didFailWithError error: Swift.Error) {
printClass(context: ("CLLocationManager didFailWithError"), message: error.localizedDescription)
if error._code == CLError.denied.rawValue {
locationManager.stopUpdatingLocation()
let alertController = UIAlertController(title: Constants.Alerts.LocationPermissions.title, message: Constants.Alerts.LocationPermissions.message, preferredStyle: .alert)
let settingsAction = UIAlertAction(title: Constants.Alerts.GeneralActions.settings, style: .default) { (_) in
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
}
guard let showReminder = userDefaults.value(forKey: Constants.UserDefaults.showLocationAuthReminder) as? Bool else {
userDefaults.set(true, forKey: Constants.UserDefaults.showLocationAuthReminder)
let cancelAction = UIAlertAction(title: Constants.Alerts.GeneralActions.cancel, style: .default, handler: nil)
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
alertController.preferredAction = settingsAction
present(alertController, animated: true)
return
}
if !showReminder {
return
}
let dontRemindAgainAction = UIAlertAction(title: Constants.Alerts.GeneralActions.dontRemind, style: .default) { (_) in
userDefaults.set(false, forKey: Constants.UserDefaults.showLocationAuthReminder)
}
alertController.addAction(dontRemindAgainAction)
alertController.addAction(settingsAction)
alertController.preferredAction = settingsAction
present(alertController, animated: true)
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
didReceiveCurrentLocation(manager.location)
}
func didReceiveCurrentLocation(_ location: CLLocation?) {
guard let currentLocation = location else { return }
let currentPlace = Place(
name: Constants.General.currentLocation,
type: .currentLocation,
latitude: currentLocation.coordinate.latitude,
longitude: currentLocation.coordinate.longitude
)
searchBarView.resultsViewController?.currentLocation = currentPlace
if searchFrom?.name == Constants.General.currentLocation {
searchFrom = currentPlace
}
if searchTo.name == Constants.General.currentLocation {
searchTo = currentPlace
}
// If haven't selected start location, set to current location
if searchFrom == nil {
let currentLocation = currentPlace
searchFrom = currentLocation
searchBarView.resultsViewController?.currentLocation = currentLocation
routeSelection.updateSearchBarTitles(from: currentLocation.name)
searchForRoutes()
}
}
}
// MARK: - TableView DataSource
extension RouteOptionsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return routes.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return routes[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Cells.routeOptionsCellIdentifier, for: indexPath) as? RouteTableViewCell
else { return UITableViewCell() }
let route = routes[indexPath.section][indexPath.row]
cell.configure(for: route, delayState: delayDictionary[route.routeId])
// Add share action for long press gestures on non 3D Touch devices
let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(_:)))
cell.addGestureRecognizer(longPressGestureRecognizer)
setCellUserInteraction(cell, to: cellUserInteraction)
return cell
}
}
// MARK: - TableView Delegate
extension RouteOptionsViewController: UITableViewDelegate {
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if refreshControl.isRefreshing {
// Update leave now time in pull to refresh
if searchTimeType == .leaveNow {
let now = Date()
searchTime = now
routeSelection.setDatepickerTitle(withDate: now, withSearchTimeType: searchTimeType)
}
searchForRoutes()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
locationManager.stopUpdatingLocation()
if let routeDetailViewController = createRouteDetailViewController(from: indexPath) {
let payload = RouteResultsCellTappedEventPayload()
Analytics.shared.log(payload)
let routeId = routes[indexPath.section][indexPath.row].routeId
routeSelected(routeId: routeId)
navigationController?.pushViewController(routeDetailViewController, animated: true)
}
}
/// Different header text based on variable data results (see designs)
func headerTitles(section: Int) -> String? {
if routes.count == 3 {
switch section {
case 1:
if routes.first?.isEmpty ?? false {
return Constants.TableHeaders.boardingSoon
} else {
return Constants.TableHeaders.boardingSoonFromNearby
}
case 2: return Constants.TableHeaders.walking
default: return nil
}
}
return section == 1 ? Constants.TableHeaders.walking : nil
}
func isEmptyHeaderView(section: Int) -> Bool {
return section == 0 && searchFrom?.type == .busStop && routes.first?.isEmpty ?? false
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let containerView = UIView()
let label = UILabel()
// Special centered message alerting no fromStop routes (first in 2D routes array)
if isEmptyHeaderView(section: section) {
label.text = Constants.TableHeaders.noAvailableRoutes + " from \(searchFrom?.name ?? "Starting Bus Stop")."
label.font = .getFont(.regular, size: 14)
label.textAlignment = .center
label.textColor = Colors.secondaryText
containerView.addSubview(label)
label.snp.makeConstraints { (make) in
make.centerX.centerY.equalToSuperview()
}
} else {
label.text = headerTitles(section: section)
label.font = .getFont(.regular, size: 12)
label.textColor = Colors.secondaryText
containerView.addSubview(label)
label.snp.makeConstraints { (make) in
make.leading.equalToSuperview().offset(12)
make.bottom.equalToSuperview().offset(-12)
}
}
return containerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if isEmptyHeaderView(section: section) {
return 60
} else {
return UIFont.getFont(.regular, size: 12).lineHeight
}
}
}
// MARK: - DZNEmptyDataSet
extension RouteOptionsViewController: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
func customView(forEmptyDataSet scrollView: UIScrollView) -> UIView? {
let customView = UIView()
var symbolView = UIView()
if showRouteSearchingLoader {
symbolView = LoadingIndicator()
} else {
let imageView = UIImageView(image: #imageLiteral(resourceName: "noRoutes"))
imageView.contentMode = .scaleAspectFit
symbolView = imageView
}
let retryButton = UIButton()
retryButton.setTitle(Constants.Buttons.retry, for: .normal)
retryButton.setTitleColor(Colors.tcatBlue, for: .normal)
retryButton.titleLabel?.font = .getFont(.regular, size: 16.0)
retryButton.addTarget(self, action: #selector(tappedRetryButton), for: .touchUpInside)
let titleLabel = UILabel()
titleLabel.font = .getFont(.regular, size: 18.0)
titleLabel.textColor = Colors.metadataIcon
titleLabel.text = showRouteSearchingLoader ? Constants.EmptyStateMessages.lookingForRoutes : Constants.EmptyStateMessages.noRoutesFound
customView.addSubview(symbolView)
customView.addSubview(titleLabel)
if !showRouteSearchingLoader {
customView.addSubview(retryButton)
}
symbolView.snp.makeConstraints { (make) in
make.centerX.equalToSuperview()
let offset = navigationController?.navigationBar.frame.height ?? 0 + routeSelection.frame.height
make.centerY.equalToSuperview().offset((showRouteSearchingLoader ? -20 : -60)+(-offset/2))
make.width.height.equalTo(showRouteSearchingLoader ? 40 : 180)
}
titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(symbolView.snp.bottom).offset(10)
make.centerX.equalTo(symbolView.snp.centerX)
}
if !showRouteSearchingLoader {
retryButton.snp.makeConstraints { (make) in
make.top.equalTo(titleLabel.snp.bottom).offset(10)
make.centerX.equalTo(titleLabel.snp.centerX)
make.height.equalTo(16)
}
}
return customView
}
@objc func tappedRetryButton(button: UIButton) {
showRouteSearchingLoader = true
routeResults.reloadData()
let delay = 1
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(delay)) {
self.searchForRoutes()
}
}
// Don't allow pull to refresh in empty state -- want users to use the retry button
func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView) -> Bool {
return false
}
// Allow for touch in empty state
func emptyDataSetShouldAllowTouch(_ scrollView: UIScrollView) -> Bool {
return true
}
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
extension RouteOptionsViewController: RouteSelectionViewDelegate {
func swapFromAndTo() {
//Swap data
let searchFromOld = searchFrom
searchFrom = searchTo
searchTo = searchFromOld
//Update UI
routeSelection.updateSearchBarTitles(from: searchFrom?.name ?? "",
to: searchTo.name)
searchForRoutes()
// Analytics
let payload = RouteOptionsSettingsPayload(description: "Swapped To and From")
Analytics.shared.log(payload)
}
func showDatePicker() {
view.bringSubviewToFront(datePickerOverlay)
view.bringSubviewToFront(datePickerView)
// set up date on datepicker view
if let time = searchTime {
datePickerView.setDatepickerDate(date: time)
}
datePickerView.setDatepickerTimeType(searchTimeType: searchTimeType)
UIView.animate(withDuration: 0.5) {
self.setupConstraintsForVisibleDatePickerView()
self.datePickerOverlay.alpha = 0.6 // darken screen when pull up datepicker
self.view.layoutIfNeeded()
}
let payload = RouteOptionsSettingsPayload(description: "Date Picker Accessed")
Analytics.shared.log(payload)
}
func searchingFrom() {
searchType = .from
presentSearchBar()
let payload = RouteOptionsSettingsPayload(description: "Searching From Tapped")
Analytics.shared.log(payload)
}
func searchingTo() {
searchType = .to
presentSearchBar()
let payload = RouteOptionsSettingsPayload(description: "Searching To Tapped")
Analytics.shared.log(payload)
}
}
| mit | 9aac7f25f0d847de2d28ce9c42fb22a6 | 35.464912 | 189 | 0.661956 | 5.363871 | false | false | false | false |
wess/reddift | reddiftSample/MessageViewController.swift | 1 | 2091 | //
// MessageViewController.swift
// reddift
//
// Created by sonson on 2015/04/21.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import reddift
class MessageViewController: UITableViewController {
var session:Session? = nil
var messageWhere = MessageWhere.Inbox
var messages:[Thing] = []
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.title = messageWhere.description
session?.getMessage(messageWhere, completion: { (result) -> Void in
switch result {
case let .Failure:
println(result.error)
case let .Success:
if let listing = result.value as? Listing {
for child in listing.children {
if let message = child as? Message {
self.messages.append(message)
}
if let link = child as? Link {
self.messages.append(link)
}
if let comment = child as? Comment {
self.messages.append(comment)
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}
}
})
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.messages.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
if indices(messages) ~= indexPath.row {
let child = messages[indexPath.row]
if let message = child as? Message {
cell.textLabel?.text = message.subject
}
else if let link = child as? Link {
cell.textLabel?.text = link.title
}
else if let comment = child as? Comment {
cell.textLabel?.text = comment.body
}
}
return cell
}
}
| mit | fc7f428ad9892bf4d5b8989590c45b2b | 28.013889 | 118 | 0.620393 | 4.41649 | false | false | false | false |
jovito-royeca/Cineko | Cineko/ThumbnailCollectionViewCell.swift | 1 | 2854 | //
// ThumbnailCollectionViewCell.swift
// Cineko
//
// Created by Jovit Royeca on 06/04/2016.
// Copyright © 2016 Jovito Royeca. All rights reserved.
//
import UIKit
public enum DisplayType : Int {
case Poster
case Backdrop
case Profile
}
public enum CaptionType : Int {
case Title
case Name
case Job
case Role
case NameAndJob
case NameAndRole
}
protocol ThumbnailDisplayable : NSObjectProtocol {
func imagePath(displayType: DisplayType) -> String?
func caption(captionType: CaptionType) -> String?
}
protocol ThumbnailDelegate : NSObjectProtocol {
func seeAllAction(tag: Int)
func didSelectItem(tag: Int, displayable: ThumbnailDisplayable, path: NSIndexPath)
}
class ThumbnailCollectionViewCell: UICollectionViewCell {
// MARK: Outlets
@IBOutlet weak var thumbnailImage: UIImageView!
// MARK: Variables
var HUDAdded = false
// MARK: Overrides
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func prepareForReuse() {
thumbnailImage.image = UIImage(named: "noImage")
}
// MARK: Custom methods
func addCaptionImage(text: String) {
if let image = thumbnailImage.image {
let textColor = UIColor.blackColor()
let font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2)
// Compute rect to draw the text inside
let imageSize = thumbnailImage.frame.size //image.size
let attr = [NSForegroundColorAttributeName: textColor, NSFontAttributeName: font]
let textSize = text.sizeWithAttributes(attr)
let width = imageSize.width
let widthNum = textSize.width > imageSize.width ? Int(textSize.width/imageSize.width) : 1
let widthExcess = textSize.width > imageSize.width ? Int(textSize.width%imageSize.width) : 0
let height = (textSize.height * CGFloat(widthNum)) + (widthExcess > 0 ? textSize.height : 0)
let textRect = CGRectMake(0, imageSize.height - height, width, height)
// Create the image
UIGraphicsBeginImageContextWithOptions(imageSize, true, 0.0)
image.drawInRect(CGRectMake(0, 0, imageSize.width, imageSize.height))
// Background
let context = UIGraphicsGetCurrentContext()
UIColor.whiteColor().colorWithAlphaComponent(0.60).set()
CGContextFillRect(context, textRect)
// Text
text.drawInRect(CGRectIntegral(textRect), withAttributes:attr)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
// done creating the image
UIGraphicsEndImageContext()
thumbnailImage.image = newImage
}
}
}
| apache-2.0 | d095b3e798bc020dca7a858a017949ff | 30.7 | 104 | 0.646688 | 5.168478 | false | false | false | false |
PomTTcat/SourceCodeGuideRead_JEFF | RxSwiftGuideRead/RxSwift-master/RxBlocking/BlockingObservable+Operators.swift | 4 | 5971 | //
// BlockingObservable+Operators.swift
// RxBlocking
//
// Created by Krunoslav Zaher on 10/19/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import RxSwift
/// The `MaterializedSequenceResult` enum represents the materialized
/// output of a BlockingObservable.
///
/// If the sequence terminates successfully, the result is represented
/// by `.completed` with the array of elements.
///
/// If the sequence terminates with error, the result is represented
/// by `.failed` with both the array of elements and the terminating error.
public enum MaterializedSequenceResult<T> {
case completed(elements: [T])
case failed(elements: [T], error: Error)
}
extension BlockingObservable {
/// Blocks current thread until sequence terminates.
///
/// If sequence terminates with error, terminating error will be thrown.
///
/// - returns: All elements of sequence.
public func toArray() throws -> [Element] {
let results = self.materializeResult()
return try self.elementsOrThrow(results)
}
}
extension BlockingObservable {
/// Blocks current thread until sequence produces first element.
///
/// If sequence terminates with error before producing first element, terminating error will be thrown.
///
/// - returns: First element of sequence. If sequence is empty `nil` is returned.
public func first() throws -> Element? {
let results = self.materializeResult(max: 1)
return try self.elementsOrThrow(results).first
}
}
extension BlockingObservable {
/// Blocks current thread until sequence terminates.
///
/// If sequence terminates with error, terminating error will be thrown.
///
/// - returns: Last element in the sequence. If sequence is empty `nil` is returned.
public func last() throws -> Element? {
let results = self.materializeResult()
return try self.elementsOrThrow(results).last
}
}
extension BlockingObservable {
/// Blocks current thread until sequence terminates.
///
/// If sequence terminates with error before producing first element, terminating error will be thrown.
///
/// - returns: Returns the only element of an sequence, and reports an error if there is not exactly one element in the observable sequence.
public func single() throws -> Element {
return try self.single { _ in true }
}
/// Blocks current thread until sequence terminates.
///
/// If sequence terminates with error before producing first element, terminating error will be thrown.
///
/// - parameter predicate: A function to test each source element for a condition.
/// - returns: Returns the only element of an sequence that satisfies the condition in the predicate, and reports an error if there is not exactly one element in the sequence.
public func single(_ predicate: @escaping (Element) throws -> Bool) throws -> Element {
let results = self.materializeResult(max: 2, predicate: predicate)
let elements = try self.elementsOrThrow(results)
if elements.count > 1 {
throw RxError.moreThanOneElement
}
guard let first = elements.first else {
throw RxError.noElements
}
return first
}
}
extension BlockingObservable {
/// Blocks current thread until sequence terminates.
///
/// The sequence is materialized as a result type capturing how the sequence terminated (completed or error), along with any elements up to that point.
///
/// - returns: On completion, returns the list of elements in the sequence. On error, returns the list of elements up to that point, along with the error itself.
public func materialize() -> MaterializedSequenceResult<Element> {
return self.materializeResult()
}
}
extension BlockingObservable {
fileprivate func materializeResult(max: Int? = nil, predicate: @escaping (Element) throws -> Bool = { _ in true }) -> MaterializedSequenceResult<Element> {
var elements = [Element]()
var error: Swift.Error?
let lock = RunLoopLock(timeout: self.timeout)
let d = SingleAssignmentDisposable()
defer {
d.dispose()
}
lock.dispatch {
let subscription = self.source.subscribe { event in
if d.isDisposed {
return
}
switch event {
case .next(let element):
do {
if try predicate(element) {
elements.append(element)
}
if let max = max, elements.count >= max {
d.dispose()
lock.stop()
}
} catch let err {
error = err
d.dispose()
lock.stop()
}
case .error(let err):
error = err
d.dispose()
lock.stop()
case .completed:
d.dispose()
lock.stop()
}
}
d.setDisposable(subscription)
}
do {
try lock.run()
} catch let err {
error = err
}
if let error = error {
return MaterializedSequenceResult.failed(elements: elements, error: error)
}
return MaterializedSequenceResult.completed(elements: elements)
}
fileprivate func elementsOrThrow(_ results: MaterializedSequenceResult<Element>) throws -> [Element] {
switch results {
case .failed(_, let error):
throw error
case .completed(let elements):
return elements
}
}
}
| mit | 2d96e96772ebef9c2e410e55fadbf6f1 | 34.117647 | 179 | 0.597152 | 5.16436 | false | false | false | false |
shaps80/Peek | Example/NotTwitter/Cell.swift | 1 | 1741 | //
// Cell.swift
// NotTwitter
//
// Created by Shaps Benkau on 10/03/2018.
// Copyright © 2018 Snippex. All rights reserved.
//
import UIKit
public final class Cell: UITableViewCell {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var messageLabel: TextView!
@IBOutlet weak var embedImageView: UIImageView!
@IBOutlet weak var replyButton: UIButton!
@IBOutlet weak var favouriteButton: UIButton!
@IBOutlet weak var shareButton: UIButton!
public override func awakeFromNib() {
super.awakeFromNib()
replyButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .footnote)
favouriteButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .footnote)
shareButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: .footnote)
if #available(iOS 10.0, *) {
usernameLabel.adjustsFontForContentSizeCategory = true
messageLabel.adjustsFontForContentSizeCategory = true
replyButton.titleLabel?.adjustsFontForContentSizeCategory = true
favouriteButton.titleLabel?.adjustsFontForContentSizeCategory = true
shareButton.titleLabel?.adjustsFontForContentSizeCategory = true
}
if #available(iOS 11.0, *) {
replyButton.adjustsImageSizeForAccessibilityContentSizeCategory = true
favouriteButton.adjustsImageSizeForAccessibilityContentSizeCategory = true
shareButton.adjustsImageSizeForAccessibilityContentSizeCategory = true
}
selectedBackgroundView = UIView()
selectedBackgroundView?.backgroundColor = .selection
}
}
| mit | 2e3acd65f57284b1c1deae7bb4c59421 | 36.826087 | 88 | 0.701149 | 5.742574 | false | false | false | false |
christopherstott/2048-ioscon | m2048UITests/m2048UITests.swift | 1 | 2397 | //
// m2048UITests.swift
// m2048UITests
//
// Created by Chris Stott on 2017-03-30.
// Copyright © 2017 Danqing. All rights reserved.
//
import XCTest
class m2048UITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
BuddyBuildSDK.startUITestsVideoRecording()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
BuddyBuildSDK.stopUITestsVideoRecording()
super.tearDown()
}
func testSwipe() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let app = XCUIApplication()
let element = app.otherElements.containing(.staticText, identifier:"2048").element
element.swipeUp()
element.swipeDown()
element.swipeLeft()
element.swipeRight()
element.swipeUp()
element.swipeDown()
element.swipeLeft()
element.swipeRight()
element.swipeUp()
element.swipeDown()
element.swipeLeft()
element.swipeRight()
}
func testSwipeThenCrash() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let app = XCUIApplication()
let element = app.otherElements.containing(.staticText, identifier:"2048").element
element.swipeUp()
element.swipeDown()
element.swipeLeft()
element.swipeRight()
XCUIApplication().buttons["Settings"].tap()
XCUIDevice.shared().orientation = .faceUp
}
}
| mit | 6c12d5e819692cce7d39d3ccd23b0289 | 32.25 | 182 | 0.63325 | 5.215686 | false | true | false | false |
pfvernon2/swiftlets | iOSX/swiftlets/swiftlets/AudioPlayerEngine.swift | 1 | 38794 | //
// AudioPlayerEngine.swift
// swiftlets
//
// Created by Frank Vernon on 7/18/15.
// Copyright © 2015 Frank Vernon. All rights reserved.
//
import AVFoundation
import MediaPlayer
//MARK: - AudioPlayerDelegate
///Watcher protocol for the AudioPlayerEngine class. All methods guaranteed to be called on main thread.
public protocol AudioPlayerDelegate: AnyObject {
func playbackStarted()
func playbackPaused()
func playbackStopped(trackCompleted: Bool)
func playbackLengthAdjusted()
}
//MARK: - Constants
//internal indication track should begin at head
fileprivate let kTrackHeadFramePosition: AVAudioFramePosition = .zero
//MARK: - AudioPlayerEngine
///Simple class to playback audio files.
///
/// Supports seeking within track, output channel mapping, and trimming of playback. Includes delegate for play/pause/stop state changes.
/// It's primary intent is for music track playback rather than background sounds or effects.
public class AudioPlayerEngine {
///Enum for indicating at which end(s) of the audio file
/// to detect and trim silence at playback.
public enum trimPositions {
case leading
case trailing
case both
}
//MARK: - Member variables - private
//AVAudioEngine and nodes
internal var engine: AVAudioEngine = AVAudioEngine()
internal var player: AVAudioPlayerNode = AVAudioPlayerNode()
internal let mixer: AVAudioMixerNode = AVAudioMixerNode()
//Trim positions
private var headPosition: AVAudioFramePosition = kTrackHeadFramePosition
private var tailPosition: AVAudioFramePosition = kTrackHeadFramePosition
//seek position
private var seekPosition: AVAudioFramePosition = kTrackHeadFramePosition
//indication of external interruption of playback
private var interrupted: Bool = false
//Queue for local state tracking of AVAudioPlayerNode
private let stateQueue: DispatchQueue = DispatchQueue(label: "com.cyberdev.AudioPlayerEngine.state")
//Tracks whether there is a segment scheduled on player… There can be only one.
@AtomicAccessor private var playerScheduled: Bool
//Frame position of pause, necessary as player does not return
// position while paused.
//
// This is used also to indicated whether we are
// paused as player has no explicit way to indicate said state.
@AtomicAccessor private var pausePosition: AVAudioFramePosition
//Tracks whether scheduled segment played up/through its expected ending frame
@AtomicAccessor private var segmentCompleted: Bool
//Tracks if we are in a seek operation, allows us to ignore early
// completion callback of previously scheduled segment
@AtomicAccessor private var inSeek: Bool
//Meter queue management
private let meterQueue: DispatchQueue = DispatchQueue(label: "com.cyberdev.AudioPlayerEngine.meters")
private var _meterValues: [Float] = []
public private(set) var meters: [Float] {
get {
meterQueue.sync {
_meterValues
}
}
set(value) {
meterQueue.async() {
self._meterValues = value
}
}
}
///AVAudioTime representing number of frames played since last start()
///
/// - note: This is not adjusted for start position in file. This is the underlying player time.
private var currentPlayerTime: AVAudioTime? {
guard let nodeTime: AVAudioTime = player.lastRenderTime else {
return nil
}
return player.playerTime(forNodeTime: nodeTime)
}
//MARK: - Member variables - public
///Delegate for notification of state changes on the player
public weak var delegate: AudioPlayerDelegate?
///Set to true to have tap installed on output for monitoring meter levels
public var meteringEnabled: Bool = false
//MARK: File Info
///Backing audio file
public private(set) var audioFile: AVAudioFile?
///File duration in seconds
public var fileDuration: TimeInterval {
audioFile?.duration ?? .zero
}
///File length of file in frames
public var fileLength: AVAudioFramePosition {
audioFile?.length ?? .zero
}
///Count of channels in file
public var fileChannelCount: UInt32 {
audioFile?.channelCount ?? .zero
}
///Processing sampleRate of file
public var fileSampleRate: Double {
audioFile?.sampleRate ?? .zero
}
//MARK: Track Timing and Positioning
///Frame position of begining of segment to be played.
///
///This either the begining of the file, a user defined head position, or user defined seek position.
private var startPosition: AVAudioFramePosition {
max(min(endPosition, seekPosition), headPosition)
}
///Frame position of end of segment to be played
///
///This either the end of the file or a user defined tail position.
private var endPosition: AVAudioFramePosition {
min(fileLength, tailPosition)
}
///Length of segment to be played in frames
private var segmentLength: AVAudioFrameCount {
AVAudioFrameCount(endPosition - startPosition)
}
///Time for head position relative to absolute length of file in seconds
public var headTime: TimeInterval {
time(forFrame: headPosition)
}
///Head position as percentage relative to absolute length of file
public var headProgress: Float {
progress(forFrame: headPosition)
}
///Time for tail position relative to absolute length of file in seconds
public var tailTime: TimeInterval {
time(forFrame: tailPosition)
}
///Tail position as percentage relative to absolute length of file
public var tailProgress: Float {
progress(forFrame: tailPosition)
}
///Length of trimmed section to be played in frames
public var trimmedLength: AVAudioFrameCount {
let tail = tailPosition > .zero ? tailPosition : fileLength
let head = headPosition
return AVAudioFrameCount(tail - head)
}
///Playback length in seconds adjusted for trim at head/tail
public var trimmedPlaybackDuration: TimeInterval {
time(forFrame: AVAudioFramePosition(trimmedLength))
}
///Playback postion as percentage 0.0->1.0 relative to trim at head/tail
public var trimmedPlaybackProgress: Float {
let current = playbackPosition - headPosition
return current.percentage(of: trimmedLength)
}
///TimeInterval of current position relative to trim at head/tail
public var trimmedPlaybackTime: TimeInterval {
let current = playbackPosition - headPosition
return time(forFrame: current)
}
///Last rendered frame including offset from startPosition
public var currentPlayerPosition: AVAudioFramePosition? {
guard let current = currentPlayerTime?.sampleTime else {
return nil
}
return current + startPosition
}
///Current frame position of playback relative to absolute length of file
///
///Setting this value will reposition the playback position to the
/// specified frame.
public var playbackPosition: AVAudioFramePosition {
get {
//playing
if isPlaying() {
return currentPlayerPosition ?? .zero
}
//paused
else if isPaused() {
return pausePosition
}
//stopped
else {
return startPosition
}
}
set(frame) {
guard audioFile != nil else {
return
}
let wasPlaying: Bool = self.isPlaying()
if wasPlaying || isPaused() {
inSeek = true
if isPaused() {
//update pausePosition so that progress updates while paused
pausePosition = frame
}
player.stop()
}
seekPosition = frame
if wasPlaying {
_play()
}
}
}
///TimeInterval of current position relative to absolute length of file
public var playbackTime: TimeInterval {
get {
time(forFrame: playbackPosition)
}
set(seconds) {
playbackPosition = frame(forTime: seconds)
}
}
///Playback postion as percentage 0.0->1.0 relative to absolute length of file
public var playbackProgress: Float {
get {
progress(forFrame: playbackPosition)
}
set (position) {
let clamped = position.clamped(to: 0.0...1.0)
let framePosition = floor(Double(fileLength) * Double(clamped))
playbackPosition = AVAudioFramePosition(framePosition)
}
}
///Indicates playback will begin at head
public var playbackAtHead: Bool {
playbackPosition == headPosition
}
//MARK: Initialization
#if os(iOS) || os(watchOS)
///Call this is to setup playback options for your app to allow simulataneous playback with other apps.
/// The default mode allows playback of audio when the ringer (mute) switch is enabled.
/// Be sure to enable audio in the BackgroundModes settings of your apps Capabilities if necessary.
public class func initAudioSessionCooperativePlayback(category: AVAudioSession.Category = .playback,
policy: AVAudioSession.RouteSharingPolicy = .longFormAudio) {
do {
try AVAudioSession.sharedInstance().setActive(false)
try AVAudioSession.sharedInstance().setCategory(category,
mode: .default,
policy: policy,
options: [])
try AVAudioSession.sharedInstance().setActive(true)
//Prevent interruptions from incoming calls - unless user has configured device
// for fullscreen call notifications
if #available(iOS 14.5, *) {
try AVAudioSession.sharedInstance().setPrefersNoInterruptionsFromSystemAlerts(true)
}
} catch {
debugPrint("failed to initialize audio session: \(error)")
}
}
#endif
public init() {
//shared queue not available until init time
_playerScheduled = AtomicAccessor(wrappedValue: false, queue: stateQueue)
_pausePosition = AtomicAccessor(wrappedValue: kTrackHeadFramePosition, queue: stateQueue)
_segmentCompleted = AtomicAccessor(wrappedValue: false, queue: stateQueue)
_inSeek = AtomicAccessor(wrappedValue: false, queue: stateQueue)
}
deinit {
NotificationCenter.default.removeObserver(self)
meteringEnabled = false
engine.stop()
}
//MARK: Public Methods
@discardableResult public func setTrack(url: URL) -> Bool {
guard let file = try? AVAudioFile.init(forReading: url) else {
return false
}
setAudioFile(file)
return true
}
public func setAudioFile(_ file: AVAudioFile) {
//managing playback state
let wasPlaying: Bool = isPlaying()
if wasPlaying {
_stop()
} else {
_reset()
}
audioFile = file
headPosition = kTrackHeadFramePosition
tailPosition = file.length
initAudioEngine()
if wasPlaying {
_play()
}
}
///This is a temporary? hack to release the avaudioengine which appears
///to have a retain cycle issue. This must be called after play has been called on the object or
///avaudioengine will retain this object indefinitetly.
public func shutdown() {
DispatchQueue.main.async {
self.stop()
self.deinitAudioEngine()
}
}
///Set outputs for the engine
public func mapOutputs(to channels: [AVAudioOutputNode.OutputChannelMapping]) {
engine.outputNode.mapRouteOutputs(to: channels)
}
public func time(forFrame frame: AVAudioFramePosition) -> TimeInterval {
audioFile?.time(forFrame: frame) ?? .zero
}
public func frame(forTime time: TimeInterval) -> AVAudioFramePosition {
audioFile?.frame(forTime: time) ?? .zero
}
public func progress(forFrame frame: AVAudioFramePosition) -> Float {
audioFile?.progress(forFrame: frame) ?? .zero
}
public func isPlaying() -> Bool {
player.isPlaying
}
public func isPaused() -> Bool {
pausePosition != kTrackHeadFramePosition
}
public func play() {
_play()
DispatchQueue.main.async {
self.delegate?.playbackStarted()
}
}
public func pause() {
guard isPlaying() else {
return
}
_pause()
DispatchQueue.main.async {
self.delegate?.playbackPaused()
}
}
public func resume() {
guard isPaused(), playerScheduled else {
return
}
//edge case where OS interruption may disable
// the engine on us.
guard engine.isRunning else {
stop()
return
}
pausePosition = kTrackHeadFramePosition
player.play()
}
///Toggle play/pause as appropriate
public func plause() {
if isPlaying() {
pause()
} else {
play()
}
}
public func stop() {
assert(Thread.isMainThread)
let wasPlaying = isPlaying()
let atEnd = segmentCompleted
//player.stop() is particular about being called from main
player.stop()
_stop()
if wasPlaying {
delegate?.playbackStopped(trackCompleted: atEnd)
}
}
///Set headPosition and/or tailPosition by scanning audio file for silence (zero value samples)
///from specified position(s) in the file.
///
/// - note: This is slightly expensive as it has to open the audio file and read
/// from the specified ends of the file for zero value samples.
public func trimSilence(_ trim: trimPositions = .both) {
guard let (head, tail) = audioFile?.silenceTrimPositions() else {
return
}
switch trim {
case .leading:
setTrimPositions(head: head)
case .trailing:
setTrimPositions(tail: tail)
case .both:
setTrimPositions(head: head, tail: tail)
}
}
///Trim start/end times.
public func setTrimPositions(head: AVAudioFramePosition? = nil,
tail: AVAudioFramePosition? = nil) {
if let head = head {
headPosition = head
}
if let tail = tail {
tailPosition = tail
}
DispatchQueue.main.async {
self.delegate?.playbackLengthAdjusted()
}
}
//MARK: Private Methods
internal func initAudioEngine() {
deinitAudioEngine()
engine.connect(engine.mainMixerNode,
to: engine.outputNode,
format: engine.outputNode.outputFormat(forBus: 0))
//attach nodes
engine.attach(player)
engine.attach(mixer)
let format = audioFile?.processingFormat
//connect nodes
// IMPORTANT: The mixer is used to abstract away
// file format (channel count, sample rate) config from
// other processing nodes which may want to connect to this stream.
// Subclasses can connect to the mixer which is configured for file format.
engine.connect(player, to: mixer, format: format)
engine.connect(mixer, to: engine.mainMixerNode, format: format)
engine.prepare()
}
internal func deinitAudioEngine() {
engine.stop()
engine = AVAudioEngine()
}
@discardableResult private func _play() -> Bool {
//check not currently playing
guard !isPlaying() else {
return true
}
//check paused but player running
guard !(isPaused() && playerScheduled) else {
resume()
return isPlaying()
}
//check we are configured to play something
guard let audioFile = audioFile, startEngine() else {
return false
}
let endFrame = startPosition + AVAudioFramePosition(segmentLength)
player.scheduleSegment(audioFile,
startingFrame: startPosition,
frameCount: segmentLength,
at: nil,
completionCallbackType: .dataPlayedBack) { state in
self.playerScheduled = false
guard !self.inSeek else {
self.inSeek = false
return
}
DispatchQueue.main.async {
self.segmentCompleted = self.currentPlayerPosition ?? .zero >= endFrame
self.stop()
}
}
playerScheduled = true
player.play()
_meter()
return isPlaying()
}
private func _pause() {
pausePosition = playbackPosition
player.pause()
}
private func _stop() {
stopEngine()
_reset()
}
private func _reset() {
seekPosition = kTrackHeadFramePosition
pausePosition = kTrackHeadFramePosition
interrupted = false
segmentCompleted = false
}
private func _meter() {
//for some reason this seems necessary to avoid random crashes
// when installing tap for the first time
engine.mainMixerNode.removeTap(onBus: 0)
meters = []
if meteringEnabled {
let format = engine.mainMixerNode.outputFormat(forBus: 0)
engine.mainMixerNode.installTap(
onBus: 0,
bufferSize: 1024,
format: format
) { buffer, _ in
if let meters = buffer.rmsPowerValues() {
self.meters = meters
}
}
}
}
//MARK: Utility
@discardableResult private func startEngine() -> Bool {
guard !engine.isRunning else {
return true
}
do {
try engine.start()
registerForMediaServerNotifications()
} catch let error as NSError {
print("Exception in audio engine start: \(error.localizedDescription)")
}
return engine.isRunning
}
@discardableResult private func stopEngine() -> Bool {
guard engine.isRunning else {
return false
}
deregisterForMediaServerNotifications()
engine.stop()
return !engine.isRunning
}
//MARK: Session notificaiton handling
#if os(iOS) || os(watchOS)
private func registerForMediaServerNotifications() {
deregisterForMediaServerNotifications()
NotificationCenter.default.addObserver(forName: AVAudioSession.interruptionNotification,
object: AVAudioSession.sharedInstance(),
queue: nil) { [weak self] (notification: Notification) in
guard let userInfo = notification.userInfo,
let interruption = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSession.InterruptionType(rawValue: interruption) else {
return
}
switch type {
case .began:
self?.interruptSessionBegin()
case .ended:
guard let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt else {
return
}
let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
self?.interruptSessionEnd(resume: options.contains(.shouldResume))
@unknown default:
break;
}
}
NotificationCenter.default.addObserver(forName: AVAudioSession.mediaServicesWereResetNotification,
object: AVAudioSession.sharedInstance(),
queue: nil) { [weak self] (notification: Notification) in
self?.stop()
}
NotificationCenter.default.addObserver(forName: AVAudioSession.routeChangeNotification,
object: AVAudioSession.sharedInstance(),
queue: nil) { /*[weak self]*/ (notification: Notification) in
guard let userInfo = notification.userInfo,
let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
let reason = AVAudioSession.RouteChangeReason(rawValue: reasonValue) else {
return
}
switch reason {
case .newDeviceAvailable:
if AVAudioSession.sharedInstance().currentRoute.hasHeadphonens {
}
case .oldDeviceUnavailable:
if let previousRoute = userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription,
!previousRoute.hasHeadphonens {
}
default:
break
}
}
}
func deregisterForMediaServerNotifications() {
NotificationCenter.default.removeObserver(self,
name: AVAudioSession.interruptionNotification,
object: AVAudioSession.sharedInstance())
NotificationCenter.default.removeObserver(self,
name: AVAudioSession.mediaServicesWereResetNotification,
object: AVAudioSession.sharedInstance())
NotificationCenter.default.removeObserver(self,
name: AVAudioSession.routeChangeNotification,
object: AVAudioSession.sharedInstance())
}
#else
private func registerForMediaServerNotifications() {
//TODO: Support media state notifications for non-iOS platforms
}
#endif
private func interruptSessionBegin() {
guard player.isPlaying else {
return
}
interrupted = true
pause()
}
private func interruptSessionEnd(resume: Bool) {
guard interrupted && resume else {
return
}
if !engine.isRunning {
startEngine()
}
self.resume()
}
public var debugDescription: String {
var outputDescriptions: [String] = []
for bus in 0..<engine.outputNode.numberOfOutputs {
let name = engine.outputNode.name(forOutputBus: bus)
let format = engine.outputNode.outputFormat(forBus: bus)
let desc = format.settings.map { "\($0) = \($1)" }.sorted()
let channelMap = engine.outputNode.auAudioUnit.channelMap?.debugDescription
outputDescriptions.append("Output \(bus):\nname = \(String(describing: name))\nChannelMap = \(String(describing: channelMap))\n\(desc.joined(separator: "\n"))")
}
return outputDescriptions.joined(separator: "\n")
}
}
//MARK: - FXAudioPlayerEngine
//Track output level constants
fileprivate let kOutputLevelDefault: Float = .zero
//Equalizer constants
fileprivate let kEQNumberOfBands: Int = 4
fileprivate let kEQLowShelfInitialFrequency: Float = 20.0
fileprivate let kEQParametricLowInitialFrequency: Float = 200.0
fileprivate let kEQParametricHighInitialFrequency: Float = 2000.0
fileprivate let kEQHighShelfInitialFrequency: Float = 20000.0
fileprivate let kEQGainDetentRange: Float = 0.5
///AudioPlayerEngine subclass that adds time rate control, four band parametric EQ, and simple output routing
public class FXAudioPlayerEngine: AudioPlayerEngine {
//Associate with mediaItem, assumes mediaItem has assetURL
public var mediaItem: MPMediaItem? = nil {
didSet {
guard let url = mediaItem?.assetURL else {
return
}
asset = nil
setTrack(url: url)
}
}
public var asset: AVURLAsset? = nil {
didSet {
guard let asset = asset else {
return
}
mediaItem = nil
setTrack(url: asset.url)
}
}
//Audio Units
private let timePitch: AVAudioUnitTimePitch = AVAudioUnitTimePitch()
private let equalizer: AVAudioUnitEQ = AVAudioUnitEQ(numberOfBands: kEQNumberOfBands)
private let routingMixer: AVAudioMixerNode = AVAudioMixerNode()
//MARK: Member variables - public
public var outputSampleRate: Double? {
get {
self.engine.mainMixerNode.outputFormat(forBus: 0).sampleRate
}
}
public var hasOutputRouting: Bool {
true
}
public var outputRouting: AudioPlayerOutputRouting? = .stereo {
didSet {
guard outputRouting != oldValue, let newRouting = outputRouting else {
return
}
guard let monoLayout = AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_Mono) else {
return
}
engine.disconnectNodeOutput(routingMixer)
let outputFormat = engine.mainMixerNode.outputFormat(forBus: 0)
let monoFormat = AVAudioFormat(commonFormat: outputFormat.commonFormat,
sampleRate: outputFormat.sampleRate,
interleaved: outputFormat.isInterleaved,
channelLayout: monoLayout)
switch newRouting {
case .stereo:
engine.connect(routingMixer, to: engine.mainMixerNode, format: outputFormat)
routingMixer.pan = .zero
case .mono:
engine.connect(routingMixer, to: engine.mainMixerNode, format: monoFormat)
routingMixer.pan = .zero
case .monoLeft:
engine.connect(routingMixer, to: engine.mainMixerNode, format: monoFormat)
routingMixer.pan = -1.0
case .monoRight:
engine.connect(routingMixer, to: engine.mainMixerNode, format: monoFormat)
routingMixer.pan = 1.0
}
}
}
///Adjust track playback level in range: -1.0 to 1.0
public var trackOutputLevelAdjust: Float? {
get {
(engine.mainMixerNode.outputVolume.doubled) - 1.0
}
set (level) {
let newLevel = level ?? kOutputLevelDefault
engine.mainMixerNode.outputVolume = (newLevel + 1.0).halved
}
}
public var timePitchQuality: AVAudioUnitTimePitch.QualityRange? = .high {
didSet {
timePitch.overlap = timePitchQuality?.rawValue ?? AVAudioUnitTimePitch.QualityRange.high.rawValue
}
}
///Adjust the time pitch rate in the range: 0.03125 to 32.0, default is 1.0
public var playbackRate: Float {
get {
timePitch.rate
}
set(rate) {
guard rate != timePitch.rate else {
return
}
timePitch.rate = rate.clamped(to: AVAudioUnitTimePitch.RateRange.range)
//Enabling bypass when at center position saves us significant CPU cycles, battery, etc.
// I presume Apple doesn't do this by default in order better predict/reserve CPU cycles
// necessary for audio processing. This optimization may need to be made conditional if
// we hit similar issues.
timePitch.bypass = (rate == AVAudioUnitTimePitch.RateRange.center.rawValue)
DispatchQueue.main.async {
self.delegate?.playbackLengthAdjusted()
}
}
}
///Playback duration of playable segment adjusted for playbackRate
public var adjustedPlaybackDuration: TimeInterval {
trimmedPlaybackDuration / TimeInterval(playbackRate)
}
///Playback time adjusted for playbackRate and head position
public var adjustedPlaybackTime: TimeInterval {
((playbackTime - headTime) / TimeInterval(playbackRate))
}
///Array of EQ filter parameters
public var equalizerBands: [AudioPlayerEQFilterParameters] {
get {
equalizer.bands.map { AudioPlayerEQFilterParameters(filter: $0) }
}
set(bands) {
for (index, band) in bands.enumerated() {
setFilter(atIndex: index, filter: band)
}
}
}
//MARK: Init
public init(mediaItem: MPMediaItem? = nil) {
super.init()
self.mediaItem = mediaItem
if let url = self.mediaItem?.assetURL {
setTrack(url: url)
}
}
public init(asset: AVURLAsset? = nil) {
super.init()
self.asset = asset
if let url = self.asset?.url {
setTrack(url: url)
}
}
override internal func initAudioEngine() {
//super first so it will setup player, etc.
super.initAudioEngine()
let format = audioFile?.processingFormat
//configure time pitch
timePitch.bypass = false
timePitch.overlap = timePitchQuality?.rawValue ?? AVAudioUnitTimePitch.QualityRange.high.rawValue
engine.attach(timePitch)
//configure eq
equalizer.bypass = false
equalizer.globalGain = .zero
engine.attach(equalizer)
resetEQ()
//configure mixer
engine.attach(routingMixer)
//construct fx node graph... connect to output of the playback mixer
engine.connect(mixer, to: timePitch, format: format)
engine.connect(timePitch, to: equalizer, format: format)
engine.connect(equalizer, to: routingMixer, format: format)
engine.connect(routingMixer, to: engine.mainMixerNode, format: format)
//configure gain structure
self.trackOutputLevelAdjust = kOutputLevelDefault
//prepare the engine
engine.prepare()
}
//MARK: Public Methods
///Reset EQ, track output level, and time pitch effect to nominal values.
public func reset() {
resetEQ()
trackOutputLevelAdjust = kOutputLevelDefault
playbackRate = AVAudioUnitTimePitch.RateRange.center.rawValue
}
///Reset EQ to nominal (flat) values
public func resetEQ() {
equalizer.bands[0].filterType = .lowShelf
equalizer.bands[0].frequency = kEQLowShelfInitialFrequency
equalizer.bands[0].gain = .zero
equalizer.bands[0].bypass = false
equalizer.bands[1].filterType = .parametric
equalizer.bands[1].bandwidth = 1.0
equalizer.bands[1].frequency = kEQParametricLowInitialFrequency
equalizer.bands[1].gain = .zero
equalizer.bands[1].bypass = false
equalizer.bands[2].filterType = .parametric
equalizer.bands[2].bandwidth = 1.0
equalizer.bands[2].frequency = kEQParametricHighInitialFrequency
equalizer.bands[2].gain = .zero
equalizer.bands[2].bypass = false
equalizer.bands[3].filterType = .highShelf
equalizer.bands[3].frequency = kEQHighShelfInitialFrequency
equalizer.bands[3].gain = .zero
equalizer.bands[3].bypass = false
}
///Adjust EQ filter at given index to given set of filter parameters
public func setFilter(atIndex filterIndex: Int,
filter: AudioPlayerEQFilterParameters) {
equalizer.bands[filterIndex].filterType = filter.filterType
setFilter(atIndex: filterIndex,
frequency: filter.frequency,
gain: filter.gain,
bandwidth: filter.bandwidth)
}
///Adjust EQ filter at given index to given set of filter parameters
public func setFilter(atIndex filterIndex: Int,
frequency: Float,
gain: Float,
bandwidth: Float = .zero) {
equalizer.bands[filterIndex].frequency = frequency
if abs(gain) <= kEQGainDetentRange {
equalizer.bands[filterIndex].gain = .zero
} else {
equalizer.bands[filterIndex].gain = gain
}
if bandwidth > 0.0 {
equalizer.bands[filterIndex].bandwidth = bandwidth
}
}
}
//Required to make AVAudioUnitEQFilterType automagically codable
extension AVAudioUnitEQFilterType: Codable {
}
///Wrapup struct for persisting EQ settings... these map directly to AVAudioUnitEQFilterParameters which is not copyable/fungable
public struct AudioPlayerEQFilterParameters: Codable, Equatable {
//Properties from AVAudioUnitEQFilterParameters
public var filterType: AVAudioUnitEQFilterType
public var frequency: Float
public var bandwidth: Float
public var gain: Float
public var bypass: Bool
public init(filter: AVAudioUnitEQFilterParameters) {
self.filterType = filter.filterType
self.frequency = filter.frequency
self.bandwidth = filter.bandwidth
self.gain = filter.gain
self.bypass = filter.bypass
}
}
///Defines simplified audio routing options
public enum AudioPlayerOutputRouting {
case stereo //stereo or mono source output to stereo device
case mono //mono output (all channels combined) to both channels of stereo device
case monoLeft //mono output (all channels combined) to left channel of stereo device
case monoRight //mono output (all channels combined) to right channel of stereo device
}
// MARK: - SystemVolumeMonitor
public extension NSNotification.Name {
static let SystemVolumeMonitor: NSNotification.Name = NSNotification.Name("com.cyberdev.SystemVolumeMonitor")
}
//KVO appears to be only way to do this, so here we are.
public class SystemVolumeMonitor: NSObject {
public class func sharedInstance() -> SystemVolumeMonitor {
return _sharedInstance
}
private static let _sharedInstance = {
SystemVolumeMonitor()
}()
private struct Observation {
static let VolumeKey = "outputVolume"
static var Context = 0
}
public override init() {
super.init()
}
deinit {
stop()
}
public func start() {
AVAudioSession.sharedInstance().addObserver(self,
forKeyPath: Observation.VolumeKey,
options: [.initial, .new],
context: &Observation.Context)
}
public func stop() {
AVAudioSession.sharedInstance().removeObserver(self,
forKeyPath: Observation.VolumeKey,
context: &Observation.Context)
}
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &Observation.Context {
if keyPath == Observation.VolumeKey,
let volume = (change?[NSKeyValueChangeKey.newKey] as? NSNumber)?.floatValue {
NotificationCenter.default.post(name: .SystemVolumeMonitor, userInfo: ["volume": volume])
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
//MARK: - AVAudioUnitTimePitch
public extension AVAudioUnitTimePitch {
enum RateRange: Float {
case min = 0.03125
case center = 1.0
case max = 32.0
public static var range: ClosedRange<Float> {
AVAudioUnitTimePitch.RateRange.min.rawValue...AVAudioUnitTimePitch.RateRange.max.rawValue
}
}
enum PitchRange: Float {
case min = -2400.0
case center = 0.0
case max = 2400.0
public static var range: ClosedRange<Float> {
AVAudioUnitTimePitch.PitchRange.min.rawValue...AVAudioUnitTimePitch.PitchRange.max.rawValue
}
}
enum QualityRange: Float {
case low = 3.0
case med = 8.0
case high = 32.0
public static var range: ClosedRange<Float> {
AVAudioUnitTimePitch.QualityRange.low.rawValue...AVAudioUnitTimePitch.QualityRange.high.rawValue
}
}
static func rateToPercent(_ rate: Float) -> Float {
(rate * 100.0) - 100.0
}
static func percentToRate(_ percent: Float) -> Float {
RateRange.center.rawValue + (percent/100.0)
}
///rate adjustment as percentage, zero based as signed whole numbers
/// 1x speed = +0%
/// 2x speed = +100%
/// 1/2 speed = -50%
var rateAsPercent: Float {
get {
AVAudioUnitTimePitch.rateToPercent(rate)
}
set(value) {
rate = AVAudioUnitTimePitch.percentToRate(value)
}
}
}
// MARK: - AVAudioSessionRouteDescription
extension AVAudioSessionRouteDescription {
var hasHeadphonens: Bool {
outputs.filter({$0.portType == .headphones}).isNotEmpty
}
}
| apache-2.0 | f2ce97bbcb58a3acbb918a472bff8fe1 | 32.154701 | 172 | 0.591632 | 5.360094 | false | false | false | false |
dpricha89/DrApp | Pods/SwiftDate/Sources/SwiftDate/DOTNETDateTimeFormatter.swift | 1 | 2545 |
import Foundation
public class DOTNETDateTimeFormatter {
private static let pattern = "\\/Date\\((-?\\d+)((?:[\\+\\-]\\d+)?)\\)\\/"
private init() {}
/// Parse a .donet formatted string returning appropriate `TimeZone` and `Dare` instance
///
/// - Parameters:
/// - string: string to pasrse
/// - calendar: calendar to use
/// - Returns: valid tuple with date and timezone, `nil` if string is not valid
public static func date(_ string: String, calendar: Calendar) -> (date: Date, tz: TimeZone)? {
guard let parsed = DOTNETDateTimeFormatter.parseDateString(string) else {
return nil
}
let date_obj = Date(timeIntervalSince1970: parsed.seconds)
return (date: date_obj, tz: parsed.tz)
}
/// Output as string representation of input `DateInRegion` instance
///
/// - Parameter date: date input
/// - Returns: a .dotnet formatted string
public static func string(_ date: DateInRegion) -> String {
let milliseconds = (date.absoluteDate.timeIntervalSince1970 * 1000.0)
let tzOffsets = (date.region.timeZone.secondsFromGMT(for: date.absoluteDate) / 3600)
let formattedStr = String(format: "/Date(%.0f%+03d00)/", milliseconds,tzOffsets)
return formattedStr
}
/// Parse a valid .donet string accounting both timezone and datetime
///
/// - Parameter string: input
/// - Returns: date and timezone, `nil` is parser fails
private static func parseDateString(_ string: String) -> (seconds: TimeInterval, tz: TimeZone)? {
do {
let parser = try NSRegularExpression(pattern: DOTNETDateTimeFormatter.pattern, options: .caseInsensitive)
guard let match = parser.firstMatch(in: string, options: .reportCompletion, range: NSRange(location: 0, length: string.characters.count)) else {
return nil
}
guard let milliseconds = TimeInterval((string as NSString).substring(with: match.range(at: 1))) else { return nil }
// Parse timezone
let raw_tz = ((string as NSString).substring(with: match.range(at: 2)) as NSString)
guard raw_tz.length > 1 else {
return nil
}
let tz_sign: String = raw_tz.substring(to: 1)
if tz_sign != "+" && tz_sign != "-" {
return nil
}
let tz_hours: String = raw_tz.substring(with: NSMakeRange(1, 2))
let tz_minutes: String = raw_tz.substring(with: NSMakeRange(3, 2))
let tz_offset = (Int(tz_hours)! * 60 * 60) + ( Int(tz_minutes)! * 60 )
guard let tz_obj = TimeZone(secondsFromGMT: tz_offset) else {
return nil
}
return (seconds: milliseconds / 1000, tz: tz_obj)
} catch {
return nil
}
}
}
| apache-2.0 | 426632016d65aa867d4f3e7eb7b906c8 | 34.347222 | 147 | 0.67387 | 3.52982 | false | false | false | false |
testpress/ios-app | ios-app/UI/ForumViewController.swift | 1 | 3391 | //
// ForumViewController.swift
// ios-app
//
// Copyright © 2017 Testpress. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class ForumViewController: UIViewController, DiscussionFilterDelegate {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var postCreateButton: UIButton!
@IBOutlet weak var containerView: UIView!
let viewController = ForumFilterViewController()
var forumTableViewController: ForumTableViewController!
override func viewDidLoad() {
super.viewDidLoad()
viewController.delegate = self
self.searchBar.delegate = self
UIUtils.setButtonDropShadow(postCreateButton)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ForumListSegue" {
if let viewController =
segue.destination as? ForumTableViewController {
self.forumTableViewController = viewController
}
}
}
@IBAction func composePost(_ sender: Any) {
let storyboard = UIStoryboard(name: Constants.POST_STORYBOARD, bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier:
Constants.POST_CREATION_VIEW_CONTROLLER) as! PostCreationViewController
viewController.parentTableViewController = forumTableViewController
present(viewController, animated: true, completion: nil)
}
func applyFilters(value: [String : Any]) {
self.forumTableViewController.filter(dict: value)
}
@IBAction func showProfileDetails(_ sender: UIBarButtonItem) {
UIUtils.showProfileDetails(self)
}
@IBAction func onFilterButtonClick(_ sender: Any) {
present(viewController, animated: true, completion: nil)
}
}
extension ForumViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
Debounce<String>.input(searchText, delay: 0.5, current: searchBar.text ?? "") {_ in
self.forumTableViewController.search(searchString: searchText)
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.forumTableViewController.search(searchString: "")
}
}
| mit | e49e7e07133c81308ea93c9cc56d4185 | 37.089888 | 91 | 0.70236 | 5.022222 | false | false | false | false |
FuckBoilerplate/RxCache | iOS/Pods/Nimble/Sources/Nimble/Matchers/BeLessThan.swift | 46 | 1660 | import Foundation
/// A Nimble matcher that succeeds when the actual value is less than the expected value.
public func beLessThan<T: Comparable>(_ expectedValue: T?) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be less than <\(stringify(expectedValue))>"
if let actual = try actualExpression.evaluate(), let expected = expectedValue {
return actual < expected
}
return false
}
}
/// A Nimble matcher that succeeds when the actual value is less than the expected value.
public func beLessThan(_ expectedValue: NMBComparable?) -> NonNilMatcherFunc<NMBComparable> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be less than <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == ComparisonResult.orderedAscending
return matches
}
}
public func <<T: Comparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beLessThan(rhs))
}
public func <(lhs: Expectation<NMBComparable>, rhs: NMBComparable?) {
lhs.to(beLessThan(rhs))
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beLessThanMatcher(_ expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let expr = actualExpression.cast { $0 as! NMBComparable? }
return try! beLessThan(expected).matches(expr, failureMessage: failureMessage)
}
}
}
#endif
| mit | bd17783a62c377670e4f9aa516445ca8 | 39.487805 | 120 | 0.708434 | 5.030303 | false | false | false | false |
shajrawi/swift | stdlib/public/core/Integers.swift | 1 | 137495 | //===--- Integers.swift.gyb -----------------------------------*- swift -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//===--- Bits for the Stdlib ----------------------------------------------===//
//===----------------------------------------------------------------------===//
// FIXME(integers): This should go in the stdlib separately, probably.
extension ExpressibleByIntegerLiteral
where Self : _ExpressibleByBuiltinIntegerLiteral {
@_transparent
public init(integerLiteral value: Self) {
self = value
}
}
//===----------------------------------------------------------------------===//
//===--- AdditiveArithmetic -----------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A type with values that support addition and subtraction.
///
/// The `AdditiveArithmetic` protocol provides a suitable basis for additive
/// arithmetic on scalar values, such as integers and floating-point numbers,
/// or vectors. You can write generic methods that operate on any numeric type
/// in the standard library by using the `AdditiveArithmetic` protocol as a
/// generic constraint.
///
/// The following code declares a method that calculates the total of any
/// sequence with `AdditiveArithmetic` elements.
///
/// extension Sequence where Element: AdditiveArithmetic {
/// func sum() -> Element {
/// return reduce(.zero, +)
/// }
/// }
///
/// The `sum()` method is now available on any sequence with values that
/// conform to `AdditiveArithmetic`, whether it is an array of `Double` or a
/// range of `Int`.
///
/// let arraySum = [1.1, 2.2, 3.3, 4.4, 5.5].sum()
/// // arraySum == 16.5
///
/// let rangeSum = (1..<10).sum()
/// // rangeSum == 45
///
/// Conforming to the AdditiveArithmetic Protocol
/// =============================================
///
/// To add `AdditiveArithmetic` protocol conformance to your own custom type,
/// implement the required operators, and provide a static `zero` property
/// using a type that can represent the magnitude of any value of your custom
/// type.
public protocol AdditiveArithmetic : Equatable {
/// The zero value.
///
/// Zero is the identity element for addition. For any value,
/// `x + .zero == x` and `.zero + x == x`.
static var zero: Self { get }
/// Adds two values and produces their sum.
///
/// The addition operator (`+`) calculates the sum of its two arguments. For
/// example:
///
/// 1 + 2 // 3
/// -10 + 15 // 5
/// -15 + -5 // -20
/// 21.5 + 3.25 // 24.75
///
/// You cannot use `+` with arguments of different types. To add values of
/// different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) + y // 1000021
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
static func +(lhs: Self, rhs: Self) -> Self
/// Adds two values and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
static func +=(lhs: inout Self, rhs: Self)
/// Subtracts one value from another and produces their difference.
///
/// The subtraction operator (`-`) calculates the difference of its two
/// arguments. For example:
///
/// 8 - 3 // 5
/// -10 - 5 // -15
/// 100 - -5 // 105
/// 10.5 - 100.0 // -89.5
///
/// You cannot use `-` with arguments of different types. To subtract values
/// of different types, convert one of the values to the other value's type.
///
/// let x: UInt8 = 21
/// let y: UInt = 1000000
/// y - UInt(x) // 999979
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
static func -(lhs: Self, rhs: Self) -> Self
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable.
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
static func -=(lhs: inout Self, rhs: Self)
}
public extension AdditiveArithmetic where Self : ExpressibleByIntegerLiteral {
/// The zero value.
///
/// Zero is the identity element for addition. For any value,
/// `x + .zero == x` and `.zero + x == x`.
static var zero: Self {
return 0
}
}
//===----------------------------------------------------------------------===//
//===--- Numeric ----------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A type with values that support multiplication.
///
/// The `Numeric` protocol provides a suitable basis for arithmetic on
/// scalar values, such as integers and floating-point numbers. You can write
/// generic methods that operate on any numeric type in the standard library
/// by using the `Numeric` protocol as a generic constraint.
///
/// The following example extends `Sequence` with a method that returns an
/// array with the sequence's values multiplied by two.
///
/// extension Sequence where Element: Numeric {
/// func doublingAll() -> [Element] {
/// return map { $0 * 2 }
/// }
/// }
///
/// With this extension, any sequence with elements that conform to `Numeric`
/// has the `doublingAll()` method. For example, you can double the elements of
/// an array of doubles or a range of integers:
///
/// let observations = [1.5, 2.0, 3.25, 4.875, 5.5]
/// let doubledObservations = observations.doublingAll()
/// // doubledObservations == [3.0, 4.0, 6.5, 9.75, 11.0]
///
/// let integers = 0..<8
/// let doubledIntegers = integers.doublingAll()
/// // doubledIntegers == [0, 2, 4, 6, 8, 10, 12, 14]
///
/// Conforming to the Numeric Protocol
/// ==================================
///
/// To add `Numeric` protocol conformance to your own custom type, implement
/// the required initializer and operators, and provide a `magnitude` property
/// using a type that can represent the magnitude of any value of your custom
/// type.
public protocol Numeric : AdditiveArithmetic, ExpressibleByIntegerLiteral {
/// Creates a new instance from the given integer, if it can be represented
/// exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `100`, while the attempt to initialize the
/// constant `y` from `1_000` fails because the `Int8` type can represent
/// `127` at maximum:
///
/// let x = Int8(exactly: 100)
/// // x == Optional(100)
/// let y = Int8(exactly: 1_000)
/// // y == nil
///
/// - Parameter source: A value to convert to this type.
init?<T : BinaryInteger>(exactly source: T)
/// A type that can represent the absolute value of any possible value of the
/// conforming type.
associatedtype Magnitude : Comparable, Numeric
/// The magnitude of this value.
///
/// For any numeric value `x`, `x.magnitude` is the absolute value of `x`.
/// You can use the `magnitude` property in operations that are simpler to
/// implement in terms of unsigned values, such as printing the value of an
/// integer, which is just printing a '-' character in front of an absolute
/// value.
///
/// let x = -200
/// // x.magnitude == 200
///
/// The global `abs(_:)` function provides more familiar syntax when you need
/// to find an absolute value. In addition, because `abs(_:)` always returns
/// a value of the same type, even in a generic context, using the function
/// instead of the `magnitude` property is encouraged.
var magnitude: Magnitude { get }
/// Multiplies two values and produces their product.
///
/// The multiplication operator (`*`) calculates the product of its two
/// arguments. For example:
///
/// 2 * 3 // 6
/// 100 * 21 // 2100
/// -10 * 15 // -150
/// 3.5 * 2.25 // 7.875
///
/// You cannot use `*` with arguments of different types. To multiply values
/// of different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) * y // 21000000
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
static func *(lhs: Self, rhs: Self) -> Self
/// Multiplies two values and stores the result in the left-hand-side
/// variable.
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
static func *=(lhs: inout Self, rhs: Self)
}
/// A type that can represent both positive and negative values.
///
/// The `SignedNumeric` protocol extends the operations defined by the
/// `Numeric` protocol to include a value's additive inverse.
///
/// Conforming to the SignedNumeric Protocol
/// ========================================
///
/// Because the `SignedNumeric` protocol provides default implementations of
/// both of its required methods, you don't need to do anything beyond
/// declaring conformance to the protocol and ensuring that the values of your
/// type support negation. To customize your type's implementation, provide
/// your own mutating `negate()` method.
///
/// When the additive inverse of a value is unrepresentable in a conforming
/// type, the operation should either trap or return an exceptional value. For
/// example, using the negation operator (prefix `-`) with `Int.min` results in
/// a runtime error.
///
/// let x = Int.min
/// let y = -x
/// // Overflow error
public protocol SignedNumeric : Numeric {
/// Returns the additive inverse of the specified value.
///
/// The negation operator (prefix `-`) returns the additive inverse of its
/// argument.
///
/// let x = 21
/// let y = -x
/// // y == -21
///
/// The resulting value must be representable in the same type as the
/// argument. In particular, negating a signed, fixed-width integer type's
/// minimum results in a value that cannot be represented.
///
/// let z = -Int8.min
/// // Overflow error
///
/// - Returns: The additive inverse of this value.
static prefix func - (_ operand: Self) -> Self
/// Replaces this value with its additive inverse.
///
/// The following example uses the `negate()` method to negate the value of
/// an integer `x`:
///
/// var x = 21
/// x.negate()
/// // x == -21
///
/// The resulting value must be representable within the value's type. In
/// particular, negating a signed, fixed-width integer type's minimum
/// results in a value that cannot be represented.
///
/// var y = Int8.min
/// y.negate()
/// // Overflow error
mutating func negate()
}
extension SignedNumeric {
/// Returns the additive inverse of the specified value.
///
/// The negation operator (prefix `-`) returns the additive inverse of its
/// argument.
///
/// let x = 21
/// let y = -x
/// // y == -21
///
/// The resulting value must be representable in the same type as the
/// argument. In particular, negating a signed, fixed-width integer type's
/// minimum results in a value that cannot be represented.
///
/// let z = -Int8.min
/// // Overflow error
///
/// - Returns: The additive inverse of the argument.
@_transparent
public static prefix func - (_ operand: Self) -> Self {
var result = operand
result.negate()
return result
}
/// Replaces this value with its additive inverse.
///
/// The following example uses the `negate()` method to negate the value of
/// an integer `x`:
///
/// var x = 21
/// x.negate()
/// // x == -21
///
/// The resulting value must be representable within the value's type. In
/// particular, negating a signed, fixed-width integer type's minimum
/// results in a value that cannot be represented.
///
/// var y = Int8.min
/// y.negate()
/// // Overflow error
@_transparent
public mutating func negate() {
self = 0 - self
}
}
/// Returns the absolute value of the given number.
///
/// The absolute value of `x` must be representable in the same type. In
/// particular, the absolute value of a signed, fixed-width integer type's
/// minimum cannot be represented.
///
/// let x = Int8.min
/// // x == -128
/// let y = abs(x)
/// // Overflow error
///
/// - Parameter x: A signed number.
/// - Returns: The absolute value of `x`.
@inlinable
public func abs<T : SignedNumeric & Comparable>(_ x: T) -> T {
if T.self == T.Magnitude.self {
return unsafeBitCast(x.magnitude, to: T.self)
}
return x < (0 as T) ? -x : x
}
extension AdditiveArithmetic {
/// Returns the given number unchanged.
///
/// You can use the unary plus operator (`+`) to provide symmetry in your
/// code for positive numbers when also using the unary minus operator.
///
/// let x = -21
/// let y = +21
/// // x == -21
/// // y == 21
///
/// - Returns: The given argument without any changes.
@_transparent
public static prefix func + (x: Self) -> Self {
return x
}
}
//===----------------------------------------------------------------------===//
//===--- BinaryInteger ----------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// An integer type with a binary representation.
///
/// The `BinaryInteger` protocol is the basis for all the integer types
/// provided by the standard library. All of the standard library's integer
/// types, such as `Int` and `UInt32`, conform to `BinaryInteger`.
///
/// Converting Between Numeric Types
/// ================================
///
/// You can create new instances of a type that conforms to the `BinaryInteger`
/// protocol from a floating-point number or another binary integer of any
/// type. The `BinaryInteger` protocol provides initializers for four
/// different kinds of conversion.
///
/// Range-Checked Conversion
/// ------------------------
///
/// You use the default `init(_:)` initializer to create a new instance when
/// you're sure that the value passed is representable in the new type. For
/// example, an instance of `Int16` can represent the value `500`, so the
/// first conversion in the code sample below succeeds. That same value is too
/// large to represent as an `Int8` instance, so the second conversion fails,
/// triggering a runtime error.
///
/// let x: Int = 500
/// let y = Int16(x)
/// // y == 500
///
/// let z = Int8(x)
/// // Error: Not enough bits to represent...
///
/// When you create a binary integer from a floating-point value using the
/// default initializer, the value is rounded toward zero before the range is
/// checked. In the following example, the value `127.75` is rounded to `127`,
/// which is representable by the `Int8` type. `128.25` is rounded to `128`,
/// which is not representable as an `Int8` instance, triggering a runtime
/// error.
///
/// let e = Int8(127.75)
/// // e == 127
///
/// let f = Int8(128.25)
/// // Error: Double value cannot be converted...
///
///
/// Exact Conversion
/// ----------------
///
/// Use the `init?(exactly:)` initializer to create a new instance after
/// checking whether the passed value is representable. Instead of trapping on
/// out-of-range values, using the failable `init?(exactly:)`
/// initializer results in `nil`.
///
/// let x = Int16(exactly: 500)
/// // x == Optional(500)
///
/// let y = Int8(exactly: 500)
/// // y == nil
///
/// When converting floating-point values, the `init?(exactly:)` initializer
/// checks both that the passed value has no fractional part and that the
/// value is representable in the resulting type.
///
/// let e = Int8(exactly: 23.0) // integral value, representable
/// // e == Optional(23)
///
/// let f = Int8(exactly: 23.75) // fractional value, representable
/// // f == nil
///
/// let g = Int8(exactly: 500.0) // integral value, nonrepresentable
/// // g == nil
///
/// Clamping Conversion
/// -------------------
///
/// Use the `init(clamping:)` initializer to create a new instance of a binary
/// integer type where out-of-range values are clamped to the representable
/// range of the type. For a type `T`, the resulting value is in the range
/// `T.min...T.max`.
///
/// let x = Int16(clamping: 500)
/// // x == 500
///
/// let y = Int8(clamping: 500)
/// // y == 127
///
/// let z = UInt8(clamping: -500)
/// // z == 0
///
/// Bit Pattern Conversion
/// ----------------------
///
/// Use the `init(truncatingIfNeeded:)` initializer to create a new instance
/// with the same bit pattern as the passed value, extending or truncating the
/// value's representation as necessary. Note that the value may not be
/// preserved, particularly when converting between signed to unsigned integer
/// types or when the destination type has a smaller bit width than the source
/// type. The following example shows how extending and truncating work for
/// nonnegative integers:
///
/// let q: Int16 = 850
/// // q == 0b00000011_01010010
///
/// let r = Int8(truncatingIfNeeded: q) // truncate 'q' to fit in 8 bits
/// // r == 82
/// // == 0b01010010
///
/// let s = Int16(truncatingIfNeeded: r) // extend 'r' to fill 16 bits
/// // s == 82
/// // == 0b00000000_01010010
///
/// Any padding is performed by *sign-extending* the passed value. When
/// nonnegative integers are extended, the result is padded with zeroes. When
/// negative integers are extended, the result is padded with ones. This
/// example shows several extending conversions of a negative value---note
/// that negative values are sign-extended even when converting to an unsigned
/// type.
///
/// let t: Int8 = -100
/// // t == -100
/// // t's binary representation == 0b10011100
///
/// let u = UInt8(truncatingIfNeeded: t)
/// // u == 156
/// // u's binary representation == 0b10011100
///
/// let v = Int16(truncatingIfNeeded: t)
/// // v == -100
/// // v's binary representation == 0b11111111_10011100
///
/// let w = UInt16(truncatingIfNeeded: t)
/// // w == 65436
/// // w's binary representation == 0b11111111_10011100
///
///
/// Comparing Across Integer Types
/// ==============================
///
/// You can use relational operators, such as the less-than and equal-to
/// operators (`<` and `==`), to compare instances of different binary integer
/// types. The following example compares instances of the `Int`, `UInt`, and
/// `UInt8` types:
///
/// let x: Int = -23
/// let y: UInt = 1_000
/// let z: UInt8 = 23
///
/// if x < y {
/// print("\(x) is less than \(y).")
/// }
/// // Prints "-23 is less than 1000."
///
/// if z > x {
/// print("\(z) is greater than \(x).")
/// }
/// // Prints "23 is greater than -23."
public protocol BinaryInteger :
Hashable, Numeric, CustomStringConvertible, Strideable
where Magnitude : BinaryInteger, Magnitude.Magnitude == Magnitude
{
/// A Boolean value indicating whether this type is a signed integer type.
///
/// *Signed* integer types can represent both positive and negative values.
/// *Unsigned* integer types can represent only nonnegative values.
static var isSigned: Bool { get }
/// Creates an integer from the given floating-point value, if it can be
/// represented exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `21.0`, while the attempt to initialize the
/// constant `y` from `21.5` fails:
///
/// let x = Int(exactly: 21.0)
/// // x == Optional(21)
/// let y = Int(exactly: 21.5)
/// // y == nil
///
/// - Parameter source: A floating-point value to convert to an integer.
init?<T : BinaryFloatingPoint>(exactly source: T)
/// Creates an integer from the given floating-point value, rounding toward
/// zero.
///
/// Any fractional part of the value passed as `source` is removed, rounding
/// the value toward zero.
///
/// let x = Int(21.5)
/// // x == 21
/// let y = Int(-21.5)
/// // y == -21
///
/// If `source` is outside the bounds of this type after rounding toward
/// zero, a runtime error may occur.
///
/// let z = UInt(-21.5)
/// // Error: ...the result would be less than UInt.min
///
/// - Parameter source: A floating-point value to convert to an integer.
/// `source` must be representable in this type after rounding toward
/// zero.
init<T : BinaryFloatingPoint>(_ source: T)
/// Creates a new instance from the given integer.
///
/// If the value passed as `source` is not representable in this type, a
/// runtime error may occur.
///
/// let x = -500 as Int
/// let y = Int32(x)
/// // y == -500
///
/// // -500 is not representable as a 'UInt32' instance
/// let z = UInt32(x)
/// // Error
///
/// - Parameter source: An integer to convert. `source` must be representable
/// in this type.
init<T : BinaryInteger>(_ source: T)
/// Creates a new instance from the bit pattern of the given instance by
/// sign-extending or truncating to fit this type.
///
/// When the bit width of `T` (the type of `source`) is equal to or greater
/// than this type's bit width, the result is the truncated
/// least-significant bits of `source`. For example, when converting a
/// 16-bit value to an 8-bit type, only the lower 8 bits of `source` are
/// used.
///
/// let p: Int16 = -500
/// // 'p' has a binary representation of 11111110_00001100
/// let q = Int8(truncatingIfNeeded: p)
/// // q == 12
/// // 'q' has a binary representation of 00001100
///
/// When the bit width of `T` is less than this type's bit width, the result
/// is *sign-extended* to fill the remaining bits. That is, if `source` is
/// negative, the result is padded with ones; otherwise, the result is
/// padded with zeros.
///
/// let u: Int8 = 21
/// // 'u' has a binary representation of 00010101
/// let v = Int16(truncatingIfNeeded: u)
/// // v == 21
/// // 'v' has a binary representation of 00000000_00010101
///
/// let w: Int8 = -21
/// // 'w' has a binary representation of 11101011
/// let x = Int16(truncatingIfNeeded: w)
/// // x == -21
/// // 'x' has a binary representation of 11111111_11101011
/// let y = UInt16(truncatingIfNeeded: w)
/// // y == 65515
/// // 'y' has a binary representation of 11111111_11101011
///
/// - Parameter source: An integer to convert to this type.
init<T : BinaryInteger>(truncatingIfNeeded source: T)
/// Creates a new instance with the representable value that's closest to the
/// given integer.
///
/// If the value passed as `source` is greater than the maximum representable
/// value in this type, the result is the type's `max` value. If `source` is
/// less than the smallest representable value in this type, the result is
/// the type's `min` value.
///
/// In this example, `x` is initialized as an `Int8` instance by clamping
/// `500` to the range `-128...127`, and `y` is initialized as a `UInt`
/// instance by clamping `-500` to the range `0...UInt.max`.
///
/// let x = Int8(clamping: 500)
/// // x == 127
/// // x == Int8.max
///
/// let y = UInt(clamping: -500)
/// // y == 0
///
/// - Parameter source: An integer to convert to this type.
init<T : BinaryInteger>(clamping source: T)
/// A type that represents the words of a binary integer.
///
/// The `Words` type must conform to the `RandomAccessCollection` protocol
/// with an `Element` type of `UInt` and `Index` type of `Int.
associatedtype Words : RandomAccessCollection
where Words.Element == UInt, Words.Index == Int
/// A collection containing the words of this value's binary
/// representation, in order from the least significant to most significant.
///
/// Negative values are returned in two's complement representation,
/// regardless of the type's underlying implementation.
var words: Words { get }
/// The least significant word in this value's binary representation.
var _lowWord: UInt { get }
/// The number of bits in the current binary representation of this value.
///
/// This property is a constant for instances of fixed-width integer
/// types.
var bitWidth: Int { get }
/// Returns the integer binary logarithm of this value.
///
/// If the value is negative or zero, a runtime error will occur.
func _binaryLogarithm() -> Int
/// The number of trailing zeros in this value's binary representation.
///
/// For example, in a fixed-width integer type with a `bitWidth` value of 8,
/// the number -8 has three trailing zeros.
///
/// let x = Int8(bitPattern: 0b1111_1000)
/// // x == -8
/// // x.trailingZeroBitCount == 3
///
/// If the value is zero, then `trailingZeroBitCount` is equal to `bitWidth`.
var trailingZeroBitCount: Int { get }
/// Returns the quotient of dividing the first value by the second.
///
/// For integer types, any remainder of the division is discarded.
///
/// let x = 21 / 5
/// // x == 4
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by. `rhs` must not be zero.
static func /(lhs: Self, rhs: Self) -> Self
/// Divides the first value by the second and stores the quotient in the
/// left-hand-side variable.
///
/// For integer types, any remainder of the division is discarded.
///
/// var x = 21
/// x /= 5
/// // x == 4
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by. `rhs` must not be zero.
static func /=(lhs: inout Self, rhs: Self)
/// Returns the remainder of dividing the first value by the second.
///
/// The result of the remainder operator (`%`) has the same sign as `lhs` and
/// has a magnitude less than `rhs.magnitude`.
///
/// let x = 22 % 5
/// // x == 2
/// let y = 22 % -5
/// // y == 2
/// let z = -22 % -5
/// // z == -2
///
/// For any two integers `a` and `b`, their quotient `q`, and their remainder
/// `r`, `a == b * q + r`.
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by. `rhs` must not be zero.
static func %(lhs: Self, rhs: Self) -> Self
/// Divides the first value by the second and stores the remainder in the
/// left-hand-side variable.
///
/// The result has the same sign as `lhs` and has a magnitude less than
/// `rhs.magnitude`.
///
/// var x = 22
/// x %= 5
/// // x == 2
///
/// var y = 22
/// y %= -5
/// // y == 2
///
/// var z = -22
/// z %= -5
/// // z == -2
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by. `rhs` must not be zero.
static func %=(lhs: inout Self, rhs: Self)
/// Adds two values and produces their sum.
///
/// The addition operator (`+`) calculates the sum of its two arguments. For
/// example:
///
/// 1 + 2 // 3
/// -10 + 15 // 5
/// -15 + -5 // -20
/// 21.5 + 3.25 // 24.75
///
/// You cannot use `+` with arguments of different types. To add values of
/// different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) + y // 1000021
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
override static func +(lhs: Self, rhs: Self) -> Self
/// Adds two values and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
override static func +=(lhs: inout Self, rhs: Self)
/// Subtracts one value from another and produces their difference.
///
/// The subtraction operator (`-`) calculates the difference of its two
/// arguments. For example:
///
/// 8 - 3 // 5
/// -10 - 5 // -15
/// 100 - -5 // 105
/// 10.5 - 100.0 // -89.5
///
/// You cannot use `-` with arguments of different types. To subtract values
/// of different types, convert one of the values to the other value's type.
///
/// let x: UInt8 = 21
/// let y: UInt = 1000000
/// y - UInt(x) // 999979
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
override static func -(lhs: Self, rhs: Self) -> Self
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable.
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
override static func -=(lhs: inout Self, rhs: Self)
/// Multiplies two values and produces their product.
///
/// The multiplication operator (`*`) calculates the product of its two
/// arguments. For example:
///
/// 2 * 3 // 6
/// 100 * 21 // 2100
/// -10 * 15 // -150
/// 3.5 * 2.25 // 7.875
///
/// You cannot use `*` with arguments of different types. To multiply values
/// of different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) * y // 21000000
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
override static func *(lhs: Self, rhs: Self) -> Self
/// Multiplies two values and stores the result in the left-hand-side
/// variable.
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
override static func *=(lhs: inout Self, rhs: Self)
/// Returns the inverse of the bits set in the argument.
///
/// The bitwise NOT operator (`~`) is a prefix operator that returns a value
/// in which all the bits of its argument are flipped: Bits that are `1` in
/// the argument are `0` in the result, and bits that are `0` in the argument
/// are `1` in the result. This is equivalent to the inverse of a set. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let notX = ~x // 0b11111010
///
/// Performing a bitwise NOT operation on 0 returns a value with every bit
/// set to `1`.
///
/// let allOnes = ~UInt8.min // 0b11111111
///
/// - Complexity: O(1).
static prefix func ~ (_ x: Self) -> Self
/// Returns the result of performing a bitwise AND operation on the two given
/// values.
///
/// A bitwise AND operation results in a value that has each bit set to `1`
/// where *both* of its arguments have that bit set to `1`. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x & y // 0b00000100
/// // z == 4
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func &(lhs: Self, rhs: Self) -> Self
/// Stores the result of performing a bitwise AND operation on the two given
/// values in the left-hand-side variable.
///
/// A bitwise AND operation results in a value that has each bit set to `1`
/// where *both* of its arguments have that bit set to `1`. For example:
///
/// var x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// x &= y // 0b00000100
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func &=(lhs: inout Self, rhs: Self)
/// Returns the result of performing a bitwise OR operation on the two given
/// values.
///
/// A bitwise OR operation results in a value that has each bit set to `1`
/// where *one or both* of its arguments have that bit set to `1`. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x | y // 0b00001111
/// // z == 15
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func |(lhs: Self, rhs: Self) -> Self
/// Stores the result of performing a bitwise OR operation on the two given
/// values in the left-hand-side variable.
///
/// A bitwise OR operation results in a value that has each bit set to `1`
/// where *one or both* of its arguments have that bit set to `1`. For
/// example:
///
/// var x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// x |= y // 0b00001111
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func |=(lhs: inout Self, rhs: Self)
/// Returns the result of performing a bitwise XOR operation on the two given
/// values.
///
/// A bitwise XOR operation, also known as an exclusive OR operation, results
/// in a value that has each bit set to `1` where *one or the other but not
/// both* of its arguments had that bit set to `1`. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x ^ y // 0b00001011
/// // z == 11
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func ^(lhs: Self, rhs: Self) -> Self
/// Stores the result of performing a bitwise XOR operation on the two given
/// values in the left-hand-side variable.
///
/// A bitwise XOR operation, also known as an exclusive OR operation, results
/// in a value that has each bit set to `1` where *one or the other but not
/// both* of its arguments had that bit set to `1`. For example:
///
/// var x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// x ^= y // 0b00001011
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func ^=(lhs: inout Self, rhs: Self)
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right.
///
/// The `>>` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a left shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*. An overshift results in `-1` for a
/// negative value of `lhs` or `0` for a nonnegative value.
/// - Using any other value for `rhs` performs a right shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted right by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x >> 2
/// // y == 7 // 0b00000111
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x >> 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a left shift
/// using `abs(rhs)`.
///
/// let a = x >> -3
/// // a == 240 // 0b11110000
/// let b = x << 3
/// // b == 240 // 0b11110000
///
/// Right shift operations on negative values "fill in" the high bits with
/// ones instead of zeros.
///
/// let q: Int8 = -30 // 0b11100010
/// let r = q >> 2
/// // r == -8 // 0b11111000
///
/// let s = q >> 11
/// // s == -1 // 0b11111111
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right.
static func >> <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self
/// Stores the result of shifting a value's binary representation the
/// specified number of digits to the right in the left-hand-side variable.
///
/// The `>>=` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a left shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*. An overshift results in `-1` for a
/// negative value of `lhs` or `0` for a nonnegative value.
/// - Using any other value for `rhs` performs a right shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted right by two bits.
///
/// var x: UInt8 = 30 // 0b00011110
/// x >>= 2
/// // x == 7 // 0b00000111
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// var y: UInt8 = 30 // 0b00011110
/// y >>= 11
/// // y == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a left shift
/// using `abs(rhs)`.
///
/// var a: UInt8 = 30 // 0b00011110
/// a >>= -3
/// // a == 240 // 0b11110000
///
/// var b: UInt8 = 30 // 0b00011110
/// b <<= 3
/// // b == 240 // 0b11110000
///
/// Right shift operations on negative values "fill in" the high bits with
/// ones instead of zeros.
///
/// var q: Int8 = -30 // 0b11100010
/// q >>= 2
/// // q == -8 // 0b11111000
///
/// var r: Int8 = -30 // 0b11100010
/// r >>= 11
/// // r == -1 // 0b11111111
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right.
static func >>= <RHS: BinaryInteger>(lhs: inout Self, rhs: RHS)
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left.
///
/// The `<<` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a right shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*, resulting in zero.
/// - Using any other value for `rhs` performs a left shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted left by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x << 2
/// // y == 120 // 0b01111000
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x << 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a right shift
/// with `abs(rhs)`.
///
/// let a = x << -3
/// // a == 3 // 0b00000011
/// let b = x >> 3
/// // b == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left.
static func << <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self
/// Stores the result of shifting a value's binary representation the
/// specified number of digits to the left in the left-hand-side variable.
///
/// The `<<` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a right shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*, resulting in zero.
/// - Using any other value for `rhs` performs a left shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted left by two bits.
///
/// var x: UInt8 = 30 // 0b00011110
/// x <<= 2
/// // x == 120 // 0b01111000
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// var y: UInt8 = 30 // 0b00011110
/// y <<= 11
/// // y == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a right shift
/// with `abs(rhs)`.
///
/// var a: UInt8 = 30 // 0b00011110
/// a <<= -3
/// // a == 3 // 0b00000011
///
/// var b: UInt8 = 30 // 0b00011110
/// b >>= 3
/// // b == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left.
static func <<=<RHS: BinaryInteger>(lhs: inout Self, rhs: RHS)
/// Returns the quotient and remainder of this value divided by the given
/// value.
///
/// Use this method to calculate the quotient and remainder of a division at
/// the same time.
///
/// let x = 1_000_000
/// let (q, r) = x.quotientAndRemainder(dividingBy: 933)
/// // q == 1071
/// // r == 757
///
/// - Parameter rhs: The value to divide this value by.
/// - Returns: A tuple containing the quotient and remainder of this value
/// divided by `rhs`. The remainder has the same sign as `rhs`.
func quotientAndRemainder(dividingBy rhs: Self)
-> (quotient: Self, remainder: Self)
/// Returns `true` if this value is a multiple of the given value, and `false`
/// otherwise.
///
/// For two integers *a* and *b*, *a* is a multiple of *b* if there exists a
/// third integer *q* such that _a = q*b_. For example, *6* is a multiple of
/// *3* because _6 = 2*3_. Zero is a multiple of everything because _0 = 0*x_
/// for any integer *x*.
///
/// Two edge cases are worth particular attention:
/// - `x.isMultiple(of: 0)` is `true` if `x` is zero and `false` otherwise.
/// - `T.min.isMultiple(of: -1)` is `true` for signed integer `T`, even
/// though the quotient `T.min / -1` isn't representable in type `T`.
///
/// - Parameter other: The value to test.
func isMultiple(of other: Self) -> Bool
/// Returns `-1` if this value is negative and `1` if it's positive;
/// otherwise, `0`.
///
/// - Returns: The sign of this number, expressed as an integer of the same
/// type.
func signum() -> Self
}
extension BinaryInteger {
/// Creates a new value equal to zero.
@_transparent
public init() {
self = 0
}
/// Returns `-1` if this value is negative and `1` if it's positive;
/// otherwise, `0`.
///
/// - Returns: The sign of this number, expressed as an integer of the same
/// type.
@inlinable
public func signum() -> Self {
return (self > (0 as Self) ? 1 : 0) - (self < (0 as Self) ? 1 : 0)
}
@_transparent
public var _lowWord: UInt {
var it = words.makeIterator()
return it.next() ?? 0
}
@inlinable
public func _binaryLogarithm() -> Int {
_precondition(self > (0 as Self))
var (quotient, remainder) =
(bitWidth &- 1).quotientAndRemainder(dividingBy: UInt.bitWidth)
remainder = remainder &+ 1
var word = UInt(truncatingIfNeeded: self >> (bitWidth &- remainder))
// If, internally, a variable-width binary integer uses digits of greater
// bit width than that of Magnitude.Words.Element (i.e., UInt), then it is
// possible that `word` could be zero. Additionally, a signed variable-width
// binary integer may have a leading word that is zero to store a clear sign
// bit.
while word == 0 {
quotient = quotient &- 1
remainder = remainder &+ UInt.bitWidth
word = UInt(truncatingIfNeeded: self >> (bitWidth &- remainder))
}
// Note that the order of operations below is important to guarantee that
// we won't overflow.
return UInt.bitWidth &* quotient &+
(UInt.bitWidth &- (word.leadingZeroBitCount &+ 1))
}
/// Returns the quotient and remainder of this value divided by the given
/// value.
///
/// Use this method to calculate the quotient and remainder of a division at
/// the same time.
///
/// let x = 1_000_000
/// let (q, r) = x.quotientAndRemainder(dividingBy: 933)
/// // q == 1071
/// // r == 757
///
/// - Parameter rhs: The value to divide this value by.
/// - Returns: A tuple containing the quotient and remainder of this value
/// divided by `rhs`.
@inlinable
public func quotientAndRemainder(dividingBy rhs: Self)
-> (quotient: Self, remainder: Self) {
return (self / rhs, self % rhs)
}
@inlinable
public func isMultiple(of other: Self) -> Bool {
// Nothing but zero is a multiple of zero.
if other == 0 { return self == 0 }
// Do the test in terms of magnitude, which guarantees there are no other
// edge cases. If we write this as `self % other` instead, it could trap
// for types that are not symmetric around zero.
return self.magnitude % other.magnitude == 0
}
//===----------------------------------------------------------------------===//
//===--- Homogeneous ------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// Returns the result of performing a bitwise AND operation on the two given
/// values.
///
/// A bitwise AND operation results in a value that has each bit set to `1`
/// where *both* of its arguments have that bit set to `1`. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x & y // 0b00000100
/// // z == 4
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
@_transparent
public static func & (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs &= rhs
return lhs
}
/// Returns the result of performing a bitwise OR operation on the two given
/// values.
///
/// A bitwise OR operation results in a value that has each bit set to `1`
/// where *one or both* of its arguments have that bit set to `1`. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x | y // 0b00001111
/// // z == 15
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
@_transparent
public static func | (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs |= rhs
return lhs
}
/// Returns the result of performing a bitwise XOR operation on the two given
/// values.
///
/// A bitwise XOR operation, also known as an exclusive OR operation, results
/// in a value that has each bit set to `1` where *one or the other but not
/// both* of its arguments had that bit set to `1`. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x ^ y // 0b00001011
/// // z == 11
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
@_transparent
public static func ^ (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs ^= rhs
return lhs
}
//===----------------------------------------------------------------------===//
//===--- Heterogeneous non-masking shift in terms of shift-assignment -----===//
//===----------------------------------------------------------------------===//
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right.
///
/// The `>>` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a left shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*. An overshift results in `-1` for a
/// negative value of `lhs` or `0` for a nonnegative value.
/// - Using any other value for `rhs` performs a right shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted right by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x >> 2
/// // y == 7 // 0b00000111
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x >> 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a left shift
/// using `abs(rhs)`.
///
/// let a = x >> -3
/// // a == 240 // 0b11110000
/// let b = x << 3
/// // b == 240 // 0b11110000
///
/// Right shift operations on negative values "fill in" the high bits with
/// ones instead of zeros.
///
/// let q: Int8 = -30 // 0b11100010
/// let r = q >> 2
/// // r == -8 // 0b11111000
///
/// let s = q >> 11
/// // s == -1 // 0b11111111
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func >> <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self {
var r = lhs
r >>= rhs
return r
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left.
///
/// The `<<` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a right shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*, resulting in zero.
/// - Using any other value for `rhs` performs a left shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted left by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x << 2
/// // y == 120 // 0b01111000
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x << 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a right shift
/// with `abs(rhs)`.
///
/// let a = x << -3
/// // a == 3 // 0b00000011
/// let b = x >> 3
/// // b == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func << <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self {
var r = lhs
r <<= rhs
return r
}
}
//===----------------------------------------------------------------------===//
//===--- CustomStringConvertible conformance ------------------------------===//
//===----------------------------------------------------------------------===//
extension BinaryInteger {
internal func _description(radix: Int, uppercase: Bool) -> String {
_precondition(2...36 ~= radix, "Radix must be between 2 and 36")
if bitWidth <= 64 {
let radix_ = Int64(radix)
return Self.isSigned
? _int64ToString(
Int64(truncatingIfNeeded: self), radix: radix_, uppercase: uppercase)
: _uint64ToString(
UInt64(truncatingIfNeeded: self), radix: radix_, uppercase: uppercase)
}
if self == (0 as Self) { return "0" }
// Bit shifting can be faster than division when `radix` is a power of two
// (although not necessarily the case for builtin types).
let isRadixPowerOfTwo = radix.nonzeroBitCount == 1
let radix_ = Magnitude(radix)
func _quotientAndRemainder(_ value: Magnitude) -> (Magnitude, Magnitude) {
return isRadixPowerOfTwo
? (value >> radix.trailingZeroBitCount, value & (radix_ - 1))
: value.quotientAndRemainder(dividingBy: radix_)
}
let hasLetters = radix > 10
func _ascii(_ digit: UInt8) -> UInt8 {
let base: UInt8
if !hasLetters || digit < 10 {
base = UInt8(("0" as Unicode.Scalar).value)
} else if uppercase {
base = UInt8(("A" as Unicode.Scalar).value) &- 10
} else {
base = UInt8(("a" as Unicode.Scalar).value) &- 10
}
return base &+ digit
}
let isNegative = Self.isSigned && self < (0 as Self)
var value = magnitude
// TODO(FIXME JIRA): All current stdlib types fit in small. Use a stack
// buffer instead of an array on the heap.
var result: [UInt8] = []
while value != 0 {
let (quotient, remainder) = _quotientAndRemainder(value)
result.append(_ascii(UInt8(truncatingIfNeeded: remainder)))
value = quotient
}
if isNegative {
result.append(UInt8(("-" as Unicode.Scalar).value))
}
result.reverse()
return result.withUnsafeBufferPointer {
return String._fromASCII($0)
}
}
/// A textual representation of this value.
public var description: String {
return _description(radix: 10, uppercase: false)
}
}
//===----------------------------------------------------------------------===//
//===--- Strideable conformance -------------------------------------------===//
//===----------------------------------------------------------------------===//
extension BinaryInteger {
/// Returns the distance from this value to the given value, expressed as a
/// stride.
///
/// For two values `x` and `y`, and a distance `n = x.distance(to: y)`,
/// `x.advanced(by: n) == y`.
///
/// - Parameter other: The value to calculate the distance to.
/// - Returns: The distance from this value to `other`.
@inlinable
@inline(__always)
public func distance(to other: Self) -> Int {
if !Self.isSigned {
if self > other {
if let result = Int(exactly: self - other) {
return -result
}
} else {
if let result = Int(exactly: other - self) {
return result
}
}
} else {
let isNegative = self < (0 as Self)
if isNegative == (other < (0 as Self)) {
if let result = Int(exactly: other - self) {
return result
}
} else {
if let result = Int(exactly: self.magnitude + other.magnitude) {
return isNegative ? result : -result
}
}
}
_preconditionFailure("Distance is not representable in Int")
}
/// Returns a value that is offset the specified distance from this value.
///
/// Use the `advanced(by:)` method in generic code to offset a value by a
/// specified distance. If you're working directly with numeric values, use
/// the addition operator (`+`) instead of this method.
///
/// For a value `x`, a distance `n`, and a value `y = x.advanced(by: n)`,
/// `x.distance(to: y) == n`.
///
/// - Parameter n: The distance to advance this value.
/// - Returns: A value that is offset from this value by `n`.
@inlinable
@inline(__always)
public func advanced(by n: Int) -> Self {
if !Self.isSigned {
return n < (0 as Int)
? self - Self(-n)
: self + Self(n)
}
if (self < (0 as Self)) == (n < (0 as Self)) {
return self + Self(n)
}
return self.magnitude < n.magnitude
? Self(Int(self) + n)
: self + Self(n)
}
}
//===----------------------------------------------------------------------===//
//===--- Heterogeneous comparison -----------------------------------------===//
//===----------------------------------------------------------------------===//
extension BinaryInteger {
/// Returns a Boolean value indicating whether the two given values are
/// equal.
///
/// You can check the equality of instances of any `BinaryInteger` types
/// using the equal-to operator (`==`). For example, you can test whether
/// the first `UInt8` value in a string's UTF-8 encoding is equal to the
/// first `UInt32` value in its Unicode scalar view:
///
/// let gameName = "Red Light, Green Light"
/// if let firstUTF8 = gameName.utf8.first,
/// let firstScalar = gameName.unicodeScalars.first?.value {
/// print("First code values are equal: \(firstUTF8 == firstScalar)")
/// }
/// // Prints "First code values are equal: true"
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func == <
Other : BinaryInteger
>(lhs: Self, rhs: Other) -> Bool {
let lhsNegative = Self.isSigned && lhs < (0 as Self)
let rhsNegative = Other.isSigned && rhs < (0 as Other)
if lhsNegative != rhsNegative { return false }
// Here we know the values are of the same sign.
//
// There are a few possible scenarios from here:
//
// 1. Both values are negative
// - If one value is strictly wider than the other, then it is safe to
// convert to the wider type.
// - If the values are of the same width, it does not matter which type we
// choose to convert to as the values are already negative, and thus
// include the sign bit if two's complement representation already.
// 2. Both values are non-negative
// - If one value is strictly wider than the other, then it is safe to
// convert to the wider type.
// - If the values are of the same width, than signedness matters, as not
// unsigned types are 'wider' in a sense they don't need to 'waste' the
// sign bit. Therefore it is safe to convert to the unsigned type.
if lhs.bitWidth < rhs.bitWidth {
return Other(truncatingIfNeeded: lhs) == rhs
}
if lhs.bitWidth > rhs.bitWidth {
return lhs == Self(truncatingIfNeeded: rhs)
}
if Self.isSigned {
return Other(truncatingIfNeeded: lhs) == rhs
}
return lhs == Self(truncatingIfNeeded: rhs)
}
/// Returns a Boolean value indicating whether the two given values are not
/// equal.
///
/// You can check the inequality of instances of any `BinaryInteger` types
/// using the not-equal-to operator (`!=`). For example, you can test
/// whether the first `UInt8` value in a string's UTF-8 encoding is not
/// equal to the first `UInt32` value in its Unicode scalar view:
///
/// let gameName = "Red Light, Green Light"
/// if let firstUTF8 = gameName.utf8.first,
/// let firstScalar = gameName.unicodeScalars.first?.value {
/// print("First code values are different: \(firstUTF8 != firstScalar)")
/// }
/// // Prints "First code values are different: false"
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func != <
Other : BinaryInteger
>(lhs: Self, rhs: Other) -> Bool {
return !(lhs == rhs)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// You can compare instances of any `BinaryInteger` types using the
/// less-than operator (`<`), even if the two instances are of different
/// types.
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func < <Other : BinaryInteger>(lhs: Self, rhs: Other) -> Bool {
let lhsNegative = Self.isSigned && lhs < (0 as Self)
let rhsNegative = Other.isSigned && rhs < (0 as Other)
if lhsNegative != rhsNegative { return lhsNegative }
if lhs == (0 as Self) && rhs == (0 as Other) { return false }
// if we get here, lhs and rhs have the same sign. If they're negative,
// then Self and Other are both signed types, and one of them can represent
// values of the other type. Otherwise, lhs and rhs are positive, and one
// of Self, Other may be signed and the other unsigned.
let rhsAsSelf = Self(truncatingIfNeeded: rhs)
let rhsAsSelfNegative = rhsAsSelf < (0 as Self)
// Can we round-trip rhs through Other?
if Other(truncatingIfNeeded: rhsAsSelf) == rhs &&
// This additional check covers the `Int8.max < (128 as UInt8)` case.
// Since the types are of the same width, init(truncatingIfNeeded:)
// will result in a simple bitcast, so that rhsAsSelf would be -128, and
// `lhs < rhsAsSelf` will return false.
// We basically guard against that bitcast by requiring rhs and rhsAsSelf
// to be the same sign.
rhsNegative == rhsAsSelfNegative {
return lhs < rhsAsSelf
}
return Other(truncatingIfNeeded: lhs) < rhs
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than or equal to that of the second argument.
///
/// You can compare instances of any `BinaryInteger` types using the
/// less-than-or-equal-to operator (`<=`), even if the two instances are of
/// different types.
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func <= <Other : BinaryInteger>(lhs: Self, rhs: Other) -> Bool {
return !(rhs < lhs)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than or equal to that of the second argument.
///
/// You can compare instances of any `BinaryInteger` types using the
/// greater-than-or-equal-to operator (`>=`), even if the two instances are
/// of different types.
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func >= <Other : BinaryInteger>(lhs: Self, rhs: Other) -> Bool {
return !(lhs < rhs)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than that of the second argument.
///
/// You can compare instances of any `BinaryInteger` types using the
/// greater-than operator (`>`), even if the two instances are of different
/// types.
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func > <Other : BinaryInteger>(lhs: Self, rhs: Other) -> Bool {
return rhs < lhs
}
}
//===----------------------------------------------------------------------===//
//===--- Ambiguity breakers -----------------------------------------------===//
//
// These two versions of the operators are not ordered with respect to one
// another, but the compiler choses the second one, and that results in infinite
// recursion.
//
// <T : Comparable>(T, T) -> Bool
// <T : BinaryInteger, U : BinaryInteger>(T, U) -> Bool
//
// so we define:
//
// <T : BinaryInteger>(T, T) -> Bool
//
//===----------------------------------------------------------------------===//
extension BinaryInteger {
@_transparent
public static func != (lhs: Self, rhs: Self) -> Bool {
return !(lhs == rhs)
}
@_transparent
public static func <= (lhs: Self, rhs: Self) -> Bool {
return !(rhs < lhs)
}
@_transparent
public static func >= (lhs: Self, rhs: Self) -> Bool {
return !(lhs < rhs)
}
@_transparent
public static func > (lhs: Self, rhs: Self) -> Bool {
return rhs < lhs
}
}
//===----------------------------------------------------------------------===//
//===--- FixedWidthInteger ------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// An integer type that uses a fixed size for every instance.
///
/// The `FixedWidthInteger` protocol adds binary bitwise operations, bit
/// shifts, and overflow handling to the operations supported by the
/// `BinaryInteger` protocol.
///
/// Use the `FixedWidthInteger` protocol as a constraint or extension point
/// when writing operations that depend on bit shifting, performing bitwise
/// operations, catching overflows, or having access to the maximum or minimum
/// representable value of a type. For example, the following code provides a
/// `binaryString` property on every fixed-width integer that represents the
/// number's binary representation, split into 8-bit chunks.
///
/// extension FixedWidthInteger {
/// var binaryString: String {
/// var result: [String] = []
/// for i in 0..<(Self.bitWidth / 8) {
/// let byte = UInt8(truncatingIfNeeded: self >> (i * 8))
/// let byteString = String(byte, radix: 2)
/// let padding = String(repeating: "0",
/// count: 8 - byteString.count)
/// result.append(padding + byteString)
/// }
/// return "0b" + result.reversed().joined(separator: "_")
/// }
/// }
///
/// print(Int16.max.binaryString)
/// // Prints "0b01111111_11111111"
/// print((101 as UInt8).binaryString)
/// // Prints "0b11001001"
///
/// The `binaryString` implementation uses the static `bitWidth` property and
/// the right shift operator (`>>`), both of which are available to any type
/// that conforms to the `FixedWidthInteger` protocol.
///
/// The next example declares a generic `squared` function, which accepts an
/// instance `x` of any fixed-width integer type. The function uses the
/// `multipliedReportingOverflow(by:)` method to multiply `x` by itself and
/// check whether the result is too large to represent in the same type.
///
/// func squared<T: FixedWidthInteger>(_ x: T) -> T? {
/// let (result, overflow) = x.multipliedReportingOverflow(by: x)
/// if overflow {
/// return nil
/// }
/// return result
/// }
///
/// let (x, y): (Int8, Int8) = (9, 123)
/// print(squared(x))
/// // Prints "Optional(81)"
/// print(squared(y))
/// // Prints "nil"
///
/// Conforming to the FixedWidthInteger Protocol
/// ============================================
///
/// To make your own custom type conform to the `FixedWidthInteger` protocol,
/// declare the required initializers, properties, and methods. The required
/// methods that are suffixed with `ReportingOverflow` serve as the
/// customization points for arithmetic operations. When you provide just those
/// methods, the standard library provides default implementations for all
/// other arithmetic methods and operators.
public protocol FixedWidthInteger : BinaryInteger, LosslessStringConvertible
where Magnitude : FixedWidthInteger & UnsignedInteger,
Stride : FixedWidthInteger & SignedInteger {
/// The number of bits used for the underlying binary representation of
/// values of this type.
///
/// An unsigned, fixed-width integer type can represent values from 0 through
/// `(2 ** bitWidth) - 1`, where `**` is exponentiation. A signed,
/// fixed-width integer type can represent values from
/// `-(2 ** (bitWidth - 1))` through `(2 ** (bitWidth - 1)) - 1`. For example,
/// the `Int8` type has a `bitWidth` value of 8 and can store any integer in
/// the range `-128...127`.
static var bitWidth: Int { get }
/// The maximum representable integer in this type.
///
/// For unsigned integer types, this value is `(2 ** bitWidth) - 1`, where
/// `**` is exponentiation. For signed integer types, this value is
/// `(2 ** (bitWidth - 1)) - 1`.
static var max: Self { get }
/// The minimum representable integer in this type.
///
/// For unsigned integer types, this value is always `0`. For signed integer
/// types, this value is `-(2 ** (bitWidth - 1))`, where `**` is
/// exponentiation.
static var min: Self { get }
/// Returns the sum of this value and the given value, along with a Boolean
/// value indicating whether overflow occurred in the operation.
///
/// - Parameter rhs: The value to add to this value.
/// - Returns: A tuple containing the result of the addition along with a
/// Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// sum. If the `overflow` component is `true`, an overflow occurred and
/// the `partialValue` component contains the truncated sum of this value
/// and `rhs`.
func addingReportingOverflow(
_ rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns the difference obtained by subtracting the given value from this
/// value, along with a Boolean value indicating whether overflow occurred in
/// the operation.
///
/// - Parameter rhs: The value to subtract from this value.
/// - Returns: A tuple containing the result of the subtraction along with a
/// Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// difference. If the `overflow` component is `true`, an overflow occurred
/// and the `partialValue` component contains the truncated result of `rhs`
/// subtracted from this value.
func subtractingReportingOverflow(
_ rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns the product of this value and the given value, along with a
/// Boolean value indicating whether overflow occurred in the operation.
///
/// - Parameter rhs: The value to multiply by this value.
/// - Returns: A tuple containing the result of the multiplication along with
/// a Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// product. If the `overflow` component is `true`, an overflow occurred and
/// the `partialValue` component contains the truncated product of this
/// value and `rhs`.
func multipliedReportingOverflow(
by rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns the quotient obtained by dividing this value by the given value,
/// along with a Boolean value indicating whether overflow occurred in the
/// operation.
///
/// Dividing by zero is not an error when using this method. For a value `x`,
/// the result of `x.dividedReportingOverflow(by: 0)` is `(x, true)`.
///
/// - Parameter rhs: The value to divide this value by.
/// - Returns: A tuple containing the result of the division along with a
/// Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// quotient. If the `overflow` component is `true`, an overflow occurred
/// and the `partialValue` component contains either the truncated quotient
/// or, if the quotient is undefined, the dividend.
func dividedReportingOverflow(
by rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns the remainder after dividing this value by the given value, along
/// with a Boolean value indicating whether overflow occurred during division.
///
/// Dividing by zero is not an error when using this method. For a value `x`,
/// the result of `x.remainderReportingOverflow(dividingBy: 0)` is
/// `(x, true)`.
///
/// - Parameter rhs: The value to divide this value by.
/// - Returns: A tuple containing the result of the operation along with a
/// Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// remainder. If the `overflow` component is `true`, an overflow occurred
/// during division and the `partialValue` component contains either the
/// entire remainder or, if the remainder is undefined, the dividend.
func remainderReportingOverflow(
dividingBy rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns a tuple containing the high and low parts of the result of
/// multiplying this value by the given value.
///
/// Use this method to calculate the full result of a product that would
/// otherwise overflow. Unlike traditional truncating multiplication, the
/// `multipliedFullWidth(by:)` method returns a tuple containing both the
/// `high` and `low` parts of the product of this value and `other`. The
/// following example uses this method to multiply two `Int8` values that
/// normally overflow when multiplied:
///
/// let x: Int8 = 48
/// let y: Int8 = -40
/// let result = x.multipliedFullWidth(by: y)
/// // result.high == -8
/// // result.low == 128
///
/// The product of `x` and `y` is `-1920`, which is too large to represent in
/// an `Int8` instance. The `high` and `low` compnents of the `result` value
/// represent `-1920` when concatenated to form a double-width integer; that
/// is, using `result.high` as the high byte and `result.low` as the low byte
/// of an `Int16` instance.
///
/// let z = Int16(result.high) << 8 | Int16(result.low)
/// // z == -1920
///
/// - Parameter other: The value to multiply this value by.
/// - Returns: A tuple containing the high and low parts of the result of
/// multiplying this value and `other`.
func multipliedFullWidth(by other: Self) -> (high: Self, low: Self.Magnitude)
/// Returns a tuple containing the quotient and remainder obtained by dividing
/// the given value by this value.
///
/// The resulting quotient must be representable within the bounds of the
/// type. If the quotient is too large to represent in the type, a runtime
/// error may occur.
///
/// The following example divides a value that is too large to be represented
/// using a single `Int` instance by another `Int` value. Because the quotient
/// is representable as an `Int`, the division succeeds.
///
/// // 'dividend' represents the value 0x506f70652053616e74612049494949
/// let dividend = (22640526660490081, 7959093232766896457 as UInt)
/// let divisor = 2241543570477705381
///
/// let (quotient, remainder) = divisor.dividingFullWidth(dividend)
/// // quotient == 186319822866995413
/// // remainder == 0
///
/// - Parameter dividend: A tuple containing the high and low parts of a
/// double-width integer.
/// - Returns: A tuple containing the quotient and remainder obtained by
/// dividing `dividend` by this value.
func dividingFullWidth(_ dividend: (high: Self, low: Self.Magnitude))
-> (quotient: Self, remainder: Self)
init(_truncatingBits bits: UInt)
/// The number of bits equal to 1 in this value's binary representation.
///
/// For example, in a fixed-width integer type with a `bitWidth` value of 8,
/// the number *31* has five bits equal to *1*.
///
/// let x: Int8 = 0b0001_1111
/// // x == 31
/// // x.nonzeroBitCount == 5
var nonzeroBitCount: Int { get }
/// The number of leading zeros in this value's binary representation.
///
/// For example, in a fixed-width integer type with a `bitWidth` value of 8,
/// the number *31* has three leading zeros.
///
/// let x: Int8 = 0b0001_1111
/// // x == 31
/// // x.leadingZeroBitCount == 3
///
/// If the value is zero, then `leadingZeroBitCount` is equal to `bitWidth`.
var leadingZeroBitCount: Int { get }
/// Creates an integer from its big-endian representation, changing the byte
/// order if necessary.
///
/// - Parameter value: A value to use as the big-endian representation of the
/// new integer.
init(bigEndian value: Self)
/// Creates an integer from its little-endian representation, changing the
/// byte order if necessary.
///
/// - Parameter value: A value to use as the little-endian representation of
/// the new integer.
init(littleEndian value: Self)
/// The big-endian representation of this integer.
///
/// If necessary, the byte order of this value is reversed from the typical
/// byte order of this integer type. On a big-endian platform, for any
/// integer `x`, `x == x.bigEndian`.
var bigEndian: Self { get }
/// The little-endian representation of this integer.
///
/// If necessary, the byte order of this value is reversed from the typical
/// byte order of this integer type. On a little-endian platform, for any
/// integer `x`, `x == x.littleEndian`.
var littleEndian: Self { get }
/// A representation of this integer with the byte order swapped.
var byteSwapped: Self { get }
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width.
///
/// Use the masking right shift operator (`&>>`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking right shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &>> 2
/// // y == 7 // 0b00000111
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &>> 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
static func &>>(lhs: Self, rhs: Self) -> Self
/// Calculates the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width, and stores the result in the left-hand-side variable.
///
/// The `&>>=` operator performs a *masking shift*, where the value passed as
/// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The
/// shift is performed using this masked value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// var x: UInt8 = 30 // 0b00011110
/// x &>>= 2
/// // x == 7 // 0b00000111
///
/// However, if you use `19` as `rhs`, the operation first bitmasks `rhs` to
/// `3`, and then uses that masked value as the number of bits to shift `lhs`.
///
/// var y: UInt8 = 30 // 0b00011110
/// y &>>= 19
/// // y == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
static func &>>=(lhs: inout Self, rhs: Self)
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width.
///
/// Use the masking left shift operator (`&<<`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking left shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &<< 2
/// // y == 120 // 0b01111000
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &<< 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
static func &<<(lhs: Self, rhs: Self) -> Self
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width, and stores the result in the left-hand-side variable.
///
/// The `&<<=` operator performs a *masking shift*, where the value used as
/// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The
/// shift is performed using this masked value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// var x: UInt8 = 30 // 0b00011110
/// x &<<= 2
/// // x == 120 // 0b01111000
///
/// However, if you pass `19` as `rhs`, the method first bitmasks `rhs` to
/// `3`, and then uses that masked value as the number of bits to shift `lhs`.
///
/// var y: UInt8 = 30 // 0b00011110
/// y &<<= 19
/// // y == 240 // 0b11110000
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
static func &<<=(lhs: inout Self, rhs: Self)
}
extension FixedWidthInteger {
/// The number of bits in the binary representation of this value.
@inlinable
public var bitWidth: Int { return Self.bitWidth }
@inlinable
public func _binaryLogarithm() -> Int {
_precondition(self > (0 as Self))
return Self.bitWidth &- (leadingZeroBitCount &+ 1)
}
/// Creates an integer from its little-endian representation, changing the
/// byte order if necessary.
///
/// - Parameter value: A value to use as the little-endian representation of
/// the new integer.
@inlinable
public init(littleEndian value: Self) {
#if _endian(little)
self = value
#else
self = value.byteSwapped
#endif
}
/// Creates an integer from its big-endian representation, changing the byte
/// order if necessary.
///
/// - Parameter value: A value to use as the big-endian representation of the
/// new integer.
@inlinable
public init(bigEndian value: Self) {
#if _endian(big)
self = value
#else
self = value.byteSwapped
#endif
}
/// The little-endian representation of this integer.
///
/// If necessary, the byte order of this value is reversed from the typical
/// byte order of this integer type. On a little-endian platform, for any
/// integer `x`, `x == x.littleEndian`.
@inlinable
public var littleEndian: Self {
#if _endian(little)
return self
#else
return byteSwapped
#endif
}
/// The big-endian representation of this integer.
///
/// If necessary, the byte order of this value is reversed from the typical
/// byte order of this integer type. On a big-endian platform, for any
/// integer `x`, `x == x.bigEndian`.
@inlinable
public var bigEndian: Self {
#if _endian(big)
return self
#else
return byteSwapped
#endif
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width.
///
/// Use the masking right shift operator (`&>>`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking right shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &>> 2
/// // y == 7 // 0b00000111
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &>> 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &>> (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs &>>= rhs
return lhs
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width.
///
/// Use the masking right shift operator (`&>>`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking right shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &>> 2
/// // y == 7 // 0b00000111
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &>> 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &>> <
Other : BinaryInteger
>(lhs: Self, rhs: Other) -> Self {
return lhs &>> Self(truncatingIfNeeded: rhs)
}
/// Calculates the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width, and stores the result in the left-hand-side variable.
///
/// The `&>>=` operator performs a *masking shift*, where the value passed as
/// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The
/// shift is performed using this masked value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// var x: UInt8 = 30 // 0b00011110
/// x &>>= 2
/// // x == 7 // 0b00000111
///
/// However, if you use `19` as `rhs`, the operation first bitmasks `rhs` to
/// `3`, and then uses that masked value as the number of bits to shift `lhs`.
///
/// var y: UInt8 = 30 // 0b00011110
/// y &>>= 19
/// // y == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &>>= <
Other : BinaryInteger
>(lhs: inout Self, rhs: Other) {
lhs = lhs &>> rhs
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width.
///
/// Use the masking left shift operator (`&<<`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking left shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &<< 2
/// // y == 120 // 0b01111000
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &<< 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &<< (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs &<<= rhs
return lhs
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width.
///
/// Use the masking left shift operator (`&<<`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking left shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &<< 2
/// // y == 120 // 0b01111000
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &<< 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &<< <
Other : BinaryInteger
>(lhs: Self, rhs: Other) -> Self {
return lhs &<< Self(truncatingIfNeeded: rhs)
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width, and stores the result in the left-hand-side variable.
///
/// The `&<<=` operator performs a *masking shift*, where the value used as
/// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The
/// shift is performed using this masked value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// var x: UInt8 = 30 // 0b00011110
/// x &<<= 2
/// // x == 120 // 0b01111000
///
/// However, if you pass `19` as `rhs`, the method first bitmasks `rhs` to
/// `3`, and then uses that masked value as the number of bits to shift `lhs`.
///
/// var y: UInt8 = 30 // 0b00011110
/// y &<<= 19
/// // y == 240 // 0b11110000
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &<<= <
Other : BinaryInteger
>(lhs: inout Self, rhs: Other) {
lhs = lhs &<< rhs
}
}
extension FixedWidthInteger {
/// Returns a random value within the specified range, using the given
/// generator as a source for randomness.
///
/// Use this method to generate an integer within a specific range when you
/// are using a custom random number generator. This example creates three
/// new values in the range `1..<100`.
///
/// for _ in 1...3 {
/// print(Int.random(in: 1..<100, using: &myGenerator))
/// }
/// // Prints "7"
/// // Prints "44"
/// // Prints "21"
///
/// - Note: The algorithm used to create random values may change in a future
/// version of Swift. If you're passing a generator that results in the
/// same sequence of integer values each time you run your program, that
/// sequence may change when your program is compiled using a different
/// version of Swift.
///
/// - Parameters:
/// - range: The range in which to create a random value.
/// `range` must not be empty.
/// - generator: The random number generator to use when creating the
/// new random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: Range<Self>,
using generator: inout T
) -> Self {
_precondition(
!range.isEmpty,
"Can't get random value with an empty range"
)
// Compute delta, the distance between the lower and upper bounds. This
// value may not representable by the type Bound if Bound is signed, but
// is always representable as Bound.Magnitude.
let delta = Magnitude(truncatingIfNeeded: range.upperBound &- range.lowerBound)
// The mathematical result we want is lowerBound plus a random value in
// 0 ..< delta. We need to be slightly careful about how we do this
// arithmetic; the Bound type cannot generally represent the random value,
// so we use a wrapping addition on Bound.Magnitude. This will often
// overflow, but produces the correct bit pattern for the result when
// converted back to Bound.
return Self(truncatingIfNeeded:
Magnitude(truncatingIfNeeded: range.lowerBound) &+
generator.next(upperBound: delta)
)
}
/// Returns a random value within the specified range.
///
/// Use this method to generate an integer within a specific range. This
/// example creates three new values in the range `1..<100`.
///
/// for _ in 1...3 {
/// print(Int.random(in: 1..<100))
/// }
/// // Prints "53"
/// // Prints "64"
/// // Prints "5"
///
/// This method is equivalent to calling the version that takes a generator,
/// passing in the system's default random generator.
///
/// - Parameter range: The range in which to create a random value.
/// `range` must not be empty.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random(in range: Range<Self>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
/// Returns a random value within the specified range, using the given
/// generator as a source for randomness.
///
/// Use this method to generate an integer within a specific range when you
/// are using a custom random number generator. This example creates three
/// new values in the range `1...100`.
///
/// for _ in 1...3 {
/// print(Int.random(in: 1...100, using: &myGenerator))
/// }
/// // Prints "7"
/// // Prints "44"
/// // Prints "21"
///
/// - Parameters:
/// - range: The range in which to create a random value.
/// - generator: The random number generator to use when creating the
/// new random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: ClosedRange<Self>,
using generator: inout T
) -> Self {
_precondition(
!range.isEmpty,
"Can't get random value with an empty range"
)
// Compute delta, the distance between the lower and upper bounds. This
// value may not representable by the type Bound if Bound is signed, but
// is always representable as Bound.Magnitude.
var delta = Magnitude(truncatingIfNeeded: range.upperBound &- range.lowerBound)
// Subtle edge case: if the range is the whole set of representable values,
// then adding one to delta to account for a closed range will overflow.
// If we used &+ instead, the result would be zero, which isn't helpful,
// so we actually need to handle this case separately.
if delta == Magnitude.max {
return Self(truncatingIfNeeded: generator.next() as Magnitude)
}
// Need to widen delta to account for the right-endpoint of a closed range.
delta += 1
// The mathematical result we want is lowerBound plus a random value in
// 0 ..< delta. We need to be slightly careful about how we do this
// arithmetic; the Bound type cannot generally represent the random value,
// so we use a wrapping addition on Bound.Magnitude. This will often
// overflow, but produces the correct bit pattern for the result when
// converted back to Bound.
return Self(truncatingIfNeeded:
Magnitude(truncatingIfNeeded: range.lowerBound) &+
generator.next(upperBound: delta)
)
}
/// Returns a random value within the specified range.
///
/// Use this method to generate an integer within a specific range. This
/// example creates three new values in the range `1...100`.
///
/// for _ in 1...3 {
/// print(Int.random(in: 1...100))
/// }
/// // Prints "53"
/// // Prints "64"
/// // Prints "5"
///
/// This method is equivalent to calling `random(in:using:)`, passing in the
/// system's default random generator.
///
/// - Parameter range: The range in which to create a random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random(in range: ClosedRange<Self>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
}
//===----------------------------------------------------------------------===//
//===--- Operators on FixedWidthInteger -----------------------------------===//
//===----------------------------------------------------------------------===//
extension FixedWidthInteger {
/// Returns the inverse of the bits set in the argument.
///
/// The bitwise NOT operator (`~`) is a prefix operator that returns a value
/// in which all the bits of its argument are flipped: Bits that are `1` in
/// the argument are `0` in the result, and bits that are `0` in the argument
/// are `1` in the result. This is equivalent to the inverse of a set. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let notX = ~x // 0b11111010
///
/// Performing a bitwise NOT operation on 0 returns a value with every bit
/// set to `1`.
///
/// let allOnes = ~UInt8.min // 0b11111111
///
/// - Complexity: O(1).
@_transparent
public static prefix func ~ (x: Self) -> Self {
return 0 &- x &- 1
}
//===----------------------------------------------------------------------===//
//=== "Smart right shift", supporting overshifts and negative shifts ------===//
//===----------------------------------------------------------------------===//
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right.
///
/// The `>>` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a left shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*. An overshift results in `-1` for a
/// negative value of `lhs` or `0` for a nonnegative value.
/// - Using any other value for `rhs` performs a right shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted right by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x >> 2
/// // y == 7 // 0b00000111
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x >> 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a left shift
/// using `abs(rhs)`.
///
/// let a = x >> -3
/// // a == 240 // 0b11110000
/// let b = x << 3
/// // b == 240 // 0b11110000
///
/// Right shift operations on negative values "fill in" the high bits with
/// ones instead of zeros.
///
/// let q: Int8 = -30 // 0b11100010
/// let r = q >> 2
/// // r == -8 // 0b11111000
///
/// let s = q >> 11
/// // s == -1 // 0b11111111
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func >> <
Other : BinaryInteger
>(lhs: Self, rhs: Other) -> Self {
var lhs = lhs
_nonMaskingRightShiftGeneric(&lhs, rhs)
return lhs
}
@_transparent
@_semantics("optimize.sil.specialize.generic.partial.never")
public static func >>= <
Other : BinaryInteger
>(lhs: inout Self, rhs: Other) {
_nonMaskingRightShiftGeneric(&lhs, rhs)
}
@_transparent
public static func _nonMaskingRightShiftGeneric <
Other : BinaryInteger
>(_ lhs: inout Self, _ rhs: Other) {
let shift = rhs < -Self.bitWidth ? -Self.bitWidth
: rhs > Self.bitWidth ? Self.bitWidth
: Int(rhs)
lhs = _nonMaskingRightShift(lhs, shift)
}
@_transparent
public static func _nonMaskingRightShift(_ lhs: Self, _ rhs: Int) -> Self {
let overshiftR = Self.isSigned ? lhs &>> (Self.bitWidth - 1) : 0
let overshiftL: Self = 0
if _fastPath(rhs >= 0) {
if _fastPath(rhs < Self.bitWidth) {
return lhs &>> Self(truncatingIfNeeded: rhs)
}
return overshiftR
}
if _slowPath(rhs <= -Self.bitWidth) {
return overshiftL
}
return lhs &<< -rhs
}
//===----------------------------------------------------------------------===//
//=== "Smart left shift", supporting overshifts and negative shifts -------===//
//===----------------------------------------------------------------------===//
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left.
///
/// The `<<` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a right shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*, resulting in zero.
/// - Using any other value for `rhs` performs a left shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted left by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x << 2
/// // y == 120 // 0b01111000
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x << 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a right shift
/// with `abs(rhs)`.
///
/// let a = x << -3
/// // a == 3 // 0b00000011
/// let b = x >> 3
/// // b == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func << <
Other : BinaryInteger
>(lhs: Self, rhs: Other) -> Self {
var lhs = lhs
_nonMaskingLeftShiftGeneric(&lhs, rhs)
return lhs
}
@_transparent
@_semantics("optimize.sil.specialize.generic.partial.never")
public static func <<= <
Other : BinaryInteger
>(lhs: inout Self, rhs: Other) {
_nonMaskingLeftShiftGeneric(&lhs, rhs)
}
@_transparent
public static func _nonMaskingLeftShiftGeneric <
Other : BinaryInteger
>(_ lhs: inout Self, _ rhs: Other) {
let shift = rhs < -Self.bitWidth ? -Self.bitWidth
: rhs > Self.bitWidth ? Self.bitWidth
: Int(rhs)
lhs = _nonMaskingLeftShift(lhs, shift)
}
@_transparent
public static func _nonMaskingLeftShift(_ lhs: Self, _ rhs: Int) -> Self {
let overshiftR = Self.isSigned ? lhs &>> (Self.bitWidth - 1) : 0
let overshiftL: Self = 0
if _fastPath(rhs >= 0) {
if _fastPath(rhs < Self.bitWidth) {
return lhs &<< Self(truncatingIfNeeded: rhs)
}
return overshiftL
}
if _slowPath(rhs <= -Self.bitWidth) {
return overshiftR
}
return lhs &>> -rhs
}
}
extension FixedWidthInteger {
@inlinable
@_semantics("optimize.sil.specialize.generic.partial.never")
public // @testable
static func _convert<Source : BinaryFloatingPoint>(
from source: Source
) -> (value: Self?, exact: Bool) {
guard _fastPath(!source.isZero) else { return (0, true) }
guard _fastPath(source.isFinite) else { return (nil, false) }
guard Self.isSigned || source > -1 else { return (nil, false) }
let exponent = source.exponent
if _slowPath(Self.bitWidth <= exponent) { return (nil, false) }
let minBitWidth = source.significandWidth
let isExact = (minBitWidth <= exponent)
let bitPattern = source.significandBitPattern
// `RawSignificand.bitWidth` is not available if `RawSignificand` does not
// conform to `FixedWidthInteger`; we can compute this value as follows if
// `source` is finite:
let bitWidth = minBitWidth &+ bitPattern.trailingZeroBitCount
let shift = exponent - Source.Exponent(bitWidth)
// Use `Self.Magnitude` to prevent sign extension if `shift < 0`.
let shiftedBitPattern = Self.Magnitude.bitWidth > bitWidth
? Self.Magnitude(truncatingIfNeeded: bitPattern) << shift
: Self.Magnitude(truncatingIfNeeded: bitPattern << shift)
if _slowPath(Self.isSigned && Self.bitWidth &- 1 == exponent) {
return source < 0 && shiftedBitPattern == 0
? (Self.min, isExact)
: (nil, false)
}
let magnitude = ((1 as Self.Magnitude) << exponent) | shiftedBitPattern
return (
Self.isSigned && source < 0 ? 0 &- Self(magnitude) : Self(magnitude),
isExact)
}
/// Creates an integer from the given floating-point value, rounding toward
/// zero. Any fractional part of the value passed as `source` is removed.
///
/// let x = Int(21.5)
/// // x == 21
/// let y = Int(-21.5)
/// // y == -21
///
/// If `source` is outside the bounds of this type after rounding toward
/// zero, a runtime error may occur.
///
/// let z = UInt(-21.5)
/// // Error: ...outside the representable range
///
/// - Parameter source: A floating-point value to convert to an integer.
/// `source` must be representable in this type after rounding toward
/// zero.
@inlinable
@_semantics("optimize.sil.specialize.generic.partial.never")
@inline(__always)
public init<T : BinaryFloatingPoint>(_ source: T) {
guard let value = Self._convert(from: source).value else {
fatalError("""
\(T.self) value cannot be converted to \(Self.self) because it is \
outside the representable range
""")
}
self = value
}
/// Creates an integer from the given floating-point value, if it can be
/// represented exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `21.0`, while the attempt to initialize the
/// constant `y` from `21.5` fails:
///
/// let x = Int(exactly: 21.0)
/// // x == Optional(21)
/// let y = Int(exactly: 21.5)
/// // y == nil
///
/// - Parameter source: A floating-point value to convert to an integer.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable
public init?<T : BinaryFloatingPoint>(exactly source: T) {
let (temporary, exact) = Self._convert(from: source)
guard exact, let value = temporary else {
return nil
}
self = value
}
/// Creates a new instance with the representable value that's closest to the
/// given integer.
///
/// If the value passed as `source` is greater than the maximum representable
/// value in this type, the result is the type's `max` value. If `source` is
/// less than the smallest representable value in this type, the result is
/// the type's `min` value.
///
/// In this example, `x` is initialized as an `Int8` instance by clamping
/// `500` to the range `-128...127`, and `y` is initialized as a `UInt`
/// instance by clamping `-500` to the range `0...UInt.max`.
///
/// let x = Int8(clamping: 500)
/// // x == 127
/// // x == Int8.max
///
/// let y = UInt(clamping: -500)
/// // y == 0
///
/// - Parameter source: An integer to convert to this type.
@inlinable
@_semantics("optimize.sil.specialize.generic.partial.never")
public init<Other : BinaryInteger>(clamping source: Other) {
if _slowPath(source < Self.min) {
self = Self.min
}
else if _slowPath(source > Self.max) {
self = Self.max
}
else { self = Self(truncatingIfNeeded: source) }
}
/// Creates a new instance from the bit pattern of the given instance by
/// truncating or sign-extending if needed to fit this type.
///
/// When the bit width of `T` (the type of `source`) is equal to or greater
/// than this type's bit width, the result is the truncated
/// least-significant bits of `source`. For example, when converting a
/// 16-bit value to an 8-bit type, only the lower 8 bits of `source` are
/// used.
///
/// let p: Int16 = -500
/// // 'p' has a binary representation of 11111110_00001100
/// let q = Int8(truncatingIfNeeded: p)
/// // q == 12
/// // 'q' has a binary representation of 00001100
///
/// When the bit width of `T` is less than this type's bit width, the result
/// is *sign-extended* to fill the remaining bits. That is, if `source` is
/// negative, the result is padded with ones; otherwise, the result is
/// padded with zeros.
///
/// let u: Int8 = 21
/// // 'u' has a binary representation of 00010101
/// let v = Int16(truncatingIfNeeded: u)
/// // v == 21
/// // 'v' has a binary representation of 00000000_00010101
///
/// let w: Int8 = -21
/// // 'w' has a binary representation of 11101011
/// let x = Int16(truncatingIfNeeded: w)
/// // x == -21
/// // 'x' has a binary representation of 11111111_11101011
/// let y = UInt16(truncatingIfNeeded: w)
/// // y == 65515
/// // 'y' has a binary representation of 11111111_11101011
///
/// - Parameter source: An integer to convert to this type.
@inlinable // FIXME(inline-always)
@inline(__always)
public init<T : BinaryInteger>(truncatingIfNeeded source: T) {
if Self.bitWidth <= Int.bitWidth {
self = Self(_truncatingBits: source._lowWord)
}
else {
let neg = source < (0 as T)
var result: Self = neg ? ~0 : 0
var shift: Self = 0
let width = Self(_truncatingBits: Self.bitWidth._lowWord)
for word in source.words {
guard shift < width else { break }
// Masking shift is OK here because we have already ensured
// that shift < Self.bitWidth. Not masking results in
// infinite recursion.
result ^= Self(_truncatingBits: neg ? ~word : word) &<< shift
shift += Self(_truncatingBits: Int.bitWidth._lowWord)
}
self = result
}
}
@_transparent
public // transparent
static var _highBitIndex: Self {
return Self.init(_truncatingBits: UInt(Self.bitWidth._value) &- 1)
}
/// Returns the sum of the two given values, wrapping the result in case of
/// any overflow.
///
/// The overflow addition operator (`&+`) discards any bits that overflow the
/// fixed width of the integer type. In the following example, the sum of
/// `100` and `121` is greater than the maximum representable `Int8` value,
/// so the result is the partial value after discarding the overflowing
/// bits.
///
/// let x: Int8 = 10 &+ 21
/// // x == 31
/// let y: Int8 = 100 &+ 121
/// // y == -35 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
@_transparent
public static func &+ (lhs: Self, rhs: Self) -> Self {
return lhs.addingReportingOverflow(rhs).partialValue
}
/// Adds two values and stores the result in the left-hand-side variable,
/// wrapping any overflow.
///
/// The masking addition assignment operator (`&+=`) silently wraps any
/// overflow that occurs during the operation. In the following example, the
/// sum of `100` and `121` is greater than the maximum representable `Int8`
/// value, so the result is the partial value after discarding the
/// overflowing bits.
///
/// var x: Int8 = 10
/// x &+= 21
/// // x == 31
/// var y: Int8 = 100
/// y &+= 121
/// // y == -35 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
@_transparent
public static func &+= (lhs: inout Self, rhs: Self) {
lhs = lhs &+ rhs
}
/// Returns the difference of the two given values, wrapping the result in
/// case of any overflow.
///
/// The overflow subtraction operator (`&-`) discards any bits that overflow
/// the fixed width of the integer type. In the following example, the
/// difference of `10` and `21` is less than zero, the minimum representable
/// `UInt` value, so the result is the partial value after discarding the
/// overflowing bits.
///
/// let x: UInt8 = 21 &- 10
/// // x == 11
/// let y: UInt8 = 10 &- 21
/// // y == 245 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
@_transparent
public static func &- (lhs: Self, rhs: Self) -> Self {
return lhs.subtractingReportingOverflow(rhs).partialValue
}
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable, wrapping any overflow.
///
/// The masking subtraction assignment operator (`&-=`) silently wraps any
/// overflow that occurs during the operation. In the following example, the
/// difference of `10` and `21` is less than zero, the minimum representable
/// `UInt` value, so the result is the result is the partial value after
/// discarding the overflowing bits.
///
/// var x: Int8 = 21
/// x &-= 10
/// // x == 11
/// var y: UInt8 = 10
/// y &-= 21
/// // y == 245 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
@_transparent
public static func &-= (lhs: inout Self, rhs: Self) {
lhs = lhs &- rhs
}
/// Returns the product of the two given values, wrapping the result in case
/// of any overflow.
///
/// The overflow multiplication operator (`&*`) discards any bits that
/// overflow the fixed width of the integer type. In the following example,
/// the product of `10` and `50` is greater than the maximum representable
/// `Int8` value, so the result is the partial value after discarding the
/// overflowing bits.
///
/// let x: Int8 = 10 &* 5
/// // x == 50
/// let y: Int8 = 10 &* 50
/// // y == -12 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
@_transparent
public static func &* (lhs: Self, rhs: Self) -> Self {
return lhs.multipliedReportingOverflow(by: rhs).partialValue
}
/// Multiplies two values and stores the result in the left-hand-side
/// variable, wrapping any overflow.
///
/// The masking multiplication assignment operator (`&*=`) silently wraps
/// any overflow that occurs during the operation. In the following example,
/// the product of `10` and `50` is greater than the maximum representable
/// `Int8` value, so the result is the partial value after discarding the
/// overflowing bits.
///
/// var x: Int8 = 10
/// x &*= 5
/// // x == 50
/// var y: Int8 = 10
/// y &*= 50
/// // y == -12 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
@_transparent
public static func &*= (lhs: inout Self, rhs: Self) {
lhs = lhs &* rhs
}
}
extension FixedWidthInteger {
@inlinable
public static func _random<R: RandomNumberGenerator>(
using generator: inout R
) -> Self {
if bitWidth <= UInt64.bitWidth {
return Self(truncatingIfNeeded: generator.next() as UInt64)
}
let (quotient, remainder) = bitWidth.quotientAndRemainder(
dividingBy: UInt64.bitWidth
)
var tmp: Self = 0
for i in 0 ..< quotient + remainder.signum() {
let next: UInt64 = generator.next()
tmp += Self(truncatingIfNeeded: next) &<< (UInt64.bitWidth * i)
}
return tmp
}
}
//===----------------------------------------------------------------------===//
//===--- UnsignedInteger --------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// An integer type that can represent only nonnegative values.
public protocol UnsignedInteger : BinaryInteger { }
extension UnsignedInteger {
/// The magnitude of this value.
///
/// Every unsigned integer is its own magnitude, so for any value `x`,
/// `x == x.magnitude`.
///
/// The global `abs(_:)` function provides more familiar syntax when you need
/// to find an absolute value. In addition, because `abs(_:)` always returns
/// a value of the same type, even in a generic context, using the function
/// instead of the `magnitude` property is encouraged.
@inlinable // FIXME(inline-always)
public var magnitude: Self {
@inline(__always)
get { return self }
}
/// A Boolean value indicating whether this type is a signed integer type.
///
/// This property is always `false` for unsigned integer types.
@inlinable // FIXME(inline-always)
public static var isSigned: Bool {
@inline(__always)
get { return false }
}
}
extension UnsignedInteger where Self : FixedWidthInteger {
/// Creates a new instance from the given integer.
///
/// Use this initializer to convert from another integer type when you know
/// the value is within the bounds of this type. Passing a value that can't
/// be represented in this type results in a runtime error.
///
/// In the following example, the constant `y` is successfully created from
/// `x`, an `Int` instance with a value of `100`. Because the `Int8` type
/// can represent `127` at maximum, the attempt to create `z` with a value
/// of `1000` results in a runtime error.
///
/// let x = 100
/// let y = Int8(x)
/// // y == 100
/// let z = Int8(x * 10)
/// // Error: Not enough bits to represent the given value
///
/// - Parameter source: A value to convert to this type of integer. The value
/// passed as `source` must be representable in this type.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable // FIXME(inline-always)
@inline(__always)
public init<T : BinaryInteger>(_ source: T) {
// This check is potentially removable by the optimizer
if T.isSigned {
_precondition(source >= (0 as T), "Negative value is not representable")
}
// This check is potentially removable by the optimizer
if source.bitWidth >= Self.bitWidth {
_precondition(source <= Self.max,
"Not enough bits to represent the passed value")
}
self.init(truncatingIfNeeded: source)
}
/// Creates a new instance from the given integer, if it can be represented
/// exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `100`, while the attempt to initialize the
/// constant `y` from `1_000` fails because the `Int8` type can represent
/// `127` at maximum:
///
/// let x = Int8(exactly: 100)
/// // x == Optional(100)
/// let y = Int8(exactly: 1_000)
/// // y == nil
///
/// - Parameter source: A value to convert to this type of integer.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable // FIXME(inline-always)
@inline(__always)
public init?<T : BinaryInteger>(exactly source: T) {
// This check is potentially removable by the optimizer
if T.isSigned && source < (0 as T) {
return nil
}
// The width check can be eliminated by the optimizer
if source.bitWidth >= Self.bitWidth &&
source > Self.max {
return nil
}
self.init(truncatingIfNeeded: source)
}
/// The maximum representable integer in this type.
///
/// For unsigned integer types, this value is `(2 ** bitWidth) - 1`, where
/// `**` is exponentiation.
@_transparent
public static var max: Self { return ~0 }
/// The minimum representable integer in this type.
///
/// For unsigned integer types, this value is always `0`.
@_transparent
public static var min: Self { return 0 }
}
//===----------------------------------------------------------------------===//
//===--- SignedInteger ----------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// An integer type that can represent both positive and negative values.
public protocol SignedInteger : BinaryInteger, SignedNumeric {
// These requirements are for the source code compatibility with Swift 3
static func _maskingAdd(_ lhs: Self, _ rhs: Self) -> Self
static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self
}
extension SignedInteger {
/// A Boolean value indicating whether this type is a signed integer type.
///
/// This property is always `true` for signed integer types.
@inlinable // FIXME(inline-always)
public static var isSigned: Bool {
@inline(__always)
get { return true }
}
}
extension SignedInteger where Self : FixedWidthInteger {
/// Creates a new instance from the given integer.
///
/// Use this initializer to convert from another integer type when you know
/// the value is within the bounds of this type. Passing a value that can't
/// be represented in this type results in a runtime error.
///
/// In the following example, the constant `y` is successfully created from
/// `x`, an `Int` instance with a value of `100`. Because the `Int8` type
/// can represent `127` at maximum, the attempt to create `z` with a value
/// of `1000` results in a runtime error.
///
/// let x = 100
/// let y = Int8(x)
/// // y == 100
/// let z = Int8(x * 10)
/// // Error: Not enough bits to represent the given value
///
/// - Parameter source: A value to convert to this type of integer. The value
/// passed as `source` must be representable in this type.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable // FIXME(inline-always)
@inline(__always)
public init<T : BinaryInteger>(_ source: T) {
// This check is potentially removable by the optimizer
if T.isSigned && source.bitWidth > Self.bitWidth {
_precondition(source >= Self.min,
"Not enough bits to represent a signed value")
}
// This check is potentially removable by the optimizer
if (source.bitWidth > Self.bitWidth) ||
(source.bitWidth == Self.bitWidth && !T.isSigned) {
_precondition(source <= Self.max,
"Not enough bits to represent the passed value")
}
self.init(truncatingIfNeeded: source)
}
/// Creates a new instance from the given integer, if it can be represented
/// exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `100`, while the attempt to initialize the
/// constant `y` from `1_000` fails because the `Int8` type can represent
/// `127` at maximum:
///
/// let x = Int8(exactly: 100)
/// // x == Optional(100)
/// let y = Int8(exactly: 1_000)
/// // y == nil
///
/// - Parameter source: A value to convert to this type of integer.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable // FIXME(inline-always)
@inline(__always)
public init?<T : BinaryInteger>(exactly source: T) {
// This check is potentially removable by the optimizer
if T.isSigned && source.bitWidth > Self.bitWidth && source < Self.min {
return nil
}
// The width check can be eliminated by the optimizer
if (source.bitWidth > Self.bitWidth ||
(source.bitWidth == Self.bitWidth && !T.isSigned)) &&
source > Self.max {
return nil
}
self.init(truncatingIfNeeded: source)
}
/// The maximum representable integer in this type.
///
/// For signed integer types, this value is `(2 ** (bitWidth - 1)) - 1`,
/// where `**` is exponentiation.
@_transparent
public static var max: Self { return ~min }
/// The minimum representable integer in this type.
///
/// For signed integer types, this value is `-(2 ** (bitWidth - 1))`, where
/// `**` is exponentiation.
@_transparent
public static var min: Self {
return (-1 as Self) &<< Self._highBitIndex
}
@inlinable
public func isMultiple(of other: Self) -> Bool {
// Nothing but zero is a multiple of zero.
if other == 0 { return self == 0 }
// Special case to avoid overflow on .min / -1 for signed types.
if other == -1 { return true }
// Having handled those special cases, this is safe.
return self % other == 0
}
}
/// Returns the given integer as the equivalent value in a different integer
/// type.
///
/// The `numericCast(_:)` function traps on overflow in `-O` and `-Onone`
/// builds.
///
/// You can use `numericCast(_:)` to convert a value when the destination type
/// can be inferred from the context. In the following example, the
/// `random(in:)` function uses `numericCast(_:)` twice to convert the
/// argument and return value of the `arc4random_uniform(_:)` function to the
/// appropriate type.
///
/// func random(in range: Range<Int>) -> Int {
/// return numericCast(arc4random_uniform(numericCast(range.count)))
/// + range.lowerBound
/// }
///
/// let number = random(in: -10...<10)
/// // number == -3, perhaps
///
/// - Parameter x: The integer to convert, and instance of type `T`.
/// - Returns: The value of `x` converted to type `U`.
@inlinable
public func numericCast<T : BinaryInteger, U : BinaryInteger>(_ x: T) -> U {
return U(x)
}
// FIXME(integers): Absence of &+ causes ambiguity in the code like the
// following:
// func f<T : SignedInteger>(_ x: T, _ y: T) {
// var _ = (x &+ (y - 1)) < x
// }
// Compiler output:
// error: ambiguous reference to member '-'
// var _ = (x &+ (y - 1)) < x
// ^
extension SignedInteger {
@_transparent
public static func _maskingAdd(_ lhs: Self, _ rhs: Self) -> Self {
fatalError("Should be overridden in a more specific type")
}
@_transparent
public static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self {
fatalError("Should be overridden in a more specific type")
}
}
extension SignedInteger where Self : FixedWidthInteger {
// This overload is supposed to break the ambiguity between the
// implementations on SignedInteger and FixedWidthInteger
@_transparent
public static func &+ (lhs: Self, rhs: Self) -> Self {
return _maskingAdd(lhs, rhs)
}
@_transparent
public static func _maskingAdd(_ lhs: Self, _ rhs: Self) -> Self {
return lhs.addingReportingOverflow(rhs).partialValue
}
// This overload is supposed to break the ambiguity between the
// implementations on SignedInteger and FixedWidthInteger
@_transparent
public static func &- (lhs: Self, rhs: Self) -> Self {
return _maskingSubtract(lhs, rhs)
}
@_transparent
public static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self {
return lhs.subtractingReportingOverflow(rhs).partialValue
}
}
| apache-2.0 | 84fbd1e79bfa7fefe6f129af572d589f | 37.00304 | 93 | 0.592196 | 4.076462 | false | false | false | false |
xedin/swift | test/Interpreter/casts.swift | 4 | 2637 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import StdlibUnittest
import Foundation
// Make sure at the end of the file we run the tests.
defer { runAllTests() }
protocol P : class { }
protocol C : class { }
class Foo : NSObject {}
var Casts = TestSuite("Casts")
@inline(never)
func castit<ObjectType>(_ o: NSObject?, _ t: ObjectType.Type) -> ObjectType? {
return o as? ObjectType
}
@inline(never)
func castitExistential<ObjectType>(_ o: C?, _ t: ObjectType.Type) -> ObjectType? {
return o as? ObjectType
}
Casts.test("cast optional<nsobject> to protocol") {
if let obj = castit(nil, P.self) {
print("fail")
expectUnreachable()
} else {
print("success")
}
}
Casts.test("cast optional<nsobject> to protocol meta") {
if let obj = castit(nil, P.Type.self) {
print("fail")
expectUnreachable()
} else {
print("success")
}
}
Casts.test("cast optional<protocol> to protocol") {
if let obj = castitExistential(nil, P.self) {
print("fail")
expectUnreachable()
} else {
print("success")
}
}
Casts.test("cast optional<protocol> to class") {
if let obj = castitExistential(nil, Foo.self) {
print("fail")
expectUnreachable()
} else {
print("success")
}
}
Casts.test("cast optional<protocol> to protocol meta") {
if let obj = castitExistential(nil, P.Type.self) {
expectUnreachable()
print("fail")
} else {
print("success")
}
}
Casts.test("cast optional<protocol> to class meta") {
if let obj = castitExistential(nil, Foo.Type.self) {
expectUnreachable()
print("fail")
} else {
print("success")
}
}
@objc public class ParentType : NSObject {
var a = LifetimeTracked(0)
}
public class ChildType : ParentType {
}
struct SwiftStructWrapper {
var a = LifetimeTracked(0)
}
extension SwiftStructWrapper : _ObjectiveCBridgeable {
typealias _ObjectiveCType = ParentType
func _bridgeToObjectiveC() -> _ObjectiveCType {
return ParentType()
}
static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
) {}
@discardableResult
static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
) -> Bool { return false }
@_effects(readonly)
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self {
return SwiftStructWrapper()
}
}
Casts.test("testConditionalBridgedCastFromSwiftToNSObjectDerivedClass") {
autoreleasepool {
let s = SwiftStructWrapper()
let z = s as? ChildType
print(z)
}
expectEqual(0, LifetimeTracked.instances)
}
| apache-2.0 | 3a848a08d7f50ac85962b58237fe947a | 20.266129 | 82 | 0.676526 | 3.827286 | false | true | false | false |
fabiomassimo/eidolon | KioskTests/App/SwiftExtensionsTests.swift | 1 | 658 | import Quick
import Nimble
import Kiosk
import ReactiveCocoa
class SwiftExtensionsTests: QuickSpec {
override func spec() {
describe("String") {
it("converts to UInt") {
let input = "4"
expect(input.toUInt()) == 4
}
it("returns nil if no conversion is available") {
let input = "not a number"
expect(input.toUInt()).to( beNil() )
}
it("uses a default if no conversion is available") {
let input = "not a number"
expect(input.toUInt(defaultValue: 4)) == 4
}
}
}
}
| mit | a7fc0fd1d6e3925ee143ba4028b34a2b | 25.32 | 64 | 0.49696 | 4.80292 | false | false | false | false |
apple/swift-corelibs-xctest | Sources/XCTest/Public/Asynchronous/XCTNSPredicateExpectation.swift | 1 | 4927 | // 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//
// XCTNSPredicateExpectation.swift
//
/// Expectation subclass for waiting on a condition defined by an NSPredicate and an optional object.
open class XCTNSPredicateExpectation: XCTestExpectation {
/// A closure to be invoked whenever evaluating the predicate against the object returns true.
///
/// - Returns: `true` if the expectation should be fulfilled, `false` if it should not.
///
/// - SeeAlso: `XCTNSPredicateExpectation.handler`
public typealias Handler = () -> Bool
private let queue = DispatchQueue(label: "org.swift.XCTest.XCTNSPredicateExpectation")
/// The predicate used by the expectation.
open private(set) var predicate: NSPredicate
/// The object against which the predicate is evaluated, if any. Default is nil.
open private(set) var object: Any?
private var _handler: Handler?
/// Handler called when evaluating the predicate against the object returns true. If the handler is not
/// provided, the first successful evaluation will fulfill the expectation. If the handler provided, the
/// handler will be queried each time the notification is received to determine whether the expectation
/// should be fulfilled or not.
open var handler: Handler? {
get {
return queue.sync { _handler }
}
set {
dispatchPrecondition(condition: .notOnQueue(queue))
queue.async { self._handler = newValue }
}
}
private let runLoop = RunLoop.current
private var timer: Timer?
private let evaluationInterval = 0.01
/// Initializes an expectation that waits for a predicate to evaluate as true with an optionally specified object.
///
/// - Parameter predicate: The predicate to evaluate.
/// - Parameter object: An optional object to evaluate `predicate` with. Default is nil.
/// - Parameter file: The file name to use in the error message if
/// expectations are not met before the wait timeout. Default is the file
/// containing the call to this method. It is rare to provide this
/// parameter when calling this method.
/// - Parameter line: The line number to use in the error message if the
/// expectations are not met before the wait timeout. Default is the line
/// number of the call to this method in the calling file. It is rare to
/// provide this parameter when calling this method.
public init(predicate: NSPredicate, object: Any? = nil, file: StaticString = #file, line: Int = #line) {
self.predicate = predicate
self.object = object
let description = "Expect predicate `\(predicate)`" + (object.map { " for object \($0)" } ?? "")
super.init(description: description, file: file, line: line)
}
deinit {
assert(timer == nil, "timer should be nil, indicates failure to call cleanUp() internally")
}
override func didBeginWaiting() {
runLoop.perform {
if self.shouldFulfill() {
self.fulfill()
} else {
self.startPolling()
}
}
}
private func startPolling() {
let timer = Timer(timeInterval: evaluationInterval, repeats: true) { [weak self] timer in
guard let self = self else {
timer.invalidate()
return
}
if self.shouldFulfill() {
self.fulfill()
timer.invalidate()
}
}
runLoop.add(timer, forMode: .default)
queue.async {
self.timer = timer
}
}
private func shouldFulfill() -> Bool {
if predicate.evaluate(with: object) {
if let handler = handler {
if handler() {
return true
}
// We do not fulfill or invalidate the timer if the handler returns
// false. The object is still re-evaluated until timeout.
} else {
return true
}
}
return false
}
override func cleanUp() {
queue.sync {
if let timer = timer {
timer.invalidate()
self.timer = nil
}
}
}
}
/// A closure to be invoked whenever evaluating the predicate against the object returns true.
///
/// - SeeAlso: `XCTNSPredicateExpectation.handler`
@available(*, deprecated, renamed: "XCTNSPredicateExpectation.Handler")
public typealias XCPredicateExpectationHandler = XCTNSPredicateExpectation.Handler
| apache-2.0 | 228075196e536ff01f9732f1e6d48516 | 35.496296 | 118 | 0.628374 | 4.917166 | false | false | false | false |
natecook1000/swift | test/Compatibility/attr_usableFromInline_swift4.swift | 2 | 3351 | // RUN: %target-typecheck-verify-swift -swift-version 4
// RUN: %target-typecheck-verify-swift -enable-testing -swift-version 4
@usableFromInline private func privateVersioned() {}
// expected-error@-1 {{'@usableFromInline' attribute can only be applied to internal declarations, but 'privateVersioned()' is private}}
@usableFromInline fileprivate func fileprivateVersioned() {}
// expected-error@-1 {{'@usableFromInline' attribute can only be applied to internal declarations, but 'fileprivateVersioned()' is fileprivate}}
@usableFromInline internal func internalVersioned() {}
// OK
@usableFromInline func implicitInternalVersioned() {}
// OK
@usableFromInline public func publicVersioned() {}
// expected-error@-1 {{'@usableFromInline' attribute can only be applied to internal declarations, but 'publicVersioned()' is public}}
internal class InternalClass {
@usableFromInline public func publicVersioned() {}
// expected-error@-1 {{'@usableFromInline' attribute can only be applied to internal declarations, but 'publicVersioned()' is public}}
}
fileprivate class filePrivateClass {
@usableFromInline internal func internalVersioned() {}
}
@usableFromInline struct S {
var x: Int
@usableFromInline var y: Int
}
@usableFromInline extension S {}
// expected-error@-1 {{'@usableFromInline' attribute cannot be applied to this declaration}}
@usableFromInline
protocol VersionedProtocol {
associatedtype T
func requirement() -> T
public func publicRequirement() -> T
// expected-error@-1 {{'public' modifier cannot be used in protocols}}
// expected-note@-2 {{protocol requirements implicitly have the same access as the protocol itself}}
@usableFromInline func versionedRequirement() -> T
// expected-error@-1 {{'@usableFromInline' attribute cannot be used in protocols}}
}
// Derived conformances had issues with @usableFromInline - rdar://problem/34342955
@usableFromInline
internal enum EqEnum {
case foo
}
@usableFromInline
internal enum RawEnum : Int {
case foo = 0
}
@inlinable
public func usesEqEnum() -> Bool {
_ = (EqEnum.foo == .foo)
_ = EqEnum.foo.hashValue
_ = RawEnum.foo.rawValue
_ = RawEnum(rawValue: 0)
}
internal struct InternalStruct {}
@usableFromInline var globalInferred = InternalStruct()
@usableFromInline var globalDeclared: InternalStruct = InternalStruct()
@usableFromInline typealias BadAlias = InternalStruct
protocol InternalProtocol {
associatedtype T
}
@usableFromInline
struct BadStruct<T, U>
where T : InternalProtocol,
T : Sequence,
T.Element == InternalStruct {
@usableFromInline init(x: InternalStruct) {}
@usableFromInline func foo(x: InternalStruct) -> InternalClass {}
@usableFromInline var propertyInferred = InternalStruct()
@usableFromInline var propertyDeclared: InternalStruct = InternalStruct()
@usableFromInline subscript(x: InternalStruct) -> Int {
get {}
set {}
}
@usableFromInline subscript(x: Int) -> InternalStruct {
get {}
set {}
}
}
@usableFromInline
protocol BadProtocol : InternalProtocol {
associatedtype X : InternalProtocol
associatedtype Y = InternalStruct
}
@usableFromInline
protocol AnotherBadProtocol where Self.T : InternalProtocol {
associatedtype T
}
@usableFromInline
enum BadEnum {
case bad(InternalStruct)
}
@usableFromInline
class BadClass : InternalClass {}
| apache-2.0 | e99970b49ae8171ba61a9fe43d147aac | 26.243902 | 144 | 0.750821 | 4.603022 | false | false | false | false |
tinypass/piano-sdk-for-ios | Samples/PianoMobile/Sources/Services/TokenService.swift | 1 | 1726 | import PianoOAuth
class TokenService: ObservableObject, PianoIDDelegate {
private let logger: Logger
@Published private(set) var initialized = false
@Published private(set) var token: PianoIDToken?
init(logger: Logger) {
self.logger = logger
/// Set Piano ID settings
PianoID.shared.endpointUrl = Settings.endpoint.api
PianoID.shared.aid = Settings.aid
PianoID.shared.delegate = self
token = PianoID.shared.currentToken
request { _ in
DispatchQueue.main.async {
self.initialized = true
}
}
}
func request(completion: @escaping (PianoIDToken?) -> Void) {
if let t = token {
if t.isExpired {
/// Refresh token if expired
PianoID.shared.refreshToken(t.refreshToken) { token, error in
if let t = token {
self.token = t
completion(t)
return
}
self.logger.error(error, or: "Invalid result")
completion(nil)
}
} else {
completion(t)
}
return
}
completion(nil)
}
/// Sign In callback
func signIn(result: PianoIDSignInResult!, withError error: Error!) {
if let r = result {
token = r.token
} else {
logger.error(error, or: "Invalid result")
}
}
/// Sign Out callback
func signOut(withError error: Error!) {
logger.error(error, or: "Invalid result")
token = nil
}
/// Cancel callback
func cancel() {
}
}
| apache-2.0 | 16b6d7318080efcc9279712dfb0c2cb4 | 24.761194 | 77 | 0.510429 | 4.848315 | false | false | false | false |
fgengine/quickly | Quickly/Table/QTableView.swift | 1 | 10597 | //
// Quickly
//
open class QTableStyleSheet : IQStyleSheet {
public var backgroundColor: UIColor?
public var isDirectionalLockEnabled: Bool
public var bounces: Bool
public var alwaysBounceVertical: Bool
public var alwaysBounceHorizontal: Bool
public var isPagingEnabled: Bool
public var isScrollEnabled: Bool
public var showsVerticalScrollIndicator: Bool
public var showsHorizontalScrollIndicator: Bool
public var scrollIndicatorStyle: UIScrollView.IndicatorStyle
public var decelerationRate: UIScrollView.DecelerationRate
public var indexDisplayMode: UIScrollView.IndexDisplayMode
public var allowsSelection: Bool
public var allowsSelectionDuringEditing: Bool
public var allowsMultipleSelection: Bool
public var allowsMultipleSelectionDuringEditing: Bool
public var separatorStyle: UITableViewCell.SeparatorStyle
public var separatorColor: UIColor?
public var separatorEffect: UIVisualEffect?
public var remembersLastFocusedIndexPath: Bool
public init(
backgroundColor: UIColor,
isDirectionalLockEnabled: Bool = false,
bounces: Bool = true,
alwaysBounceVertical: Bool = false,
alwaysBounceHorizontal: Bool = false,
isPagingEnabled: Bool = false,
isScrollEnabled: Bool = true,
showsVerticalScrollIndicator: Bool = true,
showsHorizontalScrollIndicator: Bool = true,
scrollIndicatorStyle: UIScrollView.IndicatorStyle = .default,
decelerationRate: UIScrollView.DecelerationRate = .normal,
indexDisplayMode: UIScrollView.IndexDisplayMode = .automatic,
allowsSelection: Bool = true,
allowsSelectionDuringEditing: Bool = false,
allowsMultipleSelection: Bool = false,
allowsMultipleSelectionDuringEditing: Bool = false,
separatorStyle: UITableViewCell.SeparatorStyle = .singleLine,
separatorColor: UIColor? = .gray,
separatorEffect: UIVisualEffect? = nil,
remembersLastFocusedIndexPath: Bool = false
) {
self.backgroundColor = backgroundColor
self.isDirectionalLockEnabled = isDirectionalLockEnabled
self.bounces = bounces
self.alwaysBounceVertical = alwaysBounceVertical
self.alwaysBounceHorizontal = alwaysBounceHorizontal
self.isPagingEnabled = isPagingEnabled
self.isScrollEnabled = isScrollEnabled
self.showsVerticalScrollIndicator = showsVerticalScrollIndicator
self.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator
self.scrollIndicatorStyle = scrollIndicatorStyle
self.decelerationRate = decelerationRate
self.indexDisplayMode = indexDisplayMode
self.allowsSelection = allowsSelection
self.allowsSelectionDuringEditing = allowsSelectionDuringEditing
self.allowsMultipleSelection = allowsMultipleSelection
self.allowsMultipleSelectionDuringEditing = allowsMultipleSelectionDuringEditing
self.separatorStyle = separatorStyle
self.separatorColor = separatorColor
self.separatorEffect = separatorEffect
self.remembersLastFocusedIndexPath = remembersLastFocusedIndexPath
}
public init(_ styleSheet: QTableStyleSheet) {
self.backgroundColor = styleSheet.backgroundColor
self.isDirectionalLockEnabled = styleSheet.isDirectionalLockEnabled
self.bounces = styleSheet.bounces
self.alwaysBounceVertical = styleSheet.alwaysBounceVertical
self.alwaysBounceHorizontal = styleSheet.alwaysBounceHorizontal
self.isPagingEnabled = styleSheet.isPagingEnabled
self.isScrollEnabled = styleSheet.isScrollEnabled
self.showsVerticalScrollIndicator = styleSheet.showsVerticalScrollIndicator
self.showsHorizontalScrollIndicator = styleSheet.showsHorizontalScrollIndicator
self.scrollIndicatorStyle = styleSheet.scrollIndicatorStyle
self.decelerationRate = styleSheet.decelerationRate
self.indexDisplayMode = styleSheet.indexDisplayMode
self.allowsSelection = styleSheet.allowsSelection
self.allowsSelectionDuringEditing = styleSheet.allowsSelectionDuringEditing
self.allowsMultipleSelection = styleSheet.allowsMultipleSelection
self.allowsMultipleSelectionDuringEditing = styleSheet.allowsMultipleSelectionDuringEditing
self.separatorStyle = styleSheet.separatorStyle
self.separatorColor = styleSheet.separatorColor
self.separatorEffect = styleSheet.separatorEffect
self.remembersLastFocusedIndexPath = styleSheet.remembersLastFocusedIndexPath
}
}
open class QTableView : UITableView, IQView {
open var stretchFooterView: UIView? {
willSet {
if let view = self.stretchFooterView { view.removeFromSuperview() }
}
didSet {
if let view = self.stretchFooterView { self.addSubview(view) }
}
}
public var tableController: IQTableController? {
willSet {
self.delegate = nil
self.dataSource = nil
if let tableController = self.tableController {
tableController.tableView = nil
}
}
didSet {
self.delegate = self.tableController
self.dataSource = self.tableController
if let tableController = self.tableController {
tableController.tableView = self
}
}
}
open override var refreshControl: UIRefreshControl? {
set(value) {
if #available(iOS 10, *) {
super.refreshControl = value
} else {
self._legacyRefreshControl = value
}
}
get {
if #available(iOS 10, *) {
return super.refreshControl
} else {
return self._legacyRefreshControl
}
}
}
open var contentLeftInset: CGFloat = 0
open var contentRightInset: CGFloat = 0
private var _legacyRefreshControl: UIRefreshControl? {
willSet {
guard let refreshControl = self._legacyRefreshControl else { return }
self.addSubview(refreshControl)
}
didSet {
guard let refreshControl = self._legacyRefreshControl else { return }
refreshControl.removeFromSuperview()
}
}
public override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
self.setup()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
self.setup()
}
open func setup() {
self.backgroundColor = UIColor.clear
if #available(iOS 11.0, *) {
self.contentInsetAdjustmentBehavior = .never
}
if #available(iOS 13.0, *) {
self.automaticallyAdjustsScrollIndicatorInsets = false
}
if #available(iOS 15.0, *) {
self.sectionHeaderTopPadding = 0.0
}
}
open override func setNeedsLayout() {
super.setNeedsLayout()
}
open override func layoutSubviews() {
super.layoutSubviews()
if let view = self.stretchFooterView {
let selfFrame = self.frame
let contentOffset = self.contentOffset.y
let contentHeight = self.contentSize.height
var contentInset: UIEdgeInsets
if #available(iOS 11.0, *) {
contentInset = self.adjustedContentInset
} else {
contentInset = self.contentInset
}
let fullContentHeight = contentInset.top + contentHeight
let contentBottomEdge = (contentOffset + contentInset.top) + selfFrame.height
view.frame = CGRect(
x: 0,
y: contentHeight,
width: selfFrame.size.width,
height: max(contentBottomEdge - fullContentHeight, 0)
)
}
}
public func apply(_ styleSheet: QTableStyleSheet) {
self.backgroundColor = styleSheet.backgroundColor
self.isDirectionalLockEnabled = styleSheet.isDirectionalLockEnabled
self.bounces = styleSheet.bounces
self.alwaysBounceVertical = styleSheet.alwaysBounceVertical
self.alwaysBounceHorizontal = styleSheet.alwaysBounceHorizontal
self.isPagingEnabled = styleSheet.isPagingEnabled
self.isScrollEnabled = styleSheet.isScrollEnabled
self.showsVerticalScrollIndicator = styleSheet.showsVerticalScrollIndicator
self.showsHorizontalScrollIndicator = styleSheet.showsHorizontalScrollIndicator
self.indicatorStyle = styleSheet.scrollIndicatorStyle
self.decelerationRate = styleSheet.decelerationRate
self.indexDisplayMode = styleSheet.indexDisplayMode
self.allowsSelection = styleSheet.allowsSelection
self.allowsSelectionDuringEditing = styleSheet.allowsSelectionDuringEditing
self.allowsMultipleSelection = styleSheet.allowsMultipleSelection
self.allowsMultipleSelectionDuringEditing = styleSheet.allowsMultipleSelectionDuringEditing
self.separatorStyle = styleSheet.separatorStyle
self.separatorColor = styleSheet.separatorColor
self.separatorEffect = styleSheet.separatorEffect
self.remembersLastFocusedIndexPath = styleSheet.remembersLastFocusedIndexPath
}
}
// MARK: Private
private extension QTableView {
func _tableFooterDefaultFrame(_ view: UIView) -> CGFloat {
return view.frame.height
}
func _tableFooterStretchFrame(_ view: UIView, minimum: CGFloat) -> CGFloat {
let contentOffset = self.contentOffset.y
let contentHeight = self.contentSize.height
var contentInset: UIEdgeInsets
if #available(iOS 11.0, *) {
contentInset = self.adjustedContentInset
} else {
contentInset = self.contentInset
}
let fullContentHeight = contentInset.top + contentHeight
let contentBottomEdge = (contentOffset + contentInset.top) + self.frame.height
return max(minimum, contentBottomEdge - fullContentHeight)
}
}
// MARK: IQContainerSpec
extension QTableView : IQContainerSpec {
open var containerSize: CGSize {
get { return self.bounds.inset(by: self.contentInset).size }
}
open var containerLeftInset: CGFloat {
get { return self.contentLeftInset }
}
open var containerRightInset: CGFloat {
get { return self.contentRightInset }
}
}
| mit | a6f0a93410b28dbd87acf69c9118d796 | 38.541045 | 99 | 0.684816 | 6.197076 | false | false | false | false |
almeidacavalcante/carousel | CarouselApp/CarouselApp/HeaderPhotoSelectorCell.swift | 1 | 2388 | //
// HeaderPhotoSelectorCell.swift
// CarouselApp
//
// Created by José de Almeida Cavalcante Neto on 02/08/17.
// Copyright © 2017 José de Almeida Cavalcante Neto. All rights reserved.
//
import UIKit
protocol HeaderPhotoSelectorCellDelegate {
func didTapAddButton()
func didTapBackButton()
}
class HeaderPhotoSelectorCell : UICollectionViewCell {
var delegate : HeaderPhotoSelectorCellDelegate?
let imageView : UIImageView = {
let iv = UIImageView()
iv.backgroundColor = .white
iv.contentMode = .scaleAspectFill
iv.clipsToBounds = true
return iv
}()
lazy var backButton : UIButton = {
let button = UIButton(type: .system)
button.setImage(#imageLiteral(resourceName: "arrow"), for: .normal)
button.tintColor = .white
button.addTarget(self, action: #selector(handleBackButton), for: .touchUpInside)
return button
}()
lazy var addButton : UIButton = {
let button = UIButton(type: .system)
button.setImage(#imageLiteral(resourceName: "circleplus"), for: .normal)
button.addTarget(self, action: #selector(handleAddButton), for: .touchUpInside)
button.tintColor = .white
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
addSubview(addButton)
addSubview(backButton)
imageView.anchor(top: topAnchor, left: leftAnchor, botton: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
addButton.anchor(top: topAnchor, left: nil, botton: nil, right: rightAnchor, paddingTop: 8, paddingLeft: 0, paddingBottom: 0, paddingRight: 8, width: 50, height: 50)
backButton.anchor(top: topAnchor, left: leftAnchor, botton: nil, right: nil, paddingTop: 8, paddingLeft: 8, paddingBottom: 0, paddingRight: 0, width: 50, height: 50)
}
func handleAddButton(){
print("HEADER CELL: handleAddButton()")
delegate?.didTapAddButton()
}
func handleBackButton(){
print("HEADER CELL: handleBackButton()")
delegate?.didTapBackButton()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| unlicense | 569d55b44dfecff791e862922ccd4b17 | 31.671233 | 187 | 0.647799 | 4.595376 | false | false | false | false |
P0ed/FireTek | Source/SpaceEngine/Systems/LootSystem.swift | 1 | 2111 | import SpriteKit
import PowerCore
import Fx
final class LootSystem {
fileprivate let world: World
private let collisionsSystem: CollisionsSystem
private let disposable = CompositeDisposable()
init(world: World, collisionsSystem: CollisionsSystem) {
self.world = world
self.collisionsSystem = collisionsSystem
disposable += collisionsSystem.didBeginContact.observe(
unown(self) {$0.processContact}
)
}
func update() {
spawnLoot()
}
private func spawnLoot() {
for index in world.dead.indices {
let entity = world.dead.entityAt(index)
if let lootIndex = world.loot.indexOf(entity),
let spriteIndex = world.sprites.indexOf(entity) {
spawnLoot(
loot: world.loot[lootIndex],
at: world.sprites[spriteIndex].sprite.position
)
}
}
}
private func spawnLoot(loot: LootComponent, at position: CGPoint) {
let count = Int(arc4random_uniform(UInt32(loot.count))) + 1
for index in 0..<count {
let offset = spread(at: index, outOf: count)
let crystal = generate(base: loot.crystal)
UnitFactory.addCrystal(world: world, crystal: crystal, at: position, moveBy: offset)
}
}
private func spread(at index: Int, outOf count: Int) -> CGVector {
if count == 1 { return .zero }
let angle = CGFloat(Double.pi * 2 / Double(count))
let r = CGVector(dx: 0, dy: 12)
return r.rotate(angle * CGFloat(index))
}
private func generate(base: Crystal) -> Crystal {
switch Int(arc4random_uniform(16)) {
case 0...1: return .red
case 2...3: return .green
case 4...5: return .blue
case 5...7: return .purple
case 8: return .yellow
case 9: return .cyan
case 10: return .orange
default: return base
}
}
}
private extension LootSystem {
func processContact(_ contact: SKPhysicsContact) {
guard let entityA = contact.bodyA.node?.entity,
let entityB = contact.bodyB.node?.entity,
let loot = world.crystals.first(entityA, entityB)
else { return }
world.entityManager.removeEntity(loot.entity)
let e = loot.entity == entityA ? entityB : entityA
world.sprites.refOf(e)?.value.sprite.run(SoundsFabric.crystalCollected)
}
}
| mit | 0954b194ee0e93a8c3da4332e8527677 | 25.061728 | 87 | 0.703932 | 3.174436 | false | false | false | false |
slepcat/mint-lisp | mint-lisp/mintlisp_env.swift | 1 | 6561 | //
// mintlisp_env.swift
// mint-lisp
//
// Created by NemuNeko on 2015/08/03.
// Copyright (c) 2015年 Taizo A. All rights reserved.
//
import Foundation
class Env {
var hash_table = [String: SExpr]()
var ext_env: Env?
init() {
ext_env = nil
}
/* debug print
deinit {
if hash_table.count > 10 {
print("deinit env, with \(hash_table.count) elements")
}
}
*/
func lookup(_ key : String) -> SExpr {
if let value = hash_table[key] {
return value
} else {
if let eenv = ext_env {
return eenv.lookup(key)
} else {
print("Unbouded symbol", terminator: "\n")
return MNull()
}
}
}
// todo: variable length of arguments
func extended_env(_ symbols: [SExpr], values: [SExpr]) -> Env? {
let _env = Env()
_env.ext_env = self
if symbols.count == values.count {
for i in 0..<symbols.count {
if let symbol = symbols[i] as? MSymbol {
_env.define_variable(symbol.key, val: values[i])
} else {
print("Unproper parameter values", terminator: "\n")
return nil
}
}
return _env
} else if symbols.count == 1 {
if let _ = symbols.last as? MNull {
return _env
}
}
print("Err. Number of Symbol and Value is unmatch.", terminator: "\n")
return nil
}
func clone() -> Env {
let cloned_env = Env()
cloned_env.ext_env = self.ext_env?.clone()
cloned_env.hash_table = self.hash_table
return cloned_env
}
func define_variable(_ key: String, val: SExpr) -> Bool {
if hash_table[key] == nil {
hash_table[key] = val
return true
} else {
return false
}
}
func set_variable(_ key: String, val: SExpr) -> Bool {
if hash_table[key] == nil {
return false
} else {
hash_table[key] = val
return true
}
}
func define_variable_force(_ key: String, val: SExpr) -> Bool {
hash_table[key] = val
return true
}
}
func global_environment() -> [String : SExpr] {
var primitives = [String : SExpr]()
///// basic operators /////
primitives["+"] = Plus()
primitives["-"] = Minus()
primitives["*"] = Multiply()
primitives["/"] = Divide()
primitives["="] = isEqual()
primitives[">"] = GreaterThan()
primitives["<"] = SmallerThan()
primitives[">="] = EqualOrGreaterThan()
primitives["<="] = EqualOrSmallerThan()
primitives["mod"] = Mod()
primitives["and"] = And()
primitives["or"] = Or()
primitives["not"] = Not()
primitives["pow"] = Power()
primitives["floor"] = Floor()
primitives["ceil"] = Ceil()
primitives["round"] = Round()
primitives["cos"] = Cos()
primitives["sin"] = Sin()
primitives["tan"] = Tan()
primitives["asin"] = ArcSin()
primitives["acos"] = ArcCos()
primitives["atan"] = ArcTan()
primitives["atan2"] = ArcTan2()
primitives["sinh"] = Sinh()
primitives["cosh"] = Cosh()
primitives["tanh"] = Tanh()
primitives["abs"] = Abs()
primitives["sqrt"] = Sqrt()
primitives["exp"] = Exp()
primitives["log"] = Log()
primitives["log10"] = Log10()
primitives["max"] = Max()
primitives["min"] = Min()
primitives["random"] = Random()
primitives["time"] = Time()
primitives["pi"] = MDouble(_value: M_1_PI)
///// conscell management /////
primitives["cons"] = Cons()
primitives["join"] = Join()
primitives["car"] = Car()
primitives["cdr"] = Cdr()
primitives["caar"] = Caar()
primitives["cadr"] = Cadr()
primitives["cdar"] = Cdar()
primitives["cddr"] = Cddr()
primitives["caaar"] = Caaar()
primitives["caadr"] = Caadr()
primitives["caddr"] = Caddr()
primitives["cdddr"] = Cdddr()
primitives["cdaar"] = Cdaar()
primitives["cddar"] = Cddar()
primitives["cdadr"] = Cdadr()
primitives["cadar"] = Cadar()
primitives["null"] = MNull()
///// array managemetn /////
primitives["array"] = NewArray()
primitives["at-index"] = ArrayAtIndex()
primitives["append"] = AppendArray()
primitives["joint"] = JointArray()
primitives["remove-at-index"] = RemoveAtIndex()
primitives["remove-last"] = RemoveLast()
primitives["remove-all"] = RemoveAll()
primitives["count"] = CountArray()
//primitives["list"] = isEqual()
//primitives["apply"] = isEqual()
//primitives["map"] = isEqual()
///// Type Casting /////
primitives["cast-double"] = CastDouble()
///// 3D data objects /////
primitives["vec"] = Vec()
primitives["vec.x"] = Vec_x()
primitives["vec.y"] = Vec_y()
primitives["vec.z"] = Vec_z()
primitives["vex"] = Vex()
primitives["vex.pos"] = Vex_Pos()
primitives["vex.normal"] = Vex_Normal()
primitives["vex.color"] = Vex_Color()
primitives["color"] = Color()
primitives["color.r"] = Color_r()
primitives["color.g"] = Color_g()
primitives["color.b"] = Color_b()
primitives["color.a"] = Color_a()
primitives["plane"] = Pln()
primitives["plane.normal"] = Pln_normal()
primitives["ln"] = Ln()
primitives["ln.pos"] = Ln_Pos()
primitives["ln.dir"] = Ln_Dir()
primitives["ln-seg"] = LnSeg()
primitives["poly"] = Poly()
primitives["poly.vex-at-index"] = Poly_VexAtIndex()
primitives["poly.vex-count"] = Poly_VexCount()
///// 3d primitives /////
primitives["cube"] = Cube()
primitives["sphere"] = Sphere()
primitives["cylinder"] = Cylinder()
///// 3d Transform /////
primitives["set-color"] = SetColor()
primitives["union"] = Union()
primitives["subtract"] = Subtract()
primitives["intersect"] = Intersect()
primitives["rotate"] = Rotate()
primitives["rotate-axis"] = RotateAxis()
primitives["move"] = Translate()
primitives["scale"] = Scale()
///// 2d data objects //////
primitives["shape"] = Shp()
///// IO /////
primitives["print"] = Print()
//primitives["display"] = Display()
primitives["quit"] = Quit()
return primitives
}
| apache-2.0 | 150d197af219182ceaed114caba83d65 | 26.329167 | 78 | 0.52325 | 3.87877 | false | false | false | false |
tecgirl/firefox-ios | StorageTests/TestSQLiteHistory.swift | 1 | 73393 | /* 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
@testable import Storage
import Deferred
import XCTest
let threeMonthsInMillis: UInt64 = 3 * 30 * 24 * 60 * 60 * 1000
let threeMonthsInMicros: UInt64 = UInt64(threeMonthsInMillis) * UInt64(1000)
// Start everything three months ago.
let baseInstantInMillis = Date.now() - threeMonthsInMillis
let baseInstantInMicros = Date.nowMicroseconds() - threeMonthsInMicros
func advanceTimestamp(_ timestamp: Timestamp, by: Int) -> Timestamp {
return timestamp + UInt64(by)
}
func advanceMicrosecondTimestamp(_ timestamp: MicrosecondTimestamp, by: Int) -> MicrosecondTimestamp {
return timestamp + UInt64(by)
}
extension Site {
func asPlace() -> Place {
return Place(guid: self.guid!, url: self.url, title: self.title)
}
}
class BaseHistoricalBrowserSchema: Schema {
var name: String { return "BROWSER" }
var version: Int { return -1 }
func update(_ db: SQLiteDBConnection, from: Int) -> Bool {
fatalError("Should never be called.")
}
func create(_ db: SQLiteDBConnection) -> Bool {
return false
}
func drop(_ db: SQLiteDBConnection) -> Bool {
return false
}
var supportsPartialIndices: Bool {
let v = sqlite3_libversion_number()
return v >= 3008000 // 3.8.0.
}
let oldFaviconsSQL = """
CREATE TABLE IF NOT EXISTS favicons (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
width INTEGER,
height INTEGER,
type INTEGER NOT NULL,
date REAL NOT NULL
)
"""
func run(_ db: SQLiteDBConnection, sql: String?, args: Args? = nil) -> Bool {
if let sql = sql {
do {
try db.executeChange(sql, withArgs: args)
} catch {
return false
}
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String?]) -> Bool {
for sql in queries {
if let sql = sql {
if !run(db, sql: sql) {
return false
}
}
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql) {
return false
}
}
return true
}
}
// Versions of BrowserSchema that we care about:
// v6, prior to 001c73ea1903c238be1340950770879b40c41732, July 2015.
// This is when we first started caring about database versions.
//
// v7, 81e22fa6f7446e27526a5a9e8f4623df159936c3. History tiles.
//
// v8, 02c08ddc6d805d853bbe053884725dc971ef37d7. Favicons.
//
// v10, 4428c7d181ff4779ab1efb39e857e41bdbf4de67. Mirroring. We skipped v9.
//
// These tests snapshot the table creation code at each of these points.
class BrowserSchemaV6: BaseHistoricalBrowserSchema {
override var version: Int { return 6 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql = """
INSERT INTO bookmarks
(id, guid, type, url, title, parent)
VALUES
-- Root
(?, ?, ?, NULL, ?, ?),
-- Mobile
(?, ?, ?, NULL, ?, ?),
-- Menu
(?, ?, ?, NULL, ?, ?),
-- Toolbar
(?, ?, ?, NULL, ?, ?),
-- Unsorted
(?, ?, ?, NULL, ?, ?)
"""
return self.run(db, sql: sql, args: args)
}
func CreateHistoryTable() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
-- Not null, but the value might be replaced by the server's.
guid TEXT NOT NULL UNIQUE,
-- May only be null for deleted records.
url TEXT UNIQUE,
title TEXT NOT NULL,
-- Can be null. Integer milliseconds.
server_modified INTEGER,
-- Can be null. Client clock. In extremis only.
local_modified INTEGER,
-- Boolean. Locally deleted.
is_deleted TINYINT NOT NULL,
-- Boolean. Set when changed or visits added.
should_upload TINYINT NOT NULL,
domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE,
CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)
)
"""
return sql
}
func CreateDomainsTable() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS domains (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain TEXT NOT NULL UNIQUE,
showOnTopSites TINYINT NOT NULL DEFAULT 1
)
"""
return sql
}
func CreateQueueTable() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS queue (
url TEXT NOT NULL UNIQUE,
title TEXT
)
"""
return sql
}
override func create(_ db: SQLiteDBConnection) -> Bool {
let visits = """
CREATE TABLE IF NOT EXISTS visits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
-- Microseconds since epoch.
date REAL NOT NULL,
type INTEGER NOT NULL,
-- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
is_local TINYINT NOT NULL,
UNIQUE (siteID, date, type)
)
"""
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)"
let faviconSites = """
CREATE TABLE IF NOT EXISTS favicon_sites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE,
UNIQUE (siteID, faviconID)
)
"""
let widestFavicons = """
CREATE VIEW IF NOT EXISTS view_favicons_widest AS
SELECT
favicon_sites.siteID AS siteID,
favicons.id AS iconID,
favicons.url AS iconURL,
favicons.date AS iconDate,
favicons.type AS iconType,
max(favicons.width) AS iconWidth
FROM favicon_sites, favicons
WHERE favicon_sites.faviconID = favicons.id
GROUP BY siteID
"""
let historyIDsWithIcon = """
CREATE VIEW IF NOT EXISTS view_history_id_favicon AS
SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth
FROM history LEFT OUTER JOIN view_favicons_widest ON
history.id = view_favicons_widest.siteID
"""
let iconForURL = """
CREATE VIEW IF NOT EXISTS view_icon_for_url AS
SELECT history.url AS url, icons.iconID AS iconID
FROM history, view_favicons_widest AS icons
WHERE history.id = icons.siteID
"""
let bookmarks = """
CREATE TABLE IF NOT EXISTS bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guid TEXT NOT NULL UNIQUE,
type TINYINT NOT NULL,
url TEXT,
parent INTEGER REFERENCES bookmarks(id) NOT NULL,
faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL,
title TEXT
)
"""
let queries = [
// This used to be done by FaviconsTable.
self.oldFaviconsSQL,
CreateDomainsTable(),
CreateHistoryTable(),
visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
CreateQueueTable(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserSchemaV7: BaseHistoricalBrowserSchema {
override var version: Int { return 7 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql = """
INSERT INTO bookmarks
(id, guid, type, url, title, parent)
VALUES
-- Root
(?, ?, ?, NULL, ?, ?),
-- Mobile
(?, ?, ?, NULL, ?, ?),
-- Menu
(?, ?, ?, NULL, ?, ?),
-- Toolbar
(?, ?, ?, NULL, ?, ?),
-- Unsorted
(?, ?, ?, NULL, ?, ?)
"""
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
-- Not null, but the value might be replaced by the server's.
guid TEXT NOT NULL UNIQUE,
-- May only be null for deleted records.
url TEXT UNIQUE,
title TEXT NOT NULL,
-- Can be null. Integer milliseconds.
server_modified INTEGER,
-- Can be null. Client clock. In extremis only.
local_modified INTEGER,
-- Boolean. Locally deleted.
is_deleted TINYINT NOT NULL,
-- Boolean. Set when changed or visits added.
should_upload TINYINT NOT NULL,
domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE,
CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)
)
"""
return sql
}
func getDomainsTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS domains (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain TEXT NOT NULL UNIQUE,
showOnTopSites TINYINT NOT NULL DEFAULT 1
)
"""
return sql
}
func getQueueTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS queue (
url TEXT NOT NULL UNIQUE,
title TEXT
)
"""
return sql
}
override func create(_ db: SQLiteDBConnection) -> Bool {
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits = """
CREATE TABLE IF NOT EXISTS visits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
-- Microseconds since epoch.
date REAL NOT NULL,
type INTEGER NOT NULL,
-- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
is_local TINYINT NOT NULL,
UNIQUE (siteID, date, type)
)
"""
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)"
let faviconSites = """
CREATE TABLE IF NOT EXISTS favicon_sites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE,
UNIQUE (siteID, faviconID)
)
"""
let widestFavicons = """
CREATE VIEW IF NOT EXISTS view_favicons_widest AS
SELECT
favicon_sites.siteID AS siteID,
favicons.id AS iconID,
favicons.url AS iconURL,
favicons.date AS iconDate,
favicons.type AS iconType,
max(favicons.width) AS iconWidth
FROM favicon_sites, favicons
WHERE favicon_sites.faviconID = favicons.id
GROUP BY siteID
"""
let historyIDsWithIcon = """
CREATE VIEW IF NOT EXISTS view_history_id_favicon AS
SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth
FROM history LEFT OUTER JOIN view_favicons_widest ON
history.id = view_favicons_widest.siteID
"""
let iconForURL = """
CREATE VIEW IF NOT EXISTS view_icon_for_url AS
SELECT history.url AS url, icons.iconID AS iconID
FROM history, view_favicons_widest AS icons
WHERE history.id = icons.siteID
"""
let bookmarks = """
CREATE TABLE IF NOT EXISTS bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guid TEXT NOT NULL UNIQUE,
type TINYINT NOT NULL,
url TEXT,
parent INTEGER REFERENCES bookmarks(id) NOT NULL,
faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL,
title TEXT
)
"""
let queries = [
// This used to be done by FaviconsTable.
self.oldFaviconsSQL,
getDomainsTableCreationString(),
getHistoryTableCreationString(),
visits, bookmarks, faviconSites,
indexShouldUpload, indexSiteIDDate,
widestFavicons, historyIDsWithIcon, iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserSchemaV8: BaseHistoricalBrowserSchema {
override var version: Int { return 8 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql = """
INSERT INTO bookmarks
(id, guid, type, url, title, parent)
VALUES
-- Root
(?, ?, ?, NULL, ?, ?),
-- Mobile
(?, ?, ?, NULL, ?, ?),
-- Menu
(?, ?, ?, NULL, ?, ?),
-- Toolbar
(?, ?, ?, NULL, ?, ?),
-- Unsorted
(?, ?, ?, NULL, ?, ?)
"""
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
-- Not null, but the value might be replaced by the server's.
guid TEXT NOT NULL UNIQUE,
-- May only be null for deleted records.
url TEXT UNIQUE,
title TEXT NOT NULL,
-- Can be null. Integer milliseconds.
server_modified INTEGER,
-- Can be null. Client clock. In extremis only.
local_modified INTEGER,
-- Boolean. Locally deleted.
is_deleted TINYINT NOT NULL,
-- Boolean. Set when changed or visits added.
should_upload TINYINT NOT NULL,
domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE,
CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)
)
"""
return sql
}
func getDomainsTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS domains (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain TEXT NOT NULL UNIQUE,
showOnTopSites TINYINT NOT NULL DEFAULT 1
)
"""
return sql
}
func getQueueTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS queue (
url TEXT NOT NULL UNIQUE,
title TEXT
)
"""
return sql
}
override func create(_ db: SQLiteDBConnection) -> Bool {
let favicons = """
CREATE TABLE IF NOT EXISTS favicons (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
width INTEGER,
height INTEGER,
type INTEGER NOT NULL,
date REAL NOT NULL
)
"""
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits = """
CREATE TABLE IF NOT EXISTS visits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
-- Microseconds since epoch.
date REAL NOT NULL,
type INTEGER NOT NULL,
-- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
is_local TINYINT NOT NULL,
UNIQUE (siteID, date, type)
)
"""
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)"
let faviconSites = """
CREATE TABLE IF NOT EXISTS favicon_sites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE,
UNIQUE (siteID, faviconID)
)
"""
let widestFavicons = """
CREATE VIEW IF NOT EXISTS view_favicons_widest AS
SELECT
favicon_sites.siteID AS siteID,
favicons.id AS iconID,
favicons.url AS iconURL,
favicons.date AS iconDate,
favicons.type AS iconType,
max(favicons.width) AS iconWidth
FROM favicon_sites, favicons
WHERE favicon_sites.faviconID = favicons.id
GROUP BY siteID
"""
let historyIDsWithIcon = """
CREATE VIEW IF NOT EXISTS view_history_id_favicon AS
SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth
FROM history LEFT OUTER JOIN view_favicons_widest ON
history.id = view_favicons_widest.siteID
"""
let iconForURL = """
CREATE VIEW IF NOT EXISTS view_icon_for_url AS
SELECT history.url AS url, icons.iconID AS iconID
FROM history, view_favicons_widest AS icons
WHERE history.id = icons.siteID
"""
let bookmarks = """
CREATE TABLE IF NOT EXISTS bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guid TEXT NOT NULL UNIQUE,
type TINYINT NOT NULL,
url TEXT,
parent INTEGER REFERENCES bookmarks(id) NOT NULL,
faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL,
title TEXT
)
"""
let queries: [String] = [
getDomainsTableCreationString(),
getHistoryTableCreationString(),
favicons,
visits,
bookmarks,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class BrowserSchemaV10: BaseHistoricalBrowserSchema {
override var version: Int { return 10 }
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let root = BookmarkRoots.RootID
let titleMobile = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let titleMenu = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let titleToolbar = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let titleUnsorted = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let args: Args = [
root, BookmarkRoots.RootGUID, type, "Root", root,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, titleMobile, root,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, titleMenu, root,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, titleToolbar, root,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, titleUnsorted, root,
]
let sql = """
INSERT INTO bookmarks
(id, guid, type, url, title, parent)
VALUES
-- Root
(?, ?, ?, NULL, ?, ?),
-- Mobile
(?, ?, ?, NULL, ?, ?),
-- Menu
(?, ?, ?, NULL, ?, ?),
-- Toolbar
(?, ?, ?, NULL, ?, ?),
-- Unsorted
(?, ?, ?, NULL, ?, ?)
"""
return self.run(db, sql: sql, args: args)
}
func getHistoryTableCreationString(forVersion version: Int = BrowserSchema.DefaultVersion) -> String {
let sql = """
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
-- Not null, but the value might be replaced by the server's.
guid TEXT NOT NULL UNIQUE,
-- May only be null for deleted records.
url TEXT UNIQUE,
title TEXT NOT NULL,
-- Can be null. Integer milliseconds.
server_modified INTEGER,
-- Can be null. Client clock. In extremis only.
local_modified INTEGER,
-- Boolean. Locally deleted.
is_deleted TINYINT NOT NULL,
-- Boolean. Set when changed or visits added.
should_upload TINYINT NOT NULL,
domain_id INTEGER REFERENCES domains(id) ON DELETE CASCADE,
CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)
)
"""
return sql
}
func getDomainsTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS domains (
id INTEGER PRIMARY KEY AUTOINCREMENT,
domain TEXT NOT NULL UNIQUE,
showOnTopSites TINYINT NOT NULL DEFAULT 1
)
"""
return sql
}
func getQueueTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS queue (
url TEXT NOT NULL UNIQUE,
title TEXT
)
"""
return sql
}
func getBookmarksMirrorTableCreationString() -> String {
// The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry.
// For now we have the simplest possible schema: everything in one.
let sql = """
CREATE TABLE IF NOT EXISTS bookmarksMirror
-- Shared fields.
( id INTEGER PRIMARY KEY AUTOINCREMENT
, guid TEXT NOT NULL UNIQUE
-- Type enum. TODO: BookmarkNodeType needs to be extended.
, type TINYINT NOT NULL
-- Record/envelope metadata that'll allow us to do merges.
-- Milliseconds.
, server_modified INTEGER NOT NULL
-- Boolean
, is_deleted TINYINT NOT NULL DEFAULT 0
-- Boolean, 0 (false) if deleted.
, hasDupe TINYINT NOT NULL DEFAULT 0
-- GUID
, parentid TEXT
, parentName TEXT
-- Type-specific fields. These should be NOT NULL in many cases, but we're going
-- for a sparse schema, so this'll do for now. Enforce these in the application code.
-- LIVEMARKS
, feedUri TEXT, siteUri TEXT
-- SEPARATORS
, pos INT
-- FOLDERS, BOOKMARKS, QUERIES
, title TEXT, description TEXT
-- BOOKMARKS, QUERIES
, bmkUri TEXT, tags TEXT, keyword TEXT
-- QUERIES
, folderName TEXT, queryId TEXT
, CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)
, CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)
)
"""
return sql
}
/**
* We need to explicitly store what's provided by the server, because we can't rely on
* referenced child nodes to exist yet!
*/
func getBookmarksMirrorStructureTableCreationString() -> String {
let sql = """
CREATE TABLE IF NOT EXISTS bookmarksMirrorStructure (
parent TEXT NOT NULL REFERENCES bookmarksMirror(guid) ON DELETE CASCADE,
-- Should be the GUID of a child.
child TEXT NOT NULL,
-- Should advance from 0.
idx INTEGER NOT NULL
)
"""
return sql
}
override func create(_ db: SQLiteDBConnection) -> Bool {
let favicons = """
CREATE TABLE IF NOT EXISTS favicons (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL UNIQUE,
width INTEGER,
height INTEGER,
type INTEGER NOT NULL,
date REAL NOT NULL
)
"""
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits = """
CREATE TABLE IF NOT EXISTS visits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
-- Microseconds since epoch.
date REAL NOT NULL,
type INTEGER NOT NULL,
-- Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
is_local TINYINT NOT NULL,
UNIQUE (siteID, date, type)
)
"""
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS idx_history_should_upload ON history (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS idx_visits_siteID_is_local_date ON visits (siteID, is_local, date)"
let faviconSites = """
CREATE TABLE IF NOT EXISTS favicon_sites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
siteID INTEGER NOT NULL REFERENCES history(id) ON DELETE CASCADE,
faviconID INTEGER NOT NULL REFERENCES favicons(id) ON DELETE CASCADE,
UNIQUE (siteID, faviconID)
)
"""
let widestFavicons = """
CREATE VIEW IF NOT EXISTS view_favicons_widest AS
SELECT
favicon_sites.siteID AS siteID,
favicons.id AS iconID,
favicons.url AS iconURL,
favicons.date AS iconDate,
favicons.type AS iconType,
max(favicons.width) AS iconWidth
FROM favicon_sites, favicons
WHERE favicon_sites.faviconID = favicons.id
GROUP BY siteID
"""
let historyIDsWithIcon = """
CREATE VIEW IF NOT EXISTS view_history_id_favicon AS
SELECT history.id AS id, iconID, iconURL, iconDate, iconType, iconWidth
FROM history LEFT OUTER JOIN view_favicons_widest ON
history.id = view_favicons_widest.siteID
"""
let iconForURL = """
CREATE VIEW IF NOT EXISTS view_icon_for_url AS
SELECT history.url AS url, icons.iconID AS iconID
FROM history, view_favicons_widest AS icons
WHERE history.id = icons.siteID
"""
let bookmarks = """
CREATE TABLE IF NOT EXISTS bookmarks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guid TEXT NOT NULL UNIQUE,
type TINYINT NOT NULL,
url TEXT,
parent INTEGER REFERENCES bookmarks(id) NOT NULL,
faviconID INTEGER REFERENCES favicons(id) ON DELETE SET NULL,
title TEXT
)
"""
let bookmarksMirror = getBookmarksMirrorTableCreationString()
let bookmarksMirrorStructure = getBookmarksMirrorStructureTableCreationString()
let indexStructureParentIdx =
"CREATE INDEX IF NOT EXISTS idx_bookmarksMirrorStructure_parent_idx ON bookmarksMirrorStructure (parent, idx)"
let queries: [String] = [
getDomainsTableCreationString(),
getHistoryTableCreationString(),
favicons,
visits,
bookmarks,
bookmarksMirror,
bookmarksMirrorStructure,
indexStructureParentIdx,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
getQueueTableCreationString(),
]
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
}
class TestSQLiteHistory: XCTestCase {
let files = MockFiles()
fileprivate func deleteDatabases() {
for v in ["6", "7", "8", "10", "6-data"] {
do {
try files.remove("browser-v\(v).db")
} catch {}
}
do {
try files.remove("browser.db")
try files.remove("historysynced.db")
} catch {}
}
override func tearDown() {
super.tearDown()
self.deleteDatabases()
}
override func setUp() {
super.setUp()
// Just in case tearDown didn't run or succeed last time!
self.deleteDatabases()
}
// Test that our visit partitioning for frecency is correct.
func testHistoryLocalAndRemoteVisits() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let siteL = Site(url: "http://url1/", title: "title local only")
let siteR = Site(url: "http://url2/", title: "title remote only")
let siteB = Site(url: "http://url3/", title: "title local and remote")
siteL.guid = "locallocal12"
siteR.guid = "remoteremote"
siteB.guid = "bothbothboth"
let siteVisitL1 = SiteVisit(site: siteL, date: baseInstantInMicros + 1000, type: VisitType.link)
let siteVisitL2 = SiteVisit(site: siteL, date: baseInstantInMicros + 2000, type: VisitType.link)
let siteVisitR1 = SiteVisit(site: siteR, date: baseInstantInMicros + 1000, type: VisitType.link)
let siteVisitR2 = SiteVisit(site: siteR, date: baseInstantInMicros + 2000, type: VisitType.link)
let siteVisitR3 = SiteVisit(site: siteR, date: baseInstantInMicros + 3000, type: VisitType.link)
let siteVisitBL1 = SiteVisit(site: siteB, date: baseInstantInMicros + 4000, type: VisitType.link)
let siteVisitBR1 = SiteVisit(site: siteB, date: baseInstantInMicros + 5000, type: VisitType.link)
let deferred =
history.clearHistory()
>>> { history.addLocalVisit(siteVisitL1) }
>>> { history.addLocalVisit(siteVisitL2) }
>>> { history.addLocalVisit(siteVisitBL1) }
>>> { history.insertOrUpdatePlace(siteL.asPlace(), modified: baseInstantInMillis + 2) }
>>> { history.insertOrUpdatePlace(siteR.asPlace(), modified: baseInstantInMillis + 3) }
>>> { history.insertOrUpdatePlace(siteB.asPlace(), modified: baseInstantInMillis + 5) }
// Do this step twice, so we exercise the dupe-visit handling.
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitR1, siteVisitR2, siteVisitR3], forGUID: siteR.guid!) }
>>> { history.storeRemoteVisits([siteVisitBR1], forGUID: siteB.guid!) }
>>> {
history.getFrecentHistory().getSites(whereURLContains: nil, historyLimit: 3, bookmarksLimit: 0)
>>== { (sites: Cursor) -> Success in
XCTAssertEqual(3, sites.count)
// Two local visits beat a single later remote visit and one later local visit.
// Two local visits beat three remote visits.
XCTAssertEqual(siteL.guid!, sites[0]!.guid!)
XCTAssertEqual(siteB.guid!, sites[1]!.guid!)
XCTAssertEqual(siteR.guid!, sites[2]!.guid!)
return succeed()
}
// This marks everything as modified so we can fetch it.
>>> history.onRemovedAccount
// Now check that we have no duplicate visits.
>>> { history.getModifiedHistoryToUpload()
>>== { (places) -> Success in
if let (_, visits) = places.find({$0.0.guid == siteR.guid!}) {
XCTAssertEqual(3, visits.count)
} else {
XCTFail("Couldn't find site R.")
}
return succeed()
}
}
}
XCTAssertTrue(deferred.value.isSuccess)
}
func testUpgrades() {
let sources: [(Int, Schema)] = [
(6, BrowserSchemaV6()),
(7, BrowserSchemaV7()),
(8, BrowserSchemaV8()),
(10, BrowserSchemaV10()),
]
let destination = BrowserSchema()
for (version, schema) in sources {
var db = BrowserDB(filename: "browser-v\(version).db", schema: schema, files: files)
XCTAssertTrue(db.withConnection({ connection -> Int in
connection.version
}).value.successValue == schema.version, "Creating BrowserSchema at version \(version)")
db.forceClose()
db = BrowserDB(filename: "browser-v\(version).db", schema: destination, files: files)
XCTAssertTrue(db.withConnection({ connection -> Int in
connection.version
}).value.successValue == destination.version, "Upgrading BrowserSchema from version \(version) to version \(schema.version)")
db.forceClose()
}
}
func testUpgradesWithData() {
var db = BrowserDB(filename: "browser-v6-data.db", schema: BrowserSchemaV6(), files: files)
// Insert some data.
let queries = [
"INSERT INTO domains (id, domain) VALUES (1, 'example.com')",
"INSERT INTO history (id, guid, url, title, server_modified, local_modified, is_deleted, should_upload, domain_id) VALUES (5, 'guid', 'http://www.example.com', 'title', 5, 10, 0, 1, 1)",
"INSERT INTO visits (siteID, date, type, is_local) VALUES (5, 15, 1, 1)",
"INSERT INTO favicons (url, width, height, type, date) VALUES ('http://www.example.com/favicon.ico', 10, 10, 1, 20)",
"INSERT INTO favicon_sites (siteID, faviconID) VALUES (5, 1)",
"INSERT INTO bookmarks (guid, type, url, parent, faviconID, title) VALUES ('guid', 1, 'http://www.example.com', 0, 1, 'title')"
]
XCTAssertTrue(db.run(queries).value.isSuccess)
// And we can upgrade to the current version.
db = BrowserDB(filename: "browser-v6-data.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let results = history.getSitesByLastVisit(10).value.successValue
XCTAssertNotNil(results)
XCTAssertEqual(results![0]?.url, "http://www.example.com")
db.forceClose()
}
func testDomainUpgrade() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let site = Site(url: "http://www.example.com/test1.1", title: "title one")
// Insert something with an invalid domain ID. We have to manually do this since domains are usually hidden.
let insertDeferred = db.withConnection { connection -> Void in
try connection.executeChange("PRAGMA foreign_keys = OFF")
let insert = "INSERT INTO history (guid, url, title, local_modified, is_deleted, should_upload, domain_id) VALUES (?, ?, ?, ?, ?, ?, ?)"
let args: Args = [Bytes.generateGUID(), site.url, site.title, Date.now(), 0, 0, -1]
try connection.executeChange(insert, withArgs: args)
}
XCTAssertTrue(insertDeferred.value.isSuccess)
// Now insert it again. This should update the domain.
history.addLocalVisit(SiteVisit(site: site, date: Date.nowMicroseconds(), type: VisitType.link)).succeeded()
// domain_id isn't normally exposed, so we manually query to get it.
let resultsDeferred = db.withConnection { connection -> Cursor<Int?> in
let sql = "SELECT domain_id FROM history WHERE url = ?"
let args: Args = [site.url]
return connection.executeQuery(sql, factory: { $0[0] as? Int }, withArgs: args)
}
let results = resultsDeferred.value.successValue!
let domain = results[0]! // Unwrap to get the first item from the cursor.
XCTAssertNil(domain)
}
func testDomains() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let initialGuid = Bytes.generateGUID()
let site11 = Site(url: "http://www.example.com/test1.1", title: "title one")
let site12 = Site(url: "http://www.example.com/test1.2", title: "title two")
let site13 = Place(guid: initialGuid, url: "http://www.example.com/test1.3", title: "title three")
let site3 = Site(url: "http://www.example2.com/test1", title: "title three")
let expectation = self.expectation(description: "First.")
let clearTopSites = "DELETE FROM cached_top_sites"
let updateTopSites: [(String, Args?)] = [(clearTopSites, nil), (history.getFrecentHistory().updateTopSitesCacheQuery())]
func countTopSites() -> Deferred<Maybe<Cursor<Int>>> {
return db.runQuery("SELECT count(*) FROM cached_top_sites", args: nil, factory: { sdrow -> Int in
return sdrow[0] as? Int ?? 0
})
}
history.clearHistory().bind({ success in
return all([history.addLocalVisit(SiteVisit(site: site11, date: Date.nowMicroseconds(), type: VisitType.link)),
history.addLocalVisit(SiteVisit(site: site12, date: Date.nowMicroseconds(), type: VisitType.link)),
history.addLocalVisit(SiteVisit(site: site3, date: Date.nowMicroseconds(), type: VisitType.link))])
}).bind({ (results: [Maybe<()>]) in
return history.insertOrUpdatePlace(site13, modified: Date.nowMicroseconds())
}).bind({ guid -> Success in
XCTAssertEqual(guid.successValue!, initialGuid, "Guid is correct")
return db.run(updateTopSites)
}).bind({ success in
XCTAssertTrue(success.isSuccess, "update was successful")
return countTopSites()
}).bind({ (count: Maybe<Cursor<Int>>) -> Success in
XCTAssert(count.successValue![0] == 2, "2 sites returned")
return history.removeSiteFromTopSites(site11)
}).bind({ success -> Success in
XCTAssertTrue(success.isSuccess, "Remove was successful")
return db.run(updateTopSites)
}).bind({ success -> Deferred<Maybe<Cursor<Int>>> in
XCTAssertTrue(success.isSuccess, "update was successful")
return countTopSites()
})
.upon({ (count: Maybe<Cursor<Int>>) in
XCTAssert(count.successValue![0] == 1, "1 site returned")
expectation.fulfill()
})
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testHistoryIsSynced() {
let db = BrowserDB(filename: "historysynced.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let initialGUID = Bytes.generateGUID()
let site = Place(guid: initialGUID, url: "http://www.example.com/test1.3", title: "title")
XCTAssertFalse(history.hasSyncedHistory().value.successValue ?? true)
XCTAssertTrue(history.insertOrUpdatePlace(site, modified: Date.now()).value.isSuccess)
XCTAssertTrue(history.hasSyncedHistory().value.successValue ?? false)
}
// This is a very basic test. Adds an entry, retrieves it, updates it,
// and then clears the database.
func testHistoryTable() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = SQLiteBookmarks(db: db)
let site1 = Site(url: "http://url1/", title: "title one")
let site1Changed = Site(url: "http://url1/", title: "title one alt")
let siteVisit1 = SiteVisit(site: site1, date: Date.nowMicroseconds(), type: VisitType.link)
let siteVisit2 = SiteVisit(site: site1Changed, date: Date.nowMicroseconds() + 1000, type: VisitType.bookmark)
let site2 = Site(url: "http://url2/", title: "title two")
let siteVisit3 = SiteVisit(site: site2, date: Date.nowMicroseconds() + 2000, type: VisitType.link)
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func checkSitesByFrecency(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getFrecentHistory().getSites(whereURLContains: nil, historyLimit: 10, bookmarksLimit: 0)
>>== f
}
}
func checkSitesByDate(_ f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getSitesByLastVisit(10)
>>== f
}
}
func checkSitesWithFilter(_ filter: String, f: @escaping (Cursor<Site>) -> Success) -> () -> Success {
return {
history.getFrecentHistory().getSites(whereURLContains: filter, historyLimit: 10, bookmarksLimit: 0)
>>== f
}
}
func checkDeletedCount(_ expected: Int) -> () -> Success {
return {
history.getDeletedHistoryToUpload()
>>== { guids in
XCTAssertEqual(expected, guids.count)
return succeed()
}
}
}
history.clearHistory()
>>> { history.addLocalVisit(siteVisit1) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1.title, sites[0]!.title)
XCTAssertEqual(site1.url, sites[0]!.url)
sites.close()
return succeed()
}
>>> { history.addLocalVisit(siteVisit2) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site1Changed.url, sites[0]!.url)
sites.close()
return succeed()
}
>>> { history.addLocalVisit(siteVisit3) }
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
XCTAssertEqual(site2.title, sites[1]!.title)
return succeed()
}
>>> checkSitesByDate { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(2, sites.count)
// They're in order of date last visited.
let first = sites[0]!
let second = sites[1]!
XCTAssertEqual(site2.title, first.title)
XCTAssertEqual(site1Changed.title, second.title)
XCTAssertTrue(siteVisit3.date == first.latestVisit!.date)
return succeed()
}
>>> checkSitesWithFilter("two") { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(1, sites.count)
let first = sites[0]!
XCTAssertEqual(site2.title, first.title)
return succeed()
}
>>>
checkDeletedCount(0)
>>> { history.removeHistoryForURL("http://url2/") }
>>>
checkDeletedCount(1)
>>> checkSitesByFrecency { (sites: Cursor) -> Success in
XCTAssertEqual(1, sites.count)
// They're in order of frecency.
XCTAssertEqual(site1Changed.title, sites[0]!.title)
return succeed()
}
>>> { history.clearHistory() }
>>>
checkDeletedCount(0)
>>> checkSitesByDate { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> checkSitesByFrecency { (sites: Cursor<Site>) -> Success in
XCTAssertEqual(0, sites.count)
return succeed()
}
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testFaviconTable() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
let bookmarks = SQLiteBookmarks(db: db)
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func updateFavicon() -> Success {
let fav = Favicon(url: "http://url2/", date: Date())
fav.id = 1
let site = Site(url: "http://bookmarkedurl/", title: "My Bookmark")
return history.addFavicon(fav, forSite: site) >>> succeed
}
func checkFaviconForBookmarkIsNil() -> Success {
return bookmarks.bookmarksByURL("http://bookmarkedurl/".asURL!) >>== { results in
XCTAssertEqual(1, results.count)
XCTAssertNil(results[0]?.favicon)
return succeed()
}
}
func checkFaviconWasSetForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(1, results.count)
if let actualFaviconURL = results[0]??.url {
XCTAssertEqual("http://url2/", actualFaviconURL)
}
return succeed()
}
}
func removeBookmark() -> Success {
return bookmarks.testFactory.removeByURL("http://bookmarkedurl/")
}
func checkFaviconWasRemovedForBookmark() -> Success {
return history.getFaviconsForBookmarkedURL("http://bookmarkedurl/") >>== { results in
XCTAssertEqual(0, results.count)
return succeed()
}
}
history.clearAllFavicons()
>>> bookmarks.clearBookmarks
>>> { bookmarks.addToMobileBookmarks("http://bookmarkedurl/".asURL!, title: "Title", favicon: nil) }
>>> checkFaviconForBookmarkIsNil
>>> updateFavicon
>>> checkFaviconWasSetForBookmark
>>> removeBookmark
>>> checkFaviconWasRemovedForBookmark
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testRemoveHistoryForUrl() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
let url1 = "http://url1/"
let site1 = Site(url: "http://url1/", title: "title one")
let siteVisit1 = SiteVisit(site: site1, date: Date.nowMicroseconds(), type: VisitType.link)
let url2 = "http://url2/"
let site2 = Site(url: "http://url2/", title: "title two")
let siteVisit2 = SiteVisit(site: site2, date: Date.nowMicroseconds() + 2000, type: VisitType.link)
let url3 = "http://url3/"
let site3 = Site(url: url3, title: "title three")
let siteVisit3 = SiteVisit(site: site3, date: Date.nowMicroseconds() + 4000, type: VisitType.link)
history.addLocalVisit(siteVisit1).succeeded()
history.addLocalVisit(siteVisit2).succeeded()
history.addLocalVisit(siteVisit3).succeeded()
history.removeHistoryForURL(url1).succeeded()
history.removeHistoryForURL(url2).succeeded()
history.getDeletedHistoryToUpload()
>>== { guids in
XCTAssertEqual(2, guids.count)
}
}
func testTopSitesFrecencyOrder() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
// Lets create some history. This will create 100 sites that will have 21 local and 21 remote visits
populateHistoryForFrecencyCalculations(history, siteCount: 100)
// Create a new site thats for an existing domain but a different URL.
let site = Site(url: "http://s\(5)ite\(5).com/foo-different-url", title: "A \(5) different url")
site.guid = "abc\(5)defhi"
history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).succeeded()
// Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite!
for i in 0...100 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)defhi")
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testTopSitesFiltersGoogle() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
// Lets create some history. This will create 100 sites that will have 21 local and 21 remote visits
populateHistoryForFrecencyCalculations(history, siteCount: 100)
func createTopSite(url: String, guid: String) {
let site = Site(url: url, title: "Hi")
site.guid = guid
history.insertOrUpdatePlace(site.asPlace(), modified: baseInstantInMillis - 20000).succeeded()
// Don't give it any remote visits. But give it 100 local visits. This should be the new Topsite!
for i in 0...100 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
}
createTopSite(url: "http://google.com", guid: "abcgoogle") // should not be a topsite
createTopSite(url: "http://www.google.com", guid: "abcgoogle1") // should not be a topsite
createTopSite(url: "http://google.co.za", guid: "abcgoogleza") // should not be a topsite
createTopSite(url: "http://docs.google.com", guid: "docsgoogle") // should be a topsite
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites[0]?.guid, "docsgoogle") // google docs should be the first topsite
// make sure all other google guids are not in the topsites array
topSites.forEach {
let guid: String = $0!.guid! // type checking is hard
XCTAssertNil(["abcgoogle", "abcgoogle1", "abcgoogleza"].index(of: guid))
}
XCTAssertEqual(topSites.count, 20)
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testTopSitesCache() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
// Make sure that we get back the top sites
populateHistoryForFrecencyCalculations(history, siteCount: 100)
// Add extra visits to the 5th site to bubble it to the top of the top sites cache
let site = Site(url: "http://s\(5)ite\(5).com/foo", title: "A \(5)")
site.guid = "abc\(5)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func loadCache() -> Success {
return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> succeed
}
func checkTopSitesReturnsResults() -> Success {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
func invalidateIfNeededDoesntChangeResults() -> Success {
return history.repopulate(invalidateTopSites: true, invalidateHighlights: true) >>> {
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
return succeed()
}
}
}
func addVisitsToZerothSite() -> Success {
let site = Site(url: "http://s\(0)ite\(0).com/foo", title: "A \(0)")
site.guid = "abc\(0)def"
for i in 0...20 {
addVisitForSite(site, intoHistory: history, from: .local, atTime: advanceTimestamp(baseInstantInMicros, by: 1000000 * i))
}
return succeed()
}
func markInvalidation() -> Success {
history.setTopSitesNeedsInvalidation()
return succeed()
}
func checkSitesInvalidate() -> Success {
history.repopulate(invalidateTopSites: true, invalidateHighlights: true).succeeded()
return history.getTopSitesWithLimit(20) >>== { topSites in
XCTAssertEqual(topSites.count, 20)
XCTAssertEqual(topSites[0]!.guid, "abc\(5)def")
XCTAssertEqual(topSites[1]!.guid, "abc\(0)def")
return succeed()
}
}
loadCache()
>>> checkTopSitesReturnsResults
>>> invalidateIfNeededDoesntChangeResults
>>> markInvalidation
>>> addVisitsToZerothSite
>>> checkSitesInvalidate
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
func testPinnedTopSites() {
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.setTopSitesCacheSize(20)
history.clearTopSitesCache().succeeded()
history.clearHistory().succeeded()
// add 2 sites to pinned topsite
// get pinned site and make sure it exists in the right order
// remove pinned sites
// make sure pinned sites dont exist
// create pinned sites.
let site1 = Site(url: "http://s\(1)ite\(1).com/foo", title: "A \(1)")
site1.id = 1
site1.guid = "abc\(1)def"
addVisitForSite(site1, intoHistory: history, from: .local, atTime: Date.now())
let site2 = Site(url: "http://s\(2)ite\(2).com/foo", title: "A \(2)")
site2.id = 2
site2.guid = "abc\(2)def"
addVisitForSite(site2, intoHistory: history, from: .local, atTime: Date.now())
let expectation = self.expectation(description: "First.")
func done() -> Success {
expectation.fulfill()
return succeed()
}
func addPinnedSites() -> Success {
return history.addPinnedTopSite(site1) >>== {
sleep(1) // Sleep to prevent intermittent issue with sorting on the timestamp
return history.addPinnedTopSite(site2)
}
}
func checkPinnedSites() -> Success {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 2)
XCTAssertEqual(pinnedSites[0]!.url, site2.url)
XCTAssertEqual(pinnedSites[1]!.url, site1.url, "The older pinned site should be last")
return succeed()
}
}
func removePinnedSites() -> Success {
return history.removeFromPinnedTopSites(site2) >>== {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 1, "There should only be one pinned site")
XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left")
return succeed()
}
}
}
func dupePinnedSite() -> Success {
return history.addPinnedTopSite(site1) >>== {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 1, "There should not be a dupe")
XCTAssertEqual(pinnedSites[0]!.url, site1.url, "Site2 should be the only pin left")
return succeed()
}
}
}
func removeHistory() -> Success {
return history.clearHistory() >>== {
return history.getPinnedTopSites() >>== { pinnedSites in
XCTAssertEqual(pinnedSites.count, 1, "Pinned sites should exist after a history clear")
return succeed()
}
}
}
addPinnedSites()
>>> checkPinnedSites
>>> removePinnedSites
>>> dupePinnedSite
>>> removeHistory
>>> done
waitForExpectations(timeout: 10.0) { error in
return
}
}
}
class TestSQLiteHistoryTransactionUpdate: XCTestCase {
func testUpdateInTransaction() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
let history = SQLiteHistory(db: db, prefs: prefs)
history.clearHistory().succeeded()
let site = Site(url: "http://site/foo", title: "AA")
site.guid = "abcdefghiabc"
history.insertOrUpdatePlace(site.asPlace(), modified: 1234567890).succeeded()
let ts: MicrosecondTimestamp = baseInstantInMicros
let local = SiteVisit(site: site, date: ts, type: VisitType.link)
XCTAssertTrue(history.addLocalVisit(local).value.isSuccess)
}
}
class TestSQLiteHistoryFilterSplitting: XCTestCase {
let history: SQLiteHistory = {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", schema: BrowserSchema(), files: files)
let prefs = MockProfilePrefs()
return SQLiteHistory(db: db, prefs: prefs)
}()
func testWithSingleWord() {
let (fragment, args) = computeWhereFragmentWithFilter("foo", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foo"]))
}
func testWithIdenticalWords() {
let (fragment, args) = computeWhereFragmentWithFilter("foo fo foo", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foo"]))
}
func testWithDistinctWords() {
let (fragment, args) = computeWhereFragmentWithFilter("foo bar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "? AND ?")
XCTAssert(stringArgsEqual(args, ["foo", "bar"]))
}
func testWithDistinctWordsAndWhitespace() {
let (fragment, args) = computeWhereFragmentWithFilter(" foo bar ", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "? AND ?")
XCTAssert(stringArgsEqual(args, ["foo", "bar"]))
}
func testWithSubstrings() {
let (fragment, args) = computeWhereFragmentWithFilter("foo bar foobar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foobar"]))
}
func testWithSubstringsAndIdenticalWords() {
let (fragment, args) = computeWhereFragmentWithFilter("foo bar foobar foobar", perWordFragment: "?", perWordArgs: { [$0] })
XCTAssertEqual(fragment, "?")
XCTAssert(stringArgsEqual(args, ["foobar"]))
}
fileprivate func stringArgsEqual(_ one: Args, _ other: Args) -> Bool {
return one.elementsEqual(other, by: { (oneElement: Any?, otherElement: Any?) -> Bool in
return (oneElement as! String) == (otherElement as! String)
})
}
}
// MARK - Private Test Helper Methods
enum VisitOrigin {
case local
case remote
}
private func populateHistoryForFrecencyCalculations(_ history: SQLiteHistory, siteCount count: Int) {
for i in 0...count {
let site = Site(url: "http://s\(i)ite\(i).com/foo", title: "A \(i)")
site.guid = "abc\(i)def"
let baseMillis: UInt64 = baseInstantInMillis - 20000
history.insertOrUpdatePlace(site.asPlace(), modified: baseMillis).succeeded()
for j in 0...20 {
let visitTime = advanceMicrosecondTimestamp(baseInstantInMicros, by: (1000000 * i) + (1000 * j))
addVisitForSite(site, intoHistory: history, from: .local, atTime: visitTime)
addVisitForSite(site, intoHistory: history, from: .remote, atTime: visitTime - 100)
}
}
}
func addVisitForSite(_ site: Site, intoHistory history: SQLiteHistory, from: VisitOrigin, atTime: MicrosecondTimestamp) {
let visit = SiteVisit(site: site, date: atTime, type: VisitType.link)
switch from {
case .local:
history.addLocalVisit(visit).succeeded()
case .remote:
history.storeRemoteVisits([visit], forGUID: site.guid!).succeeded()
}
}
| mpl-2.0 | d63fce013a750acba518ce05e1c3f0ab | 39.978783 | 231 | 0.57827 | 5.108799 | false | false | false | false |
mcjcloud/Show-And-Sell | Show And Sell/EditEmailViewController.swift | 1 | 3597 | //
// EditEmailViewController.swift
// Show And Sell
//
// Created by Brayden Cloud on 3/7/17.
// Copyright © 2017 Brayden Cloud. All rights reserved.
//
import UIKit
class EditEmailViewController: UIViewController {
// MARK: UI Properties
@IBOutlet var emailField: UITextField!
@IBOutlet var saveButton: UIBarButtonItem!
// MARK: Properties
var email: String!
var overlay = OverlayView(type: .loading, text: nil)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// setup textfield
setupTextField(emailField)
// make textfields dismiss when uiview tapped
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)))
// set textfield data
emailField.text = email
// set saveButton.isEnabled
saveButton.isEnabled = shouldEnableSave()
}
// MARK: Helper
func setupTextField(_ textfield: UITextField) {
// edit password field
let width = CGFloat(1.5)
let border = CALayer()
border.borderColor = UIColor(colorLiteralRed: 0.298, green: 0.686, blue: 0.322, alpha: 1.0).cgColor // Green
border.frame = CGRect(x: 0, y: textfield.frame.size.height - width, width: textfield.frame.size.width, height: textfield.frame.size.height)
border.borderWidth = width
textfield.layer.addSublayer(border)
textfield.layer.masksToBounds = true
textfield.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
}
func textChanged(_ textField: UITextField) {
saveButton.isEnabled = shouldEnableSave()
}
// dismiss a keyboard
func dismissKeyboard() {
emailField.resignFirstResponder()
}
func shouldEnableSave() -> Bool {
return emailField.text?.characters.count ?? 0 > 0
}
func displayError(text: String) {
DispatchQueue.main.async {
let alert = UIAlertController(title: "Error", message: text, preferredStyle: .alert)
let dismissAction = UIAlertAction(title: "Dismiss", style: .default, handler: nil)
alert.addAction(dismissAction)
self.present(alert, animated: true, completion: nil)
}
}
// MARK: IBAction
@IBAction func saveEmail(_ sender: UIBarButtonItem) {
// show overlay
overlay.showOverlay(view: UIApplication.shared.keyWindow!, position: .center)
if let user = AppData.user {
overlay.showOverlay(view: UIApplication.shared.keyWindow!, position: .center)
user.email = emailField.text!
HttpRequestManager.put(user: user, currentPassword: user.password) { user, response, error in
// hide overlay
DispatchQueue.main.async {
self.overlay.hideOverlayView()
}
if let u = user {
AppData.user = u
// Dismiss this
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}
else {
// error getting user
self.displayError(text: "Error verifying success of update.")
}
}
}
else {
self.displayError(text: "An error occurred. Try again.")
}
}
}
| apache-2.0 | 2853e3d73b06feb0587798e0153500da | 32.607477 | 148 | 0.583148 | 5.11522 | false | false | false | false |
PureSwift/Cacao | Tests/CacaoTests/FontTests.swift | 1 | 905 | //
// FontTests.swift
// Cacao
//
// Created by Alsey Coleman Miller on 5/31/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
import XCTest
import Cacao
final class FontTests: XCTestCase {
static let allTests = [("testCreateFont", testCreateFont)]
func testCreateFont() {
let fontNames = [
("MicrosoftSansSerif", "Microsoft Sans Serif"),
("MicrosoftSansSerif-Bold", "Microsoft Sans Serif"),
("TimesNewRoman", "Times New Roman"),
("TimesNewRoman-Bold", "Times New Roman")
]
for (fontName, expectedFullName) in fontNames {
guard let font = UIFont(name: fontName, size: 17)
else { XCTFail("Could not create font"); return }
XCTAssert(fontName == font.fontName, "\(expectedFullName) == \(fontName)")
}
}
}
| mit | 8b63374d129c4ecae4ebdd43ab7e36fa | 26.393939 | 86 | 0.567478 | 4.732984 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.