repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
simonnarang/Fandom-IOS | Fandomm/RedisClient+Keys.swift | 2 | 26037 | //
// RedisClient+Keys.swift
// Redis-Framework
//
// Copyright (c) 2015, Eric Orion Anderson
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
public enum RedisMigrationType:String
{
case Copy = "COPY"
case Replace = "REPLACE"
}
public enum RedisObjectSubCommand:String
{
case RefCount = "REFCOUNT"
case Encoding = "ENCODING"
case IdleTime = "IDLETIME"
}
extension RedisClient
{
/// DEL key [key ...] Removes the specified keys. A key is ignored if it does not exist.
///
/// - returns: Integer reply: The number of keys that were removed.
public func delete(keys:[String], completionHandler:RedisCommandIntegerBlock)
{
var command:String = "DEL"
for(_, key) in keys.enumerate() {
command = command + " " + RESPUtilities.respStringFromString(key)
}
self.sendCommandWithIntegerResponse(command, completionHandler: completionHandler)
}
/// DUMP key
///
/// Serialize the value stored at key in a Redis-specific format and return it to the user. The returned value can be synthesized back into a Redis key using the RESTORE command.
/// The serialization format is opaque and non-standard, however it has a few semantical characteristics:
/// It contains a 64-bit checksum that is used to make sure errors will be detected. The RESTORE command makes sure to check the checksum before synthesizing a key using the serialized value.
/// Values are encoded in the same format used by RDB.
/// An RDB version is encoded inside the serialized value, so that different Redis versions with incompatible RDB formats will refuse to process the serialized value.
/// The serialized value does NOT contain expire information. In order to capture the time to live of the current value the PTTL command should be used.
/// If key does not exist a nil bulk reply is returned.
///
/// - returns: Bulk string reply: the serialized value. *NOTE* This is not fully tested and doesn't encode directly to UTF-8
public func dump(key:String, completionHandler:RedisCommandDataBlock)
{
self.sendCommandWithDataResponse("DUMP \(RESPUtilities.respStringFromString(key))", completionHandler: { (data, error) -> Void in
if error != nil {
completionHandler(data: nil, error: error)
}
else //custom parsing for binary data, not UTF-8 compliant
{
let customData:NSData = data
let clrfData:NSData = "\r\n".dataUsingEncoding(NSUTF8StringEncoding)!
let crlfFirstRange:NSRange = customData.rangeOfData(clrfData, options: NSDataSearchOptions(), range: NSMakeRange(0, customData.length))
if crlfFirstRange.location != NSNotFound //simple check for the first \r\n
{
let crlfEndRange:NSRange = customData.rangeOfData(clrfData, options: NSDataSearchOptions.Backwards, range: NSMakeRange(0, customData.length))
if crlfEndRange.location != crlfFirstRange.location //assuming found last \r\n
{
let serialzedData:NSData = customData.subdataWithRange(NSMakeRange(crlfFirstRange.location+crlfFirstRange.length, customData.length-(crlfFirstRange.location+crlfFirstRange.length)-(crlfFirstRange.length)))
completionHandler(data: serialzedData, error: nil)
return
}
}
completionHandler(data: nil, error: NSError(domain: RedisErrorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey:"Unexpected response format"]))
}
})
}
/// EXISTS key
///
/// Returns if key exists.
///
/// - returns: Integer reply, specifically: 1 if the key exists. 0 if the key does not exist.
public func exists(key:String, completionHandler:RedisCommandIntegerBlock) {
self.sendCommandWithIntegerResponse("EXISTS \(RESPUtilities.respStringFromString(key))", completionHandler: completionHandler)
}
/// EXPIRE key seconds
///
/// Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is
/// often said to be volatile in Redis terminology.
/// The timeout is cleared only when the key is removed using the DEL command or overwritten using the SET or GETSET commands.
/// This means that all the operations that conceptually alter the value stored at the key without replacing it with a new one will
/// leave the timeout untouched. For instance, incrementing the value of a key with INCR, pushing a new value into a list with LPUSH,
/// or altering the field value of a hash with HSET are all operations that will leave the timeout untouched.
/// The timeout can also be cleared, turning the key back into a persistent key, using the PERSIST command.
/// If a key is renamed with RENAME, the associated time to live is transferred to the new key name.
/// If a key is overwritten by RENAME, like in the case of an existing key Key_A that is overwritten by a call like RENAME Key_B Key_A,
/// it does not matter if the original Key_A had a timeout associated or not, the new key Key_A will inherit all the characteristics of Key_B.
///
/// Refreshing expires
///
/// It is possible to call EXPIRE using as argument a key that already has an existing expire set. In this case the time to live of a key is
/// updated to the new value. There are many useful applications for this, an example is documented in the Navigation session pattern section below.
///
/// - returns: Integer reply, specifically: 1 if the timeout was set. 0 if key does not exist or the timeout could not be set.
public func expire(key:String, timeoutInSeconds:Int, completionHandler:RedisCommandIntegerBlock) {
self.sendCommandWithIntegerResponse("EXPIRE \(RESPUtilities.respStringFromString(key)) \(timeoutInSeconds)", completionHandler: completionHandler)
}
/// EXPIREAT key timestamp
///
/// EXPIREAT has the same effect and semantic as EXPIRE, but instead of specifying the number of seconds representing the TTL (time to live),
/// it takes an absolute Unix timestamp (seconds since January 1, 1970).
/// Please for the specific semantics of the command refer to the documentation of EXPIRE.
///
/// - returns: Integer reply, specifically: 1 if the timeout was set. 0 if key does not exist or the timeout could not be set (see: EXPIRE).
public func expire(key:String, at date:NSDate, completionHandler:RedisCommandIntegerBlock) {
self.sendCommandWithIntegerResponse("EXPIREAT \(RESPUtilities.respStringFromString(key)) \(Int(date.timeIntervalSince1970))", completionHandler: completionHandler)
}
/// KEYS pattern
///
/// Returns all keys matching pattern.
/// While the time complexity for this operation is O(N), the constant times are fairly low. For example,
/// Redis running on an entry level laptop can scan a 1 million key database in 40 milliseconds.
/// Warning: consider KEYS as a command that should only be used in production environments with extreme care.
/// It may ruin performance when it is executed against large databases. This command is intended for debugging and special operations,
/// such as changing your keyspace layout. Don't use KEYS in your regular application code. If you're looking for a way to find keys in a subset of your keyspace,
/// consider using SCAN or sets.
/// Supported glob-style patterns:
///
/// h?llo matches hello, hallo and hxllo
///
/// h*llo matches hllo and heeeello
///
/// h[ae]llo matches hello and hallo, but not hillo
///
/// Use \ to escape special characters if you want to match them verbatim.
///
/// - returns: Array reply: list of keys matching pattern.
public func keys(pattern:String, completionHandler:RedisCommandArrayBlock) {
self.sendCommandWithArrayResponse("KEYS \(RESPUtilities.respStringFromString(pattern))", completionHandler: completionHandler)
}
/// MIGRATE host port key destination-db timeout [COPY] [REPLACE]
///
/// Atomically transfer a key from a source Redis instance to a destination Redis instance. On success the key is deleted from the
/// original instance and is guaranteed to exist in the target instance.
/// The command is atomic and blocks the two instances for the time required to transfer the key, at any given time the key will
/// appear to exist in a given instance or in the other instance, unless a timeout error occurs.
/// The command internally uses DUMP to generate the serialized version of the key value, and RESTORE in order to synthesize the key in the target instance.
/// The source instance acts as a client for the target instance. If the target instance returns OK to the RESTORE command, the source instance deletes the key using DEL.
/// The timeout specifies the maximum idle time in any moment of the communication with the destination instance in milliseconds.
/// This means that the operation does not need to be completed within the specified amount of milliseconds,
/// but that the transfer should make progresses without blocking for more than the specified amount of milliseconds.
/// MIGRATE needs to perform I/O operations and to honor the specified timeout. When there is an I/O error during the transfer or if the timeout
/// is reached the operation is aborted and the special error - IOERR returned. When this happens the following two cases are possible:
/// The key may be on both the instances.
/// The key may be only in the source instance.
/// It is not possible for the key to get lost in the event of a timeout, but the client calling MIGRATE, in the event of a timeout error,
/// should check if the key is also present in the target instance and act accordingly.
/// When any other error is returned (starting with ERR) MIGRATE guarantees that the key is still only present in the originating instance
/// (unless a key with the same name was also already present on the target instance).
///
/// - returns: Simple string reply: On success OK is returned.
public func migrate(host:String, port:Int, key:String, destinationDB:String, timeoutInMilliseconds:Int, migrationType:RedisMigrationType, completionHandler:RedisCommandStringBlock) {
self.sendCommandWithStringResponse("MIGRATE \(host) \(port) \(RESPUtilities.respStringFromString(key)) \(RESPUtilities.respStringFromString(destinationDB)) \(timeoutInMilliseconds) \(migrationType.rawValue)", completionHandler: completionHandler)
}
/// MOVE key db
///
/// Move key from the currently selected database (see SELECT) to the specified destination database.
/// When key already exists in the destination database, or it does not exist in the source database,
/// it does nothing. It is possible to use MOVE as a locking primitive because of this.
///
/// - returns: Integer reply, specifically: 1 if key was moved. 0 if key was not moved.
public func move(key:String, db:String, completionHandler:RedisCommandIntegerBlock) {
self.sendCommandWithIntegerResponse("MOVE \(RESPUtilities.respStringFromString(key)) \(RESPUtilities.respStringFromString(db))", completionHandler: completionHandler)
}
/// OBJECT REFCOUNT key
///
/// The OBJECT command allows to inspect the internals of Redis Objects associated with keys. It is useful for debugging or to understand if your keys
/// are using the specially encoded data types to save space. Your application may also use the information reported by the OBJECT command to implement
/// application level key eviction policies when using Redis as a Cache.
///
/// - returns: Interger reply: The number of references of the value associated with the specified key. This command is mainly useful for debugging.
public func objectRefCount(key:String, completionHandler:RedisCommandIntegerBlock) {
self.sendCommandWithIntegerResponse("OBJECT REFCOUNT \(RESPUtilities.respStringFromString(key))", completionHandler: completionHandler)
}
/// OBJECT ENCODING key
///
/// The OBJECT command allows to inspect the internals of Redis Objects associated with keys. It is useful for debugging or to understand if your keys
/// are using the specially encoded data types to save space. Your application may also use the information reported by the OBJECT command to implement
/// application level key eviction policies when using Redis as a Cache.
///
/// Objects can be encoded in different ways:
/// Strings can be encoded as raw (normal string encoding) or int (strings representing integers in a 64 bit signed interval are encoded in this way in order to save space).
/// Lists can be encoded as ziplist or linkedlist. The ziplist is the special representation that is used to save space for small lists.
/// Sets can be encoded as intset or hashtable. The intset is a special encoding used for small sets composed solely of integers.
/// Hashes can be encoded as zipmap or hashtable. The zipmap is a special encoding used for small hashes.
/// Sorted Sets can be encoded as ziplist or skiplist format. As for the List type small sorted sets can be specially encoded using ziplist,
/// while the skiplist encoding is the one that works with sorted sets of any size.
///
/// - returns: Bulk string reply: The kind of internal representation used in order to store the value associated with a key.
public func objectEncoding(key:String, completionHandler:RedisCommandStringBlock) {
self.sendCommandWithStringResponse("OBJECT ENCODING \(RESPUtilities.respStringFromString(key))", completionHandler: completionHandler)
}
/// PERSIST key
///
/// Remove the existing timeout on key, turning the key from volatile (a key with an expire set) to persistent (a key that will never expire as no timeout is associated).
///
/// - returns: Integer reply, specifically: 1 if the timeout was removed. 0 if key does not exist or does not have an associated timeout.
public func persist(key:String, completionHandler:RedisCommandIntegerBlock) {
self.sendCommandWithIntegerResponse("PERSIST \(RESPUtilities.respStringFromString(key))", completionHandler: completionHandler)
}
/// PEXPIRE key milliseconds
///
/// This command works exactly like EXPIRE but the time to live of the key is specified in milliseconds instead of seconds.
///
/// - returns: Integer reply, specifically: 1 if the timeout was set. 0 if key does not exist or the timeout could not be set.
public func pExpire(key:String, timeoutInMilliseconds:UInt, completionHandler:RedisCommandIntegerBlock) {
self.sendCommandWithIntegerResponse("PEXPIRE \(RESPUtilities.respStringFromString(key)) \(timeoutInMilliseconds)", completionHandler: completionHandler)
}
/// PEXPIREAT key milliseconds-timestamp
///
/// PEXPIREAT has the same effect and semantic as EXPIREAT, but the Unix time at which the key will expire is specified in milliseconds instead of seconds.
///
/// - returns: Integer reply, specifically: 1 if the timeout was set. 0 if key does not exist or the timeout could not be set (see: EXPIRE).
public func pExpire(key:String, at date:NSDate, completionHandler:RedisCommandIntegerBlock) {
self.sendCommandWithIntegerResponse("PEXPIREAT \(RESPUtilities.respStringFromString(key)) \(Int(date.timeIntervalSince1970*1000))", completionHandler: completionHandler)
}
/// PTTL key
///
/// Like TTL this command returns the remaining time to live of a key that has an expire set,
/// with the sole difference that TTL returns the amount of remaining time in seconds while PTTL returns it in milliseconds.
///
/// In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire.
/// Starting with Redis 2.8 the return value in case of error changed:
/// The command returns -2 if the key does not exist.
/// The command returns -1 if the key exists but has no associated expire.
///
/// - returns: Integer reply: TTL in milliseconds, or a negative value in order to signal an error (see the description above).
public func pttl(key:String, completionHandler:RedisCommandIntegerBlock) {
self.sendCommandWithIntegerResponse("PTTL \(RESPUtilities.respStringFromString(key))", completionHandler: completionHandler)
}
/// RANDOMKEY
///
/// Return a random key from the currently selected database.
///
/// - returns: Bulk string reply: the random key, or nil when the database is empty.
public func randomKey(completionHandler:RedisCommandStringBlock) {
self.sendCommandWithStringResponse("RANDOMKEY", completionHandler: completionHandler)
}
/// RENAME key newkey
///
/// Renames key to newkey. It returns an error when the source and destination names are the same, or when key does not exist.
/// If newkey already exists it is overwritten, when this happens RENAME executes an implicit DEL operation, so if the deleted
/// key contains a very big value it may cause high latency even if RENAME itself is usually a constant-time operation.
///
/// - returns: Simple string reply
public func rename(key:String, newKey:String, completionHandler:RedisCommandStringBlock) {
self.sendCommandWithStringResponse("RENAME \(RESPUtilities.respStringFromString(key)) \(RESPUtilities.respStringFromString(newKey))", completionHandler: completionHandler)
}
/// RENAMENX key newkey
///
/// Renames key to newkey if newkey does not yet exist. It returns an error under the same conditions as RENAME.
///
/// - returns: Integer reply, specifically: 1 if key was renamed to newkey. 0 if newkey already exists.
public func renameNX(key:String, newKey:String, completionHandler:RedisCommandIntegerBlock) {
self.sendCommandWithIntegerResponse("RENAMENX \(RESPUtilities.respStringFromString(key)) \(RESPUtilities.respStringFromString(newKey))", completionHandler: completionHandler)
}
/// RESTORE key ttl serialized-value
///
/// Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via DUMP).
/// If ttl is 0 the key is created without any expire, otherwise the specified expire time (in milliseconds) is set.
/// RESTORE checks the RDB version and data checksum. If they don't match an error is returned.
///
/// - returns: Simple string reply: The command returns OK on success.
public func restore(key:String, ttl:UInt = 0, serializedValue:NSData, completionHandler:RedisCommandStringBlock) {
self.sendCommandWithStringResponse("RESTORE \(RESPUtilities.respStringFromString(key)) \(ttl)", data:serializedValue, completionHandler: completionHandler)
}
// SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination]
// TODO:
/// TTL key
///
/// Returns the remaining time to live of a key that has a timeout. This introspection capability allows a Redis client to check how many seconds a given key will continue to be part of the dataset.
/// In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire.
/// Starting with Redis 2.8 the return value in case of error changed:
/// The command returns -2 if the key does not exist.
/// The command returns -1 if the key exists but has no associated expire.
/// See also the PTTL command that returns the same information with milliseconds resolution (Only available in Redis 2.6 or greater).
///
/// - returns: Integer reply: TTL in seconds, or a negative value in order to signal an error (see the description above).
public func ttl(key:String, completionHandler:RedisCommandIntegerBlock) {
self.sendCommandWithIntegerResponse("TTL \(RESPUtilities.respStringFromString(key))", completionHandler: completionHandler)
}
/// TYPE key
///
/// Returns the string representation of the type of the value stored at key. The different types that can be returned are: string, list, set, zset and hash.
///
/// - returns: Simple string reply: type of key, or none when key does not exist.
public func type(key:String, completionHandler:RedisCommandStringBlock) {
self.sendCommandWithStringResponse("TYPE \(RESPUtilities.respStringFromString(key))", completionHandler: completionHandler)
}
/// SCAN cursor [MATCH pattern] [COUNT count]
///
/// SCAN basic usage
///
/// SCAN is a cursor based iterator. This means that at every call of the command, the server returns an updated cursor that the user
/// needs to use as the cursor argument in the next call.
///
/// Scan guarantees
///
/// The SCAN command, and the other commands in the SCAN family, are able to provide to the user a set of guarantees associated to full iterations.
/// A full iteration always retrieves all the elements that were present in the collection from the start to the end of a full iteration.
/// This means that if a given element is inside the collection when an iteration is started, and is still there when an iteration terminates,
/// then at some point SCAN returned it to the user.
/// A full iteration never returns any element that was NOT present in the collection from the start to the end of a full iteration.
/// So if an element was removed before the start of an iteration, and is never added back to the collection for all the time an iteration lasts,
/// SCAN ensures that this element will never be returned.
///
/// Number of elements returned at every SCAN call
///
/// SCAN family functions do not guarantee that the number of elements returned per call are in a given range.
/// The commands are also allowed to return zero elements, and the client should not consider the iteration complete as long as the returned cursor is not zero.
///
/// The COUNT option
///
/// While SCAN does not provide guarantees about the number of elements returned at every iteration,
/// it is possible to empirically adjust the behavior of SCAN using the COUNT option.
/// Basically with COUNT the user specified the amount of work that should be done at every call in order to retrieve elements from the collection.
/// This is just an hint for the implementation, however generally speaking this is what you could expect most of the times from the implementation.
/// The default COUNT value is 10.
/// When iterating the key space, or a Set, Hash or Sorted Set that is big enough to be represented by an hash table, assuming no MATCH option is used,
/// the server will usually return count or a bit more than count elements per call.
/// When iterating Sets encoded as intsets (small sets composed of just integers), or Hashes and Sorted Sets encoded as ziplists
/// (small hashes and sets composed of small individual values), usually all the elements are returned in the first SCAN call regardless of the COUNT value.
///
/// The MATCH option
///
/// It is possible to only iterate elements matching a given glob-style pattern, similarly to the behavior of the KEYS command that takes a pattern as only argument.
/// To do so, just append the MATCH <pattern> arguments at the end of the SCAN command (it works with all the SCAN family commands).
///
/// - returns: SCAN return a two elements multi-bulk reply, where the first element is a string representing an unsigned 64 bit number (the cursor), and the second element is a multi-bulk with an array of elements. SCAN array of elements is a list of keys.
public func scan(cursor:UInt, pattern:String? = nil, count:UInt? = nil, completionHandler:RedisCommandArrayBlock)
{
var command:String = "SCAN \(cursor)"
if pattern != nil {
command = command + " MATCH \(RESPUtilities.respStringFromString(pattern!))"
}
if count != nil {
command = command + " COUNT \(count!)"
}
self.sendCommandWithArrayResponse(command, completionHandler: completionHandler)
}
} | unlicense | 3b92391a94ea260f71a12583dc8283fa | 65.935733 | 260 | 0.721051 | 4.757354 | false | false | false | false |
goRestart/restart-backend-app | Tests/StorageTests/Tasks/Utils/Generator/UserGenerator.swift | 1 | 621 | import Foundation
@testable import FluentStorage
// MARK: - Helpers
@discardableResult
func givenDisabledUser(with username: String, password: String) -> UserDiskModel {
return givenUser(with: username, password: password, disabled: true)
}
@discardableResult
func givenUser(with username: String, password: String, email: String = "[email protected]", disabled: Bool = false) -> UserDiskModel {
let user = try! UserDiskModel(
username: username,
password: password
)
user.email = email
user.status = disabled ? .banned: .enabled
try! user.save()
return user
}
| gpl-3.0 | 5a164b3153a582330e3fd9227b59e315 | 26 | 134 | 0.692432 | 4.14 | false | false | false | false |
tryswift/TryParsec | excludedTests/TryParsec/Specs/CSVSpec.swift | 1 | 1954 | import TryParsec
import Quick
import Nimble
class CSVSpec: QuickSpec
{
override func spec()
{
describe("parseCSV") {
it("succeeds (\\r\\n)") {
let r = parseCSV("foo,bar,baz\r\n1,22,333\r\n")
expect(r.value?[0]) == ["foo", "bar", "baz"]
expect(r.value?[1]) == ["1", "22", "333"]
expect(r.value?.count) == 2
}
it("succeeds (\\n)") {
let r = parseCSV("foo,bar,baz\n1,22,333\n")
expect(r.value?[0]) == ["foo", "bar", "baz"]
expect(r.value?[1]) == ["1", "22", "333"]
expect(r.value?.count) == 2
}
it("succeeds (\\n + no end break)") {
let r = parseCSV("foo,bar,baz\n1,22,333")
expect(r.value?[0]) == ["foo", "bar", "baz"]
expect(r.value?[1]) == ["1", "22", "333"]
expect(r.value?.count) == 2
}
}
describe("parseCSV (separator = \t)") {
it("succeeds (\\r\\n)") {
let r = parseCSV(separator: "\t", "foo\tbar\tbaz\r\n1\t22\t333\r\n")
expect(r.value?[0]) == ["foo", "bar", "baz"]
expect(r.value?[1]) == ["1", "22", "333"]
expect(r.value?.count) == 2
}
it("succeeds (\\n)") {
let r = parseCSV(separator: "\t", "foo\tbar\tbaz\n1\t22\t333\n")
expect(r.value?[0]) == ["foo", "bar", "baz"]
expect(r.value?[1]) == ["1", "22", "333"]
expect(r.value?.count) == 2
}
it("succeeds (\\n + no end break)") {
let r = parseCSV(separator: "\t", "foo\tbar\tbaz\n1\t22\t333")
expect(r.value?[0]) == ["foo", "bar", "baz"]
expect(r.value?[1]) == ["1", "22", "333"]
expect(r.value?.count) == 2
}
}
}
}
| mit | e0435cb7164295302370344bc2cf7947 | 32.118644 | 84 | 0.397646 | 3.340171 | false | false | false | false |
tylerbrockett/cse394-principles-of-mobile-applications | final-project/Appa/WeatherForecast.swift | 1 | 3107 | /*
* @authors Tyler Brockett, Shikha Mehta, Tam Le
* @course ASU CSE 394
* @project Group Project
* @version April 15, 2016
* @project-description Allows users to track Geocaches
* @class-name WeatherForecast.swift
* @class-description Helper class to store information about the weather for a specific location
*/
import Foundation
class WeatherForecast {
var current:String = ""
var low:String = ""
var high:String = ""
var desc:String = ""
var error:Bool = true
init(result:String) {
if let data: NSData = result.dataUsingEncoding(NSUTF8StringEncoding){
do{
print(result)
let dict = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String:AnyObject]
let main:NSDictionary = dict!["main"]! as! NSDictionary
let weather:NSArray = dict!["weather"] as! NSArray
let c:Double = main["temp"] as! Double
let l:Double = main["temp_min"] as! Double
let h:Double = main["temp_max"] as! Double
let d:String = weather[0]["main"] as! String
self.current = String(format:"%.1f", c)
self.low = String(format:"%.1f", l)
self.high = String(format:"%.1f", h)
self.desc = d
self.error = false
} catch let error as NSError {
NSLog(error.localizedDescription)
}
} else {
NSLog("Error parsing Weather Forecast data")
}
}
func getTemp() -> String {
return self.current
}
func getLow() -> String {
return self.low
}
func getHigh() -> String {
return self.high
}
func getDescription() -> String {
return self.desc
}
func hasError() -> Bool {
return self.error
}
}
/* SAMPLE RESPONSE:
{
"coord":
{
"lon":-111.91,
"lat":33.41},
"weather":
[
{
"id":800,
"main":"Clear",
"description":"clear sky",
"icon":"01n"
}
],
"base":"cmc stations",
"main":
{
"temp":72.54,
"pressure":1015,
"humidity":14,
"temp_min":68,
"temp_max":75.2
},
"wind":
{
"speed":3.36,
"deg":250
},
"clouds":
{
"all":1
},
"dt":1460015468,
"sys":
{
"type":1,
"id":325,
"message":0.0035,
"country":"US",
"sunrise":1460034375,
"sunset":1460080391
},
"id":5317058,
"name":"Tempe",
"cod":200
}
}
*/
| mit | b45933ce815d5425db7da56989beb992 | 25.109244 | 127 | 0.433859 | 4.535766 | false | false | false | false |
themonki/onebusaway-iphone | Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobuf/JSONEncodingVisitor.swift | 1 | 11814 | // Sources/SwiftProtobuf/JSONEncodingVisitor.swift - JSON encoding visitor
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Visitor that writes a message in JSON format.
///
// -----------------------------------------------------------------------------
import Foundation
/// Visitor that serializes a message into JSON format.
internal struct JSONEncodingVisitor: Visitor {
private var encoder = JSONEncoder()
private var nameMap: _NameMap
private let options: JSONEncodingOptions
/// The JSON text produced by the visitor, as raw UTF8 bytes.
var dataResult: Data {
return encoder.dataResult
}
/// The JSON text produced by the visitor, as a String.
internal var stringResult: String {
return encoder.stringResult
}
/// Creates a new visitor for serializing a message of the given type to JSON
/// format.
init(type: Message.Type, options: JSONEncodingOptions) throws {
if let nameProviding = type as? _ProtoNameProviding.Type {
self.nameMap = nameProviding._protobuf_nameMap
} else {
throw JSONEncodingError.missingFieldNames
}
self.options = options
}
/// Creates a new visitor that serializes the given message to JSON format.
init(message: Message, options: JSONEncodingOptions) throws {
if let nameProviding = message as? _ProtoNameProviding {
self.nameMap = type(of: nameProviding)._protobuf_nameMap
} else {
throw JSONEncodingError.missingFieldNames
}
self.options = options
}
mutating func startArray() {
encoder.startArray()
}
mutating func endArray() {
encoder.endArray()
}
mutating func startObject() {
encoder.startObject()
}
mutating func endObject() {
encoder.endObject()
}
mutating func encodeField(name: String, stringValue value: String) {
encoder.startField(name: name)
encoder.putStringValue(value: value)
}
mutating func encodeField(name: String, jsonText text: String) {
encoder.startField(name: name)
encoder.append(text: text)
}
mutating func visitUnknown(bytes: Data) throws {
// JSON encoding has no provision for carrying proto2 unknown fields.
}
mutating func visitSingularFloatField(value: Float, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.putFloatValue(value: value)
}
mutating func visitSingularDoubleField(value: Double, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.putDoubleValue(value: value)
}
mutating func visitSingularInt32Field(value: Int32, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.putInt32(value: value)
}
mutating func visitSingularInt64Field(value: Int64, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.putInt64(value: value)
}
mutating func visitSingularUInt32Field(value: UInt32, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.putUInt32(value: value)
}
mutating func visitSingularUInt64Field(value: UInt64, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.putUInt64(value: value)
}
mutating func visitSingularFixed32Field(value: UInt32, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.putUInt32(value: value)
}
mutating func visitSingularSFixed32Field(value: Int32, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.putInt32(value: value)
}
mutating func visitSingularBoolField(value: Bool, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.putBoolValue(value: value)
}
mutating func visitSingularStringField(value: String, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.putStringValue(value: value)
}
mutating func visitSingularBytesField(value: Data, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.putBytesValue(value: value)
}
private mutating func _visitRepeated<T>(
value: [T],
fieldNumber: Int,
encode: (inout JSONEncoder, T) throws -> ()
) throws {
try startField(for: fieldNumber)
var comma = false
encoder.startArray()
for v in value {
if comma {
encoder.comma()
}
comma = true
try encode(&encoder, v)
}
encoder.endArray()
}
mutating func visitSingularEnumField<E: Enum>(value: E, fieldNumber: Int) throws {
try startField(for: fieldNumber)
if !options.alwaysPrintEnumsAsInts, let n = value.name {
encoder.appendQuoted(name: n)
} else {
encoder.putEnumInt(value: value.rawValue)
}
}
mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) throws {
try startField(for: fieldNumber)
let json = try value.jsonUTF8Data(options: options)
encoder.append(utf8Data: json)
}
mutating func visitSingularGroupField<G: Message>(value: G, fieldNumber: Int) throws {
// Google does not serialize groups into JSON
}
mutating func visitRepeatedFloatField(value: [Float], fieldNumber: Int) throws {
try _visitRepeated(value: value, fieldNumber: fieldNumber) {
(encoder: inout JSONEncoder, v: Float) in
encoder.putFloatValue(value: v)
}
}
mutating func visitRepeatedDoubleField(value: [Double], fieldNumber: Int) throws {
try _visitRepeated(value: value, fieldNumber: fieldNumber) {
(encoder: inout JSONEncoder, v: Double) in
encoder.putDoubleValue(value: v)
}
}
mutating func visitRepeatedInt32Field(value: [Int32], fieldNumber: Int) throws {
try _visitRepeated(value: value, fieldNumber: fieldNumber) {
(encoder: inout JSONEncoder, v: Int32) in
encoder.putInt32(value: v)
}
}
mutating func visitRepeatedInt64Field(value: [Int64], fieldNumber: Int) throws {
try _visitRepeated(value: value, fieldNumber: fieldNumber) {
(encoder: inout JSONEncoder, v: Int64) in
encoder.putInt64(value: v)
}
}
mutating func visitRepeatedUInt32Field(value: [UInt32], fieldNumber: Int) throws {
try _visitRepeated(value: value, fieldNumber: fieldNumber) {
(encoder: inout JSONEncoder, v: UInt32) in
encoder.putUInt32(value: v)
}
}
mutating func visitRepeatedUInt64Field(value: [UInt64], fieldNumber: Int) throws {
try _visitRepeated(value: value, fieldNumber: fieldNumber) {
(encoder: inout JSONEncoder, v: UInt64) in
encoder.putUInt64(value: v)
}
}
mutating func visitRepeatedSInt32Field(value: [Int32], fieldNumber: Int) throws {
try visitRepeatedInt32Field(value: value, fieldNumber: fieldNumber)
}
mutating func visitRepeatedSInt64Field(value: [Int64], fieldNumber: Int) throws {
try visitRepeatedInt64Field(value: value, fieldNumber: fieldNumber)
}
mutating func visitRepeatedFixed32Field(value: [UInt32], fieldNumber: Int) throws {
try visitRepeatedUInt32Field(value: value, fieldNumber: fieldNumber)
}
mutating func visitRepeatedFixed64Field(value: [UInt64], fieldNumber: Int) throws {
try visitRepeatedUInt64Field(value: value, fieldNumber: fieldNumber)
}
mutating func visitRepeatedSFixed32Field(value: [Int32], fieldNumber: Int) throws {
try visitRepeatedInt32Field(value: value, fieldNumber: fieldNumber)
}
mutating func visitRepeatedSFixed64Field(value: [Int64], fieldNumber: Int) throws {
try visitRepeatedInt64Field(value: value, fieldNumber: fieldNumber)
}
mutating func visitRepeatedBoolField(value: [Bool], fieldNumber: Int) throws {
try _visitRepeated(value: value, fieldNumber: fieldNumber) {
(encoder: inout JSONEncoder, v: Bool) in
encoder.putBoolValue(value: v)
}
}
mutating func visitRepeatedStringField(value: [String], fieldNumber: Int) throws {
try _visitRepeated(value: value, fieldNumber: fieldNumber) {
(encoder: inout JSONEncoder, v: String) in
encoder.putStringValue(value: v)
}
}
mutating func visitRepeatedBytesField(value: [Data], fieldNumber: Int) throws {
try _visitRepeated(value: value, fieldNumber: fieldNumber) {
(encoder: inout JSONEncoder, v: Data) in
encoder.putBytesValue(value: v)
}
}
mutating func visitRepeatedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws {
let alwaysPrintEnumsAsInts = options.alwaysPrintEnumsAsInts
try _visitRepeated(value: value, fieldNumber: fieldNumber) {
(encoder: inout JSONEncoder, v: E) throws in
if !alwaysPrintEnumsAsInts, let n = v.name {
encoder.appendQuoted(name: n)
} else {
encoder.putEnumInt(value: v.rawValue)
}
}
}
mutating func visitRepeatedMessageField<M: Message>(value: [M], fieldNumber: Int) throws {
let localOptions = options
try _visitRepeated(value: value, fieldNumber: fieldNumber) {
(encoder: inout JSONEncoder, v: M) throws in
let json = try v.jsonUTF8Data(options: localOptions)
encoder.append(utf8Data: json)
}
}
mutating func visitRepeatedGroupField<G: Message>(value: [G], fieldNumber: Int) throws {
// Google does not serialize groups into JSON
}
// Packed fields are handled the same as non-packed fields, so JSON just
// relies on the default implementations in Visitor.swift
mutating func visitMapField<KeyType, ValueType: MapValueType>(fieldType: _ProtobufMap<KeyType, ValueType>.Type, value: _ProtobufMap<KeyType, ValueType>.BaseType, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.append(text: "{")
var mapVisitor = JSONMapEncodingVisitor(encoder: encoder, options: options)
for (k,v) in value {
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &mapVisitor)
try ValueType.visitSingular(value: v, fieldNumber: 2, with: &mapVisitor)
}
encoder = mapVisitor.encoder
encoder.append(text: "}")
}
mutating func visitMapField<KeyType, ValueType>(fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type, value: _ProtobufEnumMap<KeyType, ValueType>.BaseType, fieldNumber: Int) throws where ValueType.RawValue == Int {
try startField(for: fieldNumber)
encoder.append(text: "{")
var mapVisitor = JSONMapEncodingVisitor(encoder: encoder, options: options)
for (k, v) in value {
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &mapVisitor)
try mapVisitor.visitSingularEnumField(value: v, fieldNumber: 2)
}
encoder = mapVisitor.encoder
encoder.append(text: "}")
}
mutating func visitMapField<KeyType, ValueType>(fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type, value: _ProtobufMessageMap<KeyType, ValueType>.BaseType, fieldNumber: Int) throws {
try startField(for: fieldNumber)
encoder.append(text: "{")
var mapVisitor = JSONMapEncodingVisitor(encoder: encoder, options: options)
for (k,v) in value {
try KeyType.visitSingular(value: k, fieldNumber: 1, with: &mapVisitor)
try mapVisitor.visitSingularMessageField(value: v, fieldNumber: 2)
}
encoder = mapVisitor.encoder
encoder.append(text: "}")
}
/// Called for each extension range.
mutating func visitExtensionFields(fields: ExtensionFieldValueSet, start: Int, end: Int) throws {
// JSON does not store extensions
}
/// Helper function that throws an error if the field number could not be
/// resolved.
private mutating func startField(for number: Int) throws {
if let jsonName = nameMap.names(for: number)?.json {
encoder.startField(name: jsonName)
} else {
throw JSONEncodingError.missingFieldNames
}
}
}
| apache-2.0 | b34cc178e47d67ba282421f3b4b8d182 | 33.343023 | 217 | 0.703064 | 4.441353 | false | false | false | false |
HotCocoaTouch/DeclarativeLayout | Example/Tests/ExampleView.swift | 1 | 5186 | import UIKit
import DeclarativeLayout
class ExampleView: UIView {
enum State {
case initial
case newConstraints
case newViewsAndConstraints
case changedConstraints
}
var currentState: State = .initial
private let views1: [UIView]
private let views2: [UIView]
init(numberOfViews: Int) {
views1 = Array(repeating: UIView(), count: numberOfViews)
views2 = Array(repeating: UIView(), count: numberOfViews)
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func layoutAndConfigure(with viewLayout: ViewLayout<ExampleView>) {
switch currentState {
case .initial: layout(with: viewLayout, views: views1, constant: 0)
case .newConstraints: layoutNewConstraints(with: viewLayout, views: views1, constant: 0)
case .newViewsAndConstraints: layout(with: viewLayout, views: views2, constant: 0)
case .changedConstraints: layout(with: viewLayout, views: views1, constant: 10)
}
}
private func layout(with viewLayout: ViewLayout<ExampleView>, views: [UIView], constant: CGFloat) {
viewLayout.updateLayoutTo { (com) in
com.view(views[0]) { (com) in
com.constraints([
com.ownedView.leadingAnchor.constraint(equalTo: com.superview.leadingAnchor, constant: constant),
com.ownedView.trailingAnchor.constraint(equalTo: com.superview.trailingAnchor, constant: constant),
com.ownedView.topAnchor.constraint(equalTo: com.superview.topAnchor, constant: constant),
com.ownedView.heightAnchor.constraint(equalToConstant: 10),
])
}
let viewsSlice = views.dropFirst().dropLast()
for viewTuple in viewsSlice.enumerated() {
com.view(viewTuple.element) { (com) in
com.constraints([
com.ownedView.leadingAnchor.constraint(equalTo: com.superview.leadingAnchor, constant: constant),
com.ownedView.trailingAnchor.constraint(equalTo: com.superview.trailingAnchor, constant: constant),
com.ownedView.topAnchor.constraint(equalTo: views[viewTuple.offset].bottomAnchor, constant: constant),
com.ownedView.heightAnchor.constraint(equalToConstant: 10),
])
}
}
com.view(views.last!) { (com) in
com.constraints([
com.ownedView.leadingAnchor.constraint(equalTo: com.superview.leadingAnchor, constant: constant),
com.ownedView.trailingAnchor.constraint(equalTo: com.superview.trailingAnchor, constant: constant),
com.ownedView.topAnchor.constraint(equalTo: views[views.count - 2].bottomAnchor, constant: constant),
com.ownedView.heightAnchor.constraint(equalToConstant: 10),
com.ownedView.bottomAnchor.constraint(equalTo: com.superview.bottomAnchor, constant: constant),
])
}
}
}
private func layoutNewConstraints(with viewLayout: ViewLayout<ExampleView>, views: [UIView], constant: CGFloat) {
viewLayout.updateLayoutTo { (com) in
com.view(views[0]) { (com) in
com.constraints([
com.ownedView.centerXAnchor.constraint(equalTo: com.superview.centerXAnchor),
com.ownedView.topAnchor.constraint(equalTo: com.superview.topAnchor, constant: constant),
com.ownedView.heightAnchor.constraint(equalToConstant: 10),
])
}
let viewsSlice = views.dropFirst().dropLast()
for viewTuple in viewsSlice.enumerated() {
com.view(viewTuple.element) { (com) in
com.constraints([
com.ownedView.centerXAnchor.constraint(equalTo: com.superview.centerXAnchor),
com.ownedView.topAnchor.constraint(equalTo: views[viewTuple.offset].bottomAnchor, constant: constant),
com.ownedView.heightAnchor.constraint(equalToConstant: 10),
])
}
}
com.view(views.last!) { (com) in
com.constraints([
com.ownedView.centerXAnchor.constraint(equalTo: com.superview.centerXAnchor),
com.ownedView.topAnchor.constraint(equalTo: views[views.count - 2].bottomAnchor, constant: constant),
com.ownedView.heightAnchor.constraint(equalToConstant: 10),
com.ownedView.bottomAnchor.constraint(equalTo: com.superview.bottomAnchor, constant: constant),
])
}
}
}
}
| mit | 5dd8d0f217da286450f2518331aae79d | 43.324786 | 126 | 0.574817 | 5.419018 | false | false | false | false |
silence0201/Swift-Study | Swifter/27PropertyObserver.playground/Contents.swift | 1 | 1546 | //: Playground - noun: a place where people can play
import Foundation
class MyClass {
let oneYearInSecond: TimeInterval = 365 * 24 * 60 * 60
var date: NSDate {
willSet {
let d = date
print("即将将日期从 \(d) 设定至 \(newValue)")
}
didSet {
if (date.timeIntervalSinceNow > oneYearInSecond) {
print("设定的时间太晚了!")
date = NSDate().addingTimeInterval(oneYearInSecond)
}
print("已经将日期从 \(oldValue) 设定至 \(date)")
}
}
init() {
date = NSDate()
}
}
let foo = MyClass()
foo.date = foo.date.addingTimeInterval(10086)
// 输出
// 即将将日期从 2014-08-23 12:47:36 +0000 设定至 2014-08-23 15:35:42 +0000
// 已经将日期从 2014-08-23 12:47:36 +0000 设定至 2014-08-23 15:35:42 +0000
// 365 * 24 * 60 * 60 = 31_536_000
foo.date = foo.date.addingTimeInterval(100_000_000)
// 输出
// 即将将日期从 2014-08-23 13:24:14 +0000 设定至 2017-10-23 23:10:54 +0000
// 设定的时间太晚了!
// 已经将日期从 2014-08-23 13:24:14 +0000 设定至 2015-08-23 13:24:14 +0000
class A {
var number :Int {
get {
print("get")
return 1
}
set {print("set")}
}
}
class B: A {
override var number: Int {
willSet {print("willSet")}
didSet {print("didSet")}
}
}
let b = B()
b.number = 0
// 输出
// get
// willSet
// set
// didSet
| mit | e6d580a06b5c47904837d082a956cecb | 18.857143 | 67 | 0.534532 | 3.373786 | false | false | false | false |
jonathanhogan/receptionkit | ReceptionKit/View Controllers/Visitor/VisitorSearchResultsTableViewController.swift | 3 | 3201 | //
// VisitorSearchResultsTableViewController.swift
// ReceptionKit
//
// Created by Andy Cho on 2015-04-23.
// Copyright (c) 2015 Andy Cho. All rights reserved.
//
import UIKit
class VisitorSearchResultsTableViewController: ReturnToHomeTableViewController {
var visitorName: String?
var searchQuery: String?
var searchResults: [Contact]?
override func viewDidLoad() {
super.viewDidLoad()
// Overwrite the theme - table should be white
self.view.backgroundColor = UIColor.whiteColor()
}
//
// MARK: - Table view data source
//
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResults!.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> ContactTableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("contactCell", forIndexPath: indexPath) as! ContactTableViewCell
let contact = searchResults![indexPath.row]
cell.contactNameLabel.text = contact.name
cell.contactPhoneLabel.text = formatPhoneString(contact.phones)
if (contact.picture != nil) {
cell.contactImage.image = contact.picture
} else {
cell.contactImage.image = UIImage(named: "UnknownContact")
}
cell.contactImage.layer.cornerRadius = 42.0
cell.contactImage.layer.masksToBounds = true
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let contact = searchResults![indexPath.row]
if visitorName == nil || visitorName == "" {
sendMessage("Someone is at the reception looking for \(contact.name)!")
} else {
sendMessage("\(visitorName!) is at the reception looking for \(contact.name)!")
}
performSegueWithIdentifier("SelectedContact", sender: self)
}
// Take the phone numbers and create a descriptive string for it
func formatPhoneString(phones: [ContactPhone]) -> String {
var workPhones = [ContactPhone]()
var mobilePhones = [ContactPhone]()
var formattedString = ""
for phone in phones {
if phone.isWorkPhone() == true {
workPhones.append(phone)
} else if phone.isMobilePhone() == true {
mobilePhones.append(phone)
}
}
for workPhone in workPhones {
if (formattedString != "") {
formattedString += "\t\t"
}
formattedString += "Work: " + workPhone.number
}
for mobilePhone in mobilePhones {
if (formattedString != "") {
formattedString += "\t\t"
}
formattedString += "Mobile: " + mobilePhone.number
}
if formattedString == "" {
return "No contact info"
} else {
return formattedString
}
}
}
| mit | 070f403e74b107dcaedac7cd6fb32739 | 31.333333 | 127 | 0.605436 | 5.273476 | false | false | false | false |
DrabWeb/Azusa | Source/Azusa/Azusa/View Controllers/SidebarController.swift | 1 | 4549 | //
// SidebarController.swift
// Azusa
//
// Created by Ushio on 2/9/17.
//
import Cocoa
class SidebarController: NSViewController {
// MARK: - Properties
// MARK: Public Properties
let items : [SidebarItemBase] = [
LibrarySidebarSection(),
SidebarSection(title: "Playlists", items: [])
];
var librarySection : LibrarySidebarSection {
return items[0] as! LibrarySidebarSection;
}
var playlistsSection : SidebarSection {
return items[1] as! SidebarSection;
}
var onNavigated : ((NavigationDestination) -> Void)?;
// MARK: Private Properties
@IBOutlet internal weak var contentOutlineView: NSOutlineView!
// MARK: - Methods
// MARK: Public Methods
func expandAll() {
contentOutlineView.expandItem(nil, expandChildren: true);
}
override func viewDidLoad() {
super.viewDidLoad();
expandAll();
}
}
// MARK: - NavigationDestination
enum NavigationDestination {
case Albums, Artists, Songs, Genres
}
// MARK: - NSOutlineViewDelegate
extension SidebarController: NSOutlineViewDelegate {
func outlineViewSelectionDidChange(_ notification: Notification) {
// TODO: Implement playlist selection handling
if let selected = contentOutlineView.item(atRow: contentOutlineView.selectedRow) as? SidebarItem {
switch selected {
case is ArtistsSidebarItem:
onNavigated?(.Artists);
break;
case is AlbumsSidebarItem:
onNavigated?(.Albums);
break;
case is SongsSidebarItem:
onNavigated?(.Songs);
break;
case is GenresSidebarItem:
onNavigated?(.Genres);
break;
default:
break;
}
}
}
func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
// Section headers have a different size
if item is SidebarSection {
return 17;
}
else {
return 24;
}
}
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if let section = item as? SidebarSection {
return section.items.count;
}
else {
return items.count;
}
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
// Only sections are collapsible
return item is SidebarSection;
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if let section = item as? SidebarSection {
return section.items[index];
}
else {
return items[index];
}
}
func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? {
return item;
}
}
// MARK: - NSOutlineViewDataSource
extension SidebarController: NSOutlineViewDataSource {
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
if let genericSidebarItem = item as? SidebarItemBase {
if let cellView = outlineView.make(withIdentifier: genericSidebarItem.cellIdentifier(), owner: self) as? NSTableCellView {
if let textField = cellView.textField {
textField.stringValue = genericSidebarItem.title;
}
if let imageView = cellView.imageView {
if let sidebarItem = genericSidebarItem as? SidebarItem {
imageView.image = sidebarItem.icon;
imageView.image?.isTemplate = true;
}
}
return cellView;
}
}
return nil;
}
func outlineView(_ outlineView: NSOutlineView, shouldSelectItem item: Any) -> Bool {
// Only allow non-section headers to be selected
return !self.outlineView(outlineView, isGroupItem: item);
}
func outlineView(_ outlineView: NSOutlineView, isGroupItem item: Any) -> Bool {
// Sections are groups
return item is SidebarSection;
}
}
| gpl-3.0 | d8a5278ee562f17244dc29d6df176141 | 28.348387 | 134 | 0.564959 | 5.520631 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionData/Locks/WithdrawalLocksCheckRepository.swift | 1 | 1153 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import FeatureTransactionDomain
final class WithdrawalLocksCheckRepository: WithdrawalLocksCheckRepositoryAPI {
// MARK: - Properties
private let client: WithdrawalLocksCheckClientAPI
// MARK: - Setup
init(client: WithdrawalLocksCheckClientAPI) {
self.client = client
}
func withdrawalLocksCheck(
paymentMethod: String?,
currencyCode: String?
) -> AnyPublisher<WithdrawalLocksCheck, Never> {
guard let paymentMethod = paymentMethod, let currencyCode = currencyCode else {
return .just(.init(lockDays: 0))
}
return client.fetchWithdrawalLocksCheck(paymentMethod: paymentMethod, currencyCode: currencyCode)
.replaceError(with: .init(rule: nil))
.map {
let lockTime = Double($0.rule?.lockTime ?? 0)
let secondsInDay = Double(86400)
let lockDays = lockTime / secondsInDay
return WithdrawalLocksCheck(lockDays: Int(lockDays.rounded(.up)))
}
.eraseToAnyPublisher()
}
}
| lgpl-3.0 | d4f88d531d4d2b3da346b1acc5c6119e | 31.914286 | 105 | 0.65191 | 5.030568 | false | false | false | false |
Coderian/SwiftedKML | SwiftedKML/Elements/Address.swift | 1 | 1593 | //
// Address.swift
// SwiftedKML
//
// Created by 佐々木 均 on 2016/02/02.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// KML Address
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <element name="address" type="string"/>
public class Address: SPXMLElement, HasXMLElementValue, HasXMLElementSimpleValue {
public static var elementName:String = "address"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch self.parent {
case let v as NetworkLink: v.value.address = self
case let v as Placemark: v.value.address = self
case let v as Document: v.value.address = self
case let v as Folder : v.value.address = self
case let v as GroundOverlay:v.value.address = self
case let v as PhotoOverlay: v.value.address = self
case let v as ScreenOverlay:v.value.address = self
default: break
}
}
}
}
public var value:String = ""
public required init(attributes:[String:String]){
super.init(attributes: attributes)
}
public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement {
self.value = contents
self.parent = parent
return parent
}
}
| mit | 7d4c698801afc024cb34d57aa0ae92ff | 33.133333 | 84 | 0.592448 | 4.063492 | false | false | false | false |
Alamofire/Alamofire | Source/RedirectHandler.swift | 8 | 4929 | //
// RedirectHandler.swift
//
// Copyright (c) 2014-2018 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
/// A type that handles how an HTTP redirect response from a remote server should be redirected to the new request.
public protocol RedirectHandler {
/// Determines how the HTTP redirect response should be redirected to the new request.
///
/// The `completion` closure should be passed one of three possible options:
///
/// 1. The new request specified by the redirect (this is the most common use case).
/// 2. A modified version of the new request (you may want to route it somewhere else).
/// 3. A `nil` value to deny the redirect request and return the body of the redirect response.
///
/// - Parameters:
/// - task: The `URLSessionTask` whose request resulted in a redirect.
/// - request: The `URLRequest` to the new location specified by the redirect response.
/// - response: The `HTTPURLResponse` containing the server's response to the original request.
/// - completion: The closure to execute containing the new `URLRequest`, a modified `URLRequest`, or `nil`.
func task(_ task: URLSessionTask,
willBeRedirectedTo request: URLRequest,
for response: HTTPURLResponse,
completion: @escaping (URLRequest?) -> Void)
}
// MARK: -
/// `Redirector` is a convenience `RedirectHandler` making it easy to follow, not follow, or modify a redirect.
public struct Redirector {
/// Defines the behavior of the `Redirector` type.
public enum Behavior {
/// Follow the redirect as defined in the response.
case follow
/// Do not follow the redirect defined in the response.
case doNotFollow
/// Modify the redirect request defined in the response.
case modify((URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?)
}
/// Returns a `Redirector` with a `.follow` `Behavior`.
public static let follow = Redirector(behavior: .follow)
/// Returns a `Redirector` with a `.doNotFollow` `Behavior`.
public static let doNotFollow = Redirector(behavior: .doNotFollow)
/// The `Behavior` of the `Redirector`.
public let behavior: Behavior
/// Creates a `Redirector` instance from the `Behavior`.
///
/// - Parameter behavior: The `Behavior`.
public init(behavior: Behavior) {
self.behavior = behavior
}
}
// MARK: -
extension Redirector: RedirectHandler {
public func task(_ task: URLSessionTask,
willBeRedirectedTo request: URLRequest,
for response: HTTPURLResponse,
completion: @escaping (URLRequest?) -> Void) {
switch behavior {
case .follow:
completion(request)
case .doNotFollow:
completion(nil)
case let .modify(closure):
let request = closure(task, request, response)
completion(request)
}
}
}
#if swift(>=5.5)
extension RedirectHandler where Self == Redirector {
/// Provides a `Redirector` which follows redirects. Equivalent to `Redirector.follow`.
public static var follow: Redirector { .follow }
/// Provides a `Redirector` which does not follow redirects. Equivalent to `Redirector.doNotFollow`.
public static var doNotFollow: Redirector { .doNotFollow }
/// Creates a `Redirector` which modifies the redirected `URLRequest` using the provided closure.
///
/// - Parameter closure: Closure used to modify the redirect.
/// - Returns: The `Redirector`.
public static func modify(using closure: @escaping (URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) -> Redirector {
Redirector(behavior: .modify(closure))
}
}
#endif
| mit | b7592adab06a4001427b794e62d8c18c | 42.619469 | 132 | 0.680868 | 4.632519 | false | false | false | false |
gaurav1981/Nuke | Sources/Nuke.swift | 1 | 3300 | // The MIT License (MIT)
//
// Copyright (c) 2017 Alexander Grebenyuk (github.com/kean).
import Foundation
#if os(macOS)
import AppKit.NSImage
/// Alias for `NSImage`.
public typealias Image = NSImage
#else
import UIKit.UIImage
/// Alias for `UIImage`.
public typealias Image = UIImage
#endif
/// Loads an image into the given target.
///
/// For more info see `loadImage(with:into:)` method of `Manager`.
public func loadImage(with url: URL, into target: Target) {
Manager.shared.loadImage(with: url, into: target)
}
/// Loads an image into the given target.
///
/// For more info see `loadImage(with:into:)` method of `Manager`.
public func loadImage(with request: Request, into target: Target) {
Manager.shared.loadImage(with: request, into: target)
}
/// Loads an image and calls the given `handler`. The method itself
/// **doesn't do** anything when the image is loaded - you have full
/// control over how to display it, etc.
///
/// The handler only gets called if the request is still associated with the
/// `target` by the time it's completed. The handler gets called immediately
/// if the image was stored in the memory cache.
///
/// See `loadImage(with:into:)` method for more info.
public func loadImage(with url: URL, into target: AnyObject, handler: @escaping Manager.Handler) {
Manager.shared.loadImage(with: url, into: target, handler: handler)
}
/// Loads an image and calls the given `handler`. The method itself
/// **doesn't do** anything when the image is loaded - you have full
/// control over how to display it, etc.
///
/// The handler only gets called if the request is still associated with the
/// `target` by the time it's completed. The handler gets called immediately
/// if the image was stored in the memory cache.
///
/// For more info see `loadImage(with:into:handler:)` method of `Manager`.
public func loadImage(with request: Request, into target: AnyObject, handler: @escaping Manager.Handler) {
Manager.shared.loadImage(with: request, into: target, handler: handler)
}
/// Cancels an outstanding request associated with the target.
public func cancelRequest(for target: AnyObject) {
Manager.shared.cancelRequest(for: target)
}
/// An enum representing either a success with a result value, or a failure.
public enum Result<T> {
case success(T), failure(Error)
/// Returns a `value` if the result is success.
public var value: T? {
if case let .success(val) = self { return val } else { return nil }
}
/// Returns an `error` if the result is failure.
public var error: Error? {
if case let .failure(err) = self { return err } else { return nil }
}
}
internal final class Lock {
var mutex = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1)
init() { pthread_mutex_init(mutex, nil) }
deinit {
pthread_mutex_destroy(mutex)
mutex.deinitialize()
mutex.deallocate(capacity: 1)
}
/// In critical places it's better to use lock() and unlock() manually
func sync<T>(_ closure: (Void) -> T) -> T {
pthread_mutex_lock(mutex)
defer { pthread_mutex_unlock(mutex) }
return closure()
}
func lock() { pthread_mutex_lock(mutex) }
func unlock() { pthread_mutex_unlock(mutex) }
}
| mit | 8d9373e2fbd0d90f1368de5dc7ee5770 | 33.020619 | 106 | 0.684242 | 3.952096 | false | false | false | false |
Pluto-Y/SwiftyEcharts | SwiftyEchartsTest_iOS/RadiusAxisSpec.swift | 1 | 10044 | //
// RadiusAxisSpec.swift
// SwiftyEcharts
//
// Created by Pluto Y on 03/08/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
import Quick
import Nimble
@testable import SwiftyEcharts
class RadiusAxisSpec: QuickSpec {
override func spec() {
let showLabelValue = false
let formatterLabelValue = Formatter.string("labelFormatterValue")
let textStyleLabelValue = TextStyle()
let paddingLabelValue = Padding.verticalAndHorizontal(5, 10)
let backgroundColorLabelValue = Color.hexColor("#029573")
let borderColorLabelValue = Color.red
let borderWidthLabelValue: Float = 0.8572
let shadowBlurLabelValue: Float = 10
let shadowColorLabelValue = rgb(100, 0, 38)
let shadowOffsetXLabelValue: Float = 0.8572
let shadowOffsetYLabelValue: Float = 8937462.7623467
let label = Label()
label.show = showLabelValue
label.formatter = formatterLabelValue
label.textStyle = textStyleLabelValue
label.padding = paddingLabelValue
label.backgroundColor = backgroundColorLabelValue
label.borderColor = borderColorLabelValue
label.borderWidth = borderWidthLabelValue
label.shadowBlur = shadowBlurLabelValue
label.shadowColor = shadowColorLabelValue
label.shadowOffsetX = shadowOffsetXLabelValue
label.shadowOffsetY = shadowOffsetYLabelValue
let showHandleValue = false
let iconHandleValue = "path://handleIconValue"
let sizeHandleValue: Pair<Float> = [20.5, 50.2]
let marginHandleValue: Float = 45
let colorHandleValue = Color.hexColor("#88ffaa")
let throttleHandleValue: Float = 5.555555
let shadowBlurHandleValue: Float = 20.20
let shadowColorHandleValue = Color.transparent
let shadowOffsetXHandleValue: Float = 0.5737
let shadowOffsetYHandleValue: Float = 85723.7234
let handle = AxisPointerForAxis.Handle()
handle.show = showHandleValue
handle.icon = iconHandleValue
handle.size = sizeHandleValue
handle.margin = marginHandleValue
handle.color = colorHandleValue
handle.throttle = throttleHandleValue
handle.shadowBlur = shadowBlurHandleValue
handle.shadowColor = shadowColorHandleValue
handle.shadowOffsetX = shadowOffsetXHandleValue
handle.shadowOffsetY = shadowOffsetYHandleValue
let showAxisPointerValue = true
let typeAxisPointerValue = SwiftyEcharts.AxisPointerForAxis.Type.line
let snapAxisPointerValue = true
let zAxisPointerValue: Float = 0.58364
let labelAxisPointerValue = label
let lineStyleAxisPointerValue = LineStyle(
.opacity(0.8573),
.shadowBlur(20.57),
.curveness(200)
)
let shadowStyleAxisPointerValue = ShadowStyle(
.color(Color.rgb(0, 0, 200)),
.shadowColor(Color.rgba(200, 0, 0, 0.01)),
.shadowOffsetX(200.0)
)
let triggerAxisPointerForTooltipValue = false
let valueAxisPointerValue: Float = 0.8576
let stateAxisPointerValue = false
let handleAxisPointerValue = handle
let axisPointer = AxisPointerForAxis()
axisPointer.show = showAxisPointerValue
axisPointer.type = typeAxisPointerValue
axisPointer.snap = snapAxisPointerValue
axisPointer.z = zAxisPointerValue
axisPointer.label = labelAxisPointerValue
axisPointer.lineStyle = lineStyleAxisPointerValue
axisPointer.shadowStyle = shadowStyleAxisPointerValue
axisPointer.triggerTooltip = triggerAxisPointerForTooltipValue
axisPointer.value = valueAxisPointerValue
axisPointer.state = stateAxisPointerValue
axisPointer.handle = handleAxisPointerValue
describe("For RadiusAxis") {
let polarIndexValue: UInt8 = 0
let typeValue = AxisType.time
let nameValue = "radiusAxisNameValue"
let nameLocationValue = Position.bottom
let nameTextStyleValue = TextStyle(
.color(Color.green),
.fontStyle(.italic),
.align(Position.right)
)
let nameGapValue: Float = 20
let nameRotateValue: Float = 90
let inverseValue = false
let boundaryGapValue: BoundaryGap = [9.2873, 200]
let minValue: Float = 0.47236
let maxValue: Float = 2000.47346
let scaleValue = true
let splitNumberValue: UInt8 = 99
let minIntervalValue: Float = 1
let intervalValue: Float = 1000
let logBaseValue: Float = 0.0000009
let silentValue = false
let triggerEventValue = false
let axisLineValue = AxisLine(
.show(false)
)
let axisLabelValue = AxisLabel(
.formatter(.string("994.238")),
.margin(29),
.rotate(-90)
)
let axisTickValue = AxisTick(
.alignWithLabel(false),
.length(400),
.interval(0)
)
let splitLineValue = SplitLine(
.interval(20%)
)
let splitAreaValue = SplitArea(
.show(true),
.interval(200)
)
let dataValue: [Jsonable] = [
false, "value", 20.57, 20
]
let axisPointerValue = axisPointer
let zlevelValue: Float = 255.552
let zValue: Float = 0.58274
let radiusAxis = RadiusAxis()
radiusAxis.polarIndex = polarIndexValue
radiusAxis.type = typeValue
radiusAxis.name = nameValue
radiusAxis.nameLocation = nameLocationValue
radiusAxis.nameTextStyle = nameTextStyleValue
radiusAxis.nameGap = nameGapValue
radiusAxis.nameRotate = nameRotateValue
radiusAxis.inverse = inverseValue
radiusAxis.boundaryGap = boundaryGapValue
radiusAxis.min = minValue
radiusAxis.max = maxValue
radiusAxis.scale = scaleValue
radiusAxis.splitNumber = splitNumberValue
radiusAxis.minInterval = minIntervalValue
radiusAxis.interval = intervalValue
radiusAxis.logBase = logBaseValue
radiusAxis.silent = silentValue
radiusAxis.triggerEvent = triggerEventValue
radiusAxis.axisLine = axisLineValue
radiusAxis.axisTick = axisTickValue
radiusAxis.axisLabel = axisLabelValue
radiusAxis.splitLine = splitLineValue
radiusAxis.splitArea = splitAreaValue
radiusAxis.data = dataValue
radiusAxis.axisPointer = axisPointerValue
radiusAxis.zlevel = zlevelValue
radiusAxis.z = zValue
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"polarIndex": polarIndexValue,
"type": typeValue,
"name": nameValue,
"nameLocation": nameLocationValue,
"nameTextStyle": nameTextStyleValue,
"nameGap": nameGapValue,
"nameRotate": nameRotateValue,
"inverse": inverseValue,
"boundaryGap": boundaryGapValue,
"min": minValue,
"max": maxValue,
"scale": scaleValue,
"splitNumber": splitNumberValue,
"minInterval": minIntervalValue,
"interval": intervalValue,
"logBase": logBaseValue,
"silent": silentValue,
"triggerEvent": triggerEventValue,
"axisLine": axisLineValue,
"axisTick": axisTickValue,
"axisLabel": axisLabelValue,
"splitLine": splitLineValue,
"splitArea": splitAreaValue,
"data": dataValue,
"axisPointer": axisPointerValue,
"zlevel": zlevelValue,
"z": zValue
]
expect(radiusAxis.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let radiusAxisByEnums = RadiusAxis(
.polarIndex(polarIndexValue),
.type(typeValue),
.name(nameValue),
.nameLocation(nameLocationValue),
.nameTextStyle(nameTextStyleValue),
.nameGap(nameGapValue),
.nameRotate(nameRotateValue),
.inverse(inverseValue),
.boundaryGap(boundaryGapValue),
.min(minValue),
.max(maxValue),
.scale(scaleValue),
.splitNumber(splitNumberValue),
.minInterval(minIntervalValue),
.interval(intervalValue),
.logBase(logBaseValue),
.silent(silentValue),
.triggerEvent(triggerEventValue),
.axisLine(axisLineValue),
.axisTick(axisTickValue),
.axisLabel(axisLabelValue),
.splitLine(splitLineValue),
.splitArea(splitAreaValue),
.data(dataValue),
.axisPointer(axisPointerValue),
.zlevel(zlevelValue),
.z(zValue)
)
expect(radiusAxisByEnums.jsonString).to(equal(radiusAxis.jsonString))
}
}
}
}
| mit | ddc002893aaea860ed1cb16071a4dd12 | 39.991837 | 85 | 0.56975 | 5.811921 | false | false | false | false |
nerd0geek1/PlayListPlayer | PlayListPlayer/classes/player/PlayListPlayer.swift | 1 | 4846 | import Foundation
import AVFoundation
public class PlayListPlayer: PlayListPlayerType {
// MARK: - public properties
public static let shared: PlayListPlayer = PlayListPlayer()
public var didStartPlayingTrack:(() -> Void)?
public var didFinishPlayingTrack:(() -> Void)?
public var didFinishPlayingPlayList:(() -> Void)?
public var playMode: PlayerPlayMode = .repeatPlayList
public var playList: [URL] {
return urls
}
public var currentIndex: Int {
return index
}
// MARK: - private properties
private let player: AVPlayer = AVPlayer()
private var urls: [URL] = []
private var index: Int = 0
// MARK: - update PlayListPlayer properties
public func set(playList: [URL]) {
self.urls = playList
self.index = 0
setupPlayerItem()
}
@discardableResult
public func set(currentIndex: Int) -> Bool {
guard isValid(index: currentIndex) else {
return false
}
self.index = currentIndex
setupPlayerItem()
return true
}
// MARK: - PlayListPlayer properties
public func engine() -> AVPlayer {
return player
}
public func hasPlayList() -> Bool {
return !urls.isEmpty
}
public func currentTrackURL() -> URL? {
guard
let currentItem: AVPlayerItem = player.currentItem,
let asset: AVURLAsset = currentItem.asset as? AVURLAsset else {
return nil
}
return asset.url
}
public func isPlaying() -> Bool {
if player.currentItem == nil {
return false
}
return player.rate != 0.0
}
// MARK: - operate PlayListPlayer
public func play() {
player.play()
}
public func pause() {
player.pause()
}
public func beginFastForwarding() {
player.rate = 2.0
}
public func endFastForwarding() {
resetPlayerRate()
}
public func skipToNextTrack() {
let isLastTrack: Bool = currentIndex == lastTrackIndex()
let nextIndex: Int = isLastTrack ? 0 : currentIndex + 1
switch playMode {
case .repeatPlayList:
set(currentIndex: nextIndex)
play()
case .repeatItem:
seekToBeginning()
case .noRepeat:
set(currentIndex: nextIndex)
if isLastTrack {
pause()
}
}
}
public func beginRewinding() {
player.rate = -2.0
}
public func endRewinding() {
resetPlayerRate()
}
public func jumpToPreviousTrack() {
let isFirstTrack: Bool = currentIndex == 0
let previousIndex: Int = isFirstTrack ? 0 : currentIndex - 1
switch playMode {
case .repeatPlayList, .noRepeat:
if isFirstTrack {
seekToBeginning()
} else {
set(currentIndex: previousIndex)
}
case .repeatItem:
seekToBeginning()
}
}
public func seekToBeginning() {
seek(to: 0)
didStartPlayingTrack?()
}
public func seek(to position: Float) {
guard let currentItem: AVPlayerItem = player.currentItem else {
return
}
let duration: CMTime = currentItem.asset.duration
let value: Float = Float(duration.value) * position
let seekTime: CMTime = CMTimeMake(CMTimeValue(value), duration.timescale)
currentItem.seek(to: seekTime)
}
// MARK: - private
private func setupPlayerItem() {
if !isValid(index: currentIndex) {
return
}
let url: URL = urls[currentIndex]
NotificationCenter.default.removeObserver(self)
let playerItem: AVPlayerItem = AVPlayerItem(url: url)
player.replaceCurrentItem(with: playerItem)
didStartPlayingTrack?()
NotificationCenter.default.addObserver(self,
selector: #selector(playerDidFinishTrackPlaying),
name: Notification.Name.AVPlayerItemDidPlayToEndTime,
object: player.currentItem)
}
private func isValid(index: Int) -> Bool {
return hasPlayList() && 0 <= index && index <= lastTrackIndex()
}
private func lastTrackIndex() -> Int {
return hasPlayList() ? urls.count - 1 : 0
}
private func resetPlayerRate() {
player.rate = 1.0
}
// MARK: - Notification
@objc private func playerDidFinishTrackPlaying(notification: NSNotification) {
didFinishPlayingTrack?()
if currentIndex == lastTrackIndex() {
didFinishPlayingPlayList?()
}
skipToNextTrack()
}
}
| mit | 553f7fae8cb36d2139b0e305071cfffd | 23.474747 | 100 | 0.571399 | 5.069038 | false | false | false | false |
dairdr/SNVideoRecorder | SNVideoRecorder/Classes/SNVideoRecorderViewController.swift | 1 | 19444 | //
// SNVideoRecorderViewController.swift
// Pods
//
// Created by Dair Diaz on 24/08/17.
//
//
import UIKit
import AVFoundation
import NVActivityIndicatorView
enum SNCaptureMode:UInt8 {
case video = 0
case photo = 1
}
public class SNVideoRecorderViewController: UIViewController {
public weak var delegate:SNVideoRecorderDelegate?
var session:AVCaptureSession?
var videoInput:AVCaptureDeviceInput?
var audioInput:AVCaptureDeviceInput?
var movieFileOutput:AVCaptureMovieFileOutput?
var imageFileOutput:AVCaptureStillImageOutput?
public var closeOnCapture:Bool = true
public var finalURL:URL?
public var maxSecondsToRecord = 59
public var initCameraPosition:AVCaptureDevice.Position = .front
public override var prefersStatusBarHidden: Bool {
return true
}
// flash light button options
public var flashLightOnIcon:UIImage?
public var flashLightOffIcon:UIImage?
// confirmation view button text
public var agreeText:String = NSLocalizedString("Ok", comment: "")
public var discardText:String = NSLocalizedString("Discard", comment: "")
// components
var previewLayer:AVCaptureVideoPreviewLayer?
let countDown:SNRecordingCountDown = {
let v = SNRecordingCountDown()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
let recordOption:SNRecordButton = {
let v = SNRecordButton()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
public let flashLightOption:UIButton = {
let v = UIButton(type: .custom)
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
v.tintColor = .white
return v
}()
public let switchCameraOption:UIButton = {
let v = UIButton(type: .custom)
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
v.tintColor = .white
return v
}()
public let closeOption:UIButton = {
let v = UIButton()
v.translatesAutoresizingMaskIntoConstraints = false
v.backgroundColor = UIColor.init(white: 0, alpha: 0.3)
v.tintColor = .white
return v
}()
let loading:NVActivityIndicatorView = {
let rect = CGRect(x: 0, y: 0, width: 50, height: 50)
let v = NVActivityIndicatorView(frame: rect, type: .ballClipRotatePulse, color: .white, padding: 5.0)
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .black
flashLightOption.setImage(flashLightOnIcon?.withRenderingMode(.alwaysTemplate), for: .normal)
addViews()
setupViews()
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupNavigationBar()
if AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == .authorized {
let _ = connect(withDeviceAt: initCameraPosition)
} else {
switchCameraOption.isEnabled = false
flashLightOption.isEnabled = false
recordOption.isEnabled = false
AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted) -> Void in
if granted {
let _ = self.connect(withDeviceAt: self.initCameraPosition)
} else {
DispatchQueue.main.async {
let title = NSLocalizedString("permission_camera_title", comment: "")
let message = NSLocalizedString("permission_camera_message", comment: "")
self.showPermissionAlert(title: title, message: message)
}
}
})
}
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
previewLayer?.frame.size = view.frame.size
closeOption.layer.cornerRadius = closeOption.frame.width / 2
switchCameraOption.layer.cornerRadius = switchCameraOption.frame.width / 2
flashLightOption.layer.cornerRadius = switchCameraOption.layer.cornerRadius
}
public override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
switch UIDevice.current.orientation {
case .portrait:
previewLayer?.connection?.videoOrientation = .portrait
case .landscapeLeft:
previewLayer?.connection?.videoOrientation = .landscapeRight
default:
previewLayer?.connection?.videoOrientation = .landscapeLeft
}
recordOption.cancel()
}
func createSession(device: AVCaptureDevice, audioDevice: AVCaptureDevice) {
session = AVCaptureSession()
session?.beginConfiguration()
do {
try device.lockForConfiguration()
videoInput = try AVCaptureDeviceInput(device: device)
audioInput = try AVCaptureDeviceInput(device: audioDevice)
} catch let error {
print(error)
}
if device.isFocusModeSupported(.autoFocus) {
device.focusMode = .autoFocus
}
guard let s = session else {
return
}
if s.canAddInput(audioInput!) {
s.addInput(audioInput!)
}
if s.canAddInput(videoInput!) {
s.addInput(videoInput!)
}
// video output
if let output = movieFileOutput {
if s.canAddOutput(output) {
s.addOutput(output)
}
}
// photo output
if let output = imageFileOutput {
if s.canAddOutput(output) {
s.addOutput(output)
}
}
updatePreview(session: s)
device.unlockForConfiguration()
s.commitConfiguration()
s.startRunning()
}
func destroySession() {
session?.removeInput(videoInput!)
videoInput = nil
if session != nil {
if session!.isRunning {
session?.stopRunning()
session = nil
}
}
}
func updatePreview(session:AVCaptureSession) {
previewLayer?.session = session
}
func cameraWithPosition(position: AVCaptureDevice.Position) -> (audio:AVCaptureDevice?, video:AVCaptureDevice?) {
let devices = AVCaptureDevice.devices()
var audio:AVCaptureDevice?
var video:AVCaptureDevice?
for device in devices {
if (device as AnyObject).hasMediaType(AVMediaType.video) {
if (device as AnyObject).position == position {
video = device
}
}
if (device as AnyObject).hasMediaType(AVMediaType.audio) {
audio = device
}
}
return (audio, video)
}
func addViews() {
// camera preview
previewLayer = AVCaptureVideoPreviewLayer()
previewLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill
view.layer.insertSublayer(previewLayer!, at: 0)
view.addSubview(loading)
// controls
view.addSubview(countDown)
view.addSubview(closeOption)
view.addSubview(flashLightOption)
view.addSubview(switchCameraOption)
view.addSubview(recordOption)
flashLightOption.addTarget(self, action: #selector(flashLightHandler), for: .touchUpInside)
closeOption.addTarget(self, action: #selector(closeHandler), for: .touchUpInside)
switchCameraOption.addTarget(self, action: #selector(switchCameraHandler), for: .touchUpInside)
}
func setupViews() {
// count down
countDown.widthAnchor.constraint(equalToConstant: 80).isActive = true
countDown.heightAnchor.constraint(equalToConstant: 30).isActive = true
countDown.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
countDown.topAnchor.constraint(equalTo: view.topAnchor, constant: 15).isActive = true
// close option
closeOption.widthAnchor.constraint(equalToConstant: 30).isActive = true
closeOption.heightAnchor.constraint(equalTo: closeOption.widthAnchor).isActive = true
closeOption.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -15).isActive = true
closeOption.centerYAnchor.constraint(equalTo: countDown.centerYAnchor).isActive = true
// flash light
flashLightOption.widthAnchor.constraint(equalToConstant: 45).isActive = true
flashLightOption.heightAnchor.constraint(equalTo: switchCameraOption.widthAnchor).isActive = true
flashLightOption.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 15).isActive = true
flashLightOption.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -15).isActive = true
// switch camera
switchCameraOption.widthAnchor.constraint(equalToConstant: 45).isActive = true
switchCameraOption.heightAnchor.constraint(equalTo: switchCameraOption.widthAnchor).isActive = true
switchCameraOption.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -15).isActive = true
switchCameraOption.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -15).isActive = true
// record option
recordOption.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
recordOption.widthAnchor.constraint(equalToConstant: 60).isActive = true
recordOption.heightAnchor.constraint(equalTo: recordOption.widthAnchor).isActive = true
recordOption.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true
// loading
loading.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loading.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
func setupNavigationBar() {
navigationController?.navigationBar.isHidden = true
navigationController?.navigationBar.isTranslucent = false
}
@objc func switchCameraHandler(sender:UIButton) {
if initCameraPosition == .front {
initCameraPosition = .back
} else {
initCameraPosition = .front
}
destroySession()
let _ = connect(withDeviceAt: initCameraPosition)
}
@objc func flashLightHandler(sender:UIButton) {
if let device = AVCaptureDevice.default(for: AVMediaType.video) {
if device.hasTorch {
do {
try device.lockForConfiguration()
let state = !device.isTorchActive
device.torchMode = state ? .on : .off
if state {
sender.setImage(flashLightOffIcon?.withRenderingMode(.alwaysTemplate), for: .normal)
} else {
sender.setImage(flashLightOnIcon?.withRenderingMode(.alwaysTemplate), for: .normal)
}
device.unlockForConfiguration()
} catch {
print(error)
}
}
} else {
print("no device camera")
}
}
@objc func closeHandler(sender:UIButton) {
closeView()
}
func connect(withDeviceAt position: AVCaptureDevice.Position) -> Bool {
let devices = cameraWithPosition(position: position)
guard let video = devices.video else {
return false
}
guard let audio = devices.audio else {
return false
}
DispatchQueue.main.async {
if video.hasTorch {
self.flashLightOption.isEnabled = true
self.flashLightOption.isHidden = false
} else {
self.flashLightOption.isEnabled = false
self.flashLightOption.isHidden = true
}
}
// video output
movieFileOutput = AVCaptureMovieFileOutput()
let maxDuration:CMTime = CMTimeMake(600, 10)
movieFileOutput?.maxRecordedDuration = maxDuration
movieFileOutput?.minFreeDiskSpaceLimit = 1024 * 1024
// image output
imageFileOutput = AVCaptureStillImageOutput()
imageFileOutput?.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
createSession(device: video, audioDevice: audio)
recordOption.delegate = self
countDown.setup(seconds: maxSecondsToRecord)
countDown.delegate = self
return false
}
func showPermissionAlert(title:String, message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("configuration", comment: ""), style: .default) { action in
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(settingsUrl, completionHandler: nil)
} else {
UIApplication.shared.openURL(settingsUrl)
}
}
})
alert.addAction(UIAlertAction(title: NSLocalizedString("cancel", comment: ""), style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
func closeView() {
if let navigation = navigationController {
let _ = navigation.popViewController(animated: true)
} else {
dismiss(animated: true) {
print("done")
}
}
}
}
extension SNVideoRecorderViewController: SNVideoRecorderViewProtocol {
}
extension SNVideoRecorderViewController: AVCaptureFileOutputRecordingDelegate {
public func fileOutput(_ captureOutput: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) {
}
public func fileOutput(_ captureOutput: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
let randomName = ProcessInfo.processInfo.globallyUniqueString
let videoFilePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(randomName).appendingPathExtension("mp4")
if FileManager.default.fileExists(atPath: videoFilePath.absoluteString) {
do {
try FileManager.default.removeItem(atPath: videoFilePath.absoluteString)
}
catch {
}
}
let sourceAsset = AVURLAsset(url: outputFileURL)
let export: AVAssetExportSession = AVAssetExportSession(asset: sourceAsset, presetName: AVAssetExportPresetMediumQuality)!
export.outputFileType = AVFileType.mp4
export.outputURL = videoFilePath
export.shouldOptimizeForNetworkUse = true
let start = CMTimeMakeWithSeconds(0.0, 0)
let range = CMTimeRangeMake(start, sourceAsset.duration)
export.timeRange = range
export.exportAsynchronously { () -> Void in
DispatchQueue.main.async(execute: {
self.loading.stopAnimating()
self.recordOption.isEnabled = true
})
switch export.status {
case .completed:
DispatchQueue.main.async(execute: {
let vc = SNVideoViewerViewController()
vc.modalPresentationStyle = .overCurrentContext
vc.delegate = self
vc.url = videoFilePath
self.present(vc, animated: false, completion: nil)
})
case .failed:
print("failed \(String(describing: export.error))")
case .cancelled:
print("cancelled \(String(describing: export.error))")
default:
print("complete")
}
}
}
}
extension SNVideoRecorderViewController: SNRecordButtonDelegate {
func didStart(mode:SNCaptureMode) {
if mode == .video {
let randomName = ProcessInfo.processInfo.globallyUniqueString
let filePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(randomName).appendingPathExtension("mp4")
movieFileOutput?.startRecording(to: filePath, recordingDelegate: self)
countDown.start(on: maxSecondsToRecord)
} else {
if let videoConnection = imageFileOutput?.connection(with: AVMediaType.video) {
imageFileOutput?.captureStillImageAsynchronously(from: videoConnection) {
(buffer, error) -> Void in
if let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer!) {
let vc = SNImageViewerViewController()
vc.modalPresentationStyle = .overCurrentContext
vc.image = UIImage(data: imageData)
vc.delegate = self
self.present(vc, animated: false, completion: nil)
}
}
}
}
}
func didEnd(isCanceled:Bool) {
guard let s = session else {
return
}
countDown.pause()
if !isCanceled {
s.stopRunning()
recordOption.isEnabled = false
loading.startAnimating()
} else {
countDown.setup(seconds: maxSecondsToRecord)
}
}
}
extension SNVideoRecorderViewController: SNRecordingCountDownDelegate {
func countDown(didStartAt time: TimeInterval) {
print("empezó el conteo regresivo")
}
func countDown(didPauseAt time: TimeInterval) {
print("el usuario ha detenido el conteo regresivo antes de finalizar")
}
func countDown(didFinishAt time: TimeInterval) {
print("terminó el tiempo máximo de grabación")
}
}
extension SNVideoRecorderViewController: SNImageViewerDelegate {
func imageView(finishWithAgree agree: Bool, andImage image: UIImage?) {
if agree {
guard let img = image else {
return
}
delegate?.videoRecorder(withImage: img)
if closeOnCapture {
closeView()
}
}
}
}
extension SNVideoRecorderViewController: SNVideoViewerDelegate {
func videoView(finishWithAgree agree: Bool, andURL url: URL?) {
if agree {
guard let value = url else {
return
}
self.delegate?.videoRecorder(withVideo: value)
if closeOnCapture {
closeView()
}
}
}
}
| mit | 94bcb73cd23e27f689826213b59be22d | 35.888046 | 163 | 0.6125 | 5.581395 | false | false | false | false |
bryzinski/skype-ios-app-sdk-samples | GuestMeetingJoin/SfBDemo/ParticipantCell.swift | 1 | 7708 | //+----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Module name: ParticipantCell.swift
//----------------------------------------------------------------
import Foundation
import GLKit
import UIKit
import SkypeForBusiness
extension SfBPerson {
var displayNameLabel: NSAttributedString {
if displayName == "" {
return NSAttributedString(string: "No Name",
attributes: [NSForegroundColorAttributeName: UIColor.grayColor()])
}
return NSAttributedString(string: displayName)
}
}
class BaseParticipantCell: UITableViewCell {
private var kvo = 0
@IBOutlet var displayName: UILabel!
@IBOutlet var sipUri: UILabel!
@IBOutlet var isTyping: UIActivityIndicatorView!
@IBOutlet var chatLabel: UILabel!
@IBOutlet var audioButton: UIButton!
var participant: SfBParticipant? {
didSet {
person = participant?.person
chat = participant?.chat
audio = participant?.audio
video = participant?.video
}
}
private var audio: SfBParticipantAudio? {
willSet {
audio?.removeObserver(self, forKeyPath: "state", context: &kvo)
audio?.removeObserver(self, forKeyPath: "isMuted", context: &kvo)
audio?.removeObserver(self, forKeyPath: "isOnHold", context: &kvo)
audio?.removeObserver(self, forKeyPath: "isSpeaking", context: &kvo)
}
didSet {
audio?.addObserver(self, forKeyPath: "state", options: [.Initial], context: &kvo)
audio?.addObserver(self, forKeyPath: "isMuted", options: [.Initial], context: &kvo)
audio?.addObserver(self, forKeyPath: "isOnHold", options: [.Initial], context: &kvo)
audio?.addObserver(self, forKeyPath: "isSpeaking", options: [.Initial], context: &kvo)
}
}
private var chat: SfBParticipantChat? {
willSet {
chat?.removeObserver(self, forKeyPath: "isTyping", context: &kvo)
chat?.removeObserver(self, forKeyPath: "state", context: &kvo)
}
didSet {
chat?.addObserver(self, forKeyPath: "isTyping", options: [.Initial], context: &kvo)
chat?.addObserver(self, forKeyPath: "state", options: [.Initial], context: &kvo)
}
}
var video: SfBParticipantVideo?
private var person: SfBPerson? {
willSet {
person?.removeObserver(self, forKeyPath: "displayName", context: &kvo)
person?.removeObserver(self, forKeyPath: "sipUri", context: &kvo)
}
didSet {
person?.addObserver(self, forKeyPath: "displayName", options: [.Initial], context: &kvo)
person?.addObserver(self, forKeyPath: "sipUri", options: [.Initial], context: &kvo)
}
}
deinit {
setValue(nil, forKey: "participant")
}
override func prepareForReuse() {
participant = nil
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard context == &kvo else {
return super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
switch keyPath! {
case "displayName":
displayName.attributedText = person?.displayNameLabel
case "sipUri":
sipUri.text = person?.sipUri.absoluteString
case "isTyping":
if chat!.isTyping {
isTyping.startAnimating()
} else {
isTyping.stopAnimating()
}
case "state":
switch object {
case is SfBParticipantChat:
chatLabel.enabled = (chat?.state == .Connected)
case is SfBParticipantAudio:
audioButton.enabled = (audio?.state == .Connected)
default:
assertionFailure()
}
case "isSpeaking":
if (audio?.isSpeaking == true) {
audioButton.setTitle("Speak", forState: .Normal)
} else {
fallthrough
}
case "isOnHold":
if (audio?.isOnHold == true) {
audioButton.setTitle("Held", forState: .Normal)
} else {
fallthrough
}
case "isMuted":
audioButton.setTitle((audio?.isMuted == false) ? "Audio" : "Muted", forState: .Normal)
default:
assertionFailure()
}
setNeedsLayout()
}
@IBAction func mute(sender: AnyObject?) {
do {
try audio!.setMuted(!audio!.isMuted)
} catch {
UIAlertView(title: "Failed to (un)mute", message: "\(error)", delegate: nil, cancelButtonTitle: "OK").show()
}
}
}
class ParticipantCell: BaseParticipantCell {
@IBOutlet var videoView: GLKView!
private var kvo2 = 0
override var video: SfBParticipantVideo? {
willSet {
video?.removeObserver(self, forKeyPath: "canSubscribe", context: &kvo2)
video?.removeObserver(self, forKeyPath: "isPaused", context: &kvo2)
}
didSet {
video?.addObserver(self, forKeyPath: "canSubscribe", options: [.Initial, .New, .Old], context: &kvo2)
video?.addObserver(self, forKeyPath: "isPaused", options: [.Initial, .New, .Old], context: &kvo2)
}
}
private var displayLink: CADisplayLink {
let dl = CADisplayLink(target: self, selector: NSSelectorFromString("render:"))
dl.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
return dl
}
private var renderTarget: SfBVideoStream?
deinit {
try? video?.unsubscribe()
displayLink.invalidate()
renderTarget = nil
}
override func prepareForReuse() {
super.prepareForReuse()
try? video?.unsubscribe()
}
private func setVideoViewHidden() {
let hide = (renderTarget == nil) || video!.isPaused
videoView.hidden = hide
displayLink.paused = hide
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard context == &kvo2 else {
return super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
switch keyPath! {
case "isPaused":
setVideoViewHidden()
case "canSubscribe":
if video!.canSubscribe {
renderTarget = try! video?.subscribe(videoView.layer as! CAEAGLLayer)
try? renderTarget?.setAutoFitMode(.Crop)
} else {
renderTarget = nil
}
setVideoViewHidden()
default:
assertionFailure()
}
}
func render(sender: CADisplayLink) {
// Any GL usage in background crashes application
if UIApplication.sharedApplication().applicationState == .Active {
try? renderTarget?.render()
}
}
}
class SelfParticipantCell: BaseParticipantCell {
private var kvo2 = 0
@IBOutlet var videoView: UIView!
var videoService: SfBVideoService? {
didSet {
renderTarget = try! videoService?.showPreviewOnView(videoView)
}
}
private var renderTarget: SfBVideoPreview?
deinit {
setValue(nil, forKey: "videoService")
}
override func prepareForReuse() {
super.prepareForReuse()
videoService = nil
}
}
| mit | c26c0803f7a1da2d5d75f5369fb5015f | 30.333333 | 157 | 0.584198 | 4.960103 | false | false | false | false |
satoshimuraki/Piko | Piko/Sources/PKViewController.swift | 1 | 5820 | //
// PKViewController.swift
//
// Copyright (c) 2014 Satoshi Muraki. All rights reserved.
//
import UIKit
class PKViewController: UIViewController {
var player: SFPlaybackManager?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.view.viewWithTag(1)?.alpha = 0.0
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
setupAudio()
}
func setupAudio() {
player = SFPlaybackManager.sharedManager()
if player?.activate() == false {
println("error: couldn't activate playback manager.")
return;
}
let sketch = makeMarioSketch()
// let sketch = makeNoiseSketch()
// let sketch = makeSineSketch()
player!.sketch = sketch;
// self.sketchView.sketch = sketch;
// [self beginObservingPlaybackManager];
// self.didSetupAudio = YES;
player!.start()
}
func makeMarioSketch() -> SFSketch {
let sketch = SFSketch()
let bps: Array<AnyObject> = [
SFBreakpoint(time: 875.0 * 0.0 / 44100.0, value: 1.0),
SFBreakpoint(time: 875.0 * 7.0 / 44100.0, value: 1.0),
SFBreakpoint(time: 875.0 * 7.0 / 44100.0, value: 0.0),
SFBreakpoint(time: 875.0 * 8.0 / 44100.0, value: 0.0),
SFBreakpoint(time: 875.0 * 8.0 / 44100.0, value: 1.0),
SFBreakpoint(time: 875.0 * 15.0 / 44100.0, value: 1.0),
SFBreakpoint(time: 875.0 * 15.0 / 44100.0, value: 0.0),
SFBreakpoint(time: 875.0 * 24.0 / 44100.0, value: 0.0),
SFBreakpoint(time: 875.0 * 24.0 / 44100.0, value: 1.0),
SFBreakpoint(time: 875.0 * 31.0 / 44100.0, value: 1.0),
SFBreakpoint(time: 875.0 * 31.0 / 44100.0, value: 0.0),
SFBreakpoint(time: DBL_MAX, value: 0.0)
]
let triangleScaleNode = SFScaleNode()
sketch.appendNode(triangleScaleNode)
let triangleScaleInputNode = SFBreakpointNode(breakpoints: bps)
sketch.appendNode(triangleScaleInputNode)
let triangleNode = SFTriangleNode()
sketch.appendNode(triangleNode)
let triangleFrequencyNode = SFStaticNode(value: 659.26)
sketch.appendNode(triangleFrequencyNode)
sketch.connect(triangleScaleInputNode.output, to: triangleScaleNode.scale)
sketch.connect(triangleFrequencyNode.output, to: triangleNode.frequency)
sketch.connect(triangleNode.output, to: triangleScaleNode.input)
// Square
let squareScaleNode = SFScaleNode()
sketch.appendNode(squareScaleNode)
let squareScaleInputNode = SFBreakpointNode(breakpoints: bps)
sketch.appendNode(squareScaleInputNode)
let squareNode = SFSquareNode()
sketch.appendNode(squareNode)
let squareFrequencyNode = SFStaticNode(value: 659.26)
sketch.appendNode(squareFrequencyNode)
sketch.connect(squareScaleInputNode.output, to: squareScaleNode.scale)
sketch.connect(squareFrequencyNode.output, to: squareNode.frequency)
sketch.connect(squareNode.output, to: squareScaleNode.input)
// White Noise
let wnbp: Array<AnyObject> = [
SFBreakpoint(time: 875.0 * 0.0 / 44100.0, value: 1.0),
SFBreakpoint(time: 875.0 * 5.0 / 44100.0, value: 1.0),
SFBreakpoint(time: 875.0 * 5.0 / 44100.0, value: 0.0),
SFBreakpoint(time: 875.0 * 8.0 / 44100.0, value: 0.0),
SFBreakpoint(time: 875.0 * 8.0 / 44100.0, value: 1.0),
SFBreakpoint(time: 875.0 * 13.0 / 44100.0, value: 1.0),
SFBreakpoint(time: 875.0 * 13.0 / 44100.0, value: 0.0),
SFBreakpoint(time: 875.0 * 24.0 / 44100.0, value: 0.0),
SFBreakpoint(time: 875.0 * 24.0 / 44100.0, value: 1.0),
SFBreakpoint(time: 875.0 * 29.0 / 44100.0, value: 1.0),
SFBreakpoint(time: 875.0 * 29.0 / 44100.0, value: 0.0),
SFBreakpoint(time: DBL_MAX, value: 0.0),
]
let wnSFBreakpointNode = SFBreakpointNode(breakpoints: wnbp)
sketch.appendNode(wnSFBreakpointNode)
let wnNode = SFWhiteNoiseNode()
sketch.appendNode(wnNode)
let wnScaleNode = SFScaleNode()
sketch.appendNode(wnScaleNode)
sketch.connect(wnNode.output, to: wnScaleNode.input)
sketch.connect(wnSFBreakpointNode.output, to: wnScaleNode.scale)
// Mixer
let mixerNode = SFMixerNode()
sketch.appendNode(mixerNode)
sketch.connect(triangleScaleNode.output, to: mixerNode.input1)
sketch.connect(squareScaleNode.output, to: mixerNode.input2)
sketch.connect(wnScaleNode.output, to: mixerNode.input3)
sketch.connect(mixerNode.output, to: sketch.outputNode.input)
return sketch
}
func makeSineSketch() -> SFSketch {
let sketch = SFSketch()
// Sine < Sketch
let sineNode = SFSineNode()
sketch.appendNode(sineNode)
sketch.connect(sineNode.output, to: sketch.outputNode.input)
// Freq < Sine < Sketch
let freqNode = SFStaticNode(value: 440.0)
sketch.appendNode(freqNode)
sketch.connect(freqNode.output, to: sineNode.frequency)
return sketch;
}
func makeNoiseSketch() -> SFSketch {
let sketch = SFSketch()
// Noise < Sketch
let noiseNode = SFWhiteNoiseNode()
sketch.appendNode(noiseNode)
sketch.connect(noiseNode.output, to: sketch.outputNode.input)
return sketch;
}
}
| mit | 6a1b1adc64fb6fe761efe1ee35c3a4e5 | 30.290323 | 82 | 0.619072 | 3.635228 | false | false | false | false |
uber/rides-ios-sdk | source/UberRides/Model/Product.swift | 1 | 11011 | //
// Product.swift
// UberRides
//
// Copyright © 2015 Uber Technologies, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND 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 UberCore
// MARK: Products
/**
* Internal object that contains a list of Uber products.
*/
struct UberProducts: Codable {
var list: [Product]?
enum CodingKeys: String, CodingKey {
case list = "products"
}
}
// MARK: Product
/**
* Contains information for a single Uber product.
*/
@objc(UBSDKProduct) public class Product: NSObject, Codable {
/// Unique identifier representing a specific product for a given latitude & longitude.
@objc public private(set) var productID: String?
/// Display name of product. Ex: "UberBLACK".
@objc public private(set) var name: String?
/// Description of product. Ex: "The original Uber".
@objc public private(set) var productDescription: String?
/// Capacity of product. Ex: 4, for a product that fits 4.
@nonobjc public private(set) var capacity: Int?
/// Capacity of product. Ex: 4, for a product that fits 4.
@objc public var objc_capacity: NSNumber? {
if let capacity = capacity {
return NSNumber(value: capacity)
} else {
return nil
}
}
/// Image URL representing the product.
@objc public private(set) var imageURL: URL?
/// The basic price details. See `PriceDetails` for structure.
@objc public private(set) var priceDetails: PriceDetails?
/// Specifies whether this product allows users to get upfront fares, instead of time + distance.
@nonobjc public private(set) var upfrontFareEnabled: Bool?
/// Specifies whether this product allows users to get upfront fares, instead of time + distance. Boolean value.
@objc public var objc_upfrontFareEnabled: NSNumber? {
if let upfrontFareEnabled = upfrontFareEnabled {
return NSNumber(value: upfrontFareEnabled)
} else {
return nil
}
}
/// Specifies whether this product allows cash payments
@nonobjc public private(set) var cashEnabled: Bool?
/// Specifies whether this product allows cash payments. Boolean value.
@objc public var objc_cashEnabled: NSNumber? {
if let cashEnabled = cashEnabled {
return NSNumber(value: cashEnabled)
} else {
return nil
}
}
/// Specifies whether this product allows for the pickup and drop off of other riders during the trip
@nonobjc public private(set) var isShared: Bool?
/// Specifies whether this product allows for the pickup and drop off of other riders during the trip. Boolean value.
@objc public var objc_isShared: NSNumber? {
if let isShared = isShared {
return NSNumber(value: isShared)
} else {
return nil
}
}
/// The product group that this product belongs to
@objc public private(set) var productGroup: ProductGroup
enum CodingKeys: String, CodingKey {
case productID = "product_id"
case name = "display_name"
case productDescription = "description"
case capacity = "capacity"
case imageURL = "image"
case priceDetails = "price_details"
case upfrontFareEnabled = "upfront_fare_enabled"
case cashEnabled = "cash_enabled"
case isShared = "shared"
case productGroup = "product_group"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
productID = try container.decodeIfPresent(String.self, forKey: .productID)
name = try container.decodeIfPresent(String.self, forKey: .name)
productDescription = try container.decodeIfPresent(String.self, forKey: .productDescription)
capacity = try container.decodeIfPresent(Int.self, forKey: .capacity)
imageURL = try container.decodeIfPresent(URL.self, forKey: .imageURL)
priceDetails = try container.decodeIfPresent(PriceDetails.self, forKey: .priceDetails)
upfrontFareEnabled = try container.decodeIfPresent(Bool.self, forKey: .upfrontFareEnabled)
cashEnabled = try container.decodeIfPresent(Bool.self, forKey: .cashEnabled)
isShared = try container.decodeIfPresent(Bool.self, forKey: .isShared)
productGroup = try container.decodeIfPresent(ProductGroup.self, forKey: .productGroup) ?? .unknown
}
}
// MARK: PriceDetails
/**
* Contains basic price details for an Uber product.
*/
@objc(UBSDKPriceDetails) public class PriceDetails: NSObject, Codable {
/// Unit of distance used to calculate fare (mile or km).
@objc public private(set) var distanceUnit: String?
/// ISO 4217 currency code.
@objc public private(set) var currencyCode: String?
/// The charge per minute (if applicable).
@nonobjc public private(set) var costPerMinute: Double?
/// The charge per minute (if applicable).
@objc(costPerMinute) public var objc_costPerMinute: NSNumber? {
if let costPerMinute = costPerMinute {
return NSNumber(value: costPerMinute)
} else {
return nil
}
}
/// The charge per distance unit (if applicable).
@nonobjc public private(set) var costPerDistance: Double?
/// The charge per distance unit (if applicable).
@objc(costPerDistance) public var objc_costPerDistance: NSNumber? {
if let costPerDistance = costPerDistance {
return NSNumber(value: costPerDistance)
} else {
return nil
}
}
/// The base price.
@nonobjc public private(set) var baseFee: Double?
/// The base price.
@objc(baseFee) public var objc_baseFee: NSNumber? {
if let baseFee = baseFee {
return NSNumber(value: baseFee)
} else {
return nil
}
}
/// The minimum price of a trip.
@nonobjc public private(set) var minimumFee: Double?
/// The minimum price of a trip.
@objc(minimumFee) public var objc_minimumFee: NSNumber? {
if let minimumFee = minimumFee {
return NSNumber(value: minimumFee)
} else {
return nil
}
}
/// The fee if a rider cancels the trip after a grace period.
@nonobjc public private(set) var cancellationFee: Double?
/// The fee if a rider cancels the trip after a grace period.
@objc(cancellationFee) public var objc_cancellationFee: NSNumber? {
if let cancellationFee = cancellationFee {
return NSNumber(value: cancellationFee)
} else {
return nil
}
}
/// Array containing additional fees added to the price. See `ServiceFee`.
@objc public private(set) var serviceFees: [ServiceFee]?
enum CodingKeys: String, CodingKey {
case distanceUnit = "distance_unit"
case currencyCode = "currency_code"
case costPerMinute = "cost_per_minute"
case costPerDistance = "cost_per_distance"
case baseFee = "base"
case minimumFee = "minimum"
case cancellationFee = "cancellation_fee"
case serviceFees = "service_fees"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
distanceUnit = try container.decodeIfPresent(String.self, forKey: .distanceUnit)
currencyCode = try container.decodeIfPresent(String.self, forKey: .currencyCode)
costPerMinute = try container.decodeIfPresent(Double.self, forKey: .costPerMinute)
costPerDistance = try container.decodeIfPresent(Double.self, forKey: .costPerDistance)
baseFee = try container.decodeIfPresent(Double.self, forKey: .baseFee)
minimumFee = try container.decodeIfPresent(Double.self, forKey: .minimumFee)
cancellationFee = try container.decodeIfPresent(Double.self, forKey: .cancellationFee)
serviceFees = try container.decodeIfPresent([ServiceFee].self, forKey: .serviceFees)
}
}
// MARK: ServiceFee
/**
* Contains information for additional fees that can be added to the price of an Uber product.
*/
@objc(UBSDKServiceFee) public class ServiceFee: NSObject, Codable {
/// The name of the service fee.
@objc public private(set) var name: String?
/// The amount of the service fee.
@nonobjc public private(set) var fee: Double?
/// The amount of the service fee.
@objc(fee) public var objc_fee: NSNumber? {
if let fee = fee {
return NSNumber(value: fee)
} else {
return nil
}
}
enum CodingKeys: String, CodingKey {
case name = "name"
case fee = "fee"
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decodeIfPresent(String.self, forKey: .name)
fee = try container.decodeIfPresent(Double.self, forKey: .fee)
}
}
/// Uber Product Category
@objc(UBSDKProductGroup) public enum ProductGroup: Int, Codable {
/// Shared rides products (eg, UberPOOL)
case rideshare
/// UberX
case uberX
/// UberXL
case uberXL
/// UberBLACK
case uberBlack
/// UberSUV
case suv
/// 3rd party taxis
case taxi
/// Unknown product group
case unknown
public init(from decoder: Decoder) throws {
let string = try decoder.singleValueContainer().decode(String.self).lowercased()
switch string {
case "rideshare":
self = .rideshare
case "uberx":
self = .uberX
case "uberxl":
self = .uberXL
case "uberblack":
self = .uberBlack
case "suv":
self = .suv
case "taxi":
self = .taxi
default:
self = .unknown
}
}
}
| mit | 76d12c3af7cbfe7cbe122bc87366f7dc | 34.746753 | 122 | 0.656676 | 4.45749 | false | false | false | false |
xjmeplws/AGDropdown | AGDropdown/AGButton.swift | 1 | 1894 | //
// AGButton.swift
// AGDropdown
//
// Created by huangyawei on 16/3/22.
// Copyright © 2016年 xjmeplws. All rights reserved.
//
import Foundation
import UIKit
class AGButton: UIButton {
private var isRotate = false
///button's image
var image: UIImage?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
if self.image == nil {
self.image = renderImage()
}
self.setImage(self.image, forState: .Normal)
self.imageEdgeInsets = UIEdgeInsetsMake(0, (self.frame.size.width - 30), 0, 0)
self.removeTarget(self, action: "rotateSelf", forControlEvents: .TouchUpInside)
self.addTarget(self, action: "rotateSelf", forControlEvents: .TouchUpInside)
}
func rotateSelf() {
guard let rotateImageView = self.imageView else {
return
}
let transform = CGAffineTransformMakeRotation(!isRotate ? CGFloat(M_PI) : 0)
isRotate = !isRotate
UIView.animateWithDuration(0.1, animations: {
rotateImageView.transform = transform
})
}
private func renderImage() -> UIImage? {
let renderRect = CGRectMake(0.0, 0.0, 14.0, 10.0)
UIGraphicsBeginImageContext(renderRect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, AGDataSource.hexColor(0xAAAAAA).CGColor)
CGContextMoveToPoint(context, 0.0, 0.0)
CGContextAddLineToPoint(context, 14.0, 0.0)
CGContextAddLineToPoint(context, 7.0, 10.0)
CGContextFillPath(context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
} | mit | 354ad7990b1a3c59bbd748374d94579d | 29.516129 | 88 | 0.640402 | 4.481043 | false | false | false | false |
ldjhust/CircleBom | CircleBom/Circle.swift | 1 | 2049 | //
// Circle.swift
// CircleBom
//
// Created by ldjhust on 15/11/26.
// Copyright © 2015年 ldj. All rights reserved.
//
import UIKit
class Circle: UIView {
var initialFrame = CGRectZero
var progress:CGFloat = 0.5
override func drawRect(rect: CGRect) {
// 获取当前画布
let offset = initialFrame.width / 3.6
let moveDistance = (initialFrame.width * 1 / 5) * CGFloat(fabs(progress - 0.5) * 2)
NSLog ("%f", moveDistance)
let originCenter = CGPoint(x: initialFrame.origin.x + initialFrame.width/2,
y: initialFrame.origin.y + initialFrame.height/2)
let pointA = CGPoint(x: originCenter.x, y: originCenter.y - initialFrame.height/2 + moveDistance)
let pointB = CGPoint(x: originCenter.x + initialFrame.width/2, y: originCenter.y)
let pointC = CGPoint(x: originCenter.x, y: originCenter.y + initialFrame.height/2 - moveDistance)
let pointD = CGPoint(x: originCenter.x - initialFrame.width/2 - moveDistance, y: originCenter.y)
let c1 = CGPoint(x: pointA.x + offset, y: pointA.y)
let c2 = CGPoint(x: pointB.x, y: pointB.y - offset)
let c3 = CGPoint(x: pointB.x, y: pointB.y + offset)
let c4 = CGPoint(x: pointC.x + offset, y: pointC.y)
let c5 = CGPoint(x: pointC.x - offset, y: pointC.y)
let c6 = CGPoint(x: pointD.x, y: pointD.y + offset - moveDistance)
let c7 = CGPoint(x: pointD.x, y: pointD.y - offset + moveDistance)
let c8 = CGPoint(x: pointA.x - offset, y: pointA.y)
let bezierPath = UIBezierPath()
// 设置填充颜色
UIColor.redColor().setFill()
// 开始画
bezierPath.moveToPoint(pointA)
bezierPath.addCurveToPoint(pointB, controlPoint1: c1, controlPoint2: c2)
bezierPath.addCurveToPoint(pointC, controlPoint1: c3, controlPoint2: c4)
bezierPath.addCurveToPoint(pointD, controlPoint1: c5, controlPoint2: c6)
bezierPath.addCurveToPoint(pointA, controlPoint1: c7, controlPoint2: c8)
bezierPath.closePath()
// 开始填充
bezierPath.fill()
}
}
| mit | 02b01797caa131a38a18e4d3cd94bb4e | 35.509091 | 101 | 0.664343 | 3.397631 | false | false | false | false |
NinjaSudo/GoodFeelsApp | GoodFeels/ViewControllers/ContactsViewController.swift | 1 | 5963 | //
// ContactsViewController.swift
// GoodFeels
//
// Created by Edward Freeman on 12/21/15.
// Copyright © 2015 NinjaSudo LLC. All rights reserved.
//
import UIKit
import Contacts
import MessageUI
import pop
class ContactsViewController: UIViewController {
@IBOutlet var backView: BackBoardView!
@IBOutlet weak var contactsTableView: UITableView!
@IBOutlet weak var sendMessageButton: UIButton!
@IBOutlet weak var bottomLayoutConstraint: NSLayoutConstraint!
private var reuseIdentifier = "ContactCell"
private var addedContentObserver: NSObjectProtocol!
var contacts : Array<CNContact> = []
var selectedContacts = [String: NSIndexPath]()
override func viewDidLoad() {
contactsTableView.delegate = self
contactsTableView.dataSource = self
contactsTableView.editing = false
backView.tableView = contactsTableView.backgroundView
addedContentObserver = NSNotificationCenter.defaultCenter().addObserverForName(ContactsManagerAddedContentNotification,
object: nil,
queue: NSOperationQueue.mainQueue()) { notification in
self.contentChangedNotification(notification)
}
if GoodFeelsClient.sharedInstance.contacts.count > 0 {
contacts = GoodFeelsClient.sharedInstance.contacts
} else {
// Load Progress HUD
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if !selectedContacts.isEmpty {
animateButtonUp()
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.navigationBarHidden = false
animateButtonDown()
}
func animateButtonUp() {
let spring = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant)
spring.toValue = 0
spring.springBounciness = 8 // a float between 0 and 20
spring.springSpeed = 10
spring.completionBlock = { (anim: POPAnimation!, done: Bool) in
self.sendMessageButton.enabled = true
}
bottomLayoutConstraint.pop_addAnimation(spring, forKey: "moveUp")
}
func animateButtonDown() {
let spring = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant)
spring.toValue = -1 * sendMessageButton.frame.height // negative height
spring.springBounciness = 10 // a float between 0 and 20
spring.springSpeed = 8
spring.completionBlock = { (anim: POPAnimation!, done: Bool) in
self.sendMessageButton.enabled = false
}
bottomLayoutConstraint.pop_addAnimation(spring, forKey: "moveDown")
}
@IBAction func sendText(sender: UIButton) {
if !selectedContacts.isEmpty && GoodFeelsClient.sharedInstance.canSendText() {
let controller = GoodFeelsClient.sharedInstance.configuredMessageComposeViewController(
Array(selectedContacts.keys),
textBody: GoodFeelsClient.sharedInstance.selectedMessage)
self.presentViewController(controller, animated: true, completion: nil)
} else {
print("This device cannot send SMS messages.")
}
}
}
extension ContactsViewController : UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 50
}
func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell.selected {
cell.selected = false
cell.accessoryType = (cell.accessoryType == .None) ? .Checkmark : .None
let contact = contacts[indexPath.row],
labeledValue = contact.phoneNumbers[0] as CNLabeledValue,
phoneNumber = labeledValue.value as! CNPhoneNumber
if cell.accessoryType == .None { // remove phone # from list
selectedContacts.removeValueForKey(phoneNumber.stringValue)
} else { // add phone # to list
selectedContacts[phoneNumber.stringValue] = indexPath
}
}
}
if !selectedContacts.isEmpty {
animateButtonUp()
}
}
}
extension ContactsViewController : UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return contacts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = contactsTableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath)
let contact = contacts[indexPath.row]
cell.selectionStyle = .None
if let nameLabel = cell.viewWithTag(101) as? UILabel {
nameLabel.text = CNContactFormatter.stringFromContact(contact, style: .FullName)
}
if let numberLabel = cell.viewWithTag(102) as? UILabel {
let labeledValue = contact.phoneNumbers[0] as CNLabeledValue
let phoneNumber = labeledValue.value as! CNPhoneNumber
cell.accessoryType = (selectedContacts.keys.contains(phoneNumber.stringValue)) ? .Checkmark : . None
numberLabel.text = phoneNumber.stringValue
}
return cell
}
}
private extension ContactsViewController {
func contentChangedNotification(notification: NSNotification!) {
contacts = GoodFeelsClient.sharedInstance.contacts
contactsTableView?.reloadData()
}
} | mit | dd71d39bd7514dfd551b3006a8387ed6 | 36.980892 | 127 | 0.654646 | 5.710728 | false | false | false | false |
jaropawlak/Signal-iOS | Signal/src/ViewControllers/GifPicker/GifPickerViewController.swift | 1 | 19191 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
@objc
protocol GifPickerViewControllerDelegate: class {
func gifPickerDidSelect(attachment: SignalAttachment)
}
class GifPickerViewController: OWSViewController, UISearchBarDelegate, UICollectionViewDataSource, UICollectionViewDelegate, GifPickerLayoutDelegate {
static let TAG = "[GifPickerViewController]"
let TAG = "[GifPickerViewController]"
// MARK: Properties
enum ViewMode {
case idle, searching, results, noResults, error
}
private var viewMode = ViewMode.idle {
didSet {
Logger.info("\(TAG) viewMode: \(viewMode)")
updateContents()
}
}
var lastQuery: String = ""
public weak var delegate: GifPickerViewControllerDelegate?
let thread: TSThread
let messageSender: MessageSender
let searchBar: UISearchBar
let layout: GifPickerLayout
let collectionView: UICollectionView
var noResultsView: UILabel?
var searchErrorView: UILabel?
var activityIndicator: UIActivityIndicatorView?
var hasSelectedCell: Bool = false
var imageInfos = [GiphyImageInfo]()
var reachability: Reachability?
private let kCellReuseIdentifier = "kCellReuseIdentifier"
var progressiveSearchTimer: Timer?
// MARK: Initializers
@available(*, unavailable, message:"use other constructor instead.")
required init?(coder aDecoder: NSCoder) {
fatalError("\(#function) is unimplemented.")
}
required init(thread: TSThread, messageSender: MessageSender) {
self.thread = thread
self.messageSender = messageSender
self.searchBar = UISearchBar()
self.layout = GifPickerLayout()
self.collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.layout)
super.init(nibName: nil, bundle: nil)
self.layout.delegate = self
}
deinit {
NotificationCenter.default.removeObserver(self)
progressiveSearchTimer?.invalidate()
}
func didBecomeActive() {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
// Prod cells to try to load when app becomes active.
ensureCellState()
}
func reachabilityChanged() {
AssertIsOnMainThread()
Logger.info("\(self.TAG) \(#function)")
// Prod cells to try to load when connectivity changes.
ensureCellState()
}
func ensureCellState() {
for cell in self.collectionView.visibleCells {
guard let cell = cell as? GifPickerCell else {
owsFail("\(TAG) unexpected cell.")
return
}
cell.ensureCellState()
}
}
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel,
target: self,
action: #selector(donePressed))
self.navigationItem.title = NSLocalizedString("GIF_PICKER_VIEW_TITLE",
comment: "Title for the 'gif picker' dialog.")
createViews()
reachability = Reachability.forInternetConnection()
NotificationCenter.default.addObserver(self,
selector: #selector(reachabilityChanged),
name: NSNotification.Name.reachabilityChanged,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(didBecomeActive),
name: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.searchBar.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
progressiveSearchTimer?.invalidate()
progressiveSearchTimer = nil
}
// MARK: Views
private func createViews() {
view.backgroundColor = UIColor.white
// Block UIKit from adjust insets of collection view which screws up
// min/max scroll positions.
self.automaticallyAdjustsScrollViewInsets = false
// Search
searchBar.searchBarStyle = .minimal
searchBar.delegate = self
searchBar.placeholder = NSLocalizedString("GIF_VIEW_SEARCH_PLACEHOLDER_TEXT",
comment: "Placeholder text for the search field in gif view")
searchBar.backgroundColor = UIColor.white
self.view.addSubview(searchBar)
searchBar.autoPinWidthToSuperview()
searchBar.autoPin(toTopLayoutGuideOf: self, withInset: 0)
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.backgroundColor = UIColor.white
self.collectionView.register(GifPickerCell.self, forCellWithReuseIdentifier: kCellReuseIdentifier)
// Inserted below searchbar because we later occlude the collectionview
// by inserting a masking layer between the search bar and collectionview
self.view.insertSubview(self.collectionView, belowSubview: searchBar)
self.collectionView.autoPinWidthToSuperview()
self.collectionView.autoPinEdge(.top, to: .bottom, of: searchBar)
// for iPhoneX devices, extends the black background to the bottom edge of the view.
let bottomBannerContainer = UIView()
bottomBannerContainer.backgroundColor = UIColor.black
self.view.addSubview(bottomBannerContainer)
bottomBannerContainer.autoPinWidthToSuperview()
bottomBannerContainer.autoPinEdge(.top, to: .bottom, of: self.collectionView)
bottomBannerContainer.autoPinEdge(toSuperviewEdge: .bottom)
let bottomBanner = UIView()
bottomBannerContainer.addSubview(bottomBanner)
bottomBanner.autoPinEdge(toSuperviewEdge: .top)
bottomBanner.autoPinWidthToSuperview()
self.autoPinView(toBottomGuideOrKeyboard:bottomBanner)
// The Giphy API requires us to "show their trademark prominently" in our GIF experience.
let logoImage = UIImage(named: "giphy_logo")
let logoImageView = UIImageView(image: logoImage)
bottomBanner.addSubview(logoImageView)
logoImageView.autoPinHeightToSuperview(withMargin: 3)
logoImageView.autoHCenterInSuperview()
let noResultsView = createErrorLabel(text: NSLocalizedString("GIF_VIEW_SEARCH_NO_RESULTS",
comment: "Indicates that the user's search had no results."))
self.noResultsView = noResultsView
self.view.addSubview(noResultsView)
noResultsView.autoPinWidthToSuperview(withMargin: 20)
noResultsView.autoAlignAxis(.horizontal, toSameAxisOf: self.collectionView)
let searchErrorView = createErrorLabel(text: NSLocalizedString("GIF_VIEW_SEARCH_ERROR",
comment: "Indicates that an error occured while searching."))
self.searchErrorView = searchErrorView
self.view.addSubview(searchErrorView)
searchErrorView.autoPinWidthToSuperview(withMargin: 20)
searchErrorView.autoAlignAxis(.horizontal, toSameAxisOf: self.collectionView)
searchErrorView.isUserInteractionEnabled = true
searchErrorView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(retryTapped)))
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
self.activityIndicator = activityIndicator
self.view.addSubview(activityIndicator)
activityIndicator.autoHCenterInSuperview()
activityIndicator.autoAlignAxis(.horizontal, toSameAxisOf: self.collectionView)
self.updateContents()
}
private func createErrorLabel(text: String) -> UILabel {
let label = UILabel()
label.text = text
label.textColor = UIColor.black
label.font = UIFont.ows_mediumFont(withSize: 20)
label.textAlignment = .center
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
return label
}
private func updateContents() {
guard let noResultsView = self.noResultsView else {
owsFail("Missing noResultsView")
return
}
guard let searchErrorView = self.searchErrorView else {
owsFail("Missing searchErrorView")
return
}
guard let activityIndicator = self.activityIndicator else {
owsFail("Missing activityIndicator")
return
}
switch viewMode {
case .idle:
self.collectionView.isHidden = true
noResultsView.isHidden = true
searchErrorView.isHidden = true
activityIndicator.isHidden = true
activityIndicator.stopAnimating()
case .searching:
self.collectionView.isHidden = true
noResultsView.isHidden = true
searchErrorView.isHidden = true
activityIndicator.isHidden = false
activityIndicator.startAnimating()
case .results:
self.collectionView.isHidden = false
noResultsView.isHidden = true
searchErrorView.isHidden = true
activityIndicator.isHidden = true
activityIndicator.stopAnimating()
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.reloadData()
case .noResults:
self.collectionView.isHidden = true
noResultsView.isHidden = false
searchErrorView.isHidden = true
activityIndicator.isHidden = true
activityIndicator.stopAnimating()
case .error:
self.collectionView.isHidden = true
noResultsView.isHidden = true
searchErrorView.isHidden = false
activityIndicator.isHidden = true
activityIndicator.stopAnimating()
}
}
// MARK: - UIScrollViewDelegate
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.searchBar.resignFirstResponder()
}
// MARK: - UICollectionViewDataSource
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageInfos.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellReuseIdentifier, for: indexPath)
guard indexPath.row < imageInfos.count else {
Logger.warn("\(TAG) indexPath: \(indexPath.row) out of range for imageInfo count: \(imageInfos.count) ")
return cell
}
let imageInfo = imageInfos[indexPath.row]
guard let gifCell = cell as? GifPickerCell else {
owsFail("\(TAG) Unexpected cell type.")
return cell
}
gifCell.imageInfo = imageInfo
return cell
}
// MARK: - UICollectionViewDelegate
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? GifPickerCell else {
owsFail("\(TAG) unexpected cell.")
return
}
guard cell.stillAsset != nil || cell.animatedAsset != nil else {
// we don't want to let the user blindly select a gray cell
Logger.debug("\(TAG) ignoring selection of cell with no preview")
return
}
guard self.hasSelectedCell == false else {
owsFail("\(TAG) Already selected cell")
return
}
self.hasSelectedCell = true
// Fade out all cells except the selected one.
let maskingView = OWSBezierPathView()
// Selecting cell behind searchbar masks part of search bar.
// So we insert mask *behind* the searchbar.
self.view.insertSubview(maskingView, belowSubview: searchBar)
let cellRect = self.collectionView.convert(cell.frame, to: self.view)
maskingView.configureShapeLayerBlock = { layer, bounds in
let path = UIBezierPath(rect: bounds)
path.append(UIBezierPath(rect: cellRect))
layer.path = path.cgPath
layer.fillRule = kCAFillRuleEvenOdd
layer.fillColor = UIColor.black.cgColor
layer.opacity = 0.7
}
maskingView.autoPinEdgesToSuperviewEdges()
cell.isCellSelected = true
self.collectionView.isUserInteractionEnabled = false
getFileForCell(cell)
}
public func getFileForCell(_ cell: GifPickerCell) {
GiphyDownloader.sharedInstance.cancelAllRequests()
cell.requestRenditionForSending().then { [weak self] (asset: GiphyAsset) -> Void in
guard let strongSelf = self else {
Logger.info("\(GifPickerViewController.TAG) ignoring send, since VC was dismissed before fetching finished.")
return
}
let filePath = asset.filePath
guard let dataSource = DataSourcePath.dataSource(withFilePath: filePath) else {
owsFail("\(strongSelf.TAG) couldn't load asset.")
return
}
let attachment = SignalAttachment(dataSource: dataSource, dataUTI: asset.rendition.utiType)
strongSelf.delegate?.gifPickerDidSelect(attachment: attachment)
strongSelf.dismiss(animated: true, completion: nil)
}.catch { [weak self] error in
guard let strongSelf = self else {
Logger.info("\(GifPickerViewController.TAG) ignoring failure, since VC was dismissed before fetching finished.")
return
}
let alert = UIAlertController(title: NSLocalizedString("GIF_PICKER_FAILURE_ALERT_TITLE", comment: "Shown when selected gif couldn't be fetched"),
message: error.localizedDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: CommonStrings.retryButton, style: .default) { _ in
strongSelf.getFileForCell(cell)
})
alert.addAction(UIAlertAction(title: CommonStrings.dismissButton, style: .cancel) { _ in
strongSelf.dismiss(animated: true, completion: nil)
})
strongSelf.present(alert, animated: true, completion: nil)
}.retainUntilComplete()
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let cell = cell as? GifPickerCell else {
owsFail("\(TAG) unexpected cell.")
return
}
// We only want to load the cells which are on-screen.
cell.isCellVisible = true
}
public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let cell = cell as? GifPickerCell else {
owsFail("\(TAG) unexpected cell.")
return
}
cell.isCellVisible = false
}
// MARK: - Event Handlers
func donePressed(sender: UIButton) {
dismiss(animated: true, completion: nil)
}
// MARK: - UISearchBarDelegate
public func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// Clear error messages immediately.
if viewMode == .error || viewMode == .noResults {
viewMode = .idle
}
// Do progressive search after a delay.
progressiveSearchTimer?.invalidate()
progressiveSearchTimer = nil
let kProgressiveSearchDelaySeconds = 1.0
progressiveSearchTimer = WeakTimer.scheduledTimer(timeInterval: kProgressiveSearchDelaySeconds, target: self, userInfo: nil, repeats: true) { [weak self] _ in
guard let strongSelf = self else {
return
}
strongSelf.tryToSearch()
}
}
public func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.searchBar.resignFirstResponder()
tryToSearch()
}
public func tryToSearch() {
progressiveSearchTimer?.invalidate()
progressiveSearchTimer = nil
guard let text = searchBar.text else {
OWSAlerts.showAlert(withTitle: NSLocalizedString("ALERT_ERROR_TITLE",
comment: ""),
message: NSLocalizedString("GIF_PICKER_VIEW_MISSING_QUERY",
comment: "Alert message shown when user tries to search for GIFs without entering any search terms."))
return
}
let query = (text as String).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if (viewMode == .searching || viewMode == .results) && lastQuery == query {
Logger.info("\(TAG) ignoring duplicate search: \(query)")
return
}
search(query: query)
}
private func search(query: String) {
Logger.info("\(TAG) searching: \(query)")
progressiveSearchTimer?.invalidate()
progressiveSearchTimer = nil
imageInfos = []
viewMode = .searching
lastQuery = query
self.collectionView.contentOffset = CGPoint.zero
GiphyAPI.sharedInstance.search(query: query, success: { [weak self] imageInfos in
guard let strongSelf = self else { return }
Logger.info("\(strongSelf.TAG) search complete")
strongSelf.imageInfos = imageInfos
if imageInfos.count > 0 {
strongSelf.viewMode = .results
} else {
strongSelf.viewMode = .noResults
}
},
failure: { [weak self] _ in
guard let strongSelf = self else { return }
Logger.info("\(strongSelf.TAG) search failed.")
// TODO: Present this error to the user.
strongSelf.viewMode = .error
})
}
// MARK: - GifPickerLayoutDelegate
func imageInfosForLayout() -> [GiphyImageInfo] {
return imageInfos
}
// MARK: - Event Handlers
func retryTapped(sender: UIGestureRecognizer) {
guard sender.state == .recognized else {
return
}
guard viewMode == .error else {
return
}
tryToSearch()
}
}
| gpl-3.0 | bb1c5950a90dd56b0be4fa3885df916c | 36.264078 | 166 | 0.6267 | 5.764794 | false | false | false | false |
ITzTravelInTime/TINU | TINU/MediaCreationManagerMain.swift | 1 | 6239 | /*
TINU, the open tool to create bootable macOS installers.
Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import Cocoa
public typealias IMCM = InstallMediaCreationManager
public class InstallMediaCreationManager: ViewID{
public let id: String = "InstallMediaCreationManager"
public typealias Creation = UnsafePointer<CreationProcess>?
internal let ref: Creation
public init(ref: Creation, controller: InstallingViewController){
self.ref = ref
initTask()
DispatchQueue.main.sync {
self.viewController = controller
self.viewController.setProgressMax(IMCM.cpc.pMaxVal)
}
}
/*
private init(){
self.ref = nil
initTask()
}
*/
private func initTask(){
DispatchQueue.global(qos: .userInteractive).sync {
//gets fresh info about the management of the progressbar
IMCM.cpc = UIManager.ProcessProgressBarSettings.init(false)!//.createFromDefaultFile(false)!
if !UIManager.ProcessProgressBarSettings.checkInstance(IMCM.cpc){
fatalError("Bad progress bar settings")
}
//claculates the division for the progrees bar usage outside the main process
IMCM.unit = IMCM.cpc.pExtDuration / Double(IMCM.preCount)
}
}
static var cpc: UIManager.ProcessProgressBarSettings = UIManager.ProcessProgressBarSettings.init(false)!//.createFromDefaultFile(false)!
//public static private(set) var shared: InstallMediaCreationManager = InstallMediaCreationManager()
var lastMinute: UInt64 = 0
var lastSecs: UInt64 = 0
//timer to trace the process
var timer = Timer()
var progressMaxVal: Double {return IMCM.cpc.pMaxVal }
var processUnit: Double {return IMCM.cpc.pExtDuration }
var processEstimatedMinutes: UInt64 {return IMCM.cpc.pMaxMins }
var processMinutesToChange: UInt64 {return IMCM.cpc.pMidMins }
//progress bar increments during installer creation
var installerProgressValueFast: Double {return IMCM.cpc.installerProgressValueFast}
var installerProgressValueSlow: Double {return IMCM.cpc.installerProgressValueSlow}
//static let processDivisor: Double = ProcessConsts.uDen
//n of pre-process operations
static let preCount: UInt8 = 10
//progress bar segments of the pre-process
static var unit: Double = 0
var viewController: InstallingViewController!
//EFI copying stuff
#if !macOnlyMode
var startProgress: Double = 0
var progressRate: Double = 0
var EFICopyEnded = false
#endif
/** Prepares the UI to then start the creation process, this function needs to be executed into the main thread because if it's usage of UI */
/*
class func startInstallProcess(ref: Creation){
//cleans it's own memory first
IMCM.shared = InstallMediaCreationManager(ref: ref)
DispatchQueue.main.sync {
IMCM.shared.viewController = UIManager.shared.window.contentViewController as? InstallingViewController
}
if IMCM.shared.viewController == nil{
fatalError("Can't get installing ViewController")
}
DispatchQueue.main.sync {
IMCM.shared.viewController.setProgressMax(IMCM.cpc.pMaxVal)
}
IMCM.shared.install()
}
*/
//this functrion just sets those 2 long ones to false
public func makeProcessNotInExecution(withResult res: Bool){
//cvm.shared.process.isPreCreationInProgress = false
//cvm.shared.process.isCreationInProgress = false
ref!.pointee.process.status = res ? .doneSuccess : .doneFailure
}
//this function stops the current executable from running and , it does runs sudo using the password stored in memory
public func stop(mustStop: Bool) -> Bool!{
guard let success = TaskKillManager.terminateProcess(PID: ref!.pointee.process.handle.process.processIdentifier) else { return false }
if !success{
return false
}
//if we need to stop the process...
if mustStop{
ref!.pointee.process.handle.process.terminate()
//dispose timer, bacause it's no longer needed
timer.invalidate()
makeProcessNotInExecution(withResult: true)
}
return true
}
//just stops the whole process and sets the related variables
public func stop() -> Bool!{
return stop(mustStop: true)
}
//asks if the suer wants to stop the process
func stopWithAsk() -> Bool!{/*
var dTitle = "Stop the bootable macOS installer creation?"
var text = "Do you want to cancel the bootable macOS installer cration process?"
if sharedInstallMac{
dTitle = "Stop the macOS installation?"
text = "Do you want to stop the macOS installation process?"
}
if !dialogCritical(question: dTitle, text: text, style: .informational, proceedButtonText: "Don't Stop", cancelButtonText: "Stop" ){
return stop(mustStop: true)
}else{
return nil
}*/
if dialogGenericWithManagerBool(self, name: "stop", parseList: nil, style: .informational, icon: nil){
return stop(mustStop: true)
}else{
return nil
}
}
public func setActivityLabelText(_ text: String){
self.viewController.setActivityLabelText(text)
}
func setProgressValue(_ value: Double){
self.viewController.setProgressValue(value)
}
func addToProgressValue(_ value: Double){
self.viewController.addToProgressValue(value)
}
func setProgressMax(_ max: Double){
self.viewController.setProgressMax(max)
}
func getProgressBarValue() -> Double{
return self.viewController!.getProgressBarValue()
}
func setProgressBarIndeterminateState(state: Bool){
self.viewController?.setProgressBarIndeterminateState(state: state)
}
func getProgressBarIndeterminateState() -> Bool{
return self.viewController.progress.isIndeterminate
}
}
| gpl-2.0 | 3732c6c31b84cfdcdd90882c99668c59 | 27.619266 | 143 | 0.748197 | 3.792705 | false | false | false | false |
externl/ice | swift/test/Ice/invoke/TestI.swift | 4 | 3686 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Ice
import PromiseKit
import TestCommon
class BlobjectI: Ice.Blobject {
func ice_invoke(inEncaps: Data, current: Ice.Current) throws -> (ok: Bool, outParams: Data) {
let communicator = current.adapter!.getCommunicator()
let inS = Ice.InputStream(communicator: communicator, bytes: inEncaps)
_ = try inS.startEncapsulation()
let outS = Ice.OutputStream(communicator: communicator)
outS.startEncapsulation()
if current.operation == "opOneway" {
return (true, Data())
} else if current.operation == "opString" {
let s: String = try inS.read()
outS.write(s)
outS.write(s)
outS.endEncapsulation()
return (true, outS.finished())
} else if current.operation == "opException" {
if current.ctx["raise"] != nil {
throw MyException()
}
let ex = MyException()
outS.write(ex)
outS.endEncapsulation()
return (false, outS.finished())
} else if current.operation == "shutdown" {
communicator.shutdown()
return (true, Data())
} else if current.operation == "ice_isA" {
let s: String = try inS.read()
if s == "::Test::MyClass" {
outS.write(true)
} else {
outS.write(false)
}
outS.endEncapsulation()
return (true, outS.finished())
} else {
throw Ice.OperationNotExistException(id: current.id, facet: current.facet, operation: current.operation)
}
}
}
class BlobjectAsyncI: Ice.BlobjectAsync {
func ice_invokeAsync(inEncaps: Data, current: Current) -> Promise<(ok: Bool, outParams: Data)> {
do {
let communicator = current.adapter!.getCommunicator()
let inS = Ice.InputStream(communicator: communicator, bytes: inEncaps)
_ = try inS.startEncapsulation()
let outS = Ice.OutputStream(communicator: communicator)
outS.startEncapsulation()
if current.operation == "opOneway" {
return Promise.value((true, Data()))
} else if current.operation == "opString" {
let s: String = try inS.read()
outS.write(s)
outS.write(s)
outS.endEncapsulation()
return Promise.value((true, outS.finished()))
} else if current.operation == "opException" {
let ex = MyException()
outS.write(ex)
outS.endEncapsulation()
return Promise.value((false, outS.finished()))
} else if current.operation == "shutdown" {
communicator.shutdown()
return Promise.value((false, Data()))
} else if current.operation == "ice_isA" {
let s: String = try inS.read()
if s == "::Test::MyClass" {
outS.write(true)
} else {
outS.write(false)
}
outS.endEncapsulation()
return Promise.value((true, outS.finished()))
} else {
throw Ice.OperationNotExistException(id: current.id,
facet: current.facet,
operation: current.operation)
}
} catch {
return Promise<(ok: Bool, outParams: Data)> { seal in
seal.reject(error)
}
}
}
}
| gpl-2.0 | 6490d8ce1ed26f4cb7ffb5497bd36099 | 38.212766 | 116 | 0.517092 | 4.830931 | false | false | false | false |
AgaKhanFoundation/WCF-iOS | Pods/Nimble/Carthage/Checkouts/CwlPreconditionTesting/Sources/CwlPreconditionTesting/CwlBadInstructionException.swift | 4 | 3582 | //
// 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
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
| bsd-3-clause | f62594bd03aa94c2bd402d24df1317db | 37.923913 | 197 | 0.748674 | 3.834047 | false | false | false | false |
blighli/iPhone2015 | 21551008王荣烨/iOS大作业/Timer/Timer/FocusViewController.swift | 1 | 12503 | //
// FocusViewController.swift
// Timer
//
// Created by Hardor on 15/12/31.
// Copyright © 2015年 Hardor. All rights reserved.
//
import UIKit
import AVFoundation
import WatchConnectivity
final class FocusViewController: UIViewController {
private var audioPlayer = AVAudioPlayer()
private var focusView: FocusView! { return self.view as! FocusView }
private var timer: NSTimer?
private var endDate: NSDate?
private var localNotification: UILocalNotification?
private var currentType = TimerType.Idle
// private var workPeriods = [NSDate]()
//private var numberOfWorkPeriods = 10
private var totalMinutes = 0
private let kLastDurationKey = "kLastDurationKey"
private let kLastEndDateKey = "kLastEndDateKey"
var session: WCSession?
//MARK: - view cycle
override func loadView() {
view = FocusView(frame: .zero)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func viewDidLoad() {
super.viewDidLoad()
focusView.workButton.addTarget(self, action: "startWork:", forControlEvents: .TouchUpInside)
focusView.breakButton.addTarget(self, action: "startBreak:", forControlEvents: .TouchUpInside)
focusView.procrastinateButton.addTarget(self, action: "startProcrastination:", forControlEvents: .TouchUpInside)
focusView.settingsButton.addTarget(self, action: "showSettings", forControlEvents: .TouchUpInside)
focusView.aboutButton.addTarget(self, action: "showAbout", forControlEvents: .TouchUpInside)
// let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "showSettingsFromLongPross:")
// focusView.addGestureRecognizer(longPressRecognizer)
}
override func viewDidLayoutSubviews() {
let minSizeDimension = min(view.frame.size.width, view.frame.size.height)
focusView.timerView.timeLabel.font = focusView.timerView.timeLabel.font.fontWithSize((minSizeDimension-2*focusView.sidePadding)*0.9/3.0-10.0)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if timer == nil {
focusView.setDuration(0, maxValue: 1)
}
let duration = NSUserDefaults.standardUserDefaults().integerForKey(TimerType.Work.rawValue)
print("duration: \(duration)")
}
//MARK: - button actions
func startWork(sender: UIButton?) {
print("startWork")
guard currentType != .Work else { showAlert(); return }
startTimerWithType(.Work)
}
func startBreak(sender: UIButton?) {
guard currentType != .Break else { showAlert(); return }
startTimerWithType(.Break)
}
func startProcrastination(sender: UIButton) {
guard currentType != .Procrastination else { showAlert(); return }
startTimerWithType(.Procrastination)
}
func showSettings() {
presentViewController(DHNavigationController(rootViewController: SettingsViewController()), animated: true, completion: nil)
}
func showSettingsFromLongPross(sender: UILongPressGestureRecognizer) {
if sender.state == .Began {
showSettings()
}
}
func showAbout() {
presentViewController(DHNavigationController(rootViewController: AboutViewController()), animated: true, completion: nil)
}
func setUIModeForTimerType(timerType: TimerType) {
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options: [], animations: {
switch timerType {
case .Work:
self.set(self.focusView.workButton, enabled: true)
self.set(self.focusView.breakButton, enabled: false)
self.set(self.focusView.procrastinateButton, enabled: false)
case .Break:
self.set(self.focusView.workButton, enabled: false)
self.set(self.focusView.breakButton, enabled: true)
self.set(self.focusView.procrastinateButton, enabled: false)
case .Procrastination:
self.set(self.focusView.workButton, enabled: false)
self.set(self.focusView.breakButton, enabled: false)
self.set(self.focusView.procrastinateButton, enabled: true)
default:
self.set(self.focusView.workButton, enabled: true)
self.set(self.focusView.breakButton, enabled: true)
self.set(self.focusView.procrastinateButton, enabled: true)
}
}, completion: nil)
}
func set(button: UIButton, enabled: Bool) {
if enabled {
button.enabled = true
button.alpha = 1.0
} else {
button.enabled = false
button.alpha = 0.3
}
}
}
//MARK: - timer methods
extension FocusViewController {
func startTimerWithType(timerType: TimerType) {
focusView.setDuration(0, maxValue: 1)
var typeName: String
switch timerType {
case .Work:
typeName = "Work"
currentType = .Work
// workPeriods.append(NSDate())
case .Break:
typeName = "Break"
currentType = .Break
case .Procrastination:
typeName = "Procrastination"
currentType = .Procrastination
default:
typeName = "None"
currentType = .Idle
resetTimer()
// focusView.numberOfWorkPeriodsLabel.text = "\(workPeriods.count)/\(numberOfWorkPeriods)"
UIApplication.sharedApplication().cancelAllLocalNotifications()
return
}
setUIModeForTimerType(currentType)
// focusView.numberOfWorkPeriodsLabel.text = "\(workPeriods.count)/\(numberOfWorkPeriods)"
let seconds = NSUserDefaults.standardUserDefaults().integerForKey(timerType.rawValue)
endDate = NSDate(timeIntervalSinceNow: Double(seconds))
// let endTimeStamp = floor(endDate!.timeIntervalSince1970)
// if let sharedDefaults = NSUserDefaults(suiteName: "group.de.dasdom.Tomate") {
// sharedDefaults.setDouble(endTimeStamp, forKey: "date")
// sharedDefaults.setInteger(seconds, forKey: "maxValue")
// sharedDefaults.synchronize()
// }
//
// if let session = session where session.paired && session.watchAppInstalled {
// do {
// try session.updateApplicationContext(["date": endTimeStamp, "maxValue": seconds])
// } catch {
// print("Error!")
// }
// // if session.complicationEnabled {
// session.transferCurrentComplicationUserInfo(["date": endTimeStamp, "maxValue": seconds])
// // }
// }
timer?.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateTimeLabel:", userInfo: ["timerType" : seconds], repeats: true)
//
// UIApplication.sharedApplication().cancelAllLocalNotifications()
//
// localNotification = UILocalNotification()
// localNotification!.fireDate = endDate
// localNotification!.alertBody = "Time for " + typeName + " is up!";
// localNotification!.soundName = UILocalNotificationDefaultSoundName
// localNotification!.category = "START_CATEGORY"
// UIApplication.sharedApplication().scheduleLocalNotification(localNotification!)
}
func updateTimeLabel(sender: NSTimer) {
var totalNumberOfSeconds: CGFloat
if let type = (sender.userInfo as! NSDictionary!)["timerType"] as? Int {
totalNumberOfSeconds = CGFloat(type)
} else {
assert(false, "This should not happen")
totalNumberOfSeconds = -1.0
}
let timeInterval = CGFloat(endDate!.timeIntervalSinceNow)
if timeInterval < 0 {
resetTimer()
if timeInterval > -1 {
// AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("mydestiny", ofType: "mp3")!)
print(alertSound)
do{
audioPlayer = try
AVAudioPlayer(contentsOfURL: alertSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
catch let error as NSError {
print("Could not create audio player: \(error)")
}
}
focusView.setDuration(0, maxValue: 1)
return
}
focusView.setDuration(timeInterval, maxValue: totalNumberOfSeconds)
}
private func resetTimer() {
timer?.invalidate()
timer = nil
currentType = .Idle
setUIModeForTimerType(.Idle)
// if let session = session where session.paired && session.watchAppInstalled {
// do {
// try session.updateApplicationContext(["date": -1.0, "maxValue": -1.0])
// } catch {
// print("Error!")
// }
// session.transferCurrentComplicationUserInfo(["date": -1.0, "maxValue": -1.0])
// }
//
// if let sharedDefaults = NSUserDefaults(suiteName: "group.de.dasdom.Tomate") {
// sharedDefaults.removeObjectForKey("date")
// sharedDefaults.synchronize()
// }
}
}
//extension FocusViewController: WCSessionDelegate {
// func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]) {
// print(userInfo)
// guard let actionString = userInfo["action"] as? String else { return }
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
// switch actionString {
// case "work":
// self.startTimerWithType(.Work)
// case "break":
// self.startTimerWithType(.Break)
// case "stop":
// self.startTimerWithType(.Idle)
// default:
// break
// }
// })
// }
// func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
// print(applicationContext)
// guard let actionString = applicationContext["action"] as? String else { return }
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
// switch actionString {
// case "work":
// self.startTimerWithType(.Work)
// case "break":
// self.startTimerWithType(.Break)
// case "stop":
// self.startTimerWithType(.Idle)
// default:
// break
// }
// })
// }
//}
//MARK: - alert
private extension FocusViewController {
func showAlert() {
var alertMessage = NSLocalizedString("你想结束当前模式吗?", comment: "first part of alert message")
switch currentType {
case .Work:
alertMessage += NSLocalizedString("工作模式", comment: "second part of alert message")
case .Break:
alertMessage += NSLocalizedString("休息模式", comment: "secont part of alert message")
case .Procrastination:
alertMessage += NSLocalizedString("放松模式", comment: "secont part of alert message")
default:
break
}
let alertController = UIAlertController(title: "结束", message: alertMessage, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: { action in
print("\(action)")
})
alertController.addAction(cancelAction)
let stopAction = UIAlertAction(title: "确定", style: .Default, handler: { action in
print("\(action)")
// if self.currentType == .Work || self.workPeriods.count > 0 {
// self.workPeriods.removeLast()
// }
self.startTimerWithType(.Idle)
})
alertController.addAction(stopAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
| mit | 13207f38441443caff29b0ca1c06ea39 | 36.481928 | 153 | 0.602298 | 4.908876 | false | false | false | false |
Geor9eLau/WorkHelper | Carthage/Checkouts/SwiftCharts/SwiftCharts/Views/ChartPointTextCircleView.swift | 1 | 2422 | //
// ChartPointTextCircleView.swift
// swift_charts
//
// Created by ischuetz on 14/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartPointTextCircleView: UILabel {
fileprivate let targetCenter: CGPoint
open var viewTapped: ((ChartPointTextCircleView) -> ())?
open var selected: Bool = false {
didSet {
if self.selected {
self.textColor = UIColor.white
self.layer.borderColor = UIColor.white.cgColor
self.layer.backgroundColor = UIColor.black.cgColor
} else {
self.textColor = UIColor.black
self.layer.borderColor = UIColor.black.cgColor
self.layer.backgroundColor = UIColor.white.cgColor
}
}
}
public init(chartPoint: ChartPoint, center: CGPoint, diameter: CGFloat, cornerRadius: CGFloat, borderWidth: CGFloat, font: UIFont) {
self.targetCenter = center
super.init(frame: CGRect(x: 0, y: center.y - diameter / 2, width: diameter, height: diameter))
self.textColor = UIColor.black
self.text = chartPoint.description
self.font = font
self.layer.cornerRadius = cornerRadius
self.layer.borderWidth = borderWidth
self.textAlignment = NSTextAlignment.center
self.layer.borderColor = UIColor.gray.cgColor
let c = UIColor(red: 1, green: 1, blue: 1, alpha: 0.85)
self.layer.backgroundColor = c.cgColor
self.isUserInteractionEnabled = true
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: {
let w: CGFloat = self.frame.size.width
let h: CGFloat = self.frame.size.height
let frame = CGRect(x: self.targetCenter.x - (w/2), y: self.targetCenter.y - (h/2), width: w, height: h)
self.frame = frame
}, completion: {finished in})
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
viewTapped?(self)
}
}
| mit | 9f1ae0a79af20a2334704249c02e50de | 33.112676 | 155 | 0.610652 | 4.675676 | false | false | false | false |
syllabix/swipe-card-carousel | Source/SwipeCardDeck.swift | 1 | 4314 | //
// SwipeCardDeck.swift
// SwipeCardCarousel
//
// Created by Tom Stoepker on 10/6/16.
// Copyright © 2016 CrushOnly. All rights reserved.
//
import UIKit
public class SwipeCardDeck: UIView, SwipeCardDelegate {
public var delegate: SwipeCardDeckDelegate?
public var cardInsets: CGFloat = 0
private var curindex: Int = 0
private var numcards: Int = 0
private var cardrect: CGRect!
private var deckready = false
private var swipedirection: SwipeCardDirection = .none
private var carddeck = [SwipeCard]()
var topcard: SwipeCard? {
get {
return carddeck.first
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func setUpDeck() {
deckready = true
guard let delegate = delegate else { return }
numcards = delegate.numberOfCardsInDeck()
if numcards < 1 { return }
let card = delegate.cardAt(index: curindex)
cardrect = bounds.insetBy(dx: cardInsets, dy: cardInsets)
card.delegate = self
card.isontop = true
card.frame = cardrect
carddeck.append(card)
addSubview(card)
card.addIndicators(delegate.labelForNextIndicatorAt(index: nextIndexValue(.next)),
right: delegate.labelForNextIndicatorAt(index: nextIndexValue(.prev)))
}
private func nextIndexValue(_ direction: SwipeCardDirection) -> Int {
let next = curindex + direction.rawValue
var newIndex = next
if next > numcards - 1 {
newIndex = 0
return newIndex
}
if next < 0 {
newIndex = numcards - 1
return newIndex
}
return newIndex
}
fileprivate func nextIndex(_ direction: SwipeCardDirection) -> Int {
curindex = nextIndexValue(direction)
return curindex
}
override public func layoutSubviews() {
super.layoutSubviews()
if !deckready {
setUpDeck()
}
}
func setCurrentIndex(_ index: Int) {
curindex = index
guard let delegate = delegate else { return }
guard let top = topcard else { return }
top.updateIndicators(delegate.labelForNextIndicatorAt(index: nextIndexValue(.next)),
right: delegate.labelForNextIndicatorAt(index: nextIndexValue(.prev)))
}
public func updateSwipe(distance: CGFloat) {
let percentTraveled = distance / bounds.size.width
let percentFromOriginState = (40 * percentTraveled) / 100
let scale = 0.6 + percentFromOriginState
if carddeck.count > 1 {
let bottomcard = carddeck.last
bottomcard?.alpha = scale
bottomcard!.transform = CGAffineTransform.identity.scaledBy(x: scale , y: scale)
}
}
public func updateSwipe(direction: SwipeCardDirection) {
guard let delegate = self.delegate else { return }
if carddeck.count > 1 {
if let btmcard = carddeck.last {
btmcard.removeFromSuperview()
carddeck.removeLast()
}
}
self.swipedirection = direction
let nextcard = delegate.cardAt(index: nextIndexValue(direction))
nextcard.delegate = self
nextcard.frame = bounds.insetBy(dx: cardInsets, dy: cardInsets)
nextcard.transform = CGAffineTransform.identity.scaledBy(x: 0.6, y: 0.6)
carddeck.append(nextcard)
addSubview(nextcard)
sendSubview(toBack: nextcard)
}
public func swipeComplete() {
let topcard = carddeck.first
let bottomcard = carddeck.last
let xPos = (cardrect.size.width + 20) * CGFloat(swipedirection.rawValue)
UIView.animate(withDuration: 0.45, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.55, options: UIViewAnimationOptions.curveEaseOut, animations: {
topcard!.frame = CGRect(origin: CGPoint(x: xPos, y: self.cardrect.origin.y), size: self.cardrect.size)
bottomcard!.transform = CGAffineTransform.identity
bottomcard!.alpha = 1.0
}, completion: { _ in
self.curindex = self.nextIndexValue(self.swipedirection)
topcard!.removeFromSuperview()
self.carddeck.removeFirst()
bottomcard!.isontop = true
if let delegate = self.delegate {
bottomcard!.addIndicators(delegate.labelForNextIndicatorAt(index: self.nextIndexValue(.next)),
right: delegate.labelForNextIndicatorAt(index: self.nextIndexValue(.prev)))
}
})
}
func showNext() {
self.updateSwipe(direction: .next)
self.swipeComplete()
}
func showPrev() {
self.updateSwipe(direction: .prev)
self.swipeComplete()
}
}
| mit | 6d0356083e47cfeff523a6a21f8c1eb8 | 27.375 | 166 | 0.710874 | 3.526574 | false | false | false | false |
huangxinping/XPKit-swift | Source/Extensions/UIKit/UIFont+XPKit.swift | 1 | 36145 | //
// UIFont+XPKit.swift
// XPKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2016 Fabrizio Brancati. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
// MARK: - Public enums -
/**
All font names for all family available from iOS 7.0 to iOS 9.0
- AcademyEngravedLetPlain: Academy Engraved Let Plain
- AlNile: Al Nile
- AlNileBold: Al Nile Bold
- AmericanTypewriter: American Typewriter
- AmericanTypewriterBold: American Typewriter Bold
- AmericanTypewriterCondensed: American Typewriter Condensed
- AmericanTypewriterCondensedBold: American Typewriter Condensed Bold
- AmericanTypewriterCondensedLight: American Typewriter Condensed Light
- AmericanTypewriterLight: American Typewriter Light
- AppleColorEmoji: Apple Color Emoji
- AppleSDGothicNeoBold: Apple SD Gothic Neo Bold
- AppleSDGothicNeoLight: Apple SD Gothic Neo Light
- AppleSDGothicNeoMedium: Apple SD Gothic Neo Medium
- AppleSDGothicNeoRegular: Apple SD Gothic Neo Regular
- AppleSDGothicNeoSemiBold: Apple SD Gothic Neo Semi Bold
- AppleSDGothicNeoThin: Apple SD Gothic Neo Thin
- ArialBoldItalicMT: Arial Bold Italic MT
- ArialBoldMT: Arial Bold MT
- ArialHebrew: Arial Hebrew
- ArialHebrewBold: Arial Hebrew Bold
- ArialHebrewLight: Arial Hebrew Light
- ArialItalicMT: Arial Italic MT
- ArialMT: Arial MT
- ArialRoundedMTBold: Arial Rounded MT Bold
- ASTHeitiLight: AST Heiti Light
- ASTHeitiMedium: AST Heiti Medium
- AvenirBlack: Avenir Black
- AvenirBlackOblique: Avenir Black Oblique
- AvenirBook: Avenir Book
- AvenirBookOblique: Avenir Book Oblique
- AvenirHeavyOblique: Avenir Heavy Oblique
- AvenirHeavy: Avenir Heavy
- AvenirLight: Avenir Light
- AvenirLightOblique: Avenir Light Oblique
- AvenirMedium: Avenir Medium
- AvenirMediumOblique: Avenir Medium Oblique
- AvenirNextBold: Avenir Next Bold
- AvenirNextBoldItalic: Avenir Next Bold Italic
- AvenirNextCondensedBold: Avenir Next Condensed Bold
- AvenirNextCondensedBoldItalic: Avenir Next Condensed Bold Italic
- AvenirNextCondensedDemiBold: Avenir Next Condensed Demi Bold
- AvenirNextCondensedDemiBoldItalic: Avenir Next Condensed Demi Bold Italic
- AvenirNextCondensedHeavy: Avenir Next Condensed Heavy
- AvenirNextCondensedHeavyItalic: Avenir Next Condensed Heavy Italic
- AvenirNextCondensedItalic: Avenir Next Condensed Italic
- AvenirNextCondensedMedium: Avenir Next Condensed Medium
- AvenirNextCondensedMediumItalic: Avenir Next Condensed Medium Italic
- AvenirNextCondensedRegular: Avenir Next Condensed Regular
- AvenirNextCondensedUltraLight: Avenir Next Condensed Ultra Light
- AvenirNextCondensedUltraLightItalic: Avenir Next Condensed Ultra Light Italic
- AvenirNextDemiBold: Avenir Next Demi Bold
- AvenirNextDemiBoldItalic: Avenir Next Demi Bold Italic
- AvenirNextHeavy: Avenir Next Heavy
- AvenirNextItalic: Avenir Next Italic
- AvenirNextMedium: Avenir Next Medium
- AvenirNextMediumItalic: Avenir Next Medium Italic
- AvenirNextRegular: Avenir Next Regular
- AvenirNextUltraLight: Avenir Next Ultra Light
- AvenirNextUltraLightItalic: Avenir Next Ultra Light Italic
- AvenirOblique: Avenir Oblique
- AvenirRoman: Avenir Roman
- Baskerville: Baskerville
- BaskervilleBold: Baskerville Bold
- BaskervilleBoldItalic: Baskerville Bold Italic
- BaskervilleItalic: Baskerville Italic
- BaskervilleSemiBold: Baskerville Semi Bold
- BaskervilleSemiBoldItalic: Baskerville Semi Bold Italic
- BodoniOrnamentsITCTT: Bodoni Ornaments ITCTT
- BodoniSvtyTwoITCTTBold: Bodoni Svty Two ITCTT Bold
- BodoniSvtyTwoITCTTBook: Bodoni Svty Two ITCTT Book
- BodoniSvtyTwoITCTTBookIta: Bodoni Svty Two ITCTT Book Ita
- BodoniSvtyTwoOSITCTTBold: Bodoni Svty Two OS ITCTT Bold
- BodoniSvtyTwoOSITCTTBook: Bodoni Svty Two OS ITCTT Book
- BodoniSvtyTwoOSITCTTBookIt: Bodoni Svty Two OS ITCTT Book It
- BodoniSvtyTwoSCITCTTBook: Bodoni Svty Two SC ITCTT Book
- BradleyHandITCTTBold: Bradley Hand ITCTT Bold
- ChalkboardSEBold: Chalkboard SE Bold
- ChalkboardSELight: Chalkboard SE Light
- ChalkboardSERegular: Chalkboard SE Regular
- Chalkduster: Chalkduster
- Cochin: Cochin
- CochinBold: Cochin Bold
- CochinBoldItalic: Cochin Bold Italic
- CochinItalic: Cochin Italic
- Copperplate: Copperplate
- CopperplateBold: Copperplate Bold
- CopperplateLight: Copperplate Light
- Courier: Courier
- CourierBold: Courier Bold
- CourierBoldOblique: Courier Bold Oblique
- CourierNewPSBoldItalicMT: Courier New PS Bold Italic MT
- CourierNewPSBoldMT: Courier New PS Bold MT
- CourierNewPSItalicMT: Courier New PS Italic MT
- CourierNewPSMT: Courier New PS MT
- CourierOblique: Courier Oblique
- Damascus: Damascus
- DamascusBold: Damascus Bold
- DamascusMedium: Damascus Medium
- DamascusSemiBold: Damascus Semi Bold
- DevanagariSangamMN: Devanagari Sangam MN
- DevanagariSangamMNBold: Devanagari Sangam MN Bold
- Didot: Didot
- DidotBold: Didot Bold
- DidotItalic: Didot Italic
- DiwanMishafi: Diwan Mishafi
- EuphemiaUCAS: Euphemia UCAS
- EuphemiaUCASBold: Euphemia UCAS Bold
- EuphemiaUCASItalic: Euphemia UCAS Italic
- Farah: Farah
- FuturaCondensedExtraBold: Futura Condensed Extra Bold
- FuturaCondensedMedium: Futura Condensed Medium
- FuturaMedium: Futura Medium
- FuturaMediumItalicm: Futura Medium Italicm
- GeezaPro: Geeza Pro
- GeezaProBold: Geeza Pro Bold
- GeezaProLight: Geeza Pro Light
- Georgia: Georgia
- GeorgiaBold: Georgia Bold
- GeorgiaBoldItalic: Georgia Bold Italic
- GeorgiaItalic: Georgia Italic
- GillSans: Gill Sans
- GillSansBold: Gill Sans Bold
- GillSansBoldItalic: Gill Sans Bold Italic
- GillSansItalic: Gill Sans Italic
- GillSansLight: Gill Sans Light
- GillSansLightItalic: Gill Sans Light Italic
- GujaratiSangamMN: Gujarati Sangam MN
- GujaratiSangamMNBold: Gujarati Sangam MN Bold
- GurmukhiMN: Gurmukhi MN
- GurmukhiMNBold: Gurmukhi MN Bold
- Helvetica: Helvetica
- HelveticaBold: Helvetica Bold
- HelveticaBoldOblique: Helvetica Bold Oblique
- HelveticaLight: Helvetica Light
- HelveticaLightOblique: Helvetica Light Oblique
- HelveticaNeue: Helvetica Neue
- HelveticaNeueBold: Helvetica Neue Bold
- HelveticaNeueBoldItalic: Helvetica Neue Bold Italic
- HelveticaNeueCondensedBlack: Helvetica Neue Condensed Black
- HelveticaNeueCondensedBold: Helvetica Neue Condensed Bold
- HelveticaNeueItalic: Helvetica Neue Italic
- HelveticaNeueLight: Helvetica Neue Light
- HelveticaNeueMedium: Helvetica Neue Medium
- HelveticaNeueMediumItalic: Helvetica Neue Medium Italic
- HelveticaNeueThin: Helvetica Neue Thin
- HelveticaNeueThinItalic: Helvetica Neue Thin Italic
- HelveticaNeueUltraLight: Helvetica Neue Ultra Light
- HelveticaNeueUltraLightItalic: Helvetica Neue Ultra Light Italic
- HelveticaOblique: Helvetica Oblique
- HiraKakuProNW3: HiraKaku Pro NW 3
- HiraKakuProNW6: HiraKaku Pro NW 6
- HiraMinProNW3: Hira Min Pro NW 3
- HiraMinProNW6: Hira Min Pro NW 6
- HoeflerTextBlack: Hoefler Text Black
- HoeflerTextBlackItalic: Hoefler Text Black Italic
- HoeflerTextItalic: Hoefler Text Italic
- HoeflerTextRegular: Hoefler Text Regular
- Kailasa: Kailasa
- KailasaBold: Kailasa Bold
- KannadaSangamMN: Kannada Sangam MN
- KannadaSangamMNBold: Kannada Sangam MN Bold
- MalayalamSangamMN: Malayalam Sangam MN
- MalayalamSangamMNBold: Malayalam Sangam MN Bold
- MarkerFeltThin: Marker Felt Thin
- MarkerFeltWide: Marker Felt Wide
- MenloBold: Menlo Bold
- MenloBoldItalic: Menlo Bold Italic
- MenloItalic: Menlo Italic
- MenloRegular: Menlo Regular
- NoteworthyBold: Noteworthy Bold
- NoteworthyLight: Noteworthy Light
- OptimaBold: Optima Bold
- OptimaBoldItalic: Optima Bold Italic
- OptimaExtraBlack: Optima Extra Black
- OptimaItalic: Optima Italic
- OptimaRegular: Optima Regular
- OriyaSangamMN: Oriya Sangam MN
- OriyaSangamMNBold: Oriya Sangam MN Bold
- PalatinoBold: Palatino Bold
- PalatinoBoldItalic: Palatino Bold Italic
- PalatinoItalic: Palatino Italic
- PalatinoRoman: Palatino Roman
- Papyrus: Papyrus
- PapyrusCondensed: Papyrus Condensed
- PartyLetPlain: Party Let Plain
- SavoyeLetPlain: Savoye Let Plain
- SinhalaSangamMN: Sinhala Sangam MN
- SinhalaSangamMNBold: Sinhala Sangam MN Bold
- SnellRoundhand: Snell Roundhand
- SnellRoundhandBlack: Snell Roundhand Black
- SnellRoundhandBold: Snell Roundhand Bold
- STHeitiSCLight: ST Heiti SC Light
- STHeitiSCMedium: ST Heiti SC Medium
- STHeitiTCLight: ST Heiti TC Light
- STHeitiTCMedium: ST Heiti TC Medium
- Symbol: Symbol
- TamilSangamMN: Tamil Sangam MN
- TamilSangamMNBold: Tamil Sangam MN Bold
- TeluguSangamMN: Telugu Sangam MN
- TeluguSangamMNBold: Telugu Sangam MN Bold
- Thonburi: Thonburi
- ThonburiBold: Thonburi Bold
- ThonburiLight: Thonburi Light
- TimesNewRomanPSBoldItalicMT: Times New Roman PS Bold Italic MT
- TimesNewRomanPSBoldMT: Times New Roman PS Bold MT
- TimesNewRomanPSItalicMT: Times New Roman PS Italic MT
- TimesNewRomanPSMT: Times New Roman PS MT
- TrebuchetBoldItalic: Trebuchet Bold Italic
- TrebuchetMS: Trebuchet MS
- TrebuchetMSBold: Trebuchet MS Bold
- TrebuchetMSItalic: Trebuchet MS Italic
- Verdana: Verdana
- VerdanaBold: Verdana Bold
- VerdanaBoldItalic: Verdana Bold Italic
- VerdanaItalic: Verdana Italic
*/
public enum FontName: String {
case AcademyEngravedLetPlain = "AcademyEngravedLetPlain"
case AlNile = "AlNile"
case AlNileBold = "AlNile-Bold"
case AmericanTypewriter = "AmericanTypewriter"
case AmericanTypewriterBold = "AmericanTypewriter-Bold"
case AmericanTypewriterCondensed = "AmericanTypewriter-Condensed"
case AmericanTypewriterCondensedBold = "AmericanTypewriter-CondensedBold"
case AmericanTypewriterCondensedLight = "AmericanTypewriter-CondensedLight"
case AmericanTypewriterLight = "AmericanTypewriter-Light"
case AppleColorEmoji = "AppleColorEmoji"
case AppleSDGothicNeoBold = "AppleSDGothicNeo-Bold"
case AppleSDGothicNeoLight = "AppleSDGothicNeo-Light"
case AppleSDGothicNeoMedium = "AppleSDGothicNeo-Medium"
case AppleSDGothicNeoRegular = "AppleSDGothicNeo-Regular"
case AppleSDGothicNeoSemiBold = "AppleSDGothicNeo-SemiBold"
case AppleSDGothicNeoThin = "AppleSDGothicNeo-Thin"
case AppleSDGothicNeoUltraLight = "AppleSDGothicNeo-UltraLight" /*@available(*, introduced=9.0)*/
case ArialBoldItalicMT = "Arial-BoldItalicMT"
case ArialBoldMT = "Arial-BoldMT"
case ArialHebrew = "ArialHebrew"
case ArialHebrewBold = "ArialHebrew-Bold"
case ArialHebrewLight = "ArialHebrew-Light"
case ArialItalicMT = "Arial-ItalicMT"
case ArialMT = "ArialMT"
case ArialRoundedMTBold = "ArialRoundedMTBold"
case ASTHeitiLight = "ASTHeiti-Light"
case ASTHeitiMedium = "ASTHeiti-Medium"
case AvenirBlack = "Avenir-Black"
case AvenirBlackOblique = "Avenir-BlackOblique"
case AvenirBook = "Avenir-Book"
case AvenirBookOblique = "Avenir-BookOblique"
case AvenirHeavyOblique = "Avenir-HeavyOblique"
case AvenirHeavy = "Avenir-Heavy"
case AvenirLight = "Avenir-Light"
case AvenirLightOblique = "Avenir-LightOblique"
case AvenirMedium = "Avenir-Medium"
case AvenirMediumOblique = "Avenir-MediumOblique"
case AvenirNextBold = "AvenirNext-Bold"
case AvenirNextBoldItalic = "AvenirNext-BoldItalic"
case AvenirNextCondensedBold = "AvenirNextCondensed-Bold"
case AvenirNextCondensedBoldItalic = "AvenirNextCondensed-BoldItalic"
case AvenirNextCondensedDemiBold = "AvenirNextCondensed-DemiBold"
case AvenirNextCondensedDemiBoldItalic = "AvenirNextCondensed-DemiBoldItalic"
case AvenirNextCondensedHeavy = "AvenirNextCondensed-Heavy"
case AvenirNextCondensedHeavyItalic = "AvenirNextCondensed-HeavyItalic"
case AvenirNextCondensedItalic = "AvenirNextCondensed-Italic"
case AvenirNextCondensedMedium = "AvenirNextCondensed-Medium"
case AvenirNextCondensedMediumItalic = "AvenirNextCondensed-MediumItalic"
case AvenirNextCondensedRegular = "AvenirNextCondensed-Regular"
case AvenirNextCondensedUltraLight = "AvenirNextCondensed-UltraLight"
case AvenirNextCondensedUltraLightItalic = "AvenirNextCondensed-UltraLightItalic"
case AvenirNextDemiBold = "AvenirNext-DemiBold"
case AvenirNextDemiBoldItalic = "AvenirNext-DemiBoldItalic"
case AvenirNextHeavy = "AvenirNext-Heavy"
case AvenirNextItalic = "AvenirNext-Italic"
case AvenirNextMedium = "AvenirNext-Medium"
case AvenirNextMediumItalic = "AvenirNext-MediumItalic"
case AvenirNextRegular = "AvenirNext-Regular"
case AvenirNextUltraLight = "AvenirNext-UltraLight"
case AvenirNextUltraLightItalic = "AvenirNext-UltraLightItalic"
case AvenirOblique = "Avenir-Oblique"
case AvenirRoman = "Avenir-Roman"
case BanglaSangamMN = "BanglaSangamMN" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case BanglaSangamMNBold = "BanglaSangamMN-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case Baskerville = "Baskerville"
case BaskervilleBold = "Baskerville-Bold"
case BaskervilleBoldItalic = "Baskerville-BoldItalic"
case BaskervilleItalic = "Baskerville-Italic"
case BaskervilleSemiBold = "Baskerville-SemiBold"
case BaskervilleSemiBoldItalic = "Baskerville-SemiBoldItalic"
case BodoniOrnamentsITCTT = "BodoniOrnamentsITCTT"
case BodoniSvtyTwoITCTTBold = "BodoniSvtyTwoITCTT-Bold"
case BodoniSvtyTwoITCTTBook = "BodoniSvtyTwoITCTT-Book"
case BodoniSvtyTwoITCTTBookIta = "BodoniSvtyTwoITCTT-BookIta"
case BodoniSvtyTwoOSITCTTBold = "BodoniSvtyTwoOSITCTT-Bold"
case BodoniSvtyTwoOSITCTTBook = "BodoniSvtyTwoOSITCTT-Book"
case BodoniSvtyTwoOSITCTTBookIt = "BodoniSvtyTwoOSITCTT-BookIt"
case BodoniSvtyTwoSCITCTTBook = "BodoniSvtyTwoSCITCTT-Book"
case BradleyHandITCTTBold = "BradleyHandITCTT-Bold"
case ChalkboardSEBold = "ChalkboardSE-Bold"
case ChalkboardSELight = "ChalkboardSE-Light"
case ChalkboardSERegular = "ChalkboardSE-Regular"
case Chalkduster = "Chalkduster"
case Cochin = "Cochin"
case CochinBold = "Cochin-Bold"
case CochinBoldItalic = "Cochin-BoldItalic"
case CochinItalic = "Cochin-Italic"
case Copperplate = "Copperplate"
case CopperplateBold = "Copperplate-Bold"
case CopperplateLight = "Copperplate-Light"
case Courier = "Courier"
case CourierBold = "Courier-Bold"
case CourierBoldOblique = "Courier-BoldOblique"
case CourierNewPSBoldItalicMT = "CourierNewPS-BoldItalicMT"
case CourierNewPSBoldMT = "CourierNewPS-BoldMT"
case CourierNewPSItalicMT = "CourierNewPS-ItalicMT"
case CourierNewPSMT = "CourierNewPSMT"
case CourierOblique = "Courier-Oblique"
case Damascus = "Damascus"
case DamascusBold = "DamascusBold"
case DamascusMedium = "DamascusMedium"
case DamascusSemiBold = "DamascusSemiBold"
case DevanagariSangamMN = "DevanagariSangamMN"
case DevanagariSangamMNBold = "DevanagariSangamMN-Bold"
case Didot = "Didot"
case DidotBold = "Didot-Bold"
case DidotItalic = "Didot-Italic"
case DINAlternateBold = "DINAlternate-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case DINCondensedBold = "DINCondensed-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case DiwanMishafi = "DiwanMishafi"
case EuphemiaUCAS = "EuphemiaUCAS"
case EuphemiaUCASBold = "EuphemiaUCAS-Bold"
case EuphemiaUCASItalic = "EuphemiaUCAS-Italic"
case Farah = "Farah"
case FuturaCondensedExtraBold = "Futura-ExtraBold"
case FuturaCondensedMedium = "Futura-CondensedMedium"
case FuturaMedium = "Futura-Medium"
case FuturaMediumItalicm = "Futura-MediumItalic"
case GeezaPro = "GeezaPro"
case GeezaProBold = "GeezaPro-Bold"
case GeezaProLight = "GeezaPro-Light"
case Georgia = "Georgia"
case GeorgiaBold = "Georgia-Bold"
case GeorgiaBoldItalic = "Georgia-BoldItalic"
case GeorgiaItalic = "Georgia-Italic"
case GillSans = "GillSans"
case GillSansBold = "GillSans-Bold"
case GillSansBoldItalic = "GillSans-BoldItalic"
case GillSansItalic = "GillSans-Italic"
case GillSansLight = "GillSans-Light"
case GillSansLightItalic = "GillSans-LightItalic"
case GujaratiSangamMN = "GujaratiSangamMN"
case GujaratiSangamMNBold = "GujaratiSangamMN-Bold"
case GurmukhiMN = "GurmukhiMN"
case GurmukhiMNBold = "GurmukhiMN-Bold"
case Helvetica = "Helvetica"
case HelveticaBold = "Helvetica-Bold"
case HelveticaBoldOblique = "Helvetica-BoldOblique"
case HelveticaLight = "Helvetica-Light"
case HelveticaLightOblique = "Helvetica-LightOblique"
case HelveticaNeue = "HelveticaNeue"
case HelveticaNeueBold = "HelveticaNeue-Bold"
case HelveticaNeueBoldItalic = "HelveticaNeue-BoldItalic"
case HelveticaNeueCondensedBlack = "HelveticaNeue-CondensedBlack"
case HelveticaNeueCondensedBold = "HelveticaNeue-CondensedBold"
case HelveticaNeueItalic = "HelveticaNeue-Italic"
case HelveticaNeueLight = "HelveticaNeue-Light"
case HelveticaNeueMedium = "HelveticaNeue-Medium"
case HelveticaNeueMediumItalic = "HelveticaNeue-MediumItalic"
case HelveticaNeueThin = "HelveticaNeue-Thin"
case HelveticaNeueThinItalic = "HelveticaNeue-ThinItalic"
case HelveticaNeueUltraLight = "HelveticaNeue-UltraLight"
case HelveticaNeueUltraLightItalic = "HelveticaNeue-UltraLightItalic"
case HelveticaOblique = "Helvetica-Oblique"
case HiraKakuProNW3 = "HiraKakuProN-W3"
case HiraKakuProNW6 = "HiraKakuProN-W6"
case HiraMinProNW3 = "HiraMinProN-W3"
case HiraMinProNW6 = "HiraMinProN-W6"
case HoeflerTextBlack = "HoeflerText-Black"
case HoeflerTextBlackItalic = "HoeflerText-BlackItalic"
case HoeflerTextItalic = "HoeflerText-Italic"
case HoeflerTextRegular = "HoeflerText-Regular"
case IowanOldStyleBold = "IowanOldStyle-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case IowanOldStyleBoldItalic = "IowanOldStyle-BoldItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case IowanOldStyleItalic = "IowanOldStyle-Italic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case IowanOldStyleRoman = "IowanOldStyle-Roman" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case Kailasa = "Kailasa"
case KailasaBold = "Kailasa-Bold"
case KannadaSangamMN = "KannadaSangamMN"
case KannadaSangamMNBold = "KannadaSangamMN-Bold"
case KhmerSangamMN = "KhmerSangamMN" /*@available(*, introduced=8.0)*/
case KohinoorBanglaLight = "KohinoorBangla-Light" /*@available(*, introduced=9.0)*/
case KohinoorBanglaMedium = "KohinoorBangla-Medium" /*@available(*, introduced=9.0)*/
case KohinoorBanglaRegular = "KohinoorBangla-Regular" /*@available(*, introduced=9.0)*/
case KohinoorDevanagariLight = "KohinoorDevanagari-Light" /*@available(*, introduced=8.0)*/
case KohinoorDevanagariMedium = "KohinoorDevanagari-Medium" /*@available(*, introduced=8.0)*/
case KohinoorDevanagariBook = "KohinoorDevanagari-Book" /*@available(*, introduced=8.0)*/
case LaoSangamMN = "LaoSangamMN" /*@available(*, introduced=8.0)*/
case MalayalamSangamMN = "MalayalamSangamMN"
case MalayalamSangamMNBold = "MalayalamSangamMN-Bold"
case MarionBold = "Marion-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case MarionItalic = "Marion-Italic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case MarionRegular = "Marion-Regular" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case MarkerFeltThin = "MarkerFelt-Thin"
case MarkerFeltWide = "MarkerFelt-Wide"
case MenloBold = "Menlo-Bold"
case MenloBoldItalic = "Menlo-BoldItalic"
case MenloItalic = "Menlo-Italic"
case MenloRegular = "Menlo-Regular"
case NoteworthyBold = "Noteworthy-Bold"
case NoteworthyLight = "Noteworthy-Light"
case OptimaBold = "Optima-Bold"
case OptimaBoldItalic = "Optima-BoldItalic"
case OptimaExtraBlack = "Optima-ExtraBold"
case OptimaItalic = "Optima-Italic"
case OptimaRegular = "Optima-Regular"
case OriyaSangamMN = "OriyaSangamMN"
case OriyaSangamMNBold = "OriyaSangamMN-Bold"
case PalatinoBold = "Palatino-Bold"
case PalatinoBoldItalic = "Palatino-BoldItalic"
case PalatinoItalic = "Palatino-Italic"
case PalatinoRoman = "Palatino-Roman"
case Papyrus = "Papyrus"
case PapyrusCondensed = "Papyrus-Condensed"
case PartyLetPlain = "PartyLetPlain"
case SavoyeLetPlain = "SavoyeLetPlain"
case SinhalaSangamMN = "SinhalaSangamMN"
case SinhalaSangamMNBold = "SinhalaSangamMN-Bold"
case SnellRoundhand = "SnellRoundhand"
case SnellRoundhandBlack = "SnellRoundhand-Black"
case SnellRoundhandBold = "SnellRoundhand-Bold"
case STHeitiSCLight = "STHeitiSC-Light"
case STHeitiSCMedium = "STHeitiSC-Medium"
case STHeitiTCLight = "STHeitiTC-Light"
case STHeitiTCMedium = "STHeitiTC-Medium"
case SuperclarendonBlack = "Superclarendon-Black" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case SuperclarendonBlackItalic = "Superclarendon-BalckItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case SuperclarendonBold = "Superclarendon-Bold" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case SuperclarendonBoldItalic = "Superclarendon-BoldItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case SuperclarendonItalic = "Superclarendon-Italic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case SuperclarendonLight = "Superclarendon-Light" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case SuperclarendonLightItalic = "Superclarendon-LightItalic" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case SuperclarendonRegular = "Superclarendon-Regular" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case Symbol = "Symbol"
case TamilSangamMN = "TamilSangamMN"
case TamilSangamMNBold = "TamilSangamMN-Bold"
case TeluguSangamMN = "TeluguSangamMN"
case TeluguSangamMNBold = "TeluguSangamMN-Bold"
case Thonburi = "Thonburi"
case ThonburiBold = "Thonburi-Bold"
case ThonburiLight = "Thonburi-Light"
case TimesNewRomanPSBoldItalicMT = "TimesNewRomanPS-BoldItalic"
case TimesNewRomanPSBoldMT = "TimesNewRomanPS-Bold"
case TimesNewRomanPSItalicMT = "TimesNewRomanPS-ItalicMT"
case TimesNewRomanPSMT = "TimesNewRomanPSMT"
case TrebuchetBoldItalic = "Trebuchet-BoldItalic"
case TrebuchetMS = "TrebuchetMS"
case TrebuchetMSBold = "TrebuchetMS-Bold"
case TrebuchetMSItalic = "TrebuchetMS-Italic"
case Verdana = "Verdana"
case VerdanaBold = "Verdana-Bold"
case VerdanaBoldItalic = "Verdana-BoldItalic"
case VerdanaItalic = "Verdana-Italic"
}
/// This extesion adds some useful functions to UIFont
public extension UIFont {
// MARK: - Class variables -
/// Static light font to use in App
public static var lightFont: UIFont {
get {
return UIFont.lightFont
}
set(newValue) {
UIFont.lightFont = newValue
}
}
/// Static regular font to use in App
public static var regularFont: UIFont {
get {
return UIFont.regularFont
}
set(newValue) {
UIFont.regularFont = newValue
}
}
/// Static bold font to use in App
public static var boldFont: UIFont {
get {
return UIFont.boldFont
}
set(newValue) {
UIFont.boldFont = newValue
}
}
// MARK: - Enums -
/**
All font family names available from iOS 7.0 to iOS 9.0
- AcademyEngravedLET: Academy Engraved LET
- AlNile: Al Nile
- AmericanTypewriter: American Typewriter
- AppleColorEmoji: Apple Color Emoji
- AppleSDGothicNeo: Apple SD Gothic Neo
- Arial: Arial
- ArialHebrew: Arial Hebrew
- ArialRoundedMTBold: Arial Rounded MT Bold
- Avenir: Avenir
- AvenirNext: Avenir Next
- AvenirNextCondensed: Avenir Next Condensed
- Baskerville: Baskerville
- Bodoni72: Bodoni 72
- Bodoni72Oldstyle: Bodoni 72 Oldstyle
- Bodoni72Smallcaps: Bodoni 72 Smallcaps
- BodoniOrnaments: Bodoni Ornaments
- BradleyHand: Bradley Hand
- ChalkboardSE: Chalkboard SE
- Chalkduster: Chalkduster
- Cochin: Cochin
- Copperplate: Copperplate
- Courier: Courier
- CourierNew: Courier New
- Damascus: Damascus
- DevanagariSangamMN: Devanagari Sangam MN
- Didot: Didot
- EuphemiaUCAS: Euphemia UCAS
- Farah: Farah
- Futura: Futura
- GeezaPro: Geeza Pro
- Georgia: Georgia
- GillSans: Gill Sans
- GujaratiSangamMN: Gujarati Sangam MN
- GurmukhiMN: Gurmukhi MN
- HeitiSC: Heiti SC
- HeitiTC: Heiti TC
- Helvetica: Helvetica
- HelveticaNeue: Helvetica Neue
- HiraginoKakuGothicProN: Hiragino Kaku Gothic Pro N
- HiraginoMinchoProN: Hiragino Mincho Pro N
- HoeflerText: Hoefler Text
- Kailasa: Kailasa
- KannadaSangamMN: Kannada Sangam MN
- MalayalamSangamMN: Malayalam Sangam MN
- MarkerFelt: Marker Felt
- Menlo: Menlo
- Mishafi: Mishafi
- Noteworthy: Noteworthy
- Optima: Optima
- OriyaSangamMN: Oriya Sangam MN
- Palatino: Palatino
- Papyrus: Papyrus
- PartyLET: Party LET
- SavoyeLET: Savoye LET
- SinhalaSangamMN: Sinhala Sangam MN
- SnellRoundhand: Snell Roundhand
- Symbol: Symbol
- TamilSangamMN: Tamil Sangam MN
- TeluguSangamMN: Telugu Sangam MN
- Thonburi: Thonburi
- TimesNewRoman: Times New Roman
- TrebuchetMS: Trebuchet MS
- Verdana: Verdana
- ZapfDingbats: Zapf Dingbats
- Zapfino: Zapfino
*/
public enum FamilyFontName: String {
case AcademyEngravedLET = "Academy Engraved LET"
case AlNile = "Al Nile"
case AmericanTypewriter = "American Typewriter"
case AppleColorEmoji = "Apple Color Emoji"
case AppleSDGothicNeo = "Apple SD Gothic Neo"
case Arial = "Arial"
case ArialHebrew = "Arial Hebrew"
case ArialRoundedMTBold = "Arial Rounded MT Bold"
case Avenir = "Avenir"
case AvenirNext = "Avenir Next"
case AvenirNextCondensed = "Avenir Next Condensed"
case BanglaSangamMN = "Bangla Sangam MN" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case Baskerville = "Baskerville"
case Bodoni72 = "Bodoni 72"
case Bodoni72Oldstyle = "Bodoni 72 Oldstyle"
case Bodoni72Smallcaps = "Bodoni 72 Smallcaps"
case BodoniOrnaments = "Bodoni Ornaments"
case BradleyHand = "Bradley Hand"
case ChalkboardSE = "Chalkboard SE"
case Chalkduster = "Chalkduster"
case Cochin = "Cochin"
case Copperplate = "Copperplate"
case Courier = "Courier"
case CourierNew = "Courier New"
case Damascus = "Damascus"
case DevanagariSangamMN = "Devanagari Sangam MN"
case Didot = "Didot"
case DINAlternate = "DIN Alternate" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case DINCondensed = "DIN Condensed" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case EuphemiaUCAS = "Euphemia UCAS"
case Farah = "Farah"
case Futura = "Futura"
case GeezaPro = "Geeza Pro"
case Georgia = "Georgia"
case GillSans = "Gill Sans"
case GujaratiSangamMN = "Gujarati Sangam MN"
case GurmukhiMN = "Gurmukhi MN"
case HeitiSC = "Heiti SC"
case HeitiTC = "Heiti TC"
case Helvetica = "Helvetica"
case HelveticaNeue = "Helvetica Neue"
case HiraginoKakuGothicProN = "Hiragino Kaku Gothic ProN"
case HiraginoMinchoProN = "Hiragino Mincho ProN"
case HoeflerText = "Hoefler Text"
case IowanOldStyle = "Iowan Old Style" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case Kailasa = "Kailasa"
case KannadaSangamMN = "Kannada Sangam MN"
case KhmerSangamMN = "Khmer Sangam MN" /*@available(*, introduced=8.0)*/
case KohinoorBangla = "Kohinoor Bangla" /*@available(*, introduced=8.0)*/
case KohinoorDevanagari = "Kohinoor Devanagari" /*@available(*, introduced=8.0)*/
case LaoSangamMN = "Lao Sangam MN" /*@available(*, introduced=8.0)*/
case MalayalamSangamMN = "Malayalam Sangam MN"
case Marion = "Marion" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case MarkerFelt = "Marker Felt"
case Menlo = "Menlo"
case Mishafi = "Mishafi"
case Noteworthy = "Noteworthy"
case Optima = "Optima"
case OriyaSangamMN = "Oriya Sangam MN"
case Palatino = "Palatino"
case Papyrus = "Papyrus"
case PartyLET = "Party LET"
case SavoyeLET = "Savoye LET"
case SinhalaSangamMN = "Sinhala Sangam MN"
case SnellRoundhand = "Snell Roundhand"
case Superclarendon = "Superclarendon" /*@available(*, introduced=7.0, deprecated=8.0, message="This font is not available after iOS 8")*/
case Symbol = "Symbol"
case TamilSangamMN = "Tamil Sangam MN"
case TeluguSangamMN = "Telugu Sangam MN"
case Thonburi = "Thonburi"
case TimesNewRoman = "Times New Roman"
case TrebuchetMS = "Trebuchet MS"
case Verdana = "Verdana"
case ZapfDingbats = "Zapf Dingbats"
case Zapfino = "Zapfino"
}
// MARK: - Init functions -
/**
Create an UIFont object from the given font name and size
- parameter fontName: Font name
- parameter size: Size of the font
- returns: Returns an UIFont from the given font name and size
*/
public convenience init?(fontName: FontName, size: CGFloat) {
self.init(name: fontName.rawValue, size: size)
}
// MARK: - Class functions -
/**
Print in console all family and font names
- returns: Returns all the font family names
*/
public static func allFamilyAndFonts() -> Dictionary<String, Array<AnyObject>> {
var fontFamilies: NSMutableArray = NSMutableArray(array: UIFont.familyNames() as NSArray)
fontFamilies = NSMutableArray.sortArrayByKey("", array: fontFamilies, ascending: true)
var fontFamilyDic: Dictionary<String, Array<AnyObject>> = Dictionary()
for i in 0 ..< fontFamilies.count {
let fontFamily: String = fontFamilies.objectAtIndex(i) as! String
let fontNames: Array = UIFont.fontNamesForFamilyName(fontFamily)
fontFamilyDic[fontFamily] = fontNames
}
return fontFamilyDic
}
/**
Print in console all font names for a given family
- parameter familyFontName: Family to print the fonts
- returns: Returns all the fonts for the given family
*/
public static func fontsNameForFamilyName(familyFontName: FamilyFontName) -> Array<AnyObject> {
let fontNames: Array = UIFont.fontNamesForFamilyName(familyFontName.rawValue)
return fontNames
}
}
| mit | 9763dd73136b6ce77d93d4b8e70ee6bd | 48.786501 | 162 | 0.675889 | 4.30144 | false | false | false | false |
seandavidmcgee/HumanKontactBeta | src/keyboardTest/GoogleWearAlertView.swift | 1 | 7956 | //
// GoogleWearAlertView.swift
// GoogleWearAlertView
//
// Created by Ashley Robinson on 27/06/2014.
// Copyright (c) 2014 Ashley Robinson. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
class func successGreen() -> UIColor {
return UIColor(red: 251.0/255.0, green: 22.0/255.0, blue: 80.0/255.0, alpha: 1)
}
class func errorRed() -> UIColor {
return UIColor(red: 255.0/255.0, green: 82.0/255.0, blue: 82.0/255.0, alpha: 1)
}
class func warningYellow() -> UIColor {
return UIColor(red: 255.0/255.0, green: 205.0/255.0, blue: 64.0/255.0, alpha: 1)
}
class func messageBlue() -> UIColor {
return UIColor(red: 2.0/255.0, green: 169.0/255.0, blue: 244.0/255.0, alpha: 1)
}
}
class GoogleWearAlertView: UIView, UIGestureRecognizerDelegate {
//Constants
let alertViewSize:CGFloat = 0.4 // 40% of presenting viewcontrollers width
let imageViewSize:CGFloat = 0.4 //4 0% of AlertViews width
let imageViewOffsetFromCentre:CGFloat = 0.25 // Offset of image along Y axis
let titleLabelWidth:CGFloat = 0.7 // 70% of AlertViews width
let titleLabelHeight:CGFloat = 30
let navControllerHeight:CGFloat = 44
/** The displayed title of this message */
var title:NSString?
/** The view controller this message is displayed in, only used to size the alert*/
var viewController:UIViewController!
/** The duration of the displayed message. If it is 0.0, it will automatically be calculated */
var duration:Double?
/** The position of the message (top or bottom) */
var alertPosition:GoogleWearAlertPosition?
/** Is the message currenlty fully displayed? Is set as soon as the message is really fully visible */
var messageIsFullyDisplayed:Bool?
/** If you'd like to customise the image shown with the alert */
var iconImage:UIImage?
/** Internal properties needed to resize the view on device rotation properly */
lazy var titleLabel: UILabel = UILabel()
lazy var iconImageView: UIImageView = UIImageView()
/** Inits the notification view. Do not call this from outside this library.
@param title The text of the notification view
@param image A custom icon image (optional)
@param notificationType The type (color) of the notification view
@param duration The duration this notification should be displayed (optional)
@param viewController the view controller this message should be displayed in
@param position The position of the message on the screen
@param dismissingEnabled Should this message be dismissed when the user taps it?
*/
init(title:String, image:UIImage?, type:GoogleWearAlertType, duration:Double, viewController:UIViewController, position:GoogleWearAlertPosition, canbeDismissedByUser:Bool) {
super.init(frame: CGRectZero)
self.title = title
self.iconImage = image
self.duration = duration
self.viewController = viewController
self.alertPosition = position
// Setup background color and choose icon
let imageProvided = image != nil
switch type {
case .Error:
backgroundColor = UIColor.errorRed()
if !imageProvided { self.iconImage = UIImage(named: "errorIcon") }
case .Message:
backgroundColor = UIColor.messageBlue()
if !imageProvided { self.iconImage = UIImage(named: "messageIcon") }
case .Success:
backgroundColor = UIColor.successGreen()
if !imageProvided { self.iconImage = UIImage(named: "successIcon") }
case .Warning:
backgroundColor = UIColor.warningYellow()
if !imageProvided { self.iconImage = UIImage(named: "warningIcon") }
case .Remove:
backgroundColor = UIColor.messageBlue()
if !imageProvided { self.iconImage = UIImage(named: "errorIcon") }
default:
NSLog("Unknown message type provided")
}
// Setup self
self.translatesAutoresizingMaskIntoConstraints = false
frame.size = CGSizeMake(viewController.view.bounds.size.width * alertViewSize, viewController.view.bounds.width * alertViewSize)
layer.cornerRadius = self.frame.width/2
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOffset = CGSizeMake(0, 0)
self.layer.shadowOpacity = 0.8
self.clipsToBounds = false
// Setup Image View
iconImageView.image = iconImage
iconImageView.frame = CGRectMake(0, 0, frame.size.width * imageViewSize, frame.size.width * imageViewSize)
iconImageView.center = center
iconImageView.center.y -= iconImageView.frame.size.height * imageViewOffsetFromCentre
self.addSubview(iconImageView)
// Setup Text Label
titleLabel.frame = CGRectMake(self.center.x - (frame.size.width * titleLabelWidth) / 2, iconImageView.frame.origin.y + iconImageView.frame.size.height - 5, frame.size.width * titleLabelWidth, titleLabelHeight)
titleLabel.textColor = UIColor.whiteColor()
titleLabel.lineBreakMode = NSLineBreakMode.ByTruncatingTail
titleLabel.numberOfLines = 2
titleLabel.text = title
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.font = UIFont.systemFontOfSize(18)
self.addSubview(titleLabel)
//Position the alert
positionAlertForPosition(position)
if canbeDismissedByUser {
let tagGestureRecognizer = UITapGestureRecognizer(target:self, action: Selector("dismissAlert"))
self.addGestureRecognizer(tagGestureRecognizer)
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
NSException(name: "init from storyboard error", reason: "alert cannot be initalized from a storybaord", userInfo: nil).raise()
}
func dismissAlert() {
GoogleWearAlert.sharedInstance.removeCurrentAlert(self)
}
func insideNavController() -> Bool {
if let vc = viewController {
if vc.parentViewController is UINavigationController {
return true
} else if vc is UINavigationController {
return true
}
}
return false
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection!) {
layoutSubviews()
}
override func layoutSubviews() {
super.layoutSubviews()
if let position = alertPosition {
positionAlertForPosition(position)
}
}
func positionAlertForPosition(position:GoogleWearAlertPosition) {
if UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) {
let centerX = viewController.view.bounds.width/2
let centerY = viewController.view.bounds.height/2
center = CGPointMake(centerX, centerY)
} else {
switch position {
case .Top:
center = CGPointMake(viewController.view.center.x, viewController.view.frame.size.height / 4)
if insideNavController() { center.y += navControllerHeight }
case .Center:
center = viewController.view.center
case .Bottom:
center = CGPointMake(viewController.view.center.x, viewController.view.frame.size.height * 0.75)
default:
NSLog("Unknown position type provided")
}
}
}
} | mit | c9ead3240e12ab7a1ff739a3a929d647 | 38.391089 | 217 | 0.633861 | 5.061069 | false | false | false | false |
DaskiOFF/RKAL | Source/RKAL.swift | 1 | 29193 | //
// The MIT License (MIT)
//
// Copyright (c) 2017 Roman Kotov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import ObjectiveC
typealias RKConstraint = NSLayoutConstraint
typealias RKConstraints = [RKConstraint]
// MARK: -
extension Array where Element: RKConstraint {
func activate() {
NSLayoutConstraint.activate(self)
}
func deactivate() {
NSLayoutConstraint.deactivate(self)
}
mutating func removeAllConstraints() {
for c in self {
c.removeFromView()
}
self.removeAll()
}
}
extension NSLayoutConstraint {
func removeFromView() {
if let view = firstItem as? UIView {
view.removeConstraint(self)
view.superview?.removeConstraint(self)
}
if let view = secondItem as? UIView {
view.removeConstraint(self)
view.superview?.removeConstraint(self)
}
}
}
enum RKConstraintPriority {
case high
case low
case required
case custom(UILayoutPriority)
var value: UILayoutPriority {
switch self {
case .high: return UILayoutPriorityDefaultHigh
case .low: return UILayoutPriorityDefaultLow
case .required: return UILayoutPriorityRequired
case .custom(let v): return v
}
}
}
fileprivate extension RKConstraint {
func set(priority: RKConstraintPriority) -> Self {
self.priority = priority.value
return self
}
func set(active: Bool) -> Self {
isActive = active
return self
}
}
// MARK: - Storage
fileprivate class RKConstraintsStorage {
var sizeWidthConstraints: RKConstraints = []
var sizeHeightConstraints: RKConstraints = []
var centerXConstraints: RKConstraints = []
var centerYConstraints: RKConstraints = []
var edgeTopConstraints: RKConstraints = []
var edgeLeftConstraints: RKConstraints = []
var edgeBottomConstraints: RKConstraints = []
var edgeRightConstraints: RKConstraints = []
var edgeLeadingConstraints: RKConstraints = []
var edgeTrailingConstraints: RKConstraints = []
}
private var ___constraintsStorage: UInt = 0
fileprivate extension UIView {
private var __constraintsStorage: RKConstraintsStorage? {
get {
return objc_getAssociatedObject(self, &___constraintsStorage) as? RKConstraintsStorage
}
set {
if let newValue = newValue {
objc_setAssociatedObject(self, &___constraintsStorage, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
var constraintsStorage: RKConstraintsStorage? {
get {
if let storage = __constraintsStorage {
return storage
}
__constraintsStorage = RKConstraintsStorage()
return __constraintsStorage!
}
}
}
// MARK: Remove
extension UIView {
// Center
func rk_alRemoveCenterXConstraints() {
guard let storage = constraintsStorage else { return }
storage.centerXConstraints.removeAllConstraints()
}
func rk_alRemoveCenterYConstraints() {
guard let storage = constraintsStorage else { return }
storage.centerYConstraints.removeAllConstraints()
}
// Size
func rk_alRemoveSizeConstraints() {
rk_alRemoveSizeWidthConstraints()
rk_alRemoveSizeHeightConstraints()
}
func rk_alRemoveSizeHeightConstraints() {
guard let storage = constraintsStorage else { return }
storage.sizeHeightConstraints.removeAllConstraints()
}
func rk_alRemoveSizeWidthConstraints() {
guard let storage = constraintsStorage else { return }
storage.sizeWidthConstraints.removeAllConstraints()
}
// EDGE
func rk_alRemoveTopConstraints() {
guard let storage = constraintsStorage else { return }
storage.edgeTopConstraints.removeAllConstraints()
}
func rk_alRemoveLeftConstraints() {
guard let storage = constraintsStorage else { return }
storage.edgeLeftConstraints.removeAllConstraints()
}
func rk_alRemoveBottomConstraints() {
guard let storage = constraintsStorage else { return }
storage.edgeBottomConstraints.removeAllConstraints()
}
func rk_alRemoveRightConstraints() {
guard let storage = constraintsStorage else { return }
storage.edgeRightConstraints.removeAllConstraints()
}
func rk_alRemoveLeadingConstraints() {
guard let storage = constraintsStorage else { return }
storage.edgeLeadingConstraints.removeAllConstraints()
}
func rk_alRemoveTrailingConstraints() {
guard let storage = constraintsStorage else { return }
storage.edgeTrailingConstraints.removeAllConstraints()
}
}
// MARK: - Center
enum RKConstraintCenter: Hashable, Equatable {
case __x(CGFloat, RKConstraintPriority, Bool)
case __xAnchor(NSLayoutXAxisAnchor, CGFloat, RKConstraintPriority, Bool)
case __y(CGFloat, RKConstraintPriority, Bool)
case __yAnchor(NSLayoutYAxisAnchor, CGFloat, RKConstraintPriority, Bool)
var hashValue: Int {
switch self {
case .__x(_, _, _), .__xAnchor(_, _, _, _): return 1
case .__y(_, _, _), .__yAnchor(_, _, _, _): return 2
}
}
static func == (lhs: RKConstraintCenter, rhs: RKConstraintCenter) -> Bool {
return lhs.hashValue == rhs.hashValue
}
// Center X
static func centerX(_ offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintCenter {
return .__x(offset, priority, isActive)
}
static func centerX(_ view: UIView, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintCenter {
return .__xAnchor(view.centerXAnchor, offset, priority, isActive)
}
static func centerX(_ anchor: NSLayoutXAxisAnchor, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintCenter {
return .__xAnchor(anchor, offset, priority, isActive)
}
// Center Y
static func centerY(_ offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintCenter {
return .__y(offset, priority, isActive)
}
static func centerY(_ view: UIView, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintCenter {
return .__yAnchor(view.centerYAnchor, offset, priority, isActive)
}
static func centerY(_ anchor: NSLayoutYAxisAnchor, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintCenter {
return .__yAnchor(anchor, offset, priority, isActive)
}
}
extension UIView {
/// Constraints for size
///
/// Example:
/// ```
/// view.rk_alCenter(values: [.centerX(100), .centerY(300)])
/// ```
/// or
/// ```
/// view.rk_alCenter(values: [.centerX(), .centerY(anotherView.topAnchor)])
///
/// ```
/// or
/// ```
/// view.rk_alCenter(values: RKConstraintCenter.center(anotherView, offsetX: -100, offsetY: -100))
/// ```
/// etc.
///
/// - Parameter values: RKConstraintSize...
/// - Returns: Array of constraints
@discardableResult
func rk_alCenter(_ values: RKConstraintCenter..., isActive: Bool = true) -> RKConstraints {
return self.rk_alCenter(with: values, isActive: isActive)
}
@discardableResult
fileprivate func rk_alCenter(with values: [RKConstraintCenter], isActive: Bool = true) -> RKConstraints {
let values = Set<RKConstraintCenter>(values)
guard !values.isEmpty else { return [] }
translatesAutoresizingMaskIntoConstraints = false
guard let storage = constraintsStorage else {
assertionFailure("rk_alCenter: constraintsStorage should not be nil!")
return []
}
guard let superview = superview else {
assertionFailure("rk_alCenter: superview should not be nil!")
return []
}
var constraints: RKConstraints = []
var constraint: NSLayoutConstraint!
var isCenterXConstraint: Bool = false
for value in values {
switch value {
// constant
case .__x(let offset, let priority, let active):
constraint = centerXAnchor.constraint(equalTo: superview.centerXAnchor, constant: offset).set(priority: priority).set(active: active && isActive)
isCenterXConstraint = true
case .__y(let offset, let priority, let active):
constraint = centerYAnchor.constraint(equalTo: superview.centerYAnchor, constant: offset).set(priority: priority).set(active: active && isActive)
// anchor
case .__xAnchor(let anchor, let offset, let priority, let active):
constraint = centerXAnchor.constraint(equalTo: anchor, constant: offset).set(priority: priority).set(active: active && isActive)
isCenterXConstraint = true
case .__yAnchor(let anchor, let offset, let priority, let active):
constraint = centerYAnchor.constraint(equalTo: anchor, constant: offset).set(priority: priority).set(active: active && isActive)
}
constraints.append(constraint)
if isCenterXConstraint {
storage.centerXConstraints.append(constraint)
} else {
storage.centerYConstraints.append(constraint)
}
}
return constraints
}
@discardableResult
func rk_alCenter(isActive: Bool = true) -> RKConstraints {
return self.rk_alCenter(.centerX(), .centerY(), isActive: isActive)
}
}
// MARK: - Size
enum RKConstraintSize: Hashable, Equatable {
case __widthPriorityActive(CGFloat, RKConstraintPriority, Bool)
case __widthDimensionPriorityActive(NSLayoutDimension, CGFloat, RKConstraintPriority, Bool)
case __widthMinPriorityActive(CGFloat, RKConstraintPriority, Bool)
case __widthMaxPriorityActive(CGFloat, RKConstraintPriority, Bool)
case __heightPriorityActive(CGFloat, RKConstraintPriority, Bool)
case __heightDimensionPriorityActive(NSLayoutDimension, CGFloat, RKConstraintPriority, Bool)
case __heightMinPriorityActive(CGFloat, RKConstraintPriority, Bool)
case __heightMaxPriorityActive(CGFloat, RKConstraintPriority, Bool)
var hashValue: Int {
switch self {
case .__widthPriorityActive(_, _, _), .__widthDimensionPriorityActive(_, _, _, _): return 1
case .__widthMinPriorityActive(_, _, _): return 2
case .__widthMaxPriorityActive(_, _, _): return 3
case .__heightPriorityActive(_, _, _), .__heightDimensionPriorityActive(_, _, _, _): return 4
case .__heightMinPriorityActive(_, _, _): return 5
case .__heightMaxPriorityActive(_, _, _): return 6
}
}
static func == (lhs: RKConstraintSize, rhs: RKConstraintSize) -> Bool {
return lhs.hashValue == rhs.hashValue
}
// MARK: Width
static func width(_ constant: CGFloat, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintSize {
return .__widthPriorityActive(constant, priority, isActive)
}
static func width(_ dimension: NSLayoutDimension, multiplier: CGFloat = 1.0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintSize {
return .__widthDimensionPriorityActive(dimension, multiplier, priority, isActive)
}
static func width(_ view: UIView, multiplier: CGFloat = 1.0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintSize {
return .width(view.widthAnchor, multiplier: multiplier, priority: priority, isActive: isActive)
}
static func width(min: CGFloat, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintSize {
return .__widthMinPriorityActive(min, priority, isActive)
}
static func width(max: CGFloat, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintSize {
return .__widthMaxPriorityActive(max, priority, isActive)
}
// MARK: Height
static func height(_ constant: CGFloat, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintSize {
return .__heightPriorityActive(constant, priority, isActive)
}
static func height(_ dimension: NSLayoutDimension, multiplier: CGFloat = 1.0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintSize {
return .__heightDimensionPriorityActive(dimension, multiplier, priority, isActive)
}
static func height(_ view: UIView, multiplier: CGFloat = 1.0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintSize {
return .height(view.heightAnchor, multiplier: multiplier, priority: priority, isActive: isActive)
}
static func height(min: CGFloat, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintSize {
return .__heightMinPriorityActive(min, priority, isActive)
}
static func height(max: CGFloat, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintSize {
return .__heightMaxPriorityActive(max, priority, isActive)
}
}
extension UIView {
/// Constraints for size
///
/// Example:
/// ```
/// view.rk_alSize(values: [.width(50), .height(anotherView, multiplier: 3)])
/// ```
/// or
/// ```
/// view.rk_alSize(values: [.width(anotherView.heightAnchor, priority: .low), .height(anotherView)])
///
/// ```
/// or
/// ```
/// view.rk_alSize(values: [.width(200), .height(min: 60), .height(max: 220)])
/// ```
/// etc.
///
/// - Parameter values: Set<RKConstraintSize>
/// - Returns: Array of constraints
@discardableResult
func rk_alSize(_ values: RKConstraintSize..., isActive: Bool = true) -> RKConstraints {
return rk_alSize(with: values, isActive: isActive)
}
@discardableResult
fileprivate func rk_alSize(with values: [RKConstraintSize], isActive: Bool = true) -> RKConstraints {
let values = Set<RKConstraintSize>(values)
guard !values.isEmpty else { return [] }
translatesAutoresizingMaskIntoConstraints = false
guard let storage = constraintsStorage else {
assertionFailure("rk_alSize: constraintsStorage should not be nil!")
return []
}
guard let _ = superview else {
assertionFailure("rk_alSize: superview should not be nil!")
return []
}
var constraints: RKConstraints = []
var constraint: NSLayoutConstraint!
var isWidthConstraint: Bool = false
for value in values {
switch value {
// constant
case .__widthPriorityActive(let constant, let priority, let active):
constraint = widthAnchor.constraint(equalToConstant: constant).set(priority: priority).set(active: active && isActive)
isWidthConstraint = true
case .__heightPriorityActive(let constant, let priority, let active):
constraint = heightAnchor.constraint(equalToConstant: constant).set(priority: priority).set(active: active && isActive)
// dimension
case .__widthDimensionPriorityActive(let dimension, let multiplier, let priority, let active):
constraint = widthAnchor.constraint(equalTo: dimension, multiplier: multiplier).set(priority: priority).set(active: active && isActive)
isWidthConstraint = true
case .__heightDimensionPriorityActive(let dimension, let multiplier, let priority, let active):
constraint = heightAnchor.constraint(equalTo: dimension, multiplier: multiplier).set(priority: priority).set(active: active && isActive)
// min constant
case .__widthMinPriorityActive(let constant, let priority, let active):
constraint = widthAnchor.constraint(greaterThanOrEqualToConstant: constant).set(priority: priority).set(active: active && isActive)
isWidthConstraint = true
case .__heightMinPriorityActive(let constant, let priority, let active):
constraint = heightAnchor.constraint(greaterThanOrEqualToConstant: constant).set(priority: priority).set(active: active && isActive)
// max constant
case .__widthMaxPriorityActive(let constant, let priority, let active):
constraint = widthAnchor.constraint(lessThanOrEqualToConstant: constant).set(priority: priority).set(active: active && isActive)
isWidthConstraint = true
case .__heightMaxPriorityActive(let constant, let priority, let active):
constraint = heightAnchor.constraint(lessThanOrEqualToConstant: constant).set(priority: priority).set(active: active && isActive)
}
if isWidthConstraint {
storage.sizeWidthConstraints.append(constraint)
} else {
storage.sizeHeightConstraints.append(constraint)
}
constraints.append(constraint)
}
return constraints
}
}
// MARK: - EDGEs
enum RKConstraintEDGE: Hashable, Equatable {
case __top(CGFloat, RKConstraintPriority, Bool)
case __topAnchor(NSLayoutYAxisAnchor, CGFloat, RKConstraintPriority, Bool)
case __left(CGFloat, RKConstraintPriority, Bool)
case __leftAnchor(NSLayoutXAxisAnchor, CGFloat, RKConstraintPriority, Bool)
case __leading(CGFloat, RKConstraintPriority, Bool)
case __leadingAnchor(NSLayoutXAxisAnchor, CGFloat, RKConstraintPriority, Bool)
case __bottom(CGFloat, RKConstraintPriority, Bool)
case __bottomAnchor(NSLayoutYAxisAnchor, CGFloat, RKConstraintPriority, Bool)
case __right(CGFloat, RKConstraintPriority, Bool)
case __rightAnchor(NSLayoutXAxisAnchor, CGFloat, RKConstraintPriority, Bool)
case __trailing(CGFloat, RKConstraintPriority, Bool)
case __trailingAnchor(NSLayoutXAxisAnchor, CGFloat, RKConstraintPriority, Bool)
var hashValue: Int {
switch self {
case .__top(_, _, _), .__topAnchor(_, _, _, _): return 1
case .__left(_, _, _), .__leftAnchor(_, _, _, _): return 2
case .__leading(_, _, _), .__leadingAnchor(_, _, _, _): return 3
case .__bottom(_, _, _), .__bottomAnchor(_, _, _, _): return 4
case .__right(_, _, _), .__rightAnchor(_, _, _, _): return 5
case .__trailing(_, _, _), .__trailingAnchor(_, _, _, _): return 6
}
}
static func == (lhs: RKConstraintEDGE, rhs: RKConstraintEDGE) -> Bool {
return lhs.hashValue == rhs.hashValue
}
// MARK: Top
static func top(_ offset: CGFloat, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__top(offset, priority, isActive)
}
static func top(_ view: UIView, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__topAnchor(view.topAnchor, offset, priority, isActive)
}
static func top(_ anchor: NSLayoutYAxisAnchor, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__topAnchor(anchor, offset, priority, isActive)
}
// MARK: Left
static func left(_ offset: CGFloat, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__left(offset, priority, isActive)
}
static func left(_ view: UIView, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__leftAnchor(view.leftAnchor, offset, priority, isActive)
}
static func left(_ anchor: NSLayoutXAxisAnchor, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__leftAnchor(anchor, offset, priority, isActive)
}
// MARK: Leading
static func leading(_ offset: CGFloat, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__leading(offset, priority, isActive)
}
static func leading(_ view: UIView, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__leadingAnchor(view.leadingAnchor, offset, priority, isActive)
}
static func leading(_ anchor: NSLayoutXAxisAnchor, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__leadingAnchor(anchor, offset, priority, isActive)
}
// MARK: Bottom
static func bottom(_ offset: CGFloat, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__bottom(offset, priority, isActive)
}
static func bottom(_ view: UIView, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__bottomAnchor(view.bottomAnchor, offset, priority, isActive)
}
static func bottom(_ anchor: NSLayoutYAxisAnchor, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__bottomAnchor(anchor, offset, priority, isActive)
}
// MARK: Right
static func right(_ offset: CGFloat, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__right(offset, priority, isActive)
}
static func right(_ view: UIView, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__rightAnchor(view.rightAnchor, offset, priority, isActive)
}
static func right(_ anchor: NSLayoutXAxisAnchor, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__rightAnchor(anchor, offset, priority, isActive)
}
// MARK: Trailing
static func trailing(_ offset: CGFloat, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__trailing(offset, priority, isActive)
}
static func trailing(_ view: UIView, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__trailingAnchor(view.trailingAnchor, offset, priority, isActive)
}
static func trailing(_ anchor: NSLayoutXAxisAnchor, offset: CGFloat = 0, priority: RKConstraintPriority = .required, isActive: Bool = true) -> RKConstraintEDGE {
return .__trailingAnchor(anchor, offset, priority, isActive)
}
}
extension UIView {
@discardableResult
func rk_alEdge(_ values: RKConstraintEDGE..., isActive: Bool = true) -> RKConstraints {
return rk_alEdge(with: values, isActive: isActive)
}
@discardableResult
func rk_alEdge(with values: [RKConstraintEDGE], isActive: Bool = true) -> RKConstraints {
let values = Set<RKConstraintEDGE>(values)
guard !values.isEmpty else { return [] }
translatesAutoresizingMaskIntoConstraints = false
guard let storage = constraintsStorage else {
assertionFailure("rk_alEdge: constraintsStorage should not be nil!")
return []
}
guard let superview = superview else {
assertionFailure("rk_alEdge: superview should not be nil!")
return []
}
var constraints: RKConstraints = []
var constraint: RKConstraint!
for value in values {
switch value {
// top
case .__top(let offset, let priority, let active):
constraint = topAnchor.constraint(equalTo: superview.topAnchor, constant: offset).set(priority: priority).set(active: active && isActive)
storage.edgeTopConstraints.append(constraint)
case .__topAnchor(let anchor, let offset, let priority, let active):
constraint = topAnchor.constraint(equalTo: anchor, constant: offset).set(priority: priority).set(active: active && isActive)
storage.edgeTopConstraints.append(constraint)
// left
case .__left(let offset, let priority, let active):
constraint = leftAnchor.constraint(equalTo: superview.leftAnchor, constant: offset).set(priority: priority).set(active: active && isActive)
storage.edgeLeftConstraints.append(constraint)
case .__leftAnchor(let anchor, let offset, let priority, let active):
constraint = leftAnchor.constraint(equalTo: anchor, constant: offset).set(priority: priority).set(active: active && isActive)
storage.edgeLeftConstraints.append(constraint)
// leading
case .__leading(let offset, let priority, let active):
constraint = leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: offset).set(priority: priority).set(active: active && isActive)
storage.edgeLeadingConstraints.append(constraint)
case .__leadingAnchor(let anchor, let offset, let priority, let active):
constraint = leadingAnchor.constraint(equalTo: anchor, constant: offset).set(priority: priority).set(active: active && isActive)
storage.edgeLeadingConstraints.append(constraint)
// bottom
case .__bottom(let offset, let priority, let active):
constraint = bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: offset).set(priority: priority).set(active: active && isActive)
storage.edgeBottomConstraints.append(constraint)
case .__bottomAnchor(let anchor, let offset, let priority, let active):
constraint = bottomAnchor.constraint(equalTo: anchor, constant: offset).set(priority: priority).set(active: active && isActive)
storage.edgeBottomConstraints.append(constraint)
// right
case .__right(let offset, let priority, let active):
constraint = rightAnchor.constraint(equalTo: superview.rightAnchor, constant: offset).set(priority: priority).set(active: active && isActive)
storage.edgeRightConstraints.append(constraint)
case .__rightAnchor(let anchor, let offset, let priority, let active):
constraint = rightAnchor.constraint(equalTo: anchor, constant: offset).set(priority: priority).set(active: active && isActive)
storage.edgeRightConstraints.append(constraint)
// trailing
case .__trailing(let offset, let priority, let active):
constraint = trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: offset).set(priority: priority).set(active: active && isActive)
storage.edgeTrailingConstraints.append(constraint)
case .__trailingAnchor(let anchor, let offset, let priority, let active):
constraint = trailingAnchor.constraint(equalTo: anchor, constant: offset).set(priority: priority).set(active: active && isActive)
storage.edgeTrailingConstraints.append(constraint)
}
constraints.append(constraint)
}
return constraints
}
}
// MARK: - Adding all
extension UIView {
func rk_alAdd(size: [RKConstraintSize] = [], center: [RKConstraintCenter] = [], edge: [RKConstraintEDGE] = [], isActive: Bool = true) -> RKConstraints {
var resultConstraints: RKConstraints = []
resultConstraints += rk_alSize(with: size, isActive: isActive)
resultConstraints += rk_alCenter(with: center, isActive: isActive)
resultConstraints += rk_alEdge(with: edge, isActive: isActive)
return resultConstraints
}
}
| mit | 7a835339fb802c763978e53a75f731a9 | 45.264659 | 170 | 0.663789 | 4.749146 | false | false | false | false |
rechsteiner/Parchment | Parchment/Structs/PageView.swift | 1 | 8884 | import SwiftUI
import UIKit
/// Check if both SwiftUI and Combine is available. Without this
/// xcodebuild fails, saying it can't find the SwiftUI types used
/// inside PageView, even though it's wrapped with an @available
/// check. Found a possible fix here: https://stackoverflow.com/questions/58233454/how-to-use-swiftui-in-framework
/// This might be related to the issue discussed in this thread:
/// https://forums.swift.org/t/weak-linking-of-frameworks-with-greater-deployment-targets/26017/24
#if canImport(SwiftUI) && !(os(iOS) && (arch(i386) || arch(arm)))
/// `PageView` provides a SwiftUI wrapper around `PagingViewController`.
/// It can be used with any fixed array of `PagingItem`s. Use the
/// `PagingOptions` struct to customize the properties.
@available(iOS 13.0, *)
public struct PageView<Item: PagingItem, Page: View>: View {
let content: (Item) -> Page
private let options: PagingOptions
private var items = [Item]()
private var onWillScroll: ((PagingItem) -> Void)?
private var onDidScroll: ((PagingItem) -> Void)?
private var onDidSelect: ((PagingItem) -> Void)?
@Binding private var selectedIndex: Int
/// Initialize a new `PageView`.
///
/// - Parameters:
/// - options: The configuration parameters we want to customize.
/// - items: The array of `PagingItem`s to display in the menu.
/// - selectedIndex: The index of the currently selected page.
/// Updating this index will transition to the new index.
/// - content: A callback that returns the `View` for each item.
public init(
options: PagingOptions = PagingOptions(),
items: [Item],
selectedIndex: Binding<Int> = .constant(Int.max),
content: @escaping (Item) -> Page
) {
_selectedIndex = selectedIndex
self.options = options
self.items = items
self.content = content
}
public var body: some View {
PagingController(
items: items,
options: options,
content: content,
onWillScroll: onWillScroll,
onDidScroll: onDidScroll,
onDidSelect: onDidSelect,
selectedIndex: $selectedIndex
)
}
/// Called when the user finished scrolling to a new view.
///
/// - Parameter action: A closure that is called with the
/// paging item that was scrolled to.
/// - Returns: An instance of self
public func didScroll(_ action: @escaping (PagingItem) -> Void) -> Self {
var view = self
view.onDidScroll = action
return view
}
/// Called when the user is about to start scrolling to a new view.
///
/// - Parameter action: A closure that is called with the
/// paging item that is being scrolled to.
/// - Returns: An instance of self
public func willScroll(_ action: @escaping (PagingItem) -> Void) -> Self {
var view = self
view.onWillScroll = action
return view
}
/// Called when an item was selected in the menu.
///
/// - Parameter action: A closure that is called with the
/// selected paging item.
/// - Returns: An instance of self
public func didSelect(_ action: @escaping (PagingItem) -> Void) -> Self {
var view = self
view.onDidSelect = action
return view
}
/// Create a custom paging view controller subclass that we
/// can use to store state to avoid reloading data unnecessary.
final class CustomPagingViewController: PagingViewController {
var items: [Item]?
}
struct PagingController: UIViewControllerRepresentable {
let items: [Item]
let options: PagingOptions
let content: (Item) -> Page
var onWillScroll: ((PagingItem) -> Void)?
var onDidScroll: ((PagingItem) -> Void)?
var onDidSelect: ((PagingItem) -> Void)?
@Binding var selectedIndex: Int
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<PagingController>) -> CustomPagingViewController {
let pagingViewController = CustomPagingViewController(options: options)
pagingViewController.dataSource = context.coordinator
pagingViewController.delegate = context.coordinator
return pagingViewController
}
func updateUIViewController(_ pagingViewController: CustomPagingViewController,
context: UIViewControllerRepresentableContext<PagingController>) {
context.coordinator.parent = self
if pagingViewController.dataSource == nil {
pagingViewController.dataSource = context.coordinator
}
// If the menu items have changed we call reload data
// to update both the menu and content views.
if let previousItems = pagingViewController.items,
!previousItems.elementsEqual(items, by: { $0.isEqual(to: $1) }) {
pagingViewController.reloadData()
}
// Store the current items so we can compare it with
// the new items the next time this method is called.
pagingViewController.items = items
// HACK: If the user don't pass a selectedIndex binding, the
// default parameter is set to .constant(Int.max) which allows
// us to check here if a binding was passed in or not (it
// doesn't seem possible to make the binding itself optional).
// This check is needed because we cannot update a .constant
// value. When the user scroll to another page, the
// selectedIndex binding will always be the same, so calling
// `select(index:)` will select the wrong page. This fixes a bug
// where the wrong page would be selected when rotating.
guard selectedIndex != Int.max else {
return
}
pagingViewController.select(index: selectedIndex, animated: true)
}
}
final class Coordinator: PagingViewControllerDataSource, PagingViewControllerDelegate {
var parent: PagingController
init(_ pagingController: PagingController) {
parent = pagingController
}
func numberOfViewControllers(in _: PagingViewController) -> Int {
return parent.items.count
}
func pagingViewController(_: PagingViewController, viewControllerAt index: Int) -> UIViewController {
let view = parent.content(parent.items[index])
let hostingViewController = UIHostingController(rootView: view)
let backgroundColor = parent.options.pagingContentBackgroundColor
hostingViewController.view.backgroundColor = backgroundColor
return hostingViewController
}
func pagingViewController(_: PagingViewController, pagingItemAt index: Int) -> PagingItem {
parent.items[index]
}
func pagingViewController(_ controller: PagingViewController,
didScrollToItem pagingItem: PagingItem,
startingViewController _: UIViewController?,
destinationViewController _: UIViewController,
transitionSuccessful _: Bool) {
if let item = pagingItem as? Item,
let index = parent.items.firstIndex(where: { $0.isEqual(to: item) }) {
parent.selectedIndex = index
}
parent.onDidScroll?(pagingItem)
}
func pagingViewController(_: PagingViewController,
willScrollToItem pagingItem: PagingItem,
startingViewController _: UIViewController,
destinationViewController _: UIViewController) {
parent.onWillScroll?(pagingItem)
}
func pagingViewController(_: PagingViewController, didSelectItem pagingItem: PagingItem) {
parent.onDidSelect?(pagingItem)
}
}
}
#endif
| mit | bd566554fb3bbf6f9cebc4752446224d | 42.763547 | 134 | 0.579919 | 5.757615 | false | false | false | false |
wordpress-mobile/WordPress-Aztec-iOS | WordPressEditor/WordPressEditor/Classes/Plugins/WordPressPlugin/Calypso/CaptionShortcode/CaptionShortcodeOutputProcessor.swift | 2 | 3233 | import Aztec
import Foundation
/// Converts <figure><img><figcaption> structures into a [caption] shortcode.
///
class CaptionShortcodeOutputProcessor: HTMLProcessor {
init() {
let shortcodeAttributeSerializer = ShortcodeAttributeSerializer()
super.init(for: "figure") { element in
guard let payload = element.content else {
return nil
}
/// Parse the Shortcode's Payload: We expect an [IMG, Figcaption]
///
let rootNode = HTMLParser().parse(payload)
guard let coreNode = rootNode.firstChild(ofType: .img) ?? rootNode.firstChild(ofType: .a),
let figcaption = rootNode.firstChild(ofType: .figcaption)
else {
return nil
}
/// Serialize the Caption's Shortcode!
///
let serializer = HTMLSerializer()
var attributes = element.attributes
var imgNode: ElementNode?
// Find img child node of caption
if coreNode.isNodeType(.img) {
imgNode = coreNode
} else {
imgNode = coreNode.firstChild(ofType: .img)
}
if let imgNode = imgNode {
attributes = CaptionShortcodeOutputProcessor.attributes(from: imgNode, basedOn: attributes)
}
if !attributes.contains(where: { $0.key == "id" }) {
attributes.insert(ShortcodeAttribute(key: "id", value: ""), at: 0)
}
let attributesHTMLRepresentation = shortcodeAttributeSerializer.serialize(attributes)
var html = "[caption " + attributesHTMLRepresentation + "]"
html += serializer.serialize(coreNode)
for child in figcaption.children {
html += serializer.serialize(child)
}
html += "[/caption]"
return html
}
}
static func attributes(from imgNode: ElementNode, basedOn baseAttributes: [ShortcodeAttribute]) -> [ShortcodeAttribute] {
var captionAttributes = baseAttributes
let imgAttributes = imgNode.attributes
for attribute in imgAttributes {
guard attribute.type != .src,
let attributeValue = attribute.value.toString() else {
continue
}
if attribute.type == .class {
let classAttributes = attributeValue.components(separatedBy: " ")
for classAttribute in classAttributes {
if classAttribute.hasPrefix("wp-image-") {
let value = classAttribute.replacingOccurrences(of: "wp-image-", with: "attachment_")
captionAttributes.set(value, forKey: "id")
} else if classAttribute.hasPrefix("align"){
captionAttributes.set(classAttribute, forKey: "align")
}
}
} else {
captionAttributes.set(attributeValue, forKey: attribute.name)
}
}
return captionAttributes
}
}
| gpl-2.0 | 21caa8d87b28278f999a258fddcba70f | 34.527473 | 125 | 0.540674 | 5.488964 | false | false | false | false |
bobbypage/Requests | RequestsDemoTests/RequestsDemoTests.swift | 1 | 5986 | //
// RequestsDemoTests.swift
// RequestsDemoTests
//
// Created by David Porter on 8/2/14.
// Copyright (c) 2014 David Porter. All rights reserved.
//
import UIKit
import XCTest
class RequestsDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
Requests.sharedInstance.basePath = ""
Requests.sharedInstance.additionalHeaders = [String:String]()
Requests.sharedInstance.paramsEncoding = Requests.ParamsEncoding.JSON
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testHTTPGetHTML() {
Requests.get("http://httpbin.org", completion: {(response, error, data) in
XCTAssertEqual(response.statusCode, 200, "Status Code should return 200")
})
}
func testHTTPGet() {
Requests.sharedInstance.additionalHeaders = ["X-Test":"Testing"]
Requests.get("http://httpbin.org/get", params: ["lang":"swift", "name":"john"], completion: {(response, error, data) in
XCTAssertEqual(response.statusCode, 200, "Status Code should return 200")
let json = data as? Dictionary<String, AnyObject>
let args = json!["args"]! as Dictionary<String, AnyObject>
var lang: AnyObject = args["lang"]!
XCTAssertEqual(lang as String, "swift", "lang should be swift")
let headers = json!["headers"]! as? Dictionary<String, AnyObject>
var testHeaderValue: AnyObject = headers!["X-Test"]!
XCTAssertEqual(testHeaderValue as String, "Testing", "X-Test header should be Testing")
})
}
func testHTTPPostJSON() {
Requests.sharedInstance.additionalHeaders = ["X-Test":"Testing"]
Requests.post("http://httpbin.org/post", params: ["lang":"swift", "name":"john"], completion: {(response, error, data) in
XCTAssertEqual(response.statusCode, 200, "Status Code should return 200")
let json = data as? Dictionary<String, AnyObject>
let args = json!["json"]! as Dictionary<String, AnyObject>
var lang: AnyObject = args["lang"]!
XCTAssertEqual(lang as String, "swift", "lang should be swift")
let headers = json!["headers"]! as? Dictionary<String, AnyObject>
var testHeaderValue: AnyObject = headers!["X-Test"]!
XCTAssertEqual(testHeaderValue as String, "Testing", "X-Test header should be Testing")
})
}
func testHTTPPostForm() {
Requests.sharedInstance.additionalHeaders = ["X-Test":"Testing"]
Requests.sharedInstance.paramsEncoding = Requests.ParamsEncoding.FormURL
Requests.post("http://httpbin.org/post", params: ["lang":"swift", "name":"john"], completion: {(response, error, data) in
XCTAssertEqual(response.statusCode, 200, "Status Code should return 200")
let json = data as? Dictionary<String, AnyObject>
let args = json!["form"]! as Dictionary<String, AnyObject>
var lang: AnyObject = args["lang"]!
XCTAssertEqual(lang as String, "swift", "lang should be swift")
let headers = json!["headers"]! as? Dictionary<String, AnyObject>
var testHeaderValue: AnyObject = headers!["X-Test"]!
XCTAssertEqual(testHeaderValue as String, "Testing", "X-Test header should be Testing")
})
}
func testHTTPPut() {
Requests.sharedInstance.additionalHeaders = ["X-Test":"Testing"]
Requests.put("http://httpbin.org/put", params: ["lang":"swift", "name":"john"], completion: {(response, error, data) in
XCTAssertEqual(response.statusCode, 200, "Status Code should return 200")
let json = data as? Dictionary<String, AnyObject>
let args = json!["json"]! as Dictionary<String, AnyObject>
var lang: AnyObject = args["lang"]!
XCTAssertEqual(lang as String, "swift", "lang should be swift")
let headers = json!["headers"]! as? Dictionary<String, AnyObject>
var testHeaderValue: AnyObject = headers!["X-Test"]!
XCTAssertEqual(testHeaderValue as String, "Testing", "X-Test header should be Testing")
})
}
func testHTTPDelete() {
Requests.sharedInstance.additionalHeaders = ["X-Test":"Testing"]
Requests.delete("http://httpbin.org/delete", params: ["lang":"swift", "name":"john"], completion: {(response, error, data) in
XCTAssertEqual(response.statusCode, 200, "Status Code should return 200")
let json = data as? Dictionary<String, AnyObject>
let args = json!["json"]! as Dictionary<String, AnyObject>
var lang: AnyObject = args["lang"]!
XCTAssertEqual(lang as String, "swift", "lang should be swift")
let headers = json!["headers"]! as? Dictionary<String, AnyObject>
var testHeaderValue: AnyObject = headers!["X-Test"]!
XCTAssertEqual(testHeaderValue as String, "Testing", "X-Test header should be Testing")
})
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
} | mit | 7121e508ea7e7aeb2a85da786ed51222 | 39.727891 | 133 | 0.585867 | 5.017603 | false | true | false | false |
andinfinity/idrop.link-osx | idrop.link/PopoverTableViewDelegate.swift | 2 | 2537 | //
// PopoverTableViewDelegate.swift
// idrop.link
//
// Created by Christian Schulze on 31/05/15.
// Copyright (c) 2015 andinfinity. All rights reserved.
//
import Cocoa
import AppKit
class PopoverTableViewDelegate: NSObject, NSTableViewDataSource, NSTableViewDelegate {
var popoverTableView: PopoverTableView?
var user:User?
override init() {
self.user = nil
}
init(user:User) {
self.user = user
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
if let usr = self.user {
return usr.drops.count
} else {
return 0
}
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
if let usr = self.user {
let cell = tableView.makeViewWithIdentifier("MainCell", owner: self) as! PopoverTableCellView
cell.imgView = nil
cell.titleTextField?.stringValue = usr.drops[row].name!
if let date = usr.drops[row].dropDate {
cell.dateTextField?.stringValue = date
} else {
cell.dateTextField?.stringValue = ""
}
return cell
} else {
return nil
}
}
func tableViewSelectionDidChange(notification: NSNotification) {
// sets selected items in bold font
self.popoverTableView?.enumerateAvailableRowViewsUsingBlock({ (rowView, row) -> Void in
for (var col = 0; col < rowView.numberOfColumns; col += 1) {
let cellView: AnyObject? = rowView.viewAtColumn(col)
if let cV: AnyObject = cellView {
if (cV.isKindOfClass(PopoverTableCellView)) {
let tabelCellView = cV as! PopoverTableCellView
let dateLabel = tabelCellView.dateTextField
let titleLabel = tabelCellView.titleTextField
if (rowView.selected) {
dateLabel?.font = NSFont.boldSystemFontOfSize(dateLabel!.font!.pointSize)
titleLabel?.font = NSFont.boldSystemFontOfSize(titleLabel!.font!.pointSize)
} else {
dateLabel?.font = NSFont.systemFontOfSize(dateLabel!.font!.pointSize)
titleLabel?.font = NSFont.systemFontOfSize(titleLabel!.font!.pointSize)
}
}
}
}
})
}
}
| mit | 6cd93585fa95dd9c50f28299c6e30df4 | 32.381579 | 113 | 0.564446 | 5.274428 | false | false | false | false |
up-n-down/Up-N-Down | Finder Sync Extension/FinderSync+ContextualMenu.swift | 1 | 3130 | //
// FinderSync+ContextualMenu.swift
// Up-N-Down
//
// Created by Thomas Paul Mann on 05/12/2016.
// Copyright © 2016 Up-N-Down. All rights reserved.
//
import FinderSync
extension FinderSync {
/// Returns a contextual menu.
func createContextualMenu() -> NSMenu {
// Todo: What do we do with directories?! Recursive I guess.
let selectedItems = finderSyncController.selectedItemsRepresentation
let commitMenuItem = NSMenuItem(title: "Commit \(selectedItems)", action: #selector(commitDidPress(_:)))
let addMenuItem = NSMenuItem(title: "Add \(selectedItems) to Index", action: #selector(addDidPress(_:)))
let removeMenuItem = NSMenuItem(title: "Remove \(selectedItems) from Index", action: #selector(removeDidPress(_:)))
let ignoreMenuItem = NSMenuItem(title: "Ignore \(selectedItems) in Index", action: #selector(ignoreDidPress(_:)))
let contextualMenu = NSMenu(title: "Contextual menu")
contextualMenu.addItem(commitMenuItem)
contextualMenu.addItem(addMenuItem)
contextualMenu.addItem(removeMenuItem)
contextualMenu.addItem(ignoreMenuItem)
return contextualMenu
}
// MARK: - Actions
@IBAction func commitDidPress(_ menuItem: NSMenuItem) {
// TODO: Make it more beautiful.
guard let targetedURL = finderSyncController.selectedItemURLs()?.first else {
return
}
NSAlert.ask(for: "Commit Changes",
message: "Enter a Commit Message:",
actionButtonTitle: "Commit",
inputTextFieldPlaceholder: "Commit ...",
completionHandler: { [weak self] response, textfield in
guard response == NSAlertFirstButtonReturn else {
return
}
let commitMessage = textfield.stringValue
self?.git.commit(commitMessage, inRepository: targetedURL) { error in
if let error = error {
NSAlert.runModal(withError: error)
}
}
})
}
@IBAction func addDidPress(_ menuItem: NSMenuItem) {
finderSyncController.selectedItemURLs()?.forEach { file in
git.add(toIndex: file) { [weak self] error in
if let error = error {
NSAlert.runModal(withError: error)
} else {
self?.requestBadgeIdentifier(for: file)
}
}
}
}
@IBAction func removeDidPress(_ menuItem: NSMenuItem) {
finderSyncController.selectedItemURLs()?.forEach { file in
git.remove(fromIndex: file) { [weak self] error in
if let error = error {
NSAlert.runModal(withError: error)
} else {
self?.requestBadgeIdentifier(for: file)
}
}
}
}
@IBAction func ignoreDidPress(_ menuItem: NSMenuItem) {
}
}
| gpl-3.0 | 32bc4e621ecf52a241fa79cdf70c6a85 | 34.965517 | 123 | 0.565037 | 5.357877 | false | false | false | false |
AnnMic/FestivalArchitect | FestivalArchitect/Classes/Components/PositionComponent.swift | 2 | 631 | //
// Speed.swift
// FestivalTycoon
//
// Created by Ann Michelsen on 25/09/14.
// Copyright (c) 2014 Ann Michelsen. All rights reserved.
//
import Foundation
class PositionComponent : Component {
var x : CGFloat!
var y : CGFloat!
var moveTarget : CGPoint!
init (x : CGFloat, y : CGFloat) {
self.x = x
self.y = y
}
init (position : CGPoint) {
self.x = position.x
self.y = position.y
}
init(moveTarget:CGPoint) {
self.moveTarget = moveTarget
}
internal override class func name() -> String {
return "PositionComponent"
}
} | mit | ebc33395b1bbe79d960b614a6d97c4f9 | 18.75 | 58 | 0.581616 | 3.755952 | false | false | false | false |
JimCampagno/Swift-Book-Projects | Chapter-7/Chapter7Code.playground/Contents.swift | 1 | 1154 |
var list = ["Legos", "Dungeons and Dragons", "Gameboy", "Monopoly", "Rubix Cube"]
let firstItem = list[0]
let lastItem = list[4]
list[4] = "Crayons"
list.append("Play-Doh")
print(list)
print("I'm not as good as my sister, but I love solving the \(lastItem)")
print(firstItem)
// Prints "Legos"
let numbers = [5, 2, 9, 22]
let colors: [String] = ["Red", "Orange", "Yellow"]
let words = ["Coffee" : "A drink made from the roasted and ground beanlike seeds of a tropical shrub, served hot or iced."]
let planets = ["Earth" : 1, "Mars" : 2, "Jupiter" : 53]
let earthMoons = planets["Earth"]
print(earthMoons)
var favoriteColors = ["Neil" : "red", "Carl" : "blue"]
favoriteColors["Isaac"] = "green"
print(favoriteColors)
// Prints "["Carl": "blue", "Isaac": "green", "Neil": "red"]"
favoriteColors["Carl"] = "white"
let carlsFavColor = favoriteColors["Carl"]
print(carlsFavColor)
// prints "Optional("white")"
let jessFavColor = favoriteColors["Jessica"]
print(jessFavColor)
// prints "nil"
if let jessicaFavColor = favoriteColors["Jessica"] {
print("Hooray!")
print(jessicaFavColor)
}
// Nothing prints!
| mit | bf40c7a63bd7fa2f6a02d8536180721a | 13.987013 | 123 | 0.654246 | 2.870647 | false | false | false | false |
benjaminsnorris/SharedHelpers | Sources/CustomTableView.swift | 1 | 2176 | /*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import UIKit
public protocol CustomTableViewDelegate: class {
func didDeselectOnTap(in tableView: CustomTableView)
}
@IBDesignable open class CustomTableView: UITableView, BackgroundColorNameable {
// MARK: - Inspectable properties
@IBInspectable open var backgroundColorName: String? {
didSet {
applyBackgroundColorName()
}
}
@IBInspectable open var separatorColorName: String? {
didSet {
updateSeparatorColor()
}
}
@IBInspectable open var tapToDeselect: Bool = false
// MARK: - Public properties
public weak var deselectionDelegate: CustomTableViewDelegate?
// MARK: - Initializers
override public init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
registerForNotifications()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
registerForNotifications()
}
open override func awakeFromNib() {
super.awakeFromNib()
updateSeparatorColor()
}
// MARK: - Lifecycle overrides
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let result = super.hitTest(point, with: event)
guard tapToDeselect else { return result }
if result == self, let selected = indexPathForSelectedRow {
deselectRow(at: selected, animated: true)
deselectionDelegate?.didDeselectOnTap(in: self)
}
return result
}
// MARK: - Functions
func registerForNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(updateColors), name: Notification.Name.AppearanceColorsUpdated, object: nil)
}
@objc func updateColors() {
applyBackgroundColorName()
updateSeparatorColor()
}
func updateSeparatorColor() {
separatorColor = UIColor(withName: separatorColorName)
}
}
| mit | 29a747f172bc8e835dc46089d5179707 | 24.547619 | 149 | 0.605778 | 5.037559 | false | false | false | false |
hamchapman/PusherSwift | Source/PusherSwift.swift | 1 | 14659 | //
// PusherSwift.swift
//
// Created by Hamilton Chapman on 19/02/2015.
//
//
import Foundation
import Alamofire
import SwiftyJSON
import Starscream
class Pusher {
let connection: PusherConnection
let PROTOCOL = 7
let VERSION = "0.0.1"
let authEndpoint: String?
init(key: String, encrypted: Bool = false, authEndpoint: String? = nil) {
self.authEndpoint = authEndpoint
var url = ""
if encrypted {
url = "wss://ws.pusherapp.com:443/app/\(key)"
} else {
url = "ws://ws.pusherapp.com:80/app/\(key)"
}
url += "?client=pusher-swift&version=\(VERSION)&protocol=\(PROTOCOL)"
connection = PusherConnection(url: url, authEndpoint: self.authEndpoint)
}
func subscribe(channelName: String) -> PusherChannel {
return self.connection.addChannel(channelName)
}
func disconnect() {
self.connection.close()
}
func connect() {
self.connection.open()
}
// func bind(event_name, &callback) {
// global_channel.bind(event_name, &callback)
// return self
// }
}
class PusherConnection: WebSocketDelegate {
let url: String
let authEndpoint: String?
var socketId: String?
lazy var socket: WebSocket = { [unowned self] in
return self.connectInternal()
}()
var connected = false
var channels = PusherChannels()
init(url: String, authEndpoint: String?) {
self.url = url
self.authEndpoint = authEndpoint
self.socket = self.connectInternal()
}
func addChannel(channelName: String) -> PusherChannel {
var newChannel = channels.add(channelName, connection: self)
if self.connected {
self.authorize(newChannel)
}
return newChannel
}
func sendEvent(event: String, data: AnyObject, channelName: String? = nil) {
if event.componentsSeparatedByString("-")[0] == "client" {
sendClientEvent(event, data: data, channelName: channelName)
} else {
self.socket.writeString(JSONStringify(["event": event, "data": data]))
}
}
func sendClientEvent(event: String, data: AnyObject, channelName: String?) {
if let cName = channelName {
if isPresenceChannel(cName) || isPrivateChannel(cName) {
self.socket.writeString(JSONStringify(["event": event, "data": data, "channel": cName]))
} else {
println("You must be subscribed to a private or presence channel to send client events")
}
}
}
func JSONStringify(value: AnyObject) -> String {
if NSJSONSerialization.isValidJSONObject(value) {
if let data = NSJSONSerialization.dataWithJSONObject(value, options: nil, error: nil) {
if let string = NSString(data: data, encoding: NSUTF8StringEncoding) {
return string as String
}
}
}
return ""
}
func close() {
if self.connected {
self.socket.disconnect()
}
}
func open() {
if self.connected {
return
} else {
self.socket = connectInternal()
}
}
func connectInternal() -> WebSocket {
let ws = WebSocket(url: NSURL(string: self.url)!)
ws.delegate = self
ws.connect()
return ws
}
func handleSubscriptionSucceededEvent(json: JSON) {
if let channelName = json["channel"].string {
if let chan = self.channels.find(channelName) {
chan.subscribed = true
if isPresenceChannel(channelName) {
if let presChan = self.channels.find(channelName) as? PresencePusherChannel {
if let data = json["data"].string {
let dataJSON = getJSONFromString(data)
if let members = dataJSON["presence"]["hash"].dictionary {
println(members)
presChan.members = members
}
}
}
}
for (eventName, data) in chan.unsentEvents {
chan.unsentEvents.removeValueForKey(channelName)
chan.trigger(eventName, data: data)
}
}
}
}
func handleConnectionEstablishedEvent(json: JSON) {
if let data = json["data"].string {
let connectionData = getJSONFromString(data)
if let socketId = connectionData["socket_id"].string {
self.connected = true
self.socketId = socketId
for (channelName, channel) in self.channels.channels {
if !channel.subscribed {
self.authorize(channel)
}
}
}
}
}
func handleMemberAddedEvent(json: JSON) {
if let data = json["data"].string {
let memberJSON = getJSONFromString(data)
if let channelName = json["channel"].string {
if let chan = self.channels.find(channelName) as? PresencePusherChannel {
chan.addMember(memberJSON)
}
}
}
}
func handleMemberRemovedEvent(json: JSON) {
if let data = json["data"].string {
let memberJSON = getJSONFromString(data)
if let channelName = json["channel"].string {
if let chan = self.channels.find(channelName) as? PresencePusherChannel {
chan.removeMember(memberJSON)
}
}
}
}
func getJSONFromString(string: String) -> JSON {
let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return JSON(data: data!)
}
func handleEvent(eventName: String, json: JSON) {
switch eventName {
case "pusher_internal:subscription_succeeded":
handleSubscriptionSucceededEvent(json)
case "pusher:connection_established":
handleConnectionEstablishedEvent(json)
case "pusher_internal:member_added":
handleMemberAddedEvent(json)
case "pusher_internal:member_removed":
handleMemberRemovedEvent(json)
default:
if let channelName = json["channel"].string {
if let internalChannel = self.channels.find(channelName) {
if let eName = json["event"].string {
if let eData = json["data"].string {
internalChannel.handleEvent(eName, eventData: eData)
}
}
}
}
}
}
func authorize(channel: PusherChannel, callback: ((Dictionary<String, String>?) -> Void)? = nil) {
if !isPresenceChannel(channel.name) && !isPrivateChannel(channel.name) {
subscribeToNormalChannel(channel)
}
if let endpoint = self.authEndpoint {
let url: NSURL = NSURL(string: endpoint)!
if let socket = self.socketId {
sendAuthorisationRequest(url, socket: socket, channel: channel, callback: callback)
} else {
println("socketId value not found")
}
} else {
println("authEndpoint not set")
}
}
func subscribeToNormalChannel(channel: PusherChannel) {
self.sendEvent("pusher:subscribe",
data: [
"channel": channel.name
]
)
}
func sendAuthorisationRequest(url: NSURL, socket: String, channel: PusherChannel, callback: ((Dictionary<String, String>?) -> Void)? = nil) {
Alamofire.request(.POST, url, parameters: ["socket_id": socket, "channel_name": channel.name])
.responseJSON { (_, _, jsonResponse, error) in
if let err = error {
println("Error authorizing channel: \(err)")
} else if let json = jsonResponse as? Dictionary<String, AnyObject> {
self.handleAuthResponse(json, channel: channel, callback: callback)
}
}
}
func handleAuthResponse(json: Dictionary<String, AnyObject>, channel: PusherChannel, callback: ((Dictionary<String, String>?) -> Void)? = nil) {
if let auth = json["auth"] as? String {
if let channelData = json["channel_data"] as? String {
handlePresenceChannelAuth(auth, channel: channel, channelData: channelData, callback: callback)
} else {
handlePrivateChannelAuth(auth, channel: channel, callback: callback)
}
}
}
func handlePresenceChannelAuth(auth: String, channel: PusherChannel, channelData: String, callback: ((Dictionary<String, String>?) -> Void)? = nil) {
if let cBack = callback {
cBack(["auth": auth, "channel_data": channelData])
} else {
self.sendEvent("pusher:subscribe",
data: [
"channel": channel.name,
"auth": auth,
"channel_data": channelData
]
)
}
}
func handlePrivateChannelAuth(auth: String, channel: PusherChannel, callback: ((Dictionary<String, String>?) -> Void)? = nil) {
if let cBack = callback {
cBack(["auth": auth])
} else {
self.sendEvent("pusher:subscribe",
data: [
"channel": channel.name,
"auth": auth
]
)
}
}
// MARK: WebSocketDelegate Implementation
func websocketDidReceiveMessage(ws: WebSocket, text: String) {
let data = (text as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let json = JSON(data: data!)
if let eventName = json["event"].string {
self.handleEvent(eventName, json: json)
}
}
func websocketDidConnect(ws: WebSocket) {
println("*******************************************")
println("Connected")
println("*******************************************")
}
func websocketDidDisconnect(ws: WebSocket, error: NSError?) {
println("——————————————")
println("Websocket is disconnected: \(error!.localizedDescription)")
println("——————————————")
self.connected = false
for (channelName, channel) in self.channels.channels {
channel.subscribed = false
}
var timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: Selector("testTimer"), userInfo: nil, repeats: true)
}
func testTimer() {
println("Looking for connection")
}
func websocketDidReceiveData(ws: WebSocket, data: NSData) {
}
}
class PusherChannel {
var callbacks: [String: (JSON) -> Void]
var subscribed = false
let name: String
let connection: PusherConnection
var unsentEvents = [String: AnyObject?]()
var userData: AnyObject? = nil
init(name: String, connection: PusherConnection) {
self.name = name
self.connection = connection
self.callbacks = [:]
}
func bind(eventName: String, callback: (JSON) -> Void) {
self.callbacks[eventName] = callback
}
func handleEvent(eventName: String, eventData: String) {
if let cb = self.callbacks[eventName] {
let data = (eventData as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let json = JSON(data: data!)
cb(json)
}
}
func trigger(eventName: String, data: AnyObject?) {
if subscribed {
if let d = data as? Dictionary<String, AnyObject> {
self.connection.sendEvent(eventName, data: d, channelName: self.name)
} else {
println("Your data is all messed up")
}
} else {
unsentEvents[eventName] = data
}
}
}
class PresencePusherChannel: PusherChannel {
var members: Dictionary<String, JSON>
override init(name: String, connection: PusherConnection) {
self.members = [:]
super.init(name: name, connection: connection)
}
func addMember(memberJSON: JSON) {
let userInfo: AnyObject = memberJSON["user_info"].object
if let userId = memberJSON["user_id"].string {
self.members[userId] = JSON(self.connection.JSONStringify(userInfo))
} else if let userId = memberJSON["user_id"].int {
self.members[String(userId)] = JSON(self.connection.JSONStringify(userInfo))
}
}
func removeMember(memberJSON: JSON) {
if let userId = memberJSON["user_id"].string {
self.members.removeValueForKey(userId)
} else if let userId = memberJSON["user_id"].int {
self.members.removeValueForKey(String(userId))
}
}
}
class Members {
//TODO: Consider setting up Members object for Presence Channels
}
class PusherChannels {
var channels = [String: PusherChannel]()
func add(channelName: String, connection: PusherConnection) -> PusherChannel {
if let channel = self.channels[channelName] {
return channel
} else {
var newChannel: PusherChannel
if isPresenceChannel(channelName) {
newChannel = PresencePusherChannel(name: channelName, connection: connection)
} else {
newChannel = PusherChannel(name: channelName, connection: connection)
}
self.channels[channelName] = newChannel
return newChannel
}
}
func remove(channelName: String) {
self.channels.removeValueForKey(channelName)
}
func find(channelName: String) -> PusherChannel? {
return self.channels[channelName]
}
}
func isPresenceChannel(channelName: String) -> Bool {
return (channelName.componentsSeparatedByString("-")[0] == "presence") ? true : false
}
func isPrivateChannel(channelName: String) -> Bool {
return (channelName.componentsSeparatedByString("-")[0] == "private") ? true : false
} | mit | fb229fef99ea7b01d2d849e4a521d28e | 32.962791 | 153 | 0.556187 | 4.935113 | false | false | false | false |
ChinaPicture/Blog | UI Testing with Xcode 7/Test/AppDelegate.swift | 3 | 814 | //
// AppDelegate.swift
// Test
//
// Created by Laurin Brandner on 15/06/15.
// Copyright © 2015 Laurin Brandner. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if NSProcessInfo.processInfo().environment["animations"] == "0" {
UIView.setAnimationsEnabled(false)
}
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = UINavigationController(rootViewController: ViewController())
window?.backgroundColor = .whiteColor()
window?.makeKeyAndVisible()
return true
}
}
| mit | e2d4ab2db33a81212912738ac69fb259 | 26.1 | 127 | 0.681427 | 5.313725 | false | false | false | false |
KimBin/DTTableViewManager | Example/XCTests/DatasourceTestCase.swift | 1 | 11860 | //
// DatasourceTestCase.swift
// DTTableViewManager
//
// Created by Denys Telezhkin on 18.07.15.
// Copyright (c) 2015 Denys Telezhkin. All rights reserved.
//
import UIKit
import XCTest
import DTModelStorage
import DTTableViewManager
import Nimble
class DatasourceTestCase: XCTestCase {
var controller = DTTestTableViewController()
override func setUp() {
super.setUp()
controller.tableView = AlwaysVisibleTableView()
let _ = controller.view
controller.manager.startManagingWithDelegate(controller)
controller.manager.viewBundle = NSBundle(forClass: self.dynamicType)
controller.manager.storage = MemoryStorage()
controller.manager.registerCellClass(NibCell)
}
func testTableItemAtIndexPath()
{
controller.manager.memoryStorage.addItems([3,2,1,6,4], toSection: 0)
expect(self.controller.verifyItem(6, atIndexPath: indexPath(3, 0))) == true
expect(self.controller.verifyItem(3, atIndexPath: indexPath(0, 0))) == true
expect(self.controller.manager.memoryStorage.itemAtIndexPath(indexPath(56, 0))).to(beNil())
}
func testShouldReturnCorrectNumberOfTableItems()
{
controller.manager.memoryStorage.addItems([1,1,1,1], toSection: 0)
controller.manager.memoryStorage.addItems([2,2,2], toSection: 1)
let tableView = controller.tableView
expect(self.controller.manager.tableView(tableView, numberOfRowsInSection: 0)) == 4
expect(self.controller.manager.tableView(tableView, numberOfRowsInSection: 1)) == 3
}
func testShouldReturnCorrectNumberOfSections()
{
controller.manager.memoryStorage.addItem(1, toSection: 0)
controller.manager.memoryStorage.addItem(4, toSection: 3)
controller.manager.memoryStorage.addItem(2, toSection: 2)
expect(self.controller.manager.numberOfSectionsInTableView(self.controller.tableView)) == 4
}
func testShouldSetSectionTitles()
{
controller.manager.memoryStorage.setSectionHeaderModels(["one","two"])
let tableView = self.controller.tableView
expect(self.controller.manager.tableView(tableView, titleForHeaderInSection: 0)) == "one"
expect(self.controller.manager.tableView(tableView, titleForHeaderInSection: 1)) == "two"
}
func testSHouldSetSectionFooterTitles()
{
controller.manager.memoryStorage.setSectionFooterModels(["one","two"])
let tableView = self.controller.tableView
expect(self.controller.manager.tableView(tableView, titleForFooterInSection: 0)) == "one"
expect(self.controller.manager.tableView(tableView, titleForFooterInSection: 1)) == "two"
}
func testShouldHandleAbsenceOfHeadersFooters()
{
controller.manager.memoryStorage.addItem(1, toSection: 0)
controller.manager.memoryStorage.addItem(2, toSection: 1)
controller.manager.tableView(controller.tableView, titleForHeaderInSection: 0)
controller.manager.tableView(controller.tableView, titleForFooterInSection: 1)
}
func testShouldAddTableItems()
{
controller.manager.memoryStorage.addItems([3,2], toSection: 0)
expect(self.controller.manager.memoryStorage.itemsInSection(0)?.count) == 2
}
func testShouldInsertTableItem()
{
controller.manager.memoryStorage.addItems([2,4,6], toSection: 0)
try! controller.manager.memoryStorage.insertItem(1, toIndexPath: indexPath(2, 0))
expect(self.controller.manager.memoryStorage.itemsInSection(0)?.count) == 4
expect(self.controller.verifyItem(1, atIndexPath: indexPath(2, 0))) == true
expect(self.controller.verifyItem(6, atIndexPath: indexPath(3, 0))) == true
}
func testReplaceItem()
{
controller.manager.memoryStorage.addItems([1,3], toSection: 0)
controller.manager.memoryStorage.addItems([4,6], toSection: 1)
try! controller.manager.memoryStorage.replaceItem(3, replacingItem: 2)
try! controller.manager.memoryStorage.replaceItem(4, replacingItem: 5)
expect(self.controller.manager.memoryStorage.itemsInSection(0)?.count) == 2
expect(self.controller.manager.memoryStorage.itemsInSection(1)?.count) == 2
expect(self.controller.verifyItem(2, atIndexPath: indexPath(1, 0))) == true
expect(self.controller.verifyItem(5, atIndexPath: indexPath(0, 1))) == true
}
func testRemoveItem()
{
controller.manager.memoryStorage.addItems([1,3,2,4], toSection: 0)
controller.manager.memoryStorage.removeItems([1,4,3,5])
expect(self.controller.manager.memoryStorage.itemsInSection(0)?.count) == 1
expect(self.controller.verifyItem(2, atIndexPath: indexPath(0, 0))) == true
}
func testRemoveItems()
{
controller.manager.memoryStorage.addItems([1,2,3], toSection: 0)
controller.manager.memoryStorage.removeAllTableItems()
expect(self.controller.manager.memoryStorage.itemsInSection(0)?.count) == 0
}
func testMovingItems()
{
controller.manager.memoryStorage.addItems([1,2,3], toSection: 0)
controller.manager.memoryStorage.moveTableItemAtIndexPath(indexPath(0, 0), toIndexPath: indexPath(2, 0))
expect(self.controller.verifySection([2,3,1], withSectionNumber: 0)) == true
}
func testShouldNotCrashWhenMovingToBadRow()
{
controller.manager.memoryStorage.addItem([1,2,3], toSection: 0)
controller.manager.memoryStorage.moveTableItemAtIndexPath(indexPath(0, 0), toIndexPath: indexPath(2, 1))
}
func testShouldNotCrashWhenMovingFromBadRow()
{
controller.manager.memoryStorage.addItem([1,2,3], toSection: 0)
controller.manager.memoryStorage.moveTableItemAtIndexPath(indexPath(0, 1), toIndexPath: indexPath(0, 0))
}
func testShouldMoveSections()
{
controller.manager.memoryStorage.addItem(1, toSection: 0)
controller.manager.memoryStorage.addItem(2, toSection: 1)
controller.manager.memoryStorage.addItem(3, toSection: 2)
controller.manager.memoryStorage.moveTableViewSection(0, toSection: 1)
expect(self.controller.verifySection([2], withSectionNumber: 0)) == true
expect(self.controller.verifySection([1], withSectionNumber: 1)) == true
expect(self.controller.verifySection([3], withSectionNumber: 2)) == true
}
func testShouldDeleteSections()
{
controller.manager.memoryStorage.addItem(0, toSection: 0)
controller.manager.memoryStorage.addItem(1, toSection: 1)
controller.manager.memoryStorage.addItem(2, toSection: 2)
controller.manager.memoryStorage.deleteSections(NSIndexSet(index: 1))
expect(self.controller.manager.memoryStorage.sections.count) == 2
expect(self.controller.verifySection([2], withSectionNumber: 1))
}
func testShouldShowTitlesOnEmptySection()
{
controller.manager.memoryStorage.setSectionHeaderModels(["Foo"])
controller.manager.configuration.displayHeaderOnEmptySection = false
expect(self.controller.manager.tableView(self.controller.tableView, titleForHeaderInSection: 0)).to(beNil())
}
func testShouldShowTitleOnEmptySectionFooter()
{
controller.manager.memoryStorage.setSectionFooterModels(["Foo"])
controller.manager.configuration.displayFooterOnEmptySection = false
expect(self.controller.manager.tableView(self.controller.tableView, titleForFooterInSection: 0)).to(beNil())
}
func testShouldShowViewHeaderOnEmptySEction()
{
controller.manager.registerHeaderClass(NibView)
controller.manager.configuration.displayHeaderOnEmptySection = false
controller.manager.memoryStorage.setSectionHeaderModels([1])
expect(self.controller.manager.tableView(self.controller.tableView, viewForHeaderInSection: 0)).to(beNil())
}
func testShouldShowViewFooterOnEmptySection()
{
controller.manager.registerFooterClass(NibView)
controller.manager.configuration.displayFooterOnEmptySection = false
controller.manager.memoryStorage.setSectionFooterModels([1])
expect(self.controller.manager.tableView(self.controller.tableView, viewForFooterInSection: 0)).to(beNil())
}
func testSupplementaryKindsShouldBeSet()
{
expect(self.controller.manager.memoryStorage.supplementaryHeaderKind) == DTTableViewElementSectionHeader
expect(self.controller.manager.memoryStorage.supplementaryFooterKind) == DTTableViewElementSectionFooter
}
func testHeaderViewShouldBeCreated()
{
controller.manager.registerHeaderClass(NibHeaderFooterView)
controller.manager.memoryStorage.setSectionHeaderModels([1])
expect(self.controller.manager.tableView(self.controller.tableView, viewForHeaderInSection: 0)).to(beAKindOf(NibHeaderFooterView))
}
func testFooterViewShouldBeCreated()
{
controller.manager.registerFooterClass(NibHeaderFooterView)
controller.manager.memoryStorage.setSectionFooterModels([1])
expect(self.controller.manager.tableView(self.controller.tableView, viewForFooterInSection: 0)).to(beAKindOf(NibHeaderFooterView))
}
func testHeaderViewShouldBeCreatedFromXib()
{
controller.manager.registerNibNamed("NibHeaderFooterView", forHeaderClass: NibHeaderFooterView.self)
controller.manager.memoryStorage.setSectionHeaderModels([1])
expect(self.controller.manager.tableView(self.controller.tableView, viewForHeaderInSection: 0)).to(beAKindOf(NibHeaderFooterView))
}
func testFooterViewShouldBeCreatedFromXib()
{
controller.manager.registerNibNamed("NibHeaderFooterView", forFooterClass: NibHeaderFooterView.self)
controller.manager.memoryStorage.setSectionFooterModels([1])
expect(self.controller.manager.tableView(self.controller.tableView, viewForFooterInSection: 0)).to(beAKindOf(NibHeaderFooterView))
}
func testObjectForCellAtIndexPathGenericConversion()
{
controller.manager.registerCellClass(NibCell)
controller.manager.memoryStorage.addItem(1, toSection: 0)
if let object = controller.manager.objectForCellClass(NibCell.self, atIndexPath: indexPath(0, 0))
{
expect(object) == 1
}
else {
XCTFail("")
}
}
func testObjectAtIndexPathGenericConversionFailsForNil()
{
controller.manager.registerCellClass(NibCell)
controller.manager.memoryStorage.addItem(1, toSection: 0)
if let _ = controller.manager.objectForCellClass(StringCell.self, atIndexPath: indexPath(0, 0))
{
XCTFail()
}
}
func testHeaderObjectForViewGenericConversion()
{
controller.manager.registerNibNamed("NibHeaderFooterView", forHeaderClass: NibHeaderFooterView.self)
controller.manager.memoryStorage.setSectionHeaderModels([1])
if let _ = controller.manager.objectForHeaderClass(NibHeaderFooterView.self, atSectionIndex: 0)
{
}
else {
XCTFail()
}
}
func testFooterObjectForViewGenericConversion()
{
controller.manager.registerNibNamed("NibHeaderFooterView", forFooterClass: NibHeaderFooterView.self)
controller.manager.memoryStorage.setSectionFooterModels([1])
if let _ = controller.manager.objectForFooterClass(NibHeaderFooterView.self, atSectionIndex: 0)
{
}
else {
XCTFail()
}
}
}
| mit | b5ef54fee8af2dfa65e217963bc08b40 | 39.756014 | 138 | 0.697386 | 4.782258 | false | true | false | false |
auermi/noted | Noted/SettingsViewController.swift | 1 | 1858 | //
// SettingsViewController.swift
// Noted
//
// Created by Michael Andrew Auer on 6/21/16.
// Copyright © 2016 Usonia LLC. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
@IBOutlet weak var signoutText: UILabel!
@IBAction func signoutButton(_ sender: AnyObject) {
let alert = UIAlertController(title: "Are you sure you want to log out?", message: "All of your notes will be deleted.", preferredStyle: UIAlertControllerStyle.alert)
let alertActionConfirm = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (UIAlertAction) in
// Hitting okay begins the logout process
let dataInterface = DataInterface()
// Delete Notes
let notes: [Note] = dataInterface.get("Note") as! [Note]
for note in notes {
dataInterface.delete(note)
}
// Delete User
let user: [User] = dataInterface.get("User") as! [User]
dataInterface.delete(user.first!)
// Move Back to Login Page
self.performSegue(withIdentifier: "signout", sender: nil)
}
let alertActionCancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel)
{
(UIAlertAction) -> Void in
}
alert.addAction(alertActionConfirm)
alert.addAction(alertActionCancel)
self.present(alert, animated: true)
{
() -> Void in
}
}
override func viewDidLoad() {
super.viewDidLoad()
let dataInterface = DataInterface();
let user: [User] = dataInterface.get("User") as! [User];
signoutText.text = "Signed in as \(user.first!.userName!)";
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | f97859ddd700a5c22db73e2f89d976ba | 33.388889 | 174 | 0.610662 | 4.713198 | false | false | false | false |
Palleas/Rewatch | Rewatch/Episode/EpisodeImageContainerView.swift | 2 | 719 | //
// EpisodeImageContainerView.swift
// Rewatch
//
// Created by Romain Pouclet on 2015-11-25.
// Copyright © 2015 Perfectly-Cooked. All rights reserved.
//
import UIKit
class EpisodeImageContainerView: UIView {
@IBOutlet var imageView: UIImageView!
@IBOutlet var bnwImageView: UIImageView!
override func layoutSubviews() {
super.layoutSubviews()
let viewRatio = frame.height / frame.width
let size = CGSize(width: frame.width, height: frame.width * viewRatio)
let diffX = (frame.width - size.width) / 2
imageView.frame = CGRect(origin: CGPoint(x: diffX, y: 0), size: size)
bnwImageView.frame = imageView.frame
}
}
| mit | a65f999bc90ce6977dff53782b476f42 | 26.615385 | 78 | 0.647632 | 4.056497 | false | false | false | false |
frodoking/GithubIOSClient | Github/Core/Common/Key.swift | 1 | 989 | //
// Key.swift
// Github
//
// Created by frodo on 15/10/24.
// Copyright © 2015年 frodo. All rights reserved.
//
import Foundation
public struct Key {
public struct User {
static let CurrentLogin = "currentLogin"
static let CurrentAvatarUrl = "currentAvatarUrl"
}
public struct SegueIdentifier {
static let Country = "Country"
static let City = "City"
}
public struct LanguageFrom {
static let User = "Language From User"
static let Repository = "Language From Repository"
static let Trending = "Repository"
}
public struct CellReuseIdentifier {
static let UserCell = "UserCell"
static let DiscoveryCell = "DiscoveryCell"
static let RepositoryCell = "RepositoryCell"
static let MoreCell = "MoreCell"
static let LanguageCell = "LanguageCell"
static let CountyCell = "CountyCell"
static let CityCell = "CityCell"
}
}
| apache-2.0 | babfcd02e7ea887aa35e824c5afca4ff | 25.648649 | 58 | 0.629817 | 4.586047 | false | false | false | false |
LeonClover/DouYu | DouYuZB/DouYuZB/Classes/Home/View/AmuseView/AmuseMenuViewCell.swift | 1 | 1526 | //
// AmuseMenuViewCell.swift
// DouYuZB
//
// Created by Leon on 2017/8/28.
// Copyright © 2017年 pingan. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
class AmuseMenuViewCell: UICollectionViewCell {
//MARK: 控件属性
@IBOutlet weak var collectionView: UICollectionView!
var group: [AnchorGroup]?{
didSet{
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let itemW = collectionView.bounds.width / 4
let itemH = collectionView.bounds.height / 2
layout.itemSize = CGSize(width: itemW, height: itemH)
}
}
extension AmuseMenuViewCell: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return group!.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
cell.lineView.isHidden = true
cell.baseGame = group![indexPath.item]
return cell
}
}
| mit | 6feb22a0b3ee703fc4883a863ad7b81a | 31.234043 | 126 | 0.69703 | 5.242215 | false | false | false | false |
sbcmadn1/swift | swiftweibo05/GZWeibo05/Class/Module/Home/View/Cell/CZStatusCell.swift | 1 | 4831 | //
// CZStatusCell.swift
// GZWeibo05
//
// Created by zhangping on 15/10/31.
// Copyright © 2015年 zhangping. All rights reserved.
//
import UIKit
let StatusCellMargin: CGFloat = 8
// cell父类
class CZStatusCell: UITableViewCell {
// MARK: - 属性
/// 配图宽度约束
var pictureViewWidthCon: NSLayoutConstraint?
/// 配图高度约束
var pictureViewHeightCon: NSLayoutConstraint?
/// 微博模型
var status: CZStatus? {
didSet {
// print("\(status?.idstr),父类监视器")
// 将模型赋值给 topView
topView.status = status
// 将模型赋值给配图视图
pictureView.status = status
// 调用模型的计算尺寸的方法
let size = pictureView.calcViewSize()
// print("配图size: \(size)")
// 重新设置配图的宽高约束
pictureViewWidthCon?.constant = size.width
pictureViewHeightCon?.constant = size.height
// 设置微博内容
contentLabel.text = status?.text
// TODO: 测试配图的高度
// 测试配图的高度,行数是随机不固定的
// let row = arc4random_uniform(1000) % 4
// pictureViewHeightCon?.constant = CGFloat(row) * 90
}
}
// 设置cell的模型,cell会根据模型,从新设置内容,更新约束.获取子控件的最大Y值
// 返回cell的高度
func rowHeight(status: CZStatus) -> CGFloat {
// 设置cell的模型
self.status = status
// 更新约束
layoutIfNeeded()
// 获取子控件的最大Y值
let maxY = CGRectGetMaxY(bottomView.frame)
return maxY
}
// MARK: - 构造函数
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
prepareUI()
}
// MARK: - 准备UI
func prepareUI() {
// 添加子控件
contentView.addSubview(topView)
contentView.addSubview(contentLabel)
contentView.addSubview(pictureView)
contentView.addSubview(bottomView)
// 添加约束
topView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: contentView, size: CGSize(width: UIScreen.width(), height: 53))
// 微博内容
contentLabel.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: topView, size: nil, offset: CGPoint(x: StatusCellMargin, y: StatusCellMargin))
// 设置宽度
contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: UIScreen.width() - 2 * StatusCellMargin))
// // 微博配图
// 因为转发微博需要设置配图约束,不能再这里设置配图的约束,需要在创建一个cell继承CZStatusCell,添加上配图的约束
// let cons = pictureView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: contentLabel, size: CGSize(width: 0, height: 0), offset: CGPoint(x: 0, y: StatusCellMargin))
//
// // 获取配图的宽高约束
// pictureViewHeightCon = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
// pictureViewWidthCon = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
// 底部视图
bottomView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: UIScreen.width(), height: 44), offset: CGPoint(x: -StatusCellMargin, y: StatusCellMargin))
// 添加contentView底部和bottomView的底部重合
// contentView.addConstraint(NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: bottomView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
}
// MARK: - 懒加载
/// 顶部视图
private lazy var topView: CZStatusTopView = CZStatusTopView()
/// 微博内容
lazy var contentLabel: UILabel = {
let label = UILabel(fonsize: 16, textColor: UIColor.blackColor())
// 显示多行
label.numberOfLines = 0
return label
}()
/// 微博配图
lazy var pictureView: CZStatusPictureView = CZStatusPictureView()
/// 底部视图
lazy var bottomView: CZStatusBottomView = CZStatusBottomView()
}
| mit | 34bb61622b0c21e0f74e22d024a03ef6 | 32.348837 | 268 | 0.616457 | 4.518908 | false | false | false | false |
ScottLegrove/HoneyDueIOS | Honey Due/LoginViewController.swift | 1 | 2659 | //
// LoginViewController.swift
// Honey Due
//
// Created by Tech on 2016-04-13.
// Copyright © 2016 Scott Legrove. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController{
@IBOutlet weak var inputUsername: UITextField!
@IBOutlet weak var inputPassword: UITextField!
var uPrefs:NSUserDefaults?;
@IBAction func onClick(sender: UIButton) {
if sender.tag == 0{
if !inputPassword.text!.isEmpty && !inputUsername.text!.isEmpty{
let uName = inputUsername.text!;
let uPass = inputPassword.text!;
let validLogin = UserHelper.Login(uName, uPass: uPass);
if validLogin != nil {
uPrefs!.setValue(validLogin, forKey: "userToken")
let didSave = uPrefs!.synchronize()
if !didSave{
let alertController = UIAlertController(title: "Failed Login", message: "Please re-enter credentials", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default){
(_) in
}
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true){}
}
self.performSegueWithIdentifier("segueToLists", sender: self)
return
}
}
}
let alertController = UIAlertController(title: "Invalid Login", message: "Please re-enter credentials", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default){
(_) in
}
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true){ }
}
override func viewDidLoad() {
super.viewDidLoad()
uPrefs = NSUserDefaults.standardUserDefaults()
// Clear Token
}
override func viewDidAppear(animated: Bool) {
let token = uPrefs!.stringForKey("userToken");
if token != nil {
self.performSegueWithIdentifier("segueToLists", sender: self)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
} | mit | dc51a6ec50a4e1383ed69f661a3d98cd | 30.654762 | 150 | 0.525207 | 5.933036 | false | false | false | false |
coodly/SlimTimerAPI | Sources/LoginRequest.swift | 1 | 2308 | /*
* Copyright 2017 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import SWXMLHash
public enum LoginResult {
case success(Int, String)
case failure(SlimTimerError)
}
private let LoginPath = "/users/token"
internal class LoginRequest: NetworkRequest<LoginResponse> {
private let email: String
private let password: String
var resultHandler: ((LoginResult) -> ())!
init(email: String, password: String) {
self.email = email
self.password = password
}
override func performRequest() {
POST(LoginPath, body: LoginRequestBody(email: email, password: password))
}
override func handle(result: NetworkResult<LoginResponse>) {
if let error = result.error {
resultHandler(.failure(error))
return
}
guard let login = result.value else {
resultHandler(.failure(.unknown))
return
}
resultHandler(.success(login.userId, login.token))
}
}
private typealias Dependencies = APIKeyConsumer
internal class LoginRequestBody: RequestBody, Dependencies {
var apiKey: String!
private let user: User
init(email: String, password: String) {
user = User(email: email, password: password)
}
}
internal struct LoginResponse: RemoteModel {
let userId: Int
let token: String
init?(xml: XMLIndexer) {
let response = xml["response"]
guard let token = response["access-token"].element?.text else {
return nil
}
guard let string = response["user-id"].element?.text, let user = Int(string) else {
return nil
}
self.token = token
self.userId = user
}
}
| apache-2.0 | 3850eadc54a94617fec6f582023c29f3 | 26.47619 | 91 | 0.643414 | 4.579365 | false | false | false | false |
blokadaorg/blokada | ios/App/UI/Tab/TabItemView.swift | 1 | 3283 | //
// This file is part of Blokada.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
// Copyright © 2020 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import SwiftUI
struct TabItemView: View {
@ObservedObject var vm = ViewModels.tab
let id: Tab
let icon: String
let text: String
let badge: Int?
let onTap: (Tab) -> Void
var body: some View {
ZStack(alignment: .topTrailing) {
Button(action: {
self.onTap(self.id)
}) {
VStack {
ZStack {
if self.icon == "blokada" {
Rectangle()
.fill(self.vm.activeTab == self.id ? Color.cAccent : Color.cPrimary)
.frame(width: 20, height: 20)
.mask(
Image(Image.iBlokada)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20)
)
} else {
Image(systemName: self.icon)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20)
}
}
.scaleEffect(self.vm.activeTab == self.id ? 1.1 : 1.0)
.animation(.easeIn)
Text(self.text)
.font(.system(size: 12))
.offset(y: -2)
}
.foregroundColor(self.vm.activeTab == self.id ? Color.cAccent : .primary)
if self.badge != nil && self.badge! > 0 {
BadgeView(number: self.badge!)
.offset(y: -8)
}
}
}
.frame(minWidth: 74)
.accessibilityLabel(Text(text))
}
}
struct TabItemView_Previews: PreviewProvider {
static var previews: some View {
Group {
TabItemView(id: .Settings, icon: "tray.and.arrow.down", text: "Inbox", badge: nil, onTap: { _ in })
.previewLayout(.sizeThatFits)
TabItemView(id: .Settings, icon: "tray.and.arrow.down", text: "Inbox", badge: nil, onTap: { _ in })
.previewLayout(.sizeThatFits)
.environment(\.sizeCategory, .extraExtraExtraLarge)
.environment(\.colorScheme, .dark)
.background(Color.black)
TabItemView(id: .Home, icon: "blokada", text: "Home", badge: nil, onTap: { _ in })
.previewLayout(.sizeThatFits)
TabItemView(id: .Home, icon: "blokada", text: "Home", badge: nil, onTap: { _ in })
.previewLayout(.sizeThatFits)
TabItemView(id: .Settings, icon: "cube.box", text: "Packs", badge: 69, onTap: { _ in })
.previewLayout(.sizeThatFits)
}
.padding()
}
}
| mpl-2.0 | 0bb37a0987d8e1e41c061af6a870ee75 | 36.295455 | 111 | 0.456734 | 4.545706 | false | false | false | false |
adrfer/swift | test/SILGen/generic_signatures.swift | 12 | 1785 | // RUN: %target-swift-frontend -emit-silgen -parse-stdlib %s
protocol P {
typealias Assoc
}
protocol Q {
typealias Assoc1
typealias Assoc2
}
struct G<T> {}
class C {}
func a<T>(x: T) {}
func b<T: P>(x: G<T>, y: T.Assoc) {}
func c<T where T: P>(x: T, y: T.Assoc) {}
func d<T: P, U: protocol<P, Q>>(x: T, y: U) {}
func e<T, U where T: P, U: P, U: Q>(x: T, y: U) {}
// FIXME: Same-type constraints expose a typechecker bug.
// <rdar://problem/15730168>
func f<T: Q where T.Assoc1 == T.Assoc2>(x: T) {}
func g<T where T: Q, T.Assoc1 == T.Assoc2>(x: T) {}
func h<T: P, U where T.Assoc == U>(x: T) {}
func i<T: P where T.Assoc: Q, T.Assoc.Assoc1 == T.Assoc.Assoc2>(x: T) {}
func j<T: C>(_: T) {}
func k<T where T: C>(_: T) {}
func l<T: C where T: P>(_: T) {}
func m<T: P where T.Assoc: C>(_: T) {}
struct Foo<V> {
func z() {}
func a<T>(x: T) {}
func b<T: P>(x: G<T>, y: T.Assoc) {}
func c<T where T: P>(x: T, y: T.Assoc) {}
func d<T: P, U: protocol<P, Q>>(x: T, y: U) {}
func e<T, U where T: P, U: P, U: Q>(x: T, y: U) {}
func f<T: Q where T.Assoc1 == T.Assoc2>(x: T) {}
func g<T where T: Q, T.Assoc1 == T.Assoc2>(x: T) {}
func h<T: P, U where T.Assoc == U>(x: T) {}
func i<T: P where T.Assoc: Q, T.Assoc.Assoc1 == T.Assoc.Assoc2>(x: T) {}
func j<T: C>(_: T) {}
func k<T where T: C>(_: T) {}
func l<T: C where T: P>(_: T) {}
func m<T: P where T.Assoc: C>(_: T) {}
}
// Test that we handle interface type lowering when accessing a dependent
// member of a dependent member that substitutes to a type parameter.
// <rdar://problem/16257259>
protocol Fooable {
typealias Foo
}
protocol Barrable {
typealias Bar: Fooable
func bar(_: Bar) -> Bar.Foo
}
struct FooBar<T: Fooable>: Barrable {
typealias Bar = T
func bar(_ x: T) -> T.Foo { }
}
| apache-2.0 | 4ea16cbc1e6c87345080bc7833e05b23 | 25.641791 | 74 | 0.565266 | 2.438525 | false | false | false | false |
novacom34/StaticLib | StaticLib/Classes/ObservableObject.swift | 1 | 2355 | //
// Base.swift
// AppBasicLibrary
//
// Created by Roma Novakov on 04.05.16.
// Copyright © 2016 novacom. All rights reserved.
//
import Foundation
//MARK: - ObservableModelProtocol Protocol
public protocol ObservableProtocol {
func registerObserver(_ observer: NSObject)
func unregisterObserver(_ observer: NSObject)
func notifyObserversWithSelector(_ selector: Selector, andObject object: Any?)
func notifyObserversInMainThreadWithSelector(_ selector: Selector, andObject object: Any?)
}
//MARK: - ObservableObject
//
//
// ObservableObject it's base class of all Observable Models in app.
//
//
open class ObservableObject : NSObject, ObservableProtocol {
private(set) open var observerSet : NSMutableSet = NSMutableSet()
lazy private(set) var safeQueue: DispatchQueue = {
let queue = DispatchQueue(label: "com.model.safeAccessThread", attributes: [])
return queue
}()
open func registerObserver(_ observer: NSObject) {
let weakLink = WeakLink(target: observer)
self.observerSet.add(weakLink)
}
open func unregisterObserver(_ observer: NSObject) {
let weakLink = WeakLink(target: observer)
self.observerSet.remove(weakLink)
}
//MARK: - Notify Observers functions
open func notifyObserversWithSelector(_ selector: Selector, andObject object: Any?) {
let observersSetCopy = self.observerSet.copy() as! NSSet
for obj in observersSetCopy {
let weakLink = obj as! WeakLink
if let isResponse = weakLink.target?.responds(to: selector) {
if isResponse {
let observer = weakLink.target
observer?.perform(selector,
with: self,
with: object)
}
}
}
}
open func notifyObserversInMainThreadWithSelector(_ selector: Selector, andObject object: Any?) {
if Thread.isMainThread {
self.notifyObserversWithSelector(selector, andObject: object)
} else {
DispatchQueue.main.async(execute: {[weak self] in
self?.notifyObserversWithSelector(selector, andObject: object)
})
}
}
//MARK: -
}
| mit | 36fb90b71046395ca08d74f379f7a1da | 26.694118 | 101 | 0.615548 | 4.784553 | false | false | false | false |
AndreyZarembo/EasyDi | Tests/Test_Context.swift | 1 | 1121 | //
// Test_Context.swift
// EasyDi
//
// Created by Andrey Zarembo
//
import Foundation
import XCTest
import EasyDi
class Test_Context: XCTestCase {
func testDefaultContext() {
class TestAssembly: Assembly { }
let assemblyInstance1 = TestAssembly.instance()
let assemblyInstance2 = TestAssembly.instance()
XCTAssertTrue(assemblyInstance1 === assemblyInstance2)
}
func testSameContext() {
class TestAssembly: Assembly { }
let context: DIContext = DIContext()
let assemblyInstance1 = TestAssembly.instance(from: context)
let assemblyInstance2 = TestAssembly.instance(from: context)
XCTAssertTrue(assemblyInstance1 === assemblyInstance2)
}
func testDifferentContexts() {
class TestAssembly: Assembly { }
let assemblyInstance1 = TestAssembly.instance()
let context: DIContext = DIContext()
let assemblyInstance2 = TestAssembly.instance(from: context)
XCTAssertFalse(assemblyInstance1 === assemblyInstance2)
}
}
| mit | aa1ee0a185e3cc0c8d3dd6dc8eb4da78 | 25.690476 | 68 | 0.644068 | 4.831897 | false | true | false | false |
dfsilva/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Managed Runtime/Navigations.swift | 3 | 2517 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
public extension UIViewController {
public func navigateDetail(_ controller: UIViewController) {
if (AADevice.isiPad) {
let split = UIApplication.shared.keyWindow?.rootViewController as! UISplitViewController
let master = split.viewControllers[0]
let detail = AANavigationController()
detail.viewControllers = [controller]
split.viewControllers = [master, detail]
} else {
let tabBar = UIApplication.shared.keyWindow?.rootViewController as! UITabBarController
controller.hidesBottomBarWhenPushed = true
(tabBar.selectedViewController as! AANavigationController).pushViewController(controller, animated: true)
}
}
}
public extension UIViewController {
public func navigateNext(_ controller: UIViewController, removeCurrent: Bool = false) {
if let aaC = controller as? AAViewController, let aaSelf = self as? AAViewController {
aaC.popover = aaSelf.popover
}
controller.hidesBottomBarWhenPushed = true
if (!removeCurrent) {
self.navigationController!.pushViewController(controller, animated: true);
} else {
var nControllers = [UIViewController]()
var oldControllers = self.navigationController!.viewControllers
if (oldControllers.count >= 2) {
for i in 0...(oldControllers.count - 2) {
nControllers.append(oldControllers[i])
}
}
nControllers.append(controller)
self.navigationController!.setViewControllers(nControllers, animated: true);
}
}
public func navigateBack() {
if (self.navigationController!.viewControllers.last != nil) {
if (self.navigationController!.viewControllers.last! == self) {
self.navigationController!.popViewController(animated: true)
} else {
}
} else {
var nControllers = [UIViewController]()
var oldControllers = self.navigationController!.viewControllers
for i in 0..<oldControllers.count {
if (oldControllers[i] != self) {
nControllers.append(oldControllers[i])
}
}
self.navigationController!.setViewControllers(nControllers, animated: true);
}
}
}
| agpl-3.0 | 146098ecb488d5a38ea11f77201bc865 | 38.952381 | 117 | 0.615415 | 5.580931 | false | false | false | false |
czak/quicksend | Quicksend/Uploader.swift | 1 | 5865 | //
// Uploader.swift
// Quicksend
//
// Created by Łukasz Adamczak on 19.07.2015.
// Copyright (c) 2015 Łukasz Adamczak. All rights reserved.
//
import Foundation
import Alamofire
class Uploader {
enum UploadStatus {
case Success(NSURL)
case Failure(String)
}
// Zmienne konfiguracyjne AWSa
var awsAccessKeyId: String! {
return NSUserDefaults.standardUserDefaults().stringForKey("awsAccessKeyId")
}
var awsSecretAccessKey: String! {
return NSUserDefaults.standardUserDefaults().stringForKey("awsSecretAccessKey")
}
var awsBucketName: String! {
return NSUserDefaults.standardUserDefaults().stringForKey("awsBucketName")
}
var awsRegion: String! {
return NSUserDefaults.standardUserDefaults().stringForKey("awsRegion")
}
func mimetypeForFile(url: NSURL) -> String {
let ext = url.pathExtension
let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext!, nil)!.takeRetainedValue()
if let mimeType = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimeType as String
}
else {
return "binary/octet-stream"
}
}
func sizeForFile(url: NSURL) -> Int {
let manager = NSFileManager.defaultManager()
let attrs = try! manager.attributesOfItemAtPath(url.path!)
return attrs[NSFileSize] as! Int
}
func uploadFile(fileURL: NSURL, completionHandler: (UploadStatus) -> Void) {
guard (awsAccessKeyId != nil && awsSecretAccessKey != nil && awsBucketName != nil && awsRegion != nil) else {
completionHandler(.Failure("Your AWS account has not been configured. Open Quicksend preferences to set up your connection details."))
return
}
// 1. Canonical request
let fileName = fileURL.lastPathComponent!.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet())!
let fileData = NSData(contentsOfURL: fileURL)!
let fileHash = sha256_hexdigest(fileData)
let date = NSDate()
let mimetype = mimetypeForFile(fileURL)
let creq = "PUT\n/\(fileName)\n\ncontent-type:\(mimetype)\nhost:\(awsBucketName).s3.amazonaws.com\nx-amz-acl:public-read\nx-amz-content-sha256:\(fileHash)\nx-amz-date:\(date.iso8601timestamp())\n\ncontent-type;host;x-amz-acl;x-amz-content-sha256;x-amz-date\n\(fileHash)"
debugPrint("--- CREQ ---")
print(creq)
print("------------")
// 2. String to sign
let creqHash = sha256_hexdigest(creq.dataUsingEncoding(NSUTF8StringEncoding)!)
let sts = "AWS4-HMAC-SHA256\n\(date.iso8601timestamp())\n\(date.iso8601datestamp())/\(awsRegion)/s3/aws4_request\n\(creqHash)"
print("--- STS ---")
print(sts)
print("-----------")
// 3. Signing key
let signingKey = awsSigningKey(key: awsSecretAccessKey,
date: date.iso8601datestamp(),
region: awsRegion,
service: "s3")
print(signingKey)
// 4. Sygnatura
let signature = hmac_sha256_hexdigest(key: signingKey, data: sts.dataUsingEncoding(NSUTF8StringEncoding)!)
print(signature)
// 5. Wykonanie requestu
let headers = [
"Authorization": "AWS4-HMAC-SHA256 Credential=\(awsAccessKeyId)/\(date.iso8601datestamp())/\(awsRegion)/s3/aws4_request, SignedHeaders=content-type;host;x-amz-acl;x-amz-content-sha256;x-amz-date, Signature=\(signature)",
"Content-Type": mimetype,
"x-amz-acl": "public-read",
"x-amz-content-sha256": fileHash,
"x-amz-date": date.iso8601timestamp()
]
let request = Alamofire.upload(.PUT, "https://\(awsBucketName).s3.amazonaws.com/\(fileName)", headers: headers, file: fileURL)
request.response { request, response, data, error in
var status: UploadStatus?
if let response = response {
switch response.statusCode {
case 200:
status = .Success(response.URL!)
case 403:
var message: String = "AWS Authentication failed. Please double-check your access keys and bucket data."
if let doc = try? NSXMLDocument(data: data!, options: 0) {
if let node = try? doc.nodesForXPath("//Message") {
if let awsMessage = node.first?.stringValue {
message += "\n\nError message received: \"\(awsMessage)\""
}
}
}
status = .Failure(message)
default:
var message: String = "Failed with status \(response.statusCode)"
// FIXME: Brzydka duplikacja tego parsowania errora
if let doc = try? NSXMLDocument(data: data!, options: 0) {
if let node = try? doc.nodesForXPath("//Message") {
if let awsMessage = node.first?.stringValue {
message += "\n\nError message received: \"\(awsMessage)\""
}
}
}
status = .Failure(message)
}
}
else {
status = .Failure("Unable to reach the S3 server. Please verify your internet connection.")
}
completionHandler(status!)
}
}
} | gpl-3.0 | d043e28bc9d814354d3c16e7bb65d409 | 38.621622 | 278 | 0.562511 | 4.902174 | false | false | false | false |
FXSolutions/FXHydra | VideoCutter.swift | 3 | 2523 | //
// VideoCutter.swift
// VideoSplash
//
// Created by Toygar Dündaralp on 8/3/15.
// Copyright (c) 2015 Toygar Dündaralp. All rights reserved.
//
import UIKit
import AVFoundation
extension String {
var convert: NSString { return (self as NSString) }
}
public class VideoCutter: NSObject {
/**
Block based method for crop video url
@param videoUrl Video url
@param startTime The starting point of the video segments
@param duration Total time, video length
*/
public func cropVideoWithUrl(videoUrl url: NSURL, startTime: CGFloat, duration: CGFloat, completion: ((videoPath: NSURL?, error: NSError?) -> Void)?) {
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
let asset = AVURLAsset(URL: url, options: nil)
let exportSession = AVAssetExportSession(asset: asset, presetName: "AVAssetExportPresetHighestQuality")
let paths: NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
var outputURL = paths.objectAtIndex(0) as! String
let manager = NSFileManager.defaultManager()
do {
try manager.createDirectoryAtPath(outputURL, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
outputURL = outputURL.convert.stringByAppendingPathComponent("output.mp4")
do {
try manager.removeItemAtPath(outputURL)
} catch _ {
}
if let exportSession = exportSession as AVAssetExportSession? {
exportSession.outputURL = NSURL(fileURLWithPath: outputURL)
exportSession.shouldOptimizeForNetworkUse = true
exportSession.outputFileType = AVFileTypeMPEG4
let start = CMTimeMakeWithSeconds(Float64(startTime), 600)
let duration = CMTimeMakeWithSeconds(Float64(duration), 600)
let range = CMTimeRangeMake(start, duration)
exportSession.timeRange = range
exportSession.exportAsynchronouslyWithCompletionHandler { () -> Void in
switch exportSession.status {
case AVAssetExportSessionStatus.Completed:
completion?(videoPath: exportSession.outputURL, error: nil)
case AVAssetExportSessionStatus.Failed:
print("Failed: \(exportSession.error)")
case AVAssetExportSessionStatus.Cancelled:
print("Failed: \(exportSession.error)")
default:
print("default case")
}
}
}
dispatch_async(dispatch_get_main_queue()) {
}
}
}
}
| mit | 91ebb78078820ff3d35666a405b3cc1c | 36.073529 | 153 | 0.689409 | 5.031936 | false | false | false | false |
icoderRo/SMAnimation | SMDemo/iOS-MVX/MVP/MVPVC.swift | 2 | 879 | //
// MVPVC.swift
// iOS-MVX
//
// Created by simon on 2017/3/2.
// Copyright © 2017年 simon. All rights reserved.
//
import UIKit
class MVPVC: UIViewController {
fileprivate lazy var mvpView: MVPView = {[unowned self] in
let mvpView = MVPView(frame: self.view.bounds)
self.view.addSubview(mvpView)
return mvpView
}()
fileprivate lazy var mvpModel: MVPModel = {
let mvpModel = MVPModel()
return mvpModel
}()
fileprivate lazy var presenter: Presenter = {
let presenter = Presenter()
return presenter
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
title = "Passive MVP"
presenter.mvpView = mvpView
presenter.mvpModel = mvpModel
presenter.setName()
}
}
| mit | 8beffbca85d143e198a8e5ece21c2980 | 20.9 | 62 | 0.583333 | 4.055556 | false | false | false | false |
fantast1k/Swiftent | Swiftent/Swiftent/Source/UIKit/UIButtonContent.swift | 1 | 1686 | //
// UIButtonContent.swift
// Swiftent
//
// Created by Dmitry Fa[n]tastik on 18/07/2016.
// Copyright © 2016 Fantastik Solution. All rights reserved.
//
import Foundation
public struct UIButtonContent {
let normal : UIButtonStateContent?
let highlighted : UIButtonStateContent?
let disabled : UIButtonStateContent?
let selected : UIButtonStateContent?
public init(normal: UIButtonStateContent?,
highlighted: UIButtonStateContent?,
disabled: UIButtonStateContent?,
selected: UIButtonStateContent?) {
self.normal = normal
self.highlighted = highlighted
self.disabled = disabled
self.selected = selected
}
public init(normal: UIButtonStateContent?) {
self.normal = normal
self.highlighted = nil
self.disabled = nil
self.selected = nil
}
public init(normal: UIButtonStateContent?, selected: UIButtonStateContent?) {
self.normal = normal
self.selected = selected
self.disabled = nil
self.highlighted = nil
}
}
public struct UIButtonStateContent {
let text : Text
let image : UIImage?
let titleColor : UIColor? = nil
let titleShadowColor : UIColor? = nil
let backgroundImage : UIImage? = nil
public init(text: Text, image: UIImage?) {
self.text = text
self.image = image
}
public init(text: Text) {
self.text = text
self.image = nil
}
public init(image: UIImage?) {
self.text = Text.Raw(nil)
self.image = image
}
public static let None = UIButtonStateContent(text: Text.Raw(nil), image: nil)
}
| gpl-3.0 | f10743aa43172606108a1d3bab0b6a0b | 24.530303 | 82 | 0.632641 | 4.410995 | false | false | false | false |
imsz5460/DouYu | DYZB/DYZB/Classes/Tools/Extensions/NetworkTools.swift | 1 | 1095 | //
// NetworkTools.swift
// DYZB
//
// Created by shizhi on 17/2/26.
// Copyright © 2017年 shizhi. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case GET
case POST
}
class NetworkTools {
}
extension NetworkTools {
class func requestDate(method: MethodType, URLString: URLStringConvertible, parameters: [String : AnyObject]?, finishedBlock:(result: AnyObject) -> ()) {
let method = method == .GET ? Method.GET : Method.POST
Alamofire.request(method, URLString, parameters: parameters).responseJSON { (response) in
guard let result = response.result.value else {
print(response.result.error)
return
}
finishedBlock(result: result)
}
}
// Alamofire.request(method, URLString, parameters: parameters).responseJSON { (response) in
// // 3.获取结果
// guard let result = response.result.value else {
// print(response.result.error)
// return
// }
}
| mit | b044b83bd83efcbb7b3bce1d6232eda9 | 20.254902 | 157 | 0.588561 | 4.370968 | false | false | false | false |
broccolii/SingleBarNavigationController | SingleBarNavigationController/SingleBarNavigationController/Resouce/Extension.swift | 1 | 3498 | //
// Extension.swift
// SingleBarNavigationController
//
// Created by Broccoli on 2016/10/27.
// Copyright © 2016年 broccoliii. All rights reserved.
//
import UIKit
extension Array {
func any(_ condition: (Element) -> Bool) -> Bool {
for element in self {
if condition(element) {
return true
}
}
return false
}
}
fileprivate var kInteractivePopGestureKey = "kInteractivePopGestureKey"
extension UIViewController {
public var exclusiveNavigationController: ExclusiveNavigationController? {
var wrapperViewController: UIViewController? = self
while (wrapperViewController as? ExclusiveNavigationController) == nil && wrapperViewController != nil {
wrapperViewController = wrapperViewController?.navigationController
}
return wrapperViewController as? ExclusiveNavigationController
}
@IBInspectable public var disableInteractivePopGesture: Bool {
get {
guard let disableInteractivePopGesture = getAssociatedObject(&kInteractivePopGestureKey) else {
return false
}
return disableInteractivePopGesture as! Bool
}
set {
setAssociatedObject(newValue as AnyObject?, associativeKey: &kInteractivePopGestureKey, policy: .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public var navigationBarClass: AnyClass? {
return nil
}
open func customBackItem(withTarget target: Any, action: Selector) -> UIBarButtonItem {
let button = UIButton(type: .custom)
let arrowImage = createBackBarButtonArrowImage((self.navigationController?.navigationBar.tintColor)!, in: CGSize(width: 13, height: 21))
button.setImage(arrowImage, for: .normal)
button.contentMode = UIViewContentMode.scaleAspectFit
button.sizeToFit()
button.addTarget(target, action: action, for: .touchUpInside)
let backBarButtonItem = UIBarButtonItem(customView: button)
return backBarButtonItem
}
private func createBackBarButtonArrowImage(_ color: UIColor = UIColor(red: 0.5, green: 0.5, blue: 0.6, alpha: 0.5), in size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let context = UIGraphicsGetCurrentContext()!
let point1 = CGPoint(x: size.width - 2, y: 2)
let point2 = CGPoint(x: 2, y: size.height / 2)
let point3 = CGPoint(x: size.width - 2, y: size.height - 2)
context.beginPath()
color.set()
context.setLineWidth(2.5)
context.move(to: point1)
context.addLine(to: point2)
context.addLine(to: point3)
context.setStrokeColor(UIColor.white.cgColor)
context.strokePath()
let arrowImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return arrowImage
}
}
extension NSObject {
func setAssociatedObject(_ value: AnyObject?, associativeKey: UnsafeRawPointer, policy: objc_AssociationPolicy) {
if let valueAsAnyObject = value {
objc_setAssociatedObject(self, associativeKey, valueAsAnyObject, policy)
}
}
func getAssociatedObject(_ associativeKey: UnsafeRawPointer) -> Any? {
guard let valueAsType = objc_getAssociatedObject(self, associativeKey) else {
return nil
}
return valueAsType
}
}
| mit | 342b8209764d9485f6262b13bfe3d698 | 34.663265 | 150 | 0.657511 | 5.094752 | false | false | false | false |
saagarjha/iina | iina/JavascriptAPIPlaylist.swift | 1 | 3873 | //
// JavascriptAPIPlaylist.swift
// iina
//
// Created by Yuze Jiang on 2/20/20.
// Copyright © 2020 lhc. All rights reserved.
//
import Foundation
import JavaScriptCore
@objc protocol JavascriptAPIPlaylistExportable: JSExport {
func list() -> [[String: Any]]
func count() -> Int
func add(_ url: JSValue, _ at: Int) -> Any
func remove(_ index: JSValue) -> Any
func move(_ index: Int, _ to: Int) -> Any
func play(_ index: Int)
func playNext()
func playPrevious()
func registerMenuItemBuilder(_ builder: JSValue)
}
class JavascriptAPIPlaylist: JavascriptAPI, JavascriptAPIPlaylistExportable {
var menuItemBuilder: JSManagedValue?
private func isPlaying() -> Bool {
if player!.info.isIdle {
log("Playlist API is only available when playing files.", level: .error)
return false
}
return true
}
func list() -> [[String: Any]] {
guard isPlaying() else { return [] }
return player!.info.playlist.map {
[
"filename": $0.filename,
"title": $0.title ?? NSNull(),
"isPlaying": $0.isPlaying,
"isCurrent": $0.isCurrent
]
}
}
func count() -> Int {
return player!.info.playlist.count
}
func add(_ url: JSValue, _ at: Int = -1) -> Any {
guard isPlaying() else { return false }
let count = player!.info.playlist.count
guard at < count else {
log("playlist.add: Invalid index.", level: .error)
return false
}
if url.isArray {
if let paths = url.toArray() as? [String] {
player!.addToPlaylist(paths: paths, at: at)
return true
}
} else if url.isString {
player!.addToPlaylist(paths: [url.toString()], at: at)
return true
}
log("playlist.add: The first argument should be a string or an array of strings.", level: .error)
return false
}
func remove(_ index: JSValue) -> Any {
guard isPlaying() else { return false }
let count = player!.info.playlist.count
if index.isArray, let indices = index.toArray() as? [Int] {
guard indices.allSatisfy({ $0 >= 0 && $0 < count }) else {
log("playlist.remove: Invalid index.", level: .error)
return false
}
player!.playlistRemove(IndexSet(indices))
return true
} else if index.isNumber {
let index = Int(index.toInt32())
guard index >= 0 && index < count else {
log("playlist.remove: Invalid index.", level: .error)
return false
}
player!.playlistRemove(index)
return true
}
log("playlist.remove: The argument should be a number or an array of numbers.", level: .error)
return false
}
func move(_ index: Int, _ to: Int) -> Any {
guard isPlaying() else { return false }
let count = player!.info.playlist.count
guard index >= 0 && index < count && to >= 0 && to < count && index != to else {
log("playlist.move: Invalid index.", level: .error)
return false
}
player!.playlistMove(index, to: to)
return true
}
func play(_ index: Int) {
guard isPlaying() else { return }
let count = player!.info.playlist.count
guard index >= 0 && index < count else {
log("playlist.play: Invalid index.", level: .error)
return
}
player!.playFileInPlaylist(index)
}
func playNext() {
guard isPlaying() else { return }
player!.navigateInPlaylist(nextMedia: true)
}
func playPrevious() {
guard isPlaying() else { return }
player!.navigateInPlaylist(nextMedia: false)
}
func registerMenuItemBuilder(_ builder: JSValue) {
if let previousBuilder = menuItemBuilder {
JSContext.current()!.virtualMachine.removeManagedReference(previousBuilder, withOwner: self)
}
menuItemBuilder = JSManagedValue(value: builder)
JSContext.current()!.virtualMachine.addManagedReference(menuItemBuilder, withOwner: self)
}
}
| gpl-3.0 | f6bde376c5890b4a5ff1f7776319b88d | 26.856115 | 101 | 0.629907 | 4 | false | false | false | false |
kjantzer/FolioReaderKit | Source/FolioReaderPlayerMenu.swift | 1 | 13349 | //
// FolioReaderFontsMenu.swift
// FolioReaderKit
//
// Created by Kevin Jantzer on 1/6/16.
// Copyright (c) 2016 Folio Reader. All rights reserved.
//
import UIKit
class FolioReaderPlayerMenu: UIViewController, SMSegmentViewDelegate, UIGestureRecognizerDelegate {
var menuView: UIView!
var playPauseBtn: UIButton!
var styleOptionBtns = [UIButton]()
var viewDidAppear = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.clearColor()
// Tap gesture
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(FolioReaderPlayerMenu.tapGesture))
tapGesture.numberOfTapsRequired = 1
tapGesture.delegate = self
view.addGestureRecognizer(tapGesture)
// Menu view
menuView = UIView(frame: CGRectMake(0, view.frame.height-165, view.frame.width, view.frame.height))
menuView.backgroundColor = isNight(readerConfig.nightModeMenuBackground, UIColor.whiteColor())
menuView.autoresizingMask = .FlexibleWidth
menuView.layer.shadowColor = UIColor.blackColor().CGColor
menuView.layer.shadowOffset = CGSize(width: 0, height: 0)
menuView.layer.shadowOpacity = 0.3
menuView.layer.shadowRadius = 6
menuView.layer.shadowPath = UIBezierPath(rect: menuView.bounds).CGPath
menuView.layer.rasterizationScale = UIScreen.mainScreen().scale
menuView.layer.shouldRasterize = true
view.addSubview(menuView)
let normalColor = UIColor(white: 0.5, alpha: 0.7)
let selectedColor = readerConfig.tintColor
let size = 55
let padX = 32
// @NOTE: could this be improved/simplified with autolayout?
let gutterX = (Int(view.frame.width) - (size * 3 ) - (padX * 4) ) / 2
//let btnX = (Int(view.frame.width) - (size * 3)) / 4
// get icon images
let play = UIImage(readerImageNamed: "play-icon")
let pause = UIImage(readerImageNamed: "pause-icon")
let prev = UIImage(readerImageNamed: "prev-icon")
let next = UIImage(readerImageNamed: "next-icon")
let playSelected = play!.imageTintColor(selectedColor).imageWithRenderingMode(.AlwaysOriginal)
let pauseSelected = pause!.imageTintColor(selectedColor).imageWithRenderingMode(.AlwaysOriginal)
let prevNormal = prev!.imageTintColor(normalColor).imageWithRenderingMode(.AlwaysOriginal)
let nextNormal = next!.imageTintColor(normalColor).imageWithRenderingMode(.AlwaysOriginal)
let prevSelected = prev!.imageTintColor(selectedColor).imageWithRenderingMode(.AlwaysOriginal)
let nextSelected = next!.imageTintColor(selectedColor).imageWithRenderingMode(.AlwaysOriginal)
// prev button
let prevBtn = UIButton(frame: CGRect(x: gutterX + padX, y: 0, width: size, height: size))
prevBtn.setImage(prevNormal, forState: .Normal)
prevBtn.setImage(prevSelected, forState: .Selected)
prevBtn.addTarget(self, action: #selector(FolioReaderPlayerMenu.prevChapter(_:)), forControlEvents: .TouchUpInside)
menuView.addSubview(prevBtn)
// play / pause button
let playPauseBtn = UIButton(frame: CGRect(x: Int(prevBtn.frame.origin.x) + padX + size, y: 0, width: size, height: size))
playPauseBtn.setTitleColor(selectedColor, forState: .Normal)
playPauseBtn.setTitleColor(selectedColor, forState: .Selected)
playPauseBtn.setImage(playSelected, forState: .Normal)
playPauseBtn.setImage(pauseSelected, forState: .Selected)
playPauseBtn.titleLabel!.font = UIFont(name: "Avenir", size: 22)!
playPauseBtn.addTarget(self, action: #selector(FolioReaderPlayerMenu.togglePlay(_:)), forControlEvents: .TouchUpInside)
menuView.addSubview(playPauseBtn)
if let audioPlayer = FolioReader.sharedInstance.readerAudioPlayer where audioPlayer.isPlaying() {
playPauseBtn.selected = true
}
// next button
let nextBtn = UIButton(frame: CGRect(x: Int(playPauseBtn.frame.origin.x) + padX + size, y: 0, width: size, height: size))
nextBtn.setImage(nextNormal, forState: .Normal)
nextBtn.setImage(nextSelected, forState: .Selected)
nextBtn.addTarget(self, action: #selector(FolioReaderPlayerMenu.nextChapter(_:)), forControlEvents: .TouchUpInside)
menuView.addSubview(nextBtn)
// Separator
let line = UIView(frame: CGRectMake(0, playPauseBtn.frame.height+playPauseBtn.frame.origin.y, view.frame.width, 1))
line.backgroundColor = readerConfig.nightModeSeparatorColor
menuView.addSubview(line)
// audio playback rate adjust
let playbackRate = SMSegmentView(frame: CGRect(x: 15, y: line.frame.height+line.frame.origin.y, width: view.frame.width-30, height: 55),
separatorColour: UIColor.clearColor(),
separatorWidth: 0,
segmentProperties: [
keySegmentOnSelectionColour: UIColor.clearColor(),
keySegmentOffSelectionColour: UIColor.clearColor(),
keySegmentOnSelectionTextColour: selectedColor,
keySegmentOffSelectionTextColour: normalColor,
keyContentVerticalMargin: 17
])
playbackRate.delegate = self
playbackRate.tag = 2
playbackRate.addSegmentWithTitle("½x", onSelectionImage: nil, offSelectionImage: nil)
playbackRate.addSegmentWithTitle("1x", onSelectionImage: nil, offSelectionImage: nil)
playbackRate.addSegmentWithTitle("1½x", onSelectionImage: nil, offSelectionImage: nil)
playbackRate.addSegmentWithTitle("2x", onSelectionImage: nil, offSelectionImage: nil)
playbackRate.segmentTitleFont = UIFont(name: "Avenir-Light", size: 17)!
playbackRate.selectSegmentAtIndex(Int(FolioReader.currentAudioRate))
menuView.addSubview(playbackRate)
// Separator
let line2 = UIView(frame: CGRectMake(0, playbackRate.frame.height+playbackRate.frame.origin.y, view.frame.width, 1))
line2.backgroundColor = readerConfig.nightModeSeparatorColor
menuView.addSubview(line2)
// Media overlay highlight styles
let style0 = UIButton(frame: CGRectMake(0, line2.frame.height+line2.frame.origin.y, view.frame.width/3, 55))
style0.titleLabel!.textAlignment = .Center
style0.titleLabel!.font = UIFont(name: "Avenir-Light", size: 17)
style0.setTitleColor(isNight(readerConfig.nightModeMenuBackground, UIColor.whiteColor()), forState: .Normal)
style0.setTitleColor(isNight(readerConfig.nightModeMenuBackground, UIColor.whiteColor()), forState: .Selected)
style0.setTitle(readerConfig.localizedPlayerMenuStyle, forState: .Normal)
menuView.addSubview(style0);
style0.titleLabel?.sizeToFit()
let style0Bgd = UIView(frame: style0.titleLabel!.frame)
style0Bgd.center = CGPointMake(style0.frame.size.width / 2, style0.frame.size.height / 2);
style0Bgd.frame.size.width += 8
style0Bgd.frame.origin.x -= 4
style0Bgd.backgroundColor = normalColor;
style0Bgd.layer.cornerRadius = 3.0;
style0Bgd.userInteractionEnabled = false
style0.insertSubview(style0Bgd, belowSubview: style0.titleLabel!)
let style1 = UIButton(frame: CGRectMake(view.frame.width/3, line2.frame.height+line2.frame.origin.y, view.frame.width/3, 55))
style1.titleLabel!.textAlignment = .Center
style1.titleLabel!.font = UIFont(name: "Avenir-Light", size: 17)
style1.setTitleColor(normalColor, forState: .Normal)
style1.setAttributedTitle(NSAttributedString(string: "Style", attributes: [
NSForegroundColorAttributeName: normalColor,
NSUnderlineStyleAttributeName: NSUnderlineStyle.PatternDot.rawValue|NSUnderlineStyle.StyleSingle.rawValue,
NSUnderlineColorAttributeName: normalColor
]), forState: .Normal)
style1.setAttributedTitle(NSAttributedString(string: readerConfig.localizedPlayerMenuStyle, attributes: [
NSForegroundColorAttributeName: isNight(UIColor.whiteColor(), UIColor.blackColor()),
NSUnderlineStyleAttributeName: NSUnderlineStyle.PatternDot.rawValue|NSUnderlineStyle.StyleSingle.rawValue,
NSUnderlineColorAttributeName: selectedColor
]), forState: .Selected)
menuView.addSubview(style1);
let style2 = UIButton(frame: CGRectMake(view.frame.width/1.5, line2.frame.height+line2.frame.origin.y, view.frame.width/3, 55))
style2.titleLabel!.textAlignment = .Center
style2.titleLabel!.font = UIFont(name: "Avenir-Light", size: 17)
style2.setTitleColor(normalColor, forState: .Normal)
style2.setTitleColor(selectedColor, forState: .Selected)
style2.setTitle(readerConfig.localizedPlayerMenuStyle, forState: .Normal)
menuView.addSubview(style2);
// add line dividers between style buttons
let style1line = UIView(frame: CGRectMake(style1.frame.origin.x, style1.frame.origin.y, 1, style1.frame.height))
style1line.backgroundColor = readerConfig.nightModeSeparatorColor
menuView.addSubview(style1line)
let style2line = UIView(frame: CGRectMake(style2.frame.origin.x, style2.frame.origin.y, 1, style2.frame.height))
style2line.backgroundColor = readerConfig.nightModeSeparatorColor
menuView.addSubview(style2line)
// select the current style
style0.selected = (FolioReader.currentMediaOverlayStyle == .Default)
style1.selected = (FolioReader.currentMediaOverlayStyle == .Underline)
style2.selected = (FolioReader.currentMediaOverlayStyle == .TextColor)
if style0.selected { style0Bgd.backgroundColor = selectedColor }
// hook up button actions
style0.tag = MediaOverlayStyle.Default.rawValue
style1.tag = MediaOverlayStyle.Underline.rawValue
style2.tag = MediaOverlayStyle.TextColor.rawValue
style0.addTarget(self, action: #selector(FolioReaderPlayerMenu.changeStyle(_:)), forControlEvents: .TouchUpInside)
style1.addTarget(self, action: #selector(FolioReaderPlayerMenu.changeStyle(_:)), forControlEvents: .TouchUpInside)
style2.addTarget(self, action: #selector(FolioReaderPlayerMenu.changeStyle(_:)), forControlEvents: .TouchUpInside)
// store ref to buttons
styleOptionBtns.append(style0)
styleOptionBtns.append(style1)
styleOptionBtns.append(style2)
}
override func viewDidAppear(animated: Bool) {
viewDidAppear = true
}
override func viewDidDisappear(animated: Bool) {
viewDidAppear = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Status Bar
override func prefersStatusBarHidden() -> Bool {
return readerConfig.shouldHideNavigationOnTap == true
}
// MARK: - SMSegmentView delegate
func segmentView(segmentView: SMSegmentView, didSelectSegmentAtIndex index: Int) {
guard viewDidAppear else { return }
if let audioPlayer = FolioReader.sharedInstance.readerAudioPlayer where segmentView.tag == 2 {
audioPlayer.setRate(index)
FolioReader.currentAudioRate = index
}
}
func prevChapter(sender: UIButton!) {
FolioReader.sharedInstance.readerAudioPlayer?.playPrevChapter()
}
func nextChapter(sender: UIButton!) {
FolioReader.sharedInstance.readerAudioPlayer?.playNextChapter()
}
func togglePlay(sender: UIButton!) {
sender.selected = sender.selected != true
FolioReader.sharedInstance.readerAudioPlayer?.togglePlay()
closeView()
}
func changeStyle(sender: UIButton!) {
FolioReader.currentMediaOverlayStyle = MediaOverlayStyle(rawValue: sender.tag)!
// select the proper style button
for btn in styleOptionBtns {
btn.selected = btn == sender
if btn.tag == MediaOverlayStyle.Default.rawValue {
btn.subviews.first?.backgroundColor = btn.selected ? readerConfig.tintColor : UIColor(white: 0.5, alpha: 0.7)
}
}
// update the current page style
if let currentPage = FolioReader.sharedInstance.readerCenter.currentPage {
currentPage.webView.js("setMediaOverlayStyle(\"\(FolioReader.currentMediaOverlayStyle.className())\")")
}
}
func closeView() {
dismiss()
if readerConfig.shouldHideNavigationOnTap == false {
FolioReader.sharedInstance.readerCenter.showBars()
}
}
// MARK: - Gestures
func tapGesture() {
closeView()
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if gestureRecognizer is UITapGestureRecognizer && touch.view == view {
return true
}
return false
}
}
| bsd-3-clause | a88861e6683558027ef5fe32ffc2095b | 45.996479 | 144 | 0.684873 | 4.874726 | false | false | false | false |
opencv/opencv | samples/swift/ios/ColorBlobDetection/ColorBlobDetection/ViewController.swift | 2 | 4611 | //
// ViewController.swift
//
// Created by Giles Payne on 2020/03/02.
//
import UIKit
import OpenCV
class ViewController: UIViewController, CvVideoCameraDelegate2 {
var isColorSelected = false
var rgba: Mat? = nil
let detector = ColorBlobDetector()
let spectrum = Mat()
var blobColorRgba = Scalar(255.0)
var blobColorHsv = Scalar(255.0)
let SPECTRUM_SIZE = Size(width: 200, height: 64)
let CONTOUR_COLOR = Scalar(255.0, 0.0, 0.0, 255.0)
var cameraHolderWidth: CGFloat = 0
var cameraHolderHeight: CGFloat = 0
func processImage(_ image: Mat!) {
rgba = image
if isColorSelected {
detector.process(rgbaImage: image)
let contours = detector.contours
NSLog("Contours count: \(contours.count))")
Imgproc.drawContours(image: image, contours: contours as! [[Point]], contourIdx: -1, color: CONTOUR_COLOR)
let colorLabel = image.submat(rowStart: 4, rowEnd: 68, colStart: 4, colEnd: 68)
colorLabel.setTo(scalar: blobColorRgba)
let spectrumLabel = image.submat(rowStart: 4, rowEnd: 4 + spectrum.rows(), colStart: 70, colEnd: 70 + spectrum.cols())
spectrum.copy(to: spectrumLabel)
}
}
var camera: CvVideoCamera2? = nil
@IBOutlet weak var cameraHolder: UIView!
override func viewDidLoad() {
super.viewDidLoad()
camera = CvVideoCamera2(parentView: cameraHolder)
camera?.rotateVideo = true
camera?.delegate = self
camera?.start()
}
override func viewDidLayoutSubviews() {
if UIDevice.current.orientation.isLandscape {
cameraHolderWidth = cameraHolder.bounds.height
cameraHolderHeight = cameraHolder.bounds.width
} else {
cameraHolderWidth = cameraHolder.bounds.width
cameraHolderHeight = cameraHolder.bounds.height
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let aRgba = rgba, touches.count == 1 {
let touch = touches.first!
let cols = CGFloat(aRgba.cols())
let rows = CGFloat(aRgba.rows())
let orientation = UIDevice.current.orientation
var x = touch.location(in: cameraHolder).x
var y = touch.location(in: cameraHolder).y
if orientation == .landscapeLeft {
let tempX = x
x = cameraHolder.bounds.height - y
y = tempX
} else if orientation == .landscapeRight {
let tempY = y
y = cameraHolder.bounds.width - x
x = tempY
}
x = x * (cols / cameraHolderWidth)
y = y * (rows / cameraHolderHeight)
if ((x < 0) || (y < 0) || (x > cols) || (y > rows)) {
return
}
let touchedRect = Rect()
touchedRect.x = (x>4) ? Int32(x)-4 : 0;
touchedRect.y = (y>4) ? Int32(y)-4 : 0;
touchedRect.width = (x+4 < cols) ? Int32(x) + 4 - touchedRect.x : Int32(cols) - touchedRect.x;
touchedRect.height = (y+4 < rows) ? Int32(y) + 4 - touchedRect.y : Int32(rows) - touchedRect.y;
let touchedRegionRgba = aRgba.submat(roi: touchedRect)
let touchedRegionHsv = Mat()
Imgproc.cvtColor(src: touchedRegionRgba, dst: touchedRegionHsv, code: .COLOR_RGB2HSV_FULL)
// Calculate average color of touched region
blobColorHsv = Core.sum(src: touchedRegionHsv)
let pointCount = touchedRect.width*touchedRect.height
blobColorHsv = blobColorHsv.mul(Scalar.all(1.0/Double(pointCount)))
blobColorRgba = convertScalarHsv2Rgba(hsvColor: blobColorHsv)
NSLog("Touched rgba color: (\(blobColorRgba.val[0]), \(blobColorRgba.val[1]), \( blobColorRgba.val[2]), \(blobColorRgba.val[3])")
detector.setHsvColor(hsvColor: blobColorHsv)
Imgproc.resize(src: detector.spectrum, dst: spectrum, dsize: SPECTRUM_SIZE, fx: 0, fy: 0, interpolation: InterpolationFlags.INTER_LINEAR_EXACT.rawValue)
isColorSelected = true
}
}
func convertScalarHsv2Rgba(hsvColor:Scalar) -> Scalar {
let pointMatRgba = Mat()
let pointMatHsv = Mat(rows: 1, cols: 1, type: CvType.CV_8UC3, scalar: hsvColor)
Imgproc.cvtColor(src: pointMatHsv, dst: pointMatRgba, code: .COLOR_HSV2RGB_FULL, dstCn: 4)
let elementData = pointMatRgba.get(row: 0, col: 0)
return Scalar(vals: elementData as [NSNumber])
}
}
| apache-2.0 | 05c35b90c9464502b12a0d78c416f76a | 36.185484 | 164 | 0.60334 | 3.817053 | false | false | false | false |
nessBautista/iOSBackup | RxSwift_02/RxTables/Pods/SwiftyJSON/Source/SwiftyJSON.swift | 7 | 32385 | // SwiftyJSON.swift
//
// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Error
///Error domain
public let ErrorDomain: String = "SwiftyJSONErrorDomain"
///Error code
public let ErrorUnsupportedType: Int = 999
public let ErrorIndexOutOfBounds: Int = 900
public let ErrorWrongType: Int = 901
public let ErrorNotExist: Int = 500
public let ErrorInvalidJSON: Int = 490
// MARK: - JSON Type
/**
JSON's type definitions.
See http://www.json.org
*/
public enum Type :Int{
case number
case string
case bool
case array
case dictionary
case null
case unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
- parameter error: error The NSErrorPointer used to return the error. `nil` by default.
- returns: The created JSON
*/
public init(data:Data, options opt: JSONSerialization.ReadingOptions = .allowFragments, error: NSErrorPointer? = nil) {
do {
let object: Any = try JSONSerialization.jsonObject(with: data, options: opt)
self.init(object)
} catch let aError as NSError {
if error != nil {
error??.pointee = aError
}
self.init(NSNull())
}
}
/**
Create a JSON from JSON string
- parameter string: Normal json string like '{"a":"b"}'
- returns: The created JSON
*/
public static func parse(_ string:String) -> JSON {
return string.data(using: String.Encoding.utf8)
.flatMap({JSON(data: $0)}) ?? JSON(NSNull())
}
/**
Creates a JSON using the object.
- parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
public init(_ object: Any) {
self.object = object
}
/**
Creates a JSON from a [JSON]
- parameter jsonArray: A Swift array of JSON objects
- returns: The created JSON
*/
public init(_ jsonArray:[JSON]) {
self.init(jsonArray.map { $0.object })
}
/**
Creates a JSON from a [String: JSON]
- parameter jsonDictionary: A Swift dictionary of JSON objects
- returns: The created JSON
*/
public init(_ jsonDictionary:[String: JSON]) {
var dictionary = [String: Any](minimumCapacity: jsonDictionary.count)
for (key, json) in jsonDictionary {
dictionary[key] = json.object
}
self.init(dictionary)
}
/// fileprivate object
fileprivate var rawArray: [Any] = []
fileprivate var rawDictionary: [String : Any] = [:]
fileprivate var rawString: String = ""
fileprivate var rawNumber: NSNumber = 0
fileprivate var rawNull: NSNull = NSNull()
fileprivate var _type: Type = .null
fileprivate var _error: NSError? = nil
/// Object in JSON
public var object: Any {
get {
switch self.type {
case .array:
return self.rawArray
case .dictionary:
return self.rawDictionary
case .string:
return self.rawString
case .number:
return self.rawNumber
case .bool:
return self.rawNumber
default:
return self.rawNull
}
}
set {
_error = nil
switch newValue {
case let number as NSNumber:
if number.isBool {
_type = .bool
} else {
_type = .number
}
self.rawNumber = number
case let string as String:
_type = .string
self.rawString = string
case _ as NSNull:
_type = .null
case let array as [Any]:
_type = .array
self.rawArray = array
case let dictionary as [String : Any]:
_type = .dictionary
self.rawDictionary = dictionary
default:
_type = .unknown
_error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
/// json type
public var type: Type { get { return _type } }
/// Error in JSON
public var error: NSError? { get { return self._error } }
/// The static null json
@available(*, unavailable, renamed:"null")
public static var nullJSON: JSON { get { return null } }
public static var null: JSON { get { return JSON(NSNull()) } }
}
public enum JSONIndex:Comparable {
case array(Int)
case dictionary(DictionaryIndex<String, JSON>)
case null
}
public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)):
return left == right
case (.dictionary(let left), .dictionary(let right)):
return left == right
default:
return false
}
}
public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)):
return left < right
case (.dictionary(let left), .dictionary(let right)):
return left < right
default:
return false
}
}
extension JSON: Collection {
public typealias Index = JSONIndex
public var startIndex: Index{
switch type {
case .array:
return .array(rawArray.startIndex)
case .dictionary:
return .dictionary(dictionaryValue.startIndex)
default:
return .null
}
}
public var endIndex: Index{
switch type {
case .array:
return .array(rawArray.endIndex)
case .dictionary:
return .dictionary(dictionaryValue.endIndex)
default:
return .null
}
}
public func index(after i: Index) -> Index {
switch i {
case .array(let idx):
return .array(rawArray.index(after: idx))
case .dictionary(let idx):
return .dictionary(dictionaryValue.index(after: idx))
default:
return .null
}
}
public subscript (position: Index) -> (String, JSON) {
switch position {
case .array(let idx):
return (String(idx), JSON(self.rawArray[idx]))
case .dictionary(let idx):
return dictionaryValue[idx]
default:
return ("", JSON.null)
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public enum JSONKey {
case index(Int)
case key(String)
}
public protocol JSONSubscriptType {
var jsonKey:JSONKey { get }
}
extension Int: JSONSubscriptType {
public var jsonKey:JSONKey {
return JSONKey.index(self)
}
}
extension String: JSONSubscriptType {
public var jsonKey:JSONKey {
return JSONKey.key(self)
}
}
extension JSON {
/// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error.
fileprivate subscript(index index: Int) -> JSON {
get {
if self.type != .array {
var r = JSON.null
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
return r
} else if index >= 0 && index < self.rawArray.count {
return JSON(self.rawArray[index])
} else {
var r = JSON.null
r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
return r
}
}
set {
if self.type == .array {
if self.rawArray.count > index && newValue.error == nil {
self.rawArray[index] = newValue.object
}
}
}
}
/// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error.
fileprivate subscript(key key: String) -> JSON {
get {
var r = JSON.null
if self.type == .dictionary {
if let o = self.rawDictionary[key] {
r = JSON(o)
} else {
r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
}
} else {
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
}
return r
}
set {
if self.type == .dictionary && newValue.error == nil {
self.rawDictionary[key] = newValue.object
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
fileprivate subscript(sub sub: JSONSubscriptType) -> JSON {
get {
switch sub.jsonKey {
case .index(let index): return self[index: index]
case .key(let key): return self[key: key]
}
}
set {
switch sub.jsonKey {
case .index(let index): self[index: index] = newValue
case .key(let key): self[key: key] = newValue
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [JSONSubscriptType]) -> JSON {
get {
return path.reduce(self) { $0[sub: $1] }
}
set {
switch path.count {
case 0:
return
case 1:
self[sub:path[0]].object = newValue.object
default:
var aPath = path; aPath.remove(at: 0)
var nextJSON = self[sub: path[0]]
nextJSON[aPath] = newValue
self[sub: path[0]] = nextJSON
}
}
}
/**
Find a json in the complex data structures by using the Int/String's array.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: JSONSubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: Swift.StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
extension JSON: Swift.IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
extension JSON: Swift.BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
extension JSON: Swift.FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
extension JSON: Swift.DictionaryLiteralConvertible {
public init(dictionaryLiteral elements: (String, Any)...) {
self.init(elements.reduce([String : Any](minimumCapacity: elements.count)){(dictionary: [String : Any], element:(String, Any)) -> [String : Any] in
var d = dictionary
d[element.0] = element.1
return d
})
}
}
extension JSON: Swift.ArrayLiteralConvertible {
public init(arrayLiteral elements: Any...) {
self.init(elements)
}
}
extension JSON: Swift.NilLiteralConvertible {
public init(nilLiteral: ()) {
self.init(NSNull())
}
}
// MARK: - Raw
extension JSON: Swift.RawRepresentable {
public init?(rawValue: Any) {
if JSON(rawValue).type == .unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: Any {
return self.object
}
public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data {
guard JSONSerialization.isValidJSONObject(self.object) else {
throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"])
}
return try JSONSerialization.data(withJSONObject: self.object, options: opt)
}
public func rawString(_ encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? {
switch self.type {
case .array, .dictionary:
do {
let data = try self.rawData(options: opt)
return String(data: data, encoding: encoding)
} catch _ {
return nil
}
case .string:
return self.rawString
case .number:
return self.rawNumber.stringValue
case .bool:
return self.rawNumber.boolValue.description
case .null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible {
public var description: String {
if let string = self.rawString(options:.prettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
get {
if self.type == .array {
return self.rawArray.map{ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
get {
return self.array ?? []
}
}
//Optional [Any]
public var arrayObject: [Any]? {
get {
switch self.type {
case .array:
return self.rawArray
default:
return nil
}
}
set {
if let array = newValue {
self.object = array
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
if self.type == .dictionary {
return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, Any)) -> [String : JSON] in
var d = dictionary
d[element.0] = JSON(element.1)
return d
}
} else {
return nil
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
return self.dictionary ?? [:]
}
//Optional [String : Any]
public var dictionaryObject: [String : Any]? {
get {
switch self.type {
case .dictionary:
return self.rawDictionary
default:
return nil
}
}
set {
if let v = newValue {
self.object = v
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON {
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .bool:
return self.rawNumber.boolValue
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .bool, .number, .string:
return (self.object as AnyObject).boolValue
default:
return false
}
}
set {
self.object = NSNumber(value: newValue)
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .string:
return self.object as? String
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = NSString(string:newValue)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
public var stringValue: String {
get {
switch self.type {
case .string:
return self.object as? String ?? ""
case .number:
return (self.object as AnyObject).stringValue
case .bool:
return (self.object as? Bool).map { String($0) } ?? ""
default:
return ""
}
}
set {
self.object = NSString(string:newValue)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .number, .bool:
return self.rawNumber
default:
return nil
}
}
set {
self.object = newValue ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .string:
let decimal = NSDecimalNumber(string: self.object as? String)
if decimal == NSDecimalNumber.notANumber { // indicates parse error
return NSDecimalNumber.zero
}
return decimal
case .number, .bool:
return self.object as? NSNumber ?? NSNumber(value: 0)
default:
return NSNumber(value: 0.0)
}
}
set {
self.object = newValue
}
}
}
//MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .null:
return self.rawNull
default:
return nil
}
}
set {
self.object = NSNull()
}
}
public func exists() -> Bool{
if let errorValue = error, errorValue.code == ErrorNotExist{
return false
}
return true
}
}
//MARK: - URL
extension JSON {
//Optional URL
public var URL: Foundation.URL? {
get {
switch self.type {
case .string:
if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
return Foundation.URL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString ?? NSNull()
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int: Int? {
get {
return self.number?.intValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.uintValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.uintValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.int8Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.int8Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt8: UInt8? {
get {
return self.number?.uint8Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.uint8Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.int16Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.int16Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.uint16Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.uint16Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.int32Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.int32Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.uint32Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.uint32Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.int64Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.int64Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.uint64Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.uint64Value
}
set {
self.object = NSNumber(value: newValue)
}
}
}
//MARK: - Comparable
extension JSON : Swift.Comparable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber == rhs.rawNumber
case (.string, .string):
return lhs.rawString == rhs.rawString
case (.bool, .bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func <=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber <= rhs.rawNumber
case (.string, .string):
return lhs.rawString <= rhs.rawString
case (.bool, .bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func >=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber >= rhs.rawNumber
case (.string, .string):
return lhs.rawString >= rhs.rawString
case (.bool, .bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.array, .array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.dictionary, .dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.null, .null):
return true
default:
return false
}
}
public func >(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber > rhs.rawNumber
case (.string, .string):
return lhs.rawString > rhs.rawString
default:
return false
}
}
public func <(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.number, .number):
return lhs.rawNumber < rhs.rawNumber
case (.string, .string):
return lhs.rawString < rhs.rawString
default:
return false
}
}
fileprivate let trueNumber = NSNumber(value: true)
fileprivate let falseNumber = NSNumber(value: false)
fileprivate let trueObjCType = String(cString: trueNumber.objCType)
fileprivate let falseObjCType = String(cString: falseNumber.objCType)
//A C++ bool or a C99 _Bool
//Do Not Know Why self.objCType is "B", maybe a bug.
fileprivate let cppBoolType = "B"
// MARK: - NSNumber: Comparable
extension NSNumber {
var isBool:Bool {
get {
let objCType = String(cString: self.objCType)
if (self.compare(trueNumber) == ComparisonResult.orderedSame && (objCType == trueObjCType || objCType == cppBoolType))
|| (self.compare(falseNumber) == ComparisonResult.orderedSame && (objCType == falseObjCType || objCType == cppBoolType)){
return true
} else {
return false
}
}
}
}
func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == ComparisonResult.orderedSame
}
}
func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == ComparisonResult.orderedAscending
}
}
func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == ComparisonResult.orderedDescending
}
}
func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != ComparisonResult.orderedDescending
}
}
func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != ComparisonResult.orderedAscending
}
}
| cc0-1.0 | bd7df1c6d54a52a22d59283dd5c50d31 | 25.012048 | 264 | 0.537842 | 4.643011 | false | false | false | false |
andressbarnes/ABLoader | ABLoader/ABLoader/ABloader.swift | 1 | 2241 | //
// ABloader.swift
// basicStart
//
// Created by John Barnes on 8/14/16.
// Copyright © 2016 Andress Barnes. All rights reserved.
//
import UIKit
class ABloader: UIView {
init(frame: CGRect, color : UIColor?, vAnchor: CGFloat?)
{
super.init(frame: frame)
let barAmount: Int = Int(frame.size.width)/12
for index in 0...(barAmount - 1) {
let rectFrame: CGRect = CGRectMake(0 + (12*CGFloat(index)), 100, 10, 10)
let rectView : RectUIView = RectUIView(frame: rectFrame)
rectView.layer.anchorPoint = CGPointMake(0.5, vAnchor!);
rectView.barColor = color
rectView.alpha = 0.0
self.addSubview(rectView)
NSTimer.scheduledTimerWithTimeInterval((0.02 * Double(index) + 0.2), target: self, selector: #selector(self.oscillateStart(_:)), userInfo:["view": rectView], repeats: false)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func oscillateStart(vc: NSTimer)
{
let userInfo = vc.userInfo as! Dictionary<String, AnyObject>
let tempView:UIView = (userInfo["view"] as! UIView)
UIView.animateWithDuration(0.25, delay: 0.0, options: [], animations: {
tempView.alpha = 1.0
tempView.transform = CGAffineTransformMakeScale(1.0, 6.6)
}, completion: {(value: Bool) in
self.oscillateOut(tempView)
})
}
func oscillateOut(vc: UIView)
{
UIView.animateWithDuration(0.25, delay: 0.0, options: [], animations: {
//vc.alpha = 0.0
vc.transform = CGAffineTransformMakeScale(1.0, 0.5)
}, completion: {(value: Bool) in
self.oscillateIn(vc)
})
}
func oscillateIn(vc: UIView)
{
UIView.animateWithDuration(0.25, delay: 0.0, options: [], animations: {
//vc.alpha = 1.0
vc.transform = CGAffineTransformMakeScale(1.0, 3.6)
}, completion: {(value: Bool) in
self.oscillateOut(vc)
})
}
}
| mit | 979d4e05df12c100619969eaa733c3e4 | 27 | 185 | 0.550893 | 4.132841 | false | false | false | false |
ducn/DNImagePicker | DNImagePicker/Classes/DNImagePickerController.swift | 1 | 4972 | //
// PhotoLibraryPickerViewController.swift
// QnR
//
// Created by Duc Ngo on 1/19/17.
// Copyright © 2017 cinnamon. All rights reserved.
//
import Foundation
import UIKit
import Photos
import MobileCoreServices
public protocol DNImagePickerControllerDelegate:class{
func imagePickerControllerDidCancel(_ picker: DNImagePickerController)
func imagePickerController(_ picker: DNImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
}
public class DNImagePickerController: UIViewController{
public weak var delegate: DNImagePickerControllerDelegate?
public var mediaTypes:[String] = [kUTTypeMovie as String, kUTTypeImage as String]
public var maxTrimLength:Float = 60.0 // in seconds
public var minTrimLength:Float = 3.0 // in seconds
override public func viewDidLoad() {
super.viewDidLoad()
useDefaultPickerUI()
}
private func useDefaultPickerUI(){
let picker = UIImagePickerController()
picker.allowsEditing = false
picker.mediaTypes = self.mediaTypes
picker.delegate = self
addChild(controller: picker)
_internalPicker = picker
}
fileprivate func openVideoEditor(with videoUrl:URL){
_internalPicker?.view.removeFromSuperview()
_internalPicker?.removeFromParentViewController()
let podBundle = Bundle(for: self.classForCoder)
if let bundleURL = podBundle.url(forResource: "DNImagePicker", withExtension: "bundle"),
let bundle = Bundle(url: bundleURL){
let videoEditor = DNVideoEditorController(nibName: "DNVideoEditorController", bundle: bundle)
videoEditor.videoUrl = videoUrl
videoEditor.delegate = self
videoEditor.maxTrimLength = maxTrimLength
videoEditor.minTrimLength = minTrimLength
addChild(controller: videoEditor)
}
}
fileprivate func openImageEditor(image: UIImage){
let screenSize = UIScreen.main.bounds
let imageEditor = WDImageCropViewController()
imageEditor.sourceImage = image
imageEditor.cropSize = CGSize(width: screenSize.width, height: screenSize.width)
imageEditor.delegate = self
addChild(controller: imageEditor)
}
fileprivate func addChild(controller: UIViewController){
let constrains = [NSLayoutAttribute.top, NSLayoutAttribute.left,
NSLayoutAttribute.right, NSLayoutAttribute.bottom]
self.addChildViewController(controller)
let subview = controller.view!
self.view.addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
for constrain in constrains {
self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: constrain, relatedBy: NSLayoutRelation.equal, toItem: subview, attribute: constrain, multiplier: 1.0, constant: 0))
}
controller.didMove(toParentViewController: self)
}
fileprivate func dismiss(){
self.dismiss(animated: true, completion: nil)
}
fileprivate weak var _internalPicker: UIImagePickerController?
}
extension DNImagePickerController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
delegate?.imagePickerControllerDidCancel(self)
dismiss()
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let mediaUrl = info[UIImagePickerControllerMediaURL] as? URL {
openVideoEditor(with: mediaUrl)
}else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
openImageEditor(image: image)
}else{
dismiss()
}
}
}
extension DNImagePickerController: DNVideoEditorControllerDelegate{
func videoEditorControllerDidCancel(_ videoEditController: DNVideoEditorController) {
delegate?.imagePickerControllerDidCancel(self)
dismiss()
}
func videoEditorController(_ videoEditController: DNVideoEditorController, didSaveEditedVideoToPath editedVideoPath: URL?) {
let info = [UIImagePickerControllerMediaURL:editedVideoPath]
delegate?.imagePickerController(self, didFinishPickingMediaWithInfo: info)
dismiss()
}
}
extension DNImagePickerController: WDImageCropControllerDelegate{
func imageCropController(_ imageCropController: WDImageCropViewController, didFinishWithCroppedImage croppedImage: UIImage) {
let info = [UIImagePickerControllerOriginalImage:croppedImage]
delegate?.imagePickerController(self, didFinishPickingMediaWithInfo: info)
dismiss()
}
func imageCropControllerDidCancel(_ imageCropController: WDImageCropViewController) {
delegate?.imagePickerControllerDidCancel(self)
dismiss()
}
}
| mit | bbef90c44bd9e24bf53c619f011aadea | 38.768 | 198 | 0.716556 | 5.504983 | false | false | false | false |
tid-kijyun/FontAwesome-IconGenerator | FontAwesome-IconGenerator/FontAwesomeIconGenerator.swift | 1 | 2992 | /**@file FontAwesomeIconGenerator.swift
FontAwesome-IconGenerator
Copyright (c) 2015 Atsushi Kiwaki (@_tid_)
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 AppKit
class FontAwesomeIconGenerator: NSObject {
static let sharedPlugin = FontAwesomeIconGenerator()
var bundle: NSBundle?
var windowController: IconGenerateWindowController?
class func pluginDidLoad(plugin: NSBundle) {
if let appName = NSBundle.mainBundle().infoDictionary?["CFBundleName"] as? String {
if appName == "Xcode" {
sharedPlugin.bundle = plugin
NSNotificationCenter.defaultCenter().addObserver(sharedPlugin, selector: "addMenuItems:", name: NSApplicationDidFinishLaunchingNotification, object: nil)
}
}
}
override init() {
super.init()
}
func addMenuItems(notification: NSNotification?) {
let rootMenuName = "Plugin"
var item = NSMenuItem(title: "FontAwesome-icon-generator", action: "show:", keyEquivalent: "")
item.target = self
if let mainMenu = NSApp.mainMenu ?? nil {
if let pluginMenu = mainMenu.itemWithTitle(rootMenuName) {
pluginMenu.submenu?.addItem(item)
} else {
var pluginMenu = NSMenu(title: rootMenuName)
pluginMenu.addItem(item)
var newMenuItem = NSMenuItem(title: rootMenuName, action: nil, keyEquivalent: "")
newMenuItem.submenu = pluginMenu
mainMenu.addItem(newMenuItem)
}
}
}
func show(sender: AnyObject?) {
showWindow()
}
func showWindow() {
if self.windowController?.window == nil {
self.windowController = IconGenerateWindowController(bundle: bundle)
}
self.windowController?.window?.setFrameAutosaveName("MyKey")
self.windowController?.window?.makeKeyAndOrderFront(self)
}
}
| mit | 5ab705da3d5a350d2a917a527d721d5e | 37.857143 | 169 | 0.678476 | 5.11453 | false | false | false | false |
jeancarlosaps/swift | Swift em 4 Semanas/Desafios/Gabaritos/Gabarito Semana 3.playground/Contents.swift | 2 | 12234 | // Playground - noun: a place where people can play
import UIKit
/*
__ __
__ \ / __
/ \ | / \
\|/ Mobgeek
_,.---v---._
/\__/\ / \ Curso Swift em 4 semanas
\_ _/ / \
\ \_| @ __|
\ \_
\ ,__/ /
~~~`~~~~~~~~~~~~~~/~~~~
*/
/*:
# **Gabarito - Semana 3**
1 - Use class precedida pelo nome da classe para criar uma classe. Uma propriedade de declaração em uma classe é escrita da mesma forma que uma declaração de uma constante ou variável, exceto que ela é escrita dentro do contexto da classe. Declarações de métodos são escritos da mesma forma que funções.
Veja o seguinte exemplo de uma forma geométrica:
*/
/* class Forma {
var númeroDeLados = 0
func descriçãoSimples() -> String {
return "Uma forma com \(númeroDeLados) lados."
}
} */
/*:
**Desafio 1:** Adicione uma propriedade constante usando `let`, e adicione um outro método que usa um argumento para comparar se duas formas geométricas possuem o mesmo número de lados.
Resposta:
*/
class Forma {
var númeroDeLados = 0
//: 1º Passo: Adicionar a propriedade constante:
let descriçãoPadrão = "Eu sou uma forma Swift"
func descriçãoSimples() -> String {
return "Uma forma com \(númeroDeLados) lados."
}
/*:
2º Passo: O método `comparaCom` compara se duas formas geométricas do tipo `Forma` possuem o mesmo número de lados. Usamos o operador `==` para fazer a comparação entre a propriedade `númeroDeLados` de cada forma.
*/
func comparaCom(forma: Forma) -> String {
if forma.númeroDeLados == self.númeroDeLados {
return "Bingo! Essas duas formas têm o mesmo nº de lados!"
} else {
return "O número de lados não é o mesmo."
}
}
}
/*:
---
2 - Agora que já criamos uma classe `Forma`, que será o nosso molde para criar diferentes formas, que tal começarmos a acessar suas propriedades e métodos?
**Desafio 2:** Usando a classe `Forma` no exercício 1, crie uma instância inserindo parêntesis após o nome da classe. Use o dot syntax (sintaxe do ponto) para acessar as propriedades e métodos de uma instância.
Resposta:
Lembrando que Swift fornece um inicializador padrão para classe, se todas as propriedades possuírem valores padrão definidos e a classe não fornecer pelo menos um initializer.
Com esse initializer padrão você pode criar uma nova instância e todas as propriedades desta instância vão conter os seus valores padrão.
1º Passo: Criar uma `Forma` e dar `7` para sua propriedade `númeroDeLados`
*/
var forma = Forma()
forma.númeroDeLados = 7
//: 2º Passo: Criar uma outra `Forma` e modifcar a sua propriedade `númeroDeLados` para que a gente possa comparar com a anterior.
var outraForma = Forma()
outraForma.númeroDeLados = 2
//: 3º Passo: Vamos usar o método de instância `comparaCom` passando a segunda `Forma` que criamos como argumento. Agora, podemos conferir ao lado se o `String` que o método retorna corresponde a realidade :-)
forma.comparaCom(outraForma)
/*:
---
3 - Até agora utilizamos o inicializador padrão fornecido pela classe Forma quando nenhum inicializador é informado. Que agora criarmos nossos próprios inicializadores customizados?
**Desafio 3:** Nesta versão de classe `Forma` há algo importante que está faltando: um inicializador para invocar uma classe quando uma instância for criada. Complete o exercício abaixo usando `init`, `self` e `func`.
*/
// class NomeDaForma{
// var númeroDeLados: Int = 0
// var nome: String
/*:
Resposta:
Aqui vamos customizar a nossa inicialização através de um `init` que definimos com um parâmetro nome do tipo `String`. Assim, podemos criar uma forma passando o seu nome como argumento.
*/
class NomeDaForma{
var númeroDeLados: Int = 0
var nome: String
// Definindo o inicializador:
init(nome: String) {
self.nome = nome
}
// A forma pode ser simplesmente descrita pela seua propriedade númeroDeLados. Por isso, criamos um método para retornar um String que faz justamente isso.
func descriçãoSimples() -> String {
return "Uma forma com \(númeroDeLados) lados."
}
}
/*:
---
4 - Métodos de uma classe que sobreescrevem (conhecidos em inglês como override) a implementação de uma subclasse são iniciados com override. O compliador também consegue detectar métodos com override que na realidade não estão sobreescrevendo nenhum método na subclasse.
Veja o seguinte exemplo:
*/
class Quadrado: NomeDaForma {
var comprimentoLado: Double
init(comprimentoLado: Double, nome: String) {
self.comprimentoLado = comprimentoLado
super.init(nome: nome)
númeroDeLados = 4
}
func área() -> Double {
return comprimentoLado * comprimentoLado
}
override func descriçãoSimples() -> String {
return "Um quadrado com o comprimento dos lados \(comprimentoLado)."
}
}
let teste = Quadrado(comprimentoLado: 5.2, nome: "meu quadrado teste")
teste.área()
teste.descriçãoSimples()
/*:
**Desafio 4:** Crie outra subclasse de `NomeDaForma` chamada de `Círculo` que possui um raio e um nome como argumentos para seu inicializador. Implemente um método de área e de `descriçãoSimples` para a classe `Círculo`.
Resposta:
Declaramos uma constante com a letra grega `π` para representar a constante matemática 'pi'. Para a grande maioria de cálculos simples podemos usar a aproximação `3,14`. Aqui vamos precisar dela para calcular a area do círculo.
*/
let π = 3.14
class Círculo: NomeDaForma {
var raio: Double
init(raio: Double, nome: String) {
//:Primeiro, vamos inicializar todas as propriedades da classe.
self.raio = raio
//:Depois, chamamos o init da superclasse apropriado para continuar a inicialização cadeia acima porque as propriedades herdadas de `NomeDaForma` também precisam ser inicializadas.
super.init(nome: nome)
}
func área() -> Double {
//:A area de do círculo: A = π * r * r
return raio * raio * π
}
//:É útil poder sobrescrever o método `descriçãoSimples` da superclasse `NomeDaForma` porque assim podemos dar uma descrição personalizada para a nossa Subclasse `Círculo`.
override func descriçãoSimples() -> String {
return "Um círculo com o raio de \(raio)."
}
}
/*:
Hora de testar se o que implementamos faz sentido:
Se liga que Swift fornece automaticamente nomes externos para cada parâmetro do initializer se você não fornecer um nome externo. Neste caso, 'raio' e 'nome' estão disponíveis como nomes externos.
*/
let circulo = Círculo(raio: 2, nome: "futuro sorriso")
circulo.área()
/*:
---
5 - Além de propriedades de armazemento que apenas guardam algum valor, existem as propriedades computadas que calculam um valor.
**Desafio 5:** Relembrando que além de propriedades armazenada, classes, estruturas e enumerações podem definir propriedades computadas. Complete a sintaxe abaixo de um triângulo equilátero usando um `getter`, um `setter` e uma `func override`.
*/
/* class TriânguloEquilátero: NomeDaForma{
var comprimentoDoLado: Double = 0.0
init(comprimentoDoLado: Double, nome: String) {
self.comprimentoDoLado = comprimentoDoLado
super.init(nome: nome)
númeroDeLados = 3
}
var perímetro: Double { … }
…
}
*/
//: Resposta:
class TriânguloEquilátero: NomeDaForma {
var comprimentoLado = 0.0
init(comprimentoLado: Double, nome: String) {
self.comprimentoLado = comprimentoLado
super.init(nome: nome)
númeroDeLados = 3
}
//:Usamos propriedades computadas para calcular um valor em vez de armazená-lo. É através do setter e do getter que vamos poder ler e dar valor as propriedades respectivamente. Ao final, você vai poder trabalhar com o perímetro como se fossse uma propriedade armazenada.
var perímetro: Double {
get {
//:Perímetro é a soma dos lados e como os lados são iguais podemos diretamente multiplicar a nossa propriedade comprimentoLado por três.
return 3.0 * comprimentoLado
}
set(novoPerímetro) {
comprimentoLado = novoPerímetro / 3.0
}
/* Uma alternativa para o nosso setter seria usar o nome implícito newValue:
set(newValue) {
comprimentoLado = newValue / 3.0
} */
}
//:Como no exemplo acima, podemos personalizar a mensagem que descreve o nosso triângulo equilátero sobrescrevendo o método `descriçãoSimples`
override func descriçãoSimples() -> String {
return "Um triângulo equilátero com o comprimento dos lados igual a \(comprimentoLado)"
}
}
var triangulo = TriânguloEquilátero(comprimentoLado: 2.5, nome: "um triângulo")
//:Chamanado o `getter`:
var perimetroDoTriangulo = triangulo.perímetro
//:Chamando o `setter`:
triangulo.perímetro = 9.3
triangulo.comprimentoLado
/*:
---
**Desafio Extra:** NTFPN*: Você pode precisar responder a atualização do valor de uma propriedade, em vez de ter que calcular uma propriedade como no exemplo anterior. Use os observadores de propriedades `willSet` e `didSet` para fornecer código que seja executado antes e/ou depois de um novo valor ser armazenado em uma propriedade. Usando estes observadores de propriedades no Playground, invoque um método de uma classe que você irá criar chamada `TriânguloEQuadrado` que garanta que o comprimento do lado do triângulo equilátero seja sempre igual ao comprimento do lado do quadrado.
*NTFPN: "Não tá fácil pra ninguém"
Resposta:
*/
class TriânguloEQuadrado {
var triângulo: TriânguloEquilátero {
//:`willSet` é chamado exatamente antes do valor ser armazenado, isto é, antes de um triângulo ser atribuído a esta propriedade. É um ótimo momento para garantir que os triângulos equiláteros e os quadrados dessa classe sempre tenhamo o mesmo comprimento de lado.
willSet {
quadrado.comprimentoLado = newValue.comprimentoLado
}
}
var quadrado: Quadrado {
willSet {
triângulo.comprimentoLado = newValue.comprimentoLado
}
}
init(comprimentoLado: Double, nome: String) {
triângulo = TriânguloEquilátero(comprimentoLado: comprimentoLado, nome:nome)
quadrado = Quadrado(comprimentoLado: comprimentoLado, nome: nome)
}
}
/*:
Importante: Os observadores `willSet`, como também `didSet`, não são chamados quando a propriedade é inicialiada. Ambos são chamados apenas quando o valor da propriedade é atualizado fora do contexto da inicialização, o que vamos fazer em seguida.
Vamos criar um instância da classe `TriânguloEQuadrado`, que por sua vez cria um triângulo equilátero e um quadrado para armazenar em suas propriedades. Os dois terão o mesmo comprimento de lado que passamos como argumento do initializer.
*/
var triânguloEQuadrado = TriânguloEQuadrado(comprimentoLado: 10, nome: "uma forma teste")
triânguloEQuadrado.quadrado.comprimentoLado
triânguloEQuadrado.triângulo.comprimentoLado
//:Será que o willSet está dando conta do recado? Vamos então atribuir um novo quadrado com um comprimentoLado diferente do anterior.
triânguloEQuadrado.quadrado = Quadrado(comprimentoLado: 45, nome: "grande quadrado")
/*:
Se o observador fez o seu papel devemos ter o triângulo com o mesmo comprimento de lado agora, ou seja, o valor 45 que passamos na última linha como argumento do initializer.
*/
triânguloEQuadrado.triângulo.comprimentoLado
| mit | a50a65af7ddaa0ea847f16c5a4af63e0 | 36.688679 | 588 | 0.68519 | 3.434097 | false | false | false | false |
shams-ahmed/SAStickyHeader | Pod/Classes/SAStickyHeaderView+Scroll.swift | 1 | 694 | //
// SAStickyHeaderView+Scroll.swift
// SA
//
// Created by shams ahmed on 18/10/2015.
//
//
import UIKit
extension SAStickyHeaderView {
// MARK:
// MARK: Scroll
/// Update header view from a drag movement
internal func updateImageViewFromScrollEvent(_ tableView: UITableView) {
let insert = tableView.contentInset
let offset = -(tableView.contentOffset.y + insert.top)
containerLayoutConstraint.constant = insert.top
containerView.clipsToBounds = offset <= 0
bottomLayoutConstraint.constant = offset >= 0 ? 0 : -offset / 2
heightLayoutConstraint.constant = max(offset + insert.top, insert.top)
}
}
| mit | a10d2d4fdf97b494f6aa86e18bafeafc | 23.785714 | 78 | 0.65562 | 4.392405 | false | false | false | false |
IAskWind/IAWExtensionTool | IAWExtensionTool/IAWExtensionTool/Classes/Common/IAW_WebViewController.swift | 1 | 3014 | //
// WebViewController.swift
// CtkApp
//
// Created by winston on 16/12/9.
// Copyright © 2016年 winston. All rights reserved.
//
import UIKit
open class IAW_WebViewController: IAW_BaseViewController {
fileprivate var webView = UIWebView()
fileprivate var urlStr: String?
fileprivate let loadProgressAnimationView: LoadProgressAnimationView = LoadProgressAnimationView(bgColor: UIColor.brown,frame: CGRect(x:0, y: 64, width: UIScreen.iawWidth, height: 3))
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
view.addSubview(webView)
webView.snp.makeConstraints{
(make) in
make.edges.equalTo(self.view)
}
webView.addSubview(loadProgressAnimationView)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(urlStr: String) {
self.init(nibName: nil, bundle: nil)
IAW_WebViewTool.webViewLoadUrl(webView: webView, urlStr: urlStr)
self.urlStr = urlStr
}
override open func viewDidLoad() {
super.viewDidLoad()
buildRightItemBarButton()
// view.backgroundColor = UIColor.colorWithCustom(230, g: 230, b: 230)
// webView.backgroundColor = UIColor.colorWithCustom(230, g: 230, b: 230)
webView.delegate = self
// / 自动对页面进行缩放以适应屏幕
webView.scalesPageToFit = true
webView.dataDetectorTypes = .all
webView.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
fileprivate func buildRightItemBarButton() {
let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 44))
rightButton.setImage(IAW_ImgXcassetsTool.v2_refreshWhite.image, for: UIControl.State())
rightButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -53)
rightButton.addTarget(self, action: #selector(IAW_WebViewController.refreshClick), for: UIControl.Event.touchUpInside)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
}
// MARK: - Action
@objc func refreshClick() {
if urlStr != nil && urlStr!.count > 1 {
IAW_WebViewTool.webViewLoadUrl(webView: webView, urlStr: urlStr!)
}
}
}
extension IAW_WebViewController: UIWebViewDelegate {
public func webViewDidStartLoad(_ webView: UIWebView) {
loadProgressAnimationView.startLoadProgressAnimation()
}
public func webViewDidFinishLoad(_ webView: UIWebView) {
loadProgressAnimationView.endLoadProgressAnimation()
IAW_WebViewTool.webViewDealValidateToken(webView: webView)
}
}
| mit | 16d27fa3be40dae07296e20cc47fa7ce | 34.094118 | 187 | 0.660409 | 4.596302 | false | false | false | false |
Brightify/ReactantUI | Sources/Tokenizer/Properties/Types/Implementation/UIColorPropertyType.swift | 1 | 6635 | //
// UIColorPropertyType.swift
// Tokenizer
//
// Created by Matouš Hýbl on 09/03/2018.
//
import Foundation
#if canImport(UIKit)
import UIKit
#endif
public enum UIColorPropertyType: AttributeSupportedPropertyType {
case color(Color)
case themed(String)
public var requiresTheme: Bool {
switch self {
case .color:
return false
case .themed:
return true
}
}
public func generate(context: SupportedPropertyTypeContext) -> String {
switch self {
case .color(.absolute(let red, let green, let blue, let alpha)):
return "UIColor(red: \(red), green: \(green), blue: \(blue), alpha: \(alpha))"
case .color(.named(let name)) where Color.systemColorNames.contains(name):
return "UIColor.\(name)"
case .color(.named(let name)):
return "UIColor(named: \"\(name)\", in: __resourceBundle, compatibleWith: nil)"
case .themed(let name):
return "theme.colors.\(name)"
}
}
#if SanAndreas
public func dematerialize(context: SupportedPropertyTypeContext) -> String {
switch color {
case .absolute(let red, let green, let blue, let alpha):
if alpha < 1 {
let rgba: Int = Int(red * 255) << 24 | Int(green * 255) << 16 | Int(blue * 255) << 8 | Int(alpha * 255)
return String(format:"#%08x", rgba)
} else {
let rgb: Int = Int(red * 255) << 16 | Int(green * 255) << 8 | Int(blue * 255)
return String(format:"#%06x", rgb)
}
case .named(let name):
return name
}
}
#endif
#if canImport(UIKit)
public func runtimeValue(context: SupportedPropertyTypeContext) -> Any? {
switch self {
case .color(.absolute(let red, let green, let blue, let alpha)):
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
case .color(.named(let name)) where Color.systemColorNames.contains(name):
return UIColor.value(forKeyPath: "\(name)Color") as? UIColor
case .color(.named(let name)):
if #available(iOS 11.0, OSX 10.13, *) {
return UIColor(named: name, in: context.resourceBundle, compatibleWith: nil)
} else {
return nil
}
case .themed(let name):
guard let themedColor = context.themed(color: name) else { return nil }
return themedColor.runtimeValue(context: context.child(for: themedColor))
}
}
#endif
public static func materialize(from value: String) throws -> UIColorPropertyType {
// we're not creating our own parser for this, so we will disallow using dots inside the values and instead enforce
// using percent signs
let colorComponents = value.components(separatedBy: "@")
func getColor(from value: String) throws -> UIColorPropertyType {
if let themedName = ApplicationDescription.themedValueName(value: value) {
return .themed(themedName)
} else if Color.systemColorNames.contains(value) {
return .color(.named(value))
} else if let materializedValue = Color(hex: value) {
return .color(materializedValue)
} else {
return .color(.named(value))
}
}
let base = try getColor(from: colorComponents[0])
guard colorComponents.count > 1 else { return base }
// note the `var color` that we're going to apply the modificators to
guard case .color(var color) = base else {
throw ParseError.message("Only direct colors support modifications for now.")
}
for colorComponent in colorComponents.dropFirst() {
let procedure = try SimpleProcedure(from: colorComponent)
// all of the current modifications require just one parameter
// feel free to change this in case you add a method that needs more than one
guard let parameter = procedure.parameters.first, procedure.parameters.count == 1 else {
throw ParseError.message("Wrong number (\(procedure.parameters.count)) of parameters in procedure \(procedure.name).")
}
let trimmedValue = parameter.value.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let floatValue: CGFloat
if let probablePercentSign = trimmedValue.last, probablePercentSign == "%", let value = Int(trimmedValue.dropLast()) {
floatValue = CGFloat(value) / 100
} else if let value = Float(trimmedValue) {
floatValue = CGFloat(value)
} else {
throw ParseError.message("\(parameter.value) is not a valid integer (with percent sign) nor floating point number to denote the value of the parameter in procedure \(procedure.name).")
}
func verifyLabel(correctLabel: String) throws {
if let label = parameter.label {
guard label == correctLabel else {
throw ParseError.message("Wrong label \(label) inside procedure \(procedure.name). \"\(correctLabel)\" or none should be used instead.")
}
}
}
switch procedure.name {
case "lighter":
try verifyLabel(correctLabel: "by")
color = color.lighter(by: floatValue)
case "darker":
try verifyLabel(correctLabel: "by")
color = color.darker(by: floatValue)
case "saturated":
try verifyLabel(correctLabel: "by")
color = color.saturated(by: floatValue)
case "desaturated":
try verifyLabel(correctLabel: "by")
color = color.desaturated(by: floatValue)
case "fadedOut":
try verifyLabel(correctLabel: "by")
color = color.fadedOut(by: floatValue)
case "fadedIn":
try verifyLabel(correctLabel: "by")
color = color.fadedIn(by: floatValue)
case "alpha":
try verifyLabel(correctLabel: "at")
color = color.withAlphaComponent(floatValue)
default:
throw ParseError.message("Unknown procedure \(procedure.name) used on color \(colorComponents[0]).")
}
}
return .color(color)
}
public static var xsdType: XSDType {
return Color.xsdType
}
}
| mit | 8a96ed39da488a8fef1b0186450acf80 | 40.45625 | 200 | 0.581336 | 4.737857 | false | false | false | false |
adamontherun/Study-iOS-With-Adam-Live | DragAndDropPlaceholder/DragAndDropPlaceholder/DonkeysTableViewController.swift | 1 | 2751 | //😘 it is 8/9/17
import UIKit
class DonkeysTableViewController: UITableViewController {
var photos = [Photo]()
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return photos.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "donkeyCell", for: indexPath)
cell.textLabel?.text = ""
let photo = photos[indexPath.row]
cell.imageView?.image = photo.image
return cell
}
private func configureTableView() {
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100.0
tableView.dropDelegate = self
}
}
extension DonkeysTableViewController: UITableViewDropDelegate {
func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
return UITableViewDropProposal(operation: .copy, intent: .insertAtDestinationIndexPath)
}
func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
for dropItem in coordinator.items {
let indexPath = coordinator.destinationIndexPath ?? IndexPath(row: 0, section: 0)
let placeholder = UITableViewDropPlaceholder(insertionIndexPath: indexPath, reuseIdentifier: "placeholderCell", rowHeight: UITableViewAutomaticDimension)
placeholder.cellUpdateHandler = { (cell) in
guard let cell = cell as? PlaceholderTableViewCell else { return }
cell.activityIndicator.startAnimating()
}
let dragItem = dropItem.dragItem
let placeholderContext = coordinator.drop(dragItem, to: placeholder)
let itemProvider = dragItem.itemProvider
loadPhoto(from: itemProvider, with: placeholderContext)
}
}
private func loadPhoto(from itemProvider: NSItemProvider, with placeholderContext: UITableViewDropPlaceholderContext) {
itemProvider.loadObject(ofClass: Photo.self) { (photo, error) in
guard error == nil,
let photo = photo as? Photo else { return }
DispatchQueue.main.async {
placeholderContext.commitInsertion(dataSourceUpdates: { (insertionIndexPath) in
self.photos.insert(photo, at: insertionIndexPath.row)
})
}
}
}
}
| mit | 5f0c37991d87029518d2335435ef7238 | 38.826087 | 177 | 0.671033 | 5.562753 | false | false | false | false |
frtlupsvn/Vietnam-To-Go | VietNamToGo/ViewControllers/Onboarding/ZCCOnboarding.swift | 1 | 8137 | //
// ZCCOnboarding.swift
// VietNamToGo
//
// Created by Zoom Nguyen on 12/20/15.
// Copyright © 2015 Zoom Nguyen. All rights reserved.
//
import UIKit
import Parse
import ParseFacebookUtilsV4
class ZCCOnboarding: ZCCViewController {
let timeChangeImage = 8.0
var timer : NSTimer!
// MARK: - IB Outlets
@IBOutlet weak var imgOnboarding: UIImageView!
@IBOutlet weak var lblOnboarding: UILabel!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var imgAvatarFacebook: UIImageView!
@IBOutlet weak var lblWelcomeBack: UILabel!
@IBOutlet weak var loginView: UIView!
@IBOutlet weak var facebookView: UIView!
// MARK: - IB Actions
@IBAction func swipeToRight(sender: UISwipeGestureRecognizer) {
changeImageWhenSwipeToRight(ofImageView: imgOnboarding, pageControl: pageControl, arrayImages: arrayImagesOnboarding)
self.resetTimer()
}
@IBAction func swipeToLeft(sender: UISwipeGestureRecognizer) {
changeImageWhenSwipeToLeft(ofImageView: imgOnboarding, pageControl: pageControl, arrayImages: arrayImagesOnboarding)
self.resetTimer()
}
// MARK: - View Cycle
let arrayImagesOnboarding = ["[email protected]","[email protected]","[email protected]","[email protected]","[email protected]"]
let arrayDescriptions = ["Despite being a quick 45-minute turboprop flight from Ho Chi Minh City, Con Son is a world away from Vietnam’s well-beaten tourist trail, with inexplicably few Western travellers.",
"A product of Vietnam’s colonial past, the beloved concoction combines a crunchy French baguette with pork, pate and an ever-changing array of fresh vegetables.",
"The Dong Van district’s Hmong villages and spectacular peaks remain so isolated, foreign tourists are all but unknown.",
"Donita Richards is planning to take her children, 3½ and 1½, to Vietnam next February and wants to know what to do and what to avoid. Our Facebook fans weighed in with travel advice.",
"Ho Chi Minh City – once the Saigon of French diplomats, English writers and American soldiers – is now in its own role as the powerhouse of Vietnam."];
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setupContent()
self.checkLogin()
self.loadData()
}
func loadData(){
self.showProgres(0,status: "Updating data")
/* get Cities and Types */
CityType.syncCityTypeWithParse { () -> Void in
self.showProgres(0.5,status: "Please wait...")
City.syncCityWithParse(){
self.showProgres(0.75,status: "Please wait...")
Places.syncPlacesWithParse { () -> Void in
self.showProgres(1,status: "Finish !")
self.hideHUDProgressAfter(0.5)
}
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.timer = NSTimer.scheduledTimerWithTimeInterval(timeChangeImage, target: self, selector: "nextImageAutomatic", userInfo: nil, repeats: true)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.timer.invalidate()
self.timer = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Functions
func setupContent(){
pageControl.numberOfPages = arrayImagesOnboarding.count
let image = UIImage(named: arrayImagesOnboarding[pageControl.currentPage] )
imgOnboarding.image = image
lblOnboarding.text = arrayDescriptions[pageControl.currentPage]
}
func checkLogin(){
if ((PFUser.currentUser()) == nil){
self.loginView.hidden = false
}else {
updateFacebookStatus()
}
}
func updateFacebookStatus(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let currentUser = PFUser.currentUser()
if let imageFile = currentUser?.objectForKey("facebookProfilePicture"){
let imageURL = NSURL(string: imageFile.url!!)
let imageData = NSData(contentsOfURL: imageURL!)
dispatch_async(dispatch_get_main_queue()) {
if (imageData != nil){
self.imgAvatarFacebook.image = UIImage(data: imageData!)
}
}
}
if let usernameString = currentUser?.objectForKey("fullname"){
dispatch_async(dispatch_get_main_queue()) {
self.lblWelcomeBack.text = "Hi " + (usernameString as! String) as? String
}
}else{
dispatch_async(dispatch_get_main_queue()) {
self.lblWelcomeBack.text = "Hi " + ((currentUser?.objectForKey("email"))! as! String) as? String
}
}
}
self.imgAvatarFacebook.image = UIImage(named: "[email protected]")
self.facebookView.hidden = false
}
func resetTimer(){
self.timer.invalidate()
self.timer = nil
self.timer = NSTimer.scheduledTimerWithTimeInterval(timeChangeImage, target: self, selector: "nextImageAutomatic", userInfo: nil, repeats: true)
}
func nextImageAutomatic(){
changeImageWhenSwipeToLeft(ofImageView: imgOnboarding, pageControl: pageControl, arrayImages: arrayImagesOnboarding)
}
func changeText(){
lblOnboarding.text = arrayDescriptions[pageControl.currentPage]
}
func changeImageWhenSwipeToRight(ofImageView imageView:UIImageView, pageControl:UIPageControl, arrayImages:NSArray){
var nextIndex:Int?
if (pageControl.currentPage == 0){
nextIndex = arrayImages.count - 1
}else {
nextIndex = pageControl.currentPage - 1
}
pageControl.currentPage = nextIndex!
let image = UIImage(named: arrayImages[nextIndex!] as! String)
UIView .transitionWithView(imageView, duration: 0.8, options: .TransitionCrossDissolve, animations: { () -> Void in
imageView.image = image
}, completion: nil)
changeText()
}
func changeImageWhenSwipeToLeft(ofImageView imageView:UIImageView, pageControl:UIPageControl, arrayImages:NSArray){
var nextIndex:Int?
if (pageControl.currentPage == arrayImages.count - 1){
nextIndex = 0
}else {
nextIndex = pageControl.currentPage + 1
}
pageControl.currentPage = nextIndex!
let image = UIImage(named: arrayImages[nextIndex!] as! String)
UIView .transitionWithView(imageView, duration: 0.8, options: .TransitionCrossDissolve, animations: { () -> Void in
imageView.image = image
}, completion: nil)
changeText()
}
// MARK: - 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.
if (segue.identifier == "Segue_Login"){
let loginVC = segue.destinationViewController as! ZCCLoginViewController
loginVC.imageBG = self.imgOnboarding.image
}
if (segue.identifier == "Segue_Register"){
let registerVC = segue.destinationViewController as! ZCCRegisterViewController
registerVC.imageBG = self.imgOnboarding.image
}
}
}
| mit | 19f6698414c12c01b2c9df84c66fa0da | 33.866953 | 211 | 0.61386 | 4.914701 | false | false | false | false |
loudnate/LoopKit | MockKit/Extensions/Collection.swift | 1 | 987 | //
// Collection.swift
// LoopKit
//
// Created by Michael Pangburn on 12/4/18.
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import Dispatch
import LoopKit
extension Collection {
func asyncMap<NewElement>(
_ asyncTransform: (
_ element: Element,
_ completion: @escaping (NewElement) -> Void
) -> Void,
notifyingOn queue: DispatchQueue = .global(),
completion: @escaping ([NewElement]) -> Void
) {
let result = Locked(Array<NewElement?>(repeating: nil, count: count))
let group = DispatchGroup()
for (resultIndex, element) in enumerated() {
group.enter()
asyncTransform(element) { newElement in
result.value[resultIndex] = newElement
group.leave()
}
}
group.notify(queue: queue) {
let transformed = result.value.map { $0! }
completion(transformed)
}
}
}
| mit | e5c568d61b78eb9528c9b031307a4150 | 24.947368 | 77 | 0.565923 | 4.481818 | false | false | false | false |
cafbuddy/cafbuddy-iOS | Caf Buddy/Utilities.swift | 1 | 4933 | //
// Utilities.swift
// CafMate
//
// Created by Jacob Forster on 11/8/14.
// Copyright (c) 2014 St. Olaf ACM. All rights reserved.
//
import Foundation
import UIKit
let COLOR_MAIN_BACKGROUND_OFFWHITE = "#eaeaea" //"#0dc5d4" "#eaeaea" #468499
let COLOR_ACCENT_BLUE = "#0EDBEC"//"#1FB1C3"//
let COLOR_DARKER_BLUE = "#1FB1C3"
let COLOR_ACCENT_GREEN = "#0eec8e" //"#0dd480" //"#0eec8e" //0cd47f
let COLOR_ACCENT_GREEN_DARKER = "#0dd480"
let COLOR_BUTTON_UNPRESSED_GRAY = "#f4f4f4"
let COLOR_BUTTON_PRESSED_GRAY = "#f0f0f0"
let COLOR_COOL_GREY = "#B8B8B8"
let NAV_BAR_HEIGHT = 44
let STATUS_BAR_HEIGHT = 20
let TAB_BAR_HEIGHT = 49
let KEYBOARD_HEIGHT = 216
let TOOLBAR_KEYBOARD_HEIGHT = 35
let BUTTON_WIDTH = 300
func convertFromLocalToUTCTime(targetDate: NSDate) ->NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // superset of OP's format
let str = dateFormatter.stringFromDate(targetDate)
//let str = "2012-12-17 01:00:25";
let utcDf:NSDateFormatter = NSDateFormatter()
//[gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
utcDf.timeZone = NSTimeZone(name: "UTC")
utcDf.dateFormat = "yyyy-MM-dd HH:mm:ss"
//setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
let utcDate = utcDf.dateFromString(str)
return utcDate!
}
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (countElements(cString) != 6) {
return UIColor.grayColor()
}
var rString = (cString as NSString).substringToIndex(2)
var gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
var bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
func filledImageFrom(source : UIImage, color : UIColor) -> UIImage {
// begin a new image context, to draw our colored image onto with the right scale
UIGraphicsBeginImageContextWithOptions(source.size, false, UIScreen.mainScreen().scale)
// get a reference to that context we created
var context : CGContextRef = UIGraphicsGetCurrentContext()
// set the fill color
color.setFill()
// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, source.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, kCGBlendModeColorBurn);
var rect : CGRect = CGRectMake(0, 0, source.size.width, source.size.height);
CGContextDrawImage(context, rect, source.CGImage);
CGContextSetBlendMode(context, kCGBlendModeSourceIn);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);
// generate a new UIImage from the graphics context we drew onto
var coloredImg : UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//return the color-burned image
return coloredImg;
}
func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
var rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
var image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
/*FACTOR THIS INTO SWIFT AND USE TO ROUND THE CORNERS!!!!
+ (UIImage *)imageWithRoundedCornersSize:(float)cornerRadius usingImage:(UIImage *)original
{
CGRect frame = CGRectMake(0, 0, original.size.width, original.size.height);
// Begin a new image that will be the new image with the rounded corners
// (here with the size of an UIImageView)
UIGraphicsBeginImageContextWithOptions(original.size, NO, 1.0);
// Add a clip before drawing anything, in the shape of an rounded rect
[[UIBezierPath bezierPathWithRoundedRect:frame
cornerRadius:cornerRadius] addClip];
// Draw your image
[original drawInRect:frame];
// Get the image, here setting the UIImageView image
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// Lets forget about that we were drawing
UIGraphicsEndImageContext();
return image;
}*/
func showAlert(title:String,message:String)
{
let alert = UIAlertView()
alert.title = title
alert.message = message
alert.addButtonWithTitle("Cancel")
alert.show()
}
| mit | 11b7fa5ec03f04d12740c18beac82880 | 33.739437 | 127 | 0.70525 | 4.060082 | false | false | false | false |
citysite102/kapi-kaffeine | kapi-kaffeine/KPLoginRequest.swift | 1 | 1399 | //
// KPLoginRequest.swift
// kapi-kaffeine
//
// Created by YU CHONKAO on 2017/5/26.
// Copyright © 2017年 kapi-kaffeine. All rights reserved.
//
import UIKit
import PromiseKit
import Alamofire
class KPLoginRequest: NetworkRequest {
typealias ResponseType = RawJsonResult
var endpoint: String { return "/login" }
var identifier: String!
var displayName: String!
var photoURL: String!
var email: String!
var method: Alamofire.HTTPMethod { return .post }
var parameters: [String : Any]? {
var parameters = [String : Any]()
parameters["member_id"] = self.identifier
parameters["display_name"] = self.displayName
parameters["photo_url"] = self.photoURL
parameters["email"] = self.email
return parameters
}
var headers: [String : String] {
return ["Content-Type": "application/json",
"User-Agent": "iReMW4K4fyWos"]
}
public func perform(_ identifier: String!,
_ displayName: String!,
_ photoURL: String!,
_ email: String!) -> Promise<(ResponseType)> {
self.identifier = identifier
self.displayName = displayName
self.photoURL = photoURL
self.email = email
return networkClient.performRequest(self).then(execute: responseHandler)
}
}
| mit | c4ab98ac30fbf6f5f8676c50fe646e17 | 27.489796 | 80 | 0.605301 | 4.592105 | false | false | false | false |
randallli/material-components-ios | components/Tabs/examples/supplemental/TabBarIndicatorTemplateExampleSupplemental.swift | 1 | 4623 | /*
Copyright 2017-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialComponents.MaterialButtons
import MaterialComponents.MaterialButtons_ButtonThemer
extension TabBarIndicatorTemplateExample {
private func themeButton(_ button: MDCButton) {
let buttonScheme = MDCButtonScheme()
buttonScheme.colorScheme = colorScheme
buttonScheme.typographyScheme = typographyScheme
MDCContainedButtonThemer.applyScheme(buttonScheme, to: button)
}
func makeAlignmentButton() -> MDCButton {
let button = MDCButton()
themeButton(button)
button.setTitle("Change Alignment", for: .normal)
return button
}
func makeAppearanceButton() -> MDCButton {
let button = MDCButton()
themeButton(button)
button.setTitle("Change Appearance", for: .normal)
return button
}
func makeAppBar() -> MDCAppBar {
let appBar = MDCAppBar()
self.addChildViewController(appBar.headerViewController)
appBar.navigationBar.backgroundColor = UIColor.white
appBar.headerViewController.headerView.backgroundColor = UIColor.white
// Give the tab bar enough height to accomodate all possible item appearances.
appBar.headerViewController.headerView.minMaxHeightIncludesSafeArea = false
appBar.headerViewController.headerView.minimumHeight = 128
appBar.headerStackView.bottomBar = self.tabBar
appBar.headerStackView.setNeedsLayout()
return appBar
}
func setupExampleViews() {
view.backgroundColor = UIColor.white
appBar.addSubviewsToParent()
// Set up buttons
alignmentButton.translatesAutoresizingMaskIntoConstraints = false
appearanceButton.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(alignmentButton)
self.view.addSubview(appearanceButton)
// Buttons are laid out relative to the safe area, if available.
let alignmentGuide: Any
#if swift(>=3.2)
if #available(iOS 11.0, *) {
alignmentGuide = view.safeAreaLayoutGuide
} else {
alignmentGuide = view
}
#else
alignmentGuide = view
#endif
NSLayoutConstraint.activate([
// Center alignment button
NSLayoutConstraint(item: alignmentButton,
attribute: .centerX,
relatedBy: .equal,
toItem: self.view,
attribute: .centerX,
multiplier: 1,
constant: 0),
NSLayoutConstraint(item: alignmentButton,
attribute: .bottom,
relatedBy: .equal,
toItem: alignmentGuide,
attribute: .bottom,
multiplier: 1,
constant: -40),
// Place appearance button above
NSLayoutConstraint(item: appearanceButton,
attribute: .centerX,
relatedBy: .equal,
toItem: self.view,
attribute: .centerX,
multiplier: 1,
constant: 0),
NSLayoutConstraint(item: appearanceButton,
attribute: .bottom,
relatedBy: .equal,
toItem: alignmentButton,
attribute: .top,
multiplier: 1,
constant: -8),
])
self.title = "Custom Selection Indicator"
}
}
extension TabBarIndicatorTemplateExample {
override var childViewControllerForStatusBarStyle: UIViewController? {
return appBar.headerViewController
}
}
// MARK: - Catalog by convention
extension TabBarIndicatorTemplateExample {
@objc class func catalogBreadcrumbs() -> [String] {
return ["Tab Bar", "Custom Selection Indicator"]
}
@objc class func catalogIsPrimaryDemo() -> Bool {
return false
}
func catalogShouldHideNavigation() -> Bool {
return true
}
@objc class func catalogIsPresentable() -> Bool {
return true
}
}
| apache-2.0 | 7d4716608dc712969fdfc02d7b85a60f | 31.104167 | 85 | 0.646334 | 5.483986 | false | false | false | false |
ollie-williams/octopus | json.swift | 1 | 2432 | typealias JSObject = [String:JSValue]
func makeObj(values:[(String,JSValue)]) -> JSObject {
var record = JSObject()
for (name,val) in values {
record[name] = val
}
return record
}
enum JSValue : CustomStringConvertible {
case string(String)
case number(Double)
case object(JSObject)
case array([JSValue])
case bool(Bool)
case null
static func make(s:String) -> JSValue {return string(s)}
static func make(n:Double) -> JSValue {return number(n)}
static func make(b:Bool) -> JSValue {return bool(b)}
static func make(o:JSObject) -> JSValue {return object(o)}
static func makeary(a:[JSValue]) -> JSValue {return array(a)}
var description: String {
switch self {
case string(let s): return s
case number(let n) : return "\(n)"
case object(let obj) : return "\(obj)"
case bool(let b): return "\(b)"
case array(let a): return "\(a)"
case null: return "null"
}
}
}
struct JSParser : Parser {
static let skip = regex("\\s*")
static let dquote = const("\"")
static let ocurly = const("{") ~> skip
static let ccurly = const("}") ~> skip
static let obrack = const("[") ~> skip
static let cbrack = const("]") ~> skip
static let comma = const(",") ~> skip
static let colon = const(":") ~> skip
static let string = dquote >~ regex("[^\"]*") ~> dquote ~> skip
static let stringval = string |> JSValue.make
static let number = FloatParser(strict:false) |> JSValue.make
static let object = LateBound<JSObject>()
static let objval = object |> JSValue.make
static let array = LateBound<JSValue>()
static let bool = (const(true) | const(false)) |> JSValue.make
static let null = token(const("null"), value: JSValue.null)
static let value = (null | objval | array | bool | stringval | number) ~> skip
static let pair = string ~>~ (colon >~ value)
static let objimpl = ocurly >~ sepby(pair, sep: comma) ~> ccurly |> makeObj
static let arrayimpl = obrack >~ sepby(value, sep: comma) ~> cbrack |> JSValue.makeary
static func parse(str:String) -> JSObject? {
let stream = CharStream(str:str)
return parse(stream)
}
static func parse(stream:CharStream) -> JSObject? {
object.inner = objimpl.parse
array.inner = arrayimpl.parse
return object.parse(stream)
}
// Parse implementation
typealias Target = JSObject
func parse(stream:CharStream) -> Target? {
return JSParser.parse(stream)
}
}
| apache-2.0 | d576a77a151f537156c863bdb3c0a3d9 | 30.584416 | 88 | 0.651316 | 3.651652 | false | false | false | false |
huonw/swift | benchmark/single-source/TwoSum.swift | 12 | 3865 | //===--- TwoSum.swift -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test is solves 2SUM problem:
// Given an array and a number C, find elements A and B such that A+B = C
import TestsUtils
public let TwoSum = BenchmarkInfo(
name: "TwoSum",
runFunction: run_TwoSum,
tags: [.validation, .api, .Dictionary, .Array, .algorithm])
let array = [
959, 81, 670, 727, 416, 171, 401, 398, 707, 596, 200, 9, 414, 98, 43,
352, 752, 158, 593, 418, 240, 912, 542, 445, 429, 456, 993, 618, 52, 649,
759, 190, 126, 306, 966, 37, 787, 981, 606, 372, 597, 901, 158, 284, 809,
820, 173, 538, 644, 428, 932, 967, 962, 959, 233, 467, 220, 8, 729, 889,
277, 494, 554, 670, 91, 657, 606, 248, 644, 8, 366, 815, 567, 993, 696,
763, 800, 531, 301, 863, 680, 703, 279, 388, 871, 124, 302, 617, 410, 366,
813, 599, 543, 508, 336, 312, 212, 86, 524, 64, 641, 533, 207, 893, 146,
534, 104, 888, 534, 464, 423, 583, 365, 420, 642, 514, 336, 974, 846, 437,
604, 121, 180, 794, 278, 467, 818, 603, 537, 167, 169, 704, 9, 843, 555,
154, 598, 566, 676, 682, 828, 128, 875, 445, 918, 505, 393, 571, 3, 406,
719, 165, 505, 750, 396, 726, 404, 391, 532, 403, 728, 240, 89, 917, 665,
561, 282, 302, 438, 714, 6, 290, 939, 200, 788, 128, 773, 900, 934, 772,
130, 884, 60, 870, 812, 750, 349, 35, 155, 905, 595, 806, 771, 443, 304,
283, 404, 905, 861, 820, 338, 380, 709, 927, 42, 478, 789, 656, 106, 218,
412, 453, 262, 864, 701, 686, 770, 34, 624, 597, 843, 913, 966, 230, 942,
112, 991, 299, 669, 399, 630, 943, 934, 448, 62, 745, 917, 397, 440, 286,
875, 22, 989, 235, 732, 906, 923, 643, 853, 68, 48, 524, 86, 89, 688,
224, 546, 73, 963, 755, 413, 524, 680, 472, 19, 996, 81, 100, 338, 626,
911, 358, 887, 242, 159, 731, 494, 985, 83, 597, 98, 270, 909, 828, 988,
684, 622, 499, 932, 299, 449, 888, 533, 801, 844, 940, 642, 501, 513, 735,
674, 211, 394, 635, 372, 213, 618, 280, 792, 487, 605, 755, 584, 163, 358,
249, 784, 153, 166, 685, 264, 457, 677, 824, 391, 830, 310, 629, 591, 62,
265, 373, 195, 803, 756, 601, 592, 843, 184, 220, 155, 396, 828, 303, 553,
778, 477, 735, 430, 93, 464, 306, 579, 828, 759, 809, 916, 759, 336, 926,
776, 111, 746, 217, 585, 441, 928, 236, 959, 417, 268, 200, 231, 181, 228,
627, 675, 814, 534, 90, 665, 1, 604, 479, 598, 109, 370, 719, 786, 700,
591, 536, 7, 147, 648, 864, 162, 404, 536, 768, 175, 517, 394, 14, 945,
865, 490, 630, 963, 49, 904, 277, 16, 349, 301, 840, 817, 590, 738, 357,
199, 581, 601, 33, 659, 951, 640, 126, 302, 632, 265, 894, 892, 587, 274,
487, 499, 789, 954, 652, 825, 512, 170, 882, 269, 471, 571, 185, 364, 217,
427, 38, 715, 950, 808, 270, 746, 830, 501, 264, 581, 211, 466, 970, 395,
610, 930, 885, 696, 568, 920, 487, 764, 896, 903, 241, 894, 773, 896, 341,
126, 22, 420, 959, 691, 207, 745, 126, 873, 341, 166, 127, 108, 426, 497,
681, 796, 430, 367, 363
]
@inline(never)
public func run_TwoSum(_ N: Int) {
var i1: Int?
var i2: Int?
var Dict: Dictionary<Int, Int> = [:]
for _ in 1...2*N {
for Sum in 500..<600 {
Dict = [:]
i1 = nil
i2 = nil
for n in 0..<array.count {
if let m = Dict[Sum-array[n]] {
i1 = m
i2 = n
break
}
Dict[array[n]] = n
}
CheckResults(i1 != nil && i2 != nil)
CheckResults(Sum == array[i1!] + array[i2!])
}
}
}
| apache-2.0 | d3e4b9d0c3e58bc4990ed6e95a7ec2ab | 46.716049 | 80 | 0.555498 | 2.480745 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournalTests/Helpers/MockUserManager.swift | 1 | 2207 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
@testable import third_party_sciencejournal_ios_ScienceJournalOpen
/// A mock user manager that allows for injecting dependencies.
class MockUserManager: UserManager {
var driveSyncManager: DriveSyncManager?
var metadataManager: MetadataManager
var preferenceManager: PreferenceManager
var sensorDataManager: SensorDataManager
var assetManager: UserAssetManager
let experimentDataDeleter: ExperimentDataDeleter
let documentManager: DocumentManager
var exportType: UserExportType {
return .saveToFiles
}
var isDriveSyncEnabled: Bool {
return false
}
init(driveSyncManager: DriveSyncManager?,
metadataManager: MetadataManager,
preferenceManager: PreferenceManager,
sensorDataManager: SensorDataManager,
assetManager: UserAssetManager) {
self.driveSyncManager = driveSyncManager
self.metadataManager = metadataManager
self.preferenceManager = preferenceManager
self.sensorDataManager = sensorDataManager
self.assetManager = assetManager
experimentDataDeleter = ExperimentDataDeleter(accountID: "MockUser",
metadataManager: metadataManager,
sensorDataManager: sensorDataManager)
documentManager = DocumentManager(experimentDataDeleter: experimentDataDeleter,
metadataManager: metadataManager,
sensorDataManager: sensorDataManager)
}
func tearDown() {}
func deleteAllUserData() throws {}
}
| apache-2.0 | ed92f05798c7bc3cd0a5285c139e170a | 35.783333 | 87 | 0.714092 | 5.573232 | false | false | false | false |
sora0077/QiitaKit | QiitaKit/src/Meta/Meta.swift | 1 | 2126 | //
// Meta.swift
// QiitaKit
//
// Created by 林達也 on 2015/07/05.
// Copyright (c) 2015年 林達也. All rights reserved.
//
import Foundation
private func toInt(key: String, _ dict: [NSObject: AnyObject]) -> Int {
let s = dict["Rate-Limit"] as! String
return Int(s)!
}
func find(items: [NSURLQueryItem], name: String) -> NSURLQueryItem? {
return items.filter { $0.name == name }.first
}
public class Meta {
public let rateLimit: Int
public let rateRemaining: Int
public let rateReset: Int
init(dict: [NSObject: AnyObject]) {
self.rateLimit = toInt("Rate-Limit", dict)
self.rateRemaining = toInt("Rate-Remaining", dict)
self.rateReset = toInt("Rate-Reset", dict)
}
}
public protocol LinkProtocol {
var page: Int { get }
var per_page: Int { get }
init!(url: NSURL!)
}
public class LinkMeta<T: LinkProtocol>: Meta {
public let first: T
public let last: T
public let prev: T?
public let next: T?
public let totalCount: Int
override init(dict: [NSObject : AnyObject]) {
self.totalCount = toInt("Total-Count", dict)
let link = (dict["Link"] as! String).componentsSeparatedByString(",")
var links: [String: String] = [:]
let regex = try! NSRegularExpression(pattern: "^.?<(.+)>; rel=\"(.*)\".?$", options: [])
for l in link as [NSString] {
if let result = regex.firstMatchInString(l as String, options: [], range: NSRange(location: 0, length: l.length)) {
let key = l.substringWithRange(result.rangeAtIndex(2))
let url = l.substringWithRange(result.rangeAtIndex(1))
links[key] = url
}
}
self.first = T(url: NSURL(string: links["first"]!))
self.last = T(url: NSURL(string: links["last"]!))
self.prev = links["prev"].flatMap { T(url: NSURL(string: $0)) }
self.next = links["next"].flatMap { T(url: NSURL(string: $0)) }
super.init(dict: dict)
}
}
| mit | f77e166f21af2c9b23f5e63fb83831b0 | 26.428571 | 127 | 0.565814 | 3.940299 | false | false | false | false |
wangCanHui/weiboSwift | weiboSwift/Classes/Module/Home/View/Cell/CZStatusCell.swift | 1 | 5598 | //
// CZStatusCell.swift
// weiboSwift
//
// Created by 王灿辉 on 15/10/31.
// Copyright © 2015年 王灿辉. All rights reserved.
//
import UIKit
let StatusCellMargin: CGFloat = 8
class CZStatusCell: UITableViewCell {
// MARK: - 属性
/// 代理
weak var cellDelegate: CZStatusCellDelegate?
/// 配图宽度约束
var pictureViewWidthCons: NSLayoutConstraint?
/// 配图高度约束
var pictureViewHeightCons: NSLayoutConstraint?
/// 微博模型
var status: CZStatus? {
didSet{
// 将模型赋值给 topView
topView.status = status
// 将模型赋值给配图视图
pictureView.status = status
// 重新设置配图的宽高约束
pictureViewWidthCons?.constant = pictureView.calcPictureViewSize().width
pictureViewHeightCons?.constant = pictureView.calcPictureViewSize().height
// 设置微博内容
// contentLabel.text = status?.text
// 设置带图片的微博内容
contentLabel.attributedText = status?.attrText
}
}
// 设置cell的模型,cell会根据模型,从新设置内容,更新约束.获取子控件的最大Y值
// 返回cell的高度
func rowHeight(status: CZStatus) -> CGFloat {
self.status = status
// 重新布局
layoutIfNeeded()
// 获取子控件的最大Y值
let maxY: CGFloat = CGRectGetMaxY(bottomView.frame)
return maxY
}
// MARK: - 构造函数
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
prepareUI()
}
// MARK: - 准备UI
func prepareUI() {
// 添加子控件
contentView.addSubview(topView)
contentView.addSubview(contentLabel)
contentView.addSubview(pictureView)
contentView.addSubview(bottomView)
// 设置约束
// 1. topView
topView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: contentView, size: CGSizeMake(UIScreen.width(), 54))
// 2 .微博内容
contentLabel.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: topView, size: nil, offset: CGPointMake(StatusCellMargin, StatusCellMargin))
// 设置宽度
// contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: -StatusCellMargin*2))
// 不能使用上面的约束方法,来约束contentLabel得宽度,会导致部分cell的高度改变,底部留下空白,原因不明
contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: UIScreen.width() - 2 * StatusCellMargin))
// 微博配图
// 因为转发微博需要设置配图约束,不能再这里设置配图的约束,需要在创建一个cell继承CZStatusCell,添加上配图的约束
// let cons = pictureView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: contentLabel, size:
// CGSizeZero, offset: CGPointMake(0, StatusCellMargin))
// // 获取配图的宽高约束
// pictureViewWidthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
// pictureViewHeightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
// 3. bottomView
bottomView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: pictureView, size: CGSizeMake(UIScreen.width(), 44), offset: CGPointMake(-StatusCellMargin, StatusCellMargin))
// 3. 添加contentView底部和bottomView的底部重合
// contentView.addConstraint(NSLayoutConstraint(item: contentView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: bottomView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: StatusCellMargin))
}
// MARK: - 懒加载
/// 顶部视图
private lazy var topView:CZStatusTopView = CZStatusTopView()
/// 微博内容
lazy var contentLabel:FFLabel = {
let label = FFLabel(fontSize: 16, textColor: UIColor.blackColor())
// 设置显示多行
label.numberOfLines = 0
label.labelDelegate = self
return label
}()
/// 微博配图
lazy var pictureView: CZStatusPictureView = CZStatusPictureView()
/// 底部视图
lazy var bottomView: CZStatusBottomView = CZStatusBottomView()
}
// MARK: - 扩展CZStatusCell,实现FFLabelDelegate协议
extension CZStatusCell: FFLabelDelegate {
// 当有高亮的文字被点击
func labelDidSelectedLinkText(label: FFLabel, text: String) {
// print("点中的文字:\(text)")
// 如果点击的是网址,就弹出网址对应的内容
if text.hasPrefix("http") {
print("弹出内容")
cellDelegate?.urlClick(text)
}
}
}
// MARK: - 自定义CZStatusCellDelegate
protocol CZStatusCellDelegate: NSObjectProtocol {
// cell里面的url地址被点击了
func urlClick(text: String)
}
| apache-2.0 | 6347326594712b8e2f5c37eae903c782 | 34.056738 | 270 | 0.653652 | 4.543199 | false | false | false | false |
Szaq/Grower | Grower/PackedStructArray.swift | 1 | 708 | //
// PackedStructArray.swift
// Grower
//
// Created by Lukasz Kwoska on 12/12/14.
// Copyright (c) 2014 Spinal Development. All rights reserved.
//
import Foundation
class PackedStructArray<T : PackedStruct> {
private(set) var data: [Float]
let count: Int
init(count: Int) {
self.count = count
self.data = [Float](count: count * T.size() / sizeof(Float), repeatedValue:0)
}
subscript (idx: Int) -> T {
let type = T.self
assert(idx < count)
let offset = type.size() * idx
let resp = type(ptr: ptr(&data).advancedBy(offset))
return resp
}
private func ptr(ptr:UnsafeMutablePointer<Void>) -> UnsafeMutablePointer<Void> {
return ptr
}
}
| mit | ed45d4cda374e834f765f3e224d08d04 | 19.228571 | 82 | 0.637006 | 3.42029 | false | false | false | false |
silence0201/Swift-Study | Note/Day 02/02-数组的使用.playground/Contents.swift | 1 | 1658 | //: Playground - noun: a place where people can play
import UIKit
/*
数组的使用
1.数组的定义
1> 定义不可变数组
2> 定义可变数组
2.对可变数组的基本操作
增删改查
3.数组的遍历
1> 获取数组的长度
2> 数组的遍历(i/item/index-item)
4.数组的合并
*/
// 1.数组的定义
// 1> 定义不可变数组: 使用let修饰
// 数组的类型: 1> Array<String> 2> [String] (推荐)
let array = ["why", "lmj", "lnj"]
// array.append("yz")
// 2> 定义可变数组: 使用var修饰
// UIView() CGRect()
// var arrayM = Array<String>()
var arrayM = [String]()
// 2.对可变数组的基本操作
// 增删改查
// 2.1.添加元素
arrayM.append("why")
arrayM.append("lmj")
arrayM.append("lnj")
// 2.2.删除元素
arrayM.remove(at: 0)
arrayM
// 2.3.修改元素
arrayM[0] = "yz"
arrayM
// 2.4.获取元素
let item = arrayM[1]
// 3.对数组的遍历
// 3.1.获取数组的长度
let count = array.count
// 3.2.对数组进行遍历(可以获取到下标值)
for i in 0..<count {
print(array[i])
}
// 3.3.对数组进行遍历(不需要获取下标值)
for item in array {
print(item)
}
// 3.4.对数组进行遍历(既获取下标值,又获取元素)
for (index, item) in array.enumerated() {
print(index)
print(item)
}
// 4.数组的合并
// 如果两个数组中存放的是相同的元素,那么在swift中可以对两个数组进行相加,直接合并
let array1 = ["why", "yz"]
let array2 = ["lmj", "lnj"]
let array3 = [12, 20, 30]
let resultArray = array1 + array2
// let result = array1 + array3 错误写法
| mit | 6b0395841dd5f33e1e4087c8ec1ae929 | 12.83908 | 52 | 0.602159 | 2.370079 | false | false | false | false |
argent-os/argent-ios | app-ios/SignupViewControllerThree.swift | 1 | 11811 | //
// SignupViewControllerThree.swift
// argent-ios
//
// Created by Sinan Ulkuatam on 2/19/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import Foundation
import UIKit
import UIColor_Hex_Swift
import KeychainSwift
import StepSlider
import SCLAlertView
class SignupViewControllerThree: UIViewController, UITextFieldDelegate, UIScrollViewDelegate {
// WHEN NAVIGATING TO A NAVIGATION CONTROLLER USE SEGUE SHOW NOT MODAL!
@IBOutlet weak var continueButton: UIButton!
let passwordTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300, height: 40))
let repeatPasswordTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300, height: 40))
// Keychain
let keychain = KeychainSwift()
override func viewDidAppear(animated: Bool) {
let stepButton = UIBarButtonItem(title: "3/4", style: UIBarButtonItemStyle.Plain, target: nil, action: Selector(""))
navigationItem.rightBarButtonItem = stepButton
navigationItem.rightBarButtonItem?.tintColor = UIColor.lightBlue()
navigationItem.rightBarButtonItem?.setTitleTextAttributes([
NSFontAttributeName: UIFont(name: "SFUIText-Regular", size: 17)!,
NSForegroundColorAttributeName:UIColor.lightBlue()
], forState: .Normal)
self.continueButton.enabled = false
// Allow continue to be clicked
let _ = Timeout(0.3) {
self.continueButton.enabled = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
addToolbarButton()
// Focuses view controller on first name text input
passwordTextField.becomeFirstResponder()
// Set screen bounds
let screen = UIScreen.mainScreen().bounds
let screenWidth = screen.size.width
let screenHeight = screen.size.height
let stepper = StepSlider()
stepper.frame = CGRect(x: 30, y: 65, width: screenWidth-60, height: 15)
stepper.index = 2
stepper.trackColor = UIColor.groupTableViewBackgroundColor()
stepper.trackHeight = 2
stepper.trackCircleRadius = 3
stepper.sliderCircleColor = UIColor.slateBlue()
stepper.sliderCircleRadius = 3
stepper.maxCount = 4
stepper.tintColor = UIColor.slateBlue()
stepper.backgroundColor = UIColor.clearColor()
// self.view.addSubview(stepper)
let scrollView:UIScrollView = UIScrollView()
scrollView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
scrollView.delegate = self
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollEnabled = true
scrollView.userInteractionEnabled = true
scrollView.contentSize = CGSizeMake(screenWidth, 550)
self.view!.addSubview(scrollView)
// Inherit UITextField Delegate, this is used for next and join on keyboard
self.passwordTextField.delegate = self
self.repeatPasswordTextField.delegate = self
continueButton.layer.cornerRadius = 0
continueButton.backgroundColor = UIColor.brandGreen()
scrollView.addSubview(continueButton)
// Programatically set the input fields
passwordTextField.tag = 234
passwordTextField.textAlignment = NSTextAlignment.Center
passwordTextField.font = UIFont.systemFontOfSize(17)
passwordTextField.layer.borderColor = UIColor.whiteColor().colorWithAlphaComponent(0.0).CGColor
passwordTextField.layer.borderWidth = 1
passwordTextField.layer.cornerRadius = 10
passwordTextField.backgroundColor = UIColor.clearColor()
passwordTextField.placeholder = "Password"
passwordTextField.textColor = UIColor.lightBlue()
passwordTextField.autocapitalizationType = UITextAutocapitalizationType.Words
passwordTextField.secureTextEntry = true
passwordTextField.autocorrectionType = UITextAutocorrectionType.No
passwordTextField.keyboardType = UIKeyboardType.Default
passwordTextField.returnKeyType = UIReturnKeyType.Next
passwordTextField.clearButtonMode = UITextFieldViewMode.Never
passwordTextField.frame = CGRect(x: screenWidth/2-150, y: screenHeight*0.20, width: 300, height: 50)
passwordTextField.returnKeyType = UIReturnKeyType.Next
scrollView.addSubview(passwordTextField)
repeatPasswordTextField.tag = 235
repeatPasswordTextField.textAlignment = NSTextAlignment.Center
repeatPasswordTextField.font = UIFont.systemFontOfSize(17)
repeatPasswordTextField.layer.borderColor = UIColor.whiteColor().colorWithAlphaComponent(0.0).CGColor
repeatPasswordTextField.layer.borderWidth = 1
repeatPasswordTextField.layer.cornerRadius = 10
repeatPasswordTextField.backgroundColor = UIColor.clearColor()
repeatPasswordTextField.placeholder = "Repeat Password"
repeatPasswordTextField.textColor = UIColor.lightBlue()
repeatPasswordTextField.autocapitalizationType = UITextAutocapitalizationType.Words
repeatPasswordTextField.secureTextEntry = true
repeatPasswordTextField.autocorrectionType = UITextAutocorrectionType.No
repeatPasswordTextField.keyboardType = UIKeyboardType.EmailAddress
repeatPasswordTextField.returnKeyType = UIReturnKeyType.Next
repeatPasswordTextField.clearButtonMode = UITextFieldViewMode.Never
repeatPasswordTextField.frame = CGRect(x: screenWidth/2-150, y: screenHeight*0.30, width: 300, height: 50)
repeatPasswordTextField.returnKeyType = UIReturnKeyType.Next
scrollView.addSubview(repeatPasswordTextField)
// Focuses view controller on first name text input
passwordTextField.becomeFirstResponder()
self.navigationController?.navigationBar.tintColor = UIColor.lightBlue()
title = ""
// Transparent navigation bar
self.navigationController?.view.backgroundColor = UIColor.clearColor()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.backgroundColor = UIColor.clearColor()
self.navigationController?.navigationBar.tintColor = UIColor.mediumBlue()
let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 65))
navBar.translucent = true
navBar.tintColor = UIColor.whiteColor()
navBar.backgroundColor = UIColor.clearColor()
navBar.shadowImage = UIImage()
navBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
navBar.titleTextAttributes = [
NSFontAttributeName: UIFont(name: "SFUIText-Regular", size: 17)!,
NSForegroundColorAttributeName:UIColor.lightBlue()
]
self.view.addSubview(navBar)
let navItem = UINavigationItem(title: "Create a Password")
navItem.leftBarButtonItem?.tintColor = UIColor.mediumBlue()
navBar.setItems([navItem], animated: true)
// Do any additional setup after loading the view, typically from a nib.
}
// Add send toolbar
func addToolbarButton()
{
let screen = UIScreen.mainScreen().bounds
let screenWidth = screen.size.width
let sendToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, screenWidth, 50))
// sendToolbar.barStyle = UIBarStyle.Default
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Continue", style: UIBarButtonItemStyle.Done, target: self, action: #selector(SignupViewControllerThree.nextStep(_:)))
done.setTitleTextAttributes([
NSFontAttributeName : UIFont(name: "SFUIText-Regular", size: 15)!,
NSForegroundColorAttributeName : UIColor.whiteColor()
], forState: .Normal)
var items: [UIBarButtonItem]? = [UIBarButtonItem]()
items?.append(flexSpace)
items?.append(done)
items?.append(flexSpace)
sendToolbar.items = items
sendToolbar.sizeToFit()
passwordTextField.inputAccessoryView=sendToolbar
repeatPasswordTextField.inputAccessoryView=sendToolbar
}
func nextStep(sender: AnyObject) {
let x = performValidation()
if x == true {
performSegueWithIdentifier("finishView", sender: sender)
}
}
func displayErrorAlertMessage(alertMessage:String) {
showAlert(.Error, title: "Error", msg: alertMessage)
self.view.endEditing(true)
}
// Allow use of next and join on keyboard
func textFieldShouldReturn(textField: UITextField) -> Bool {
let nextTag: Int = textField.tag + 1
let nextResponder: UIResponder? = textField.superview?.superview?.viewWithTag(nextTag)
if let nextR = nextResponder
{
// Found next responder, so set it.
nextR.becomeFirstResponder()
}
else
{
// Not found, so remove keyboard.
textField.resignFirstResponder()
return true
}
return false
}
// Checks for password to have at least one uppercase, at least a number, and a minimum length of 6 characters + a maximum of 15.
func isValidPassword(candidate: String) -> Bool {
let passwordRegex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{6,15}$"
return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluateWithObject(candidate)
}
func performValidation() -> Bool {
if(passwordTextField.text != repeatPasswordTextField.text) {
// display alert
displayErrorAlertMessage("Passwords do not match");
return false
} else if(passwordTextField.text == "" || repeatPasswordTextField.text == "") {
// display alert
displayErrorAlertMessage("Password cannot be empty");
return false
} else if(!isValidPassword(passwordTextField.text!)) {
displayErrorAlertMessage("Password must contain at least 1 capital letter and 1 number, be longer than 6 characters and cannot be more than 15 characters in length");
return false
} else {
keychain.set(passwordTextField.text!, forKey: "userPassword")
}
return true
}
// VALIDATION
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject!) -> Bool {
if(identifier == "finishView") {
if(passwordTextField.text != repeatPasswordTextField.text) {
// display alert
displayErrorAlertMessage("Passwords do not match");
return false
} else if(passwordTextField.text == "" || repeatPasswordTextField.text == "") {
// display alert
displayErrorAlertMessage("Password cannot be empty");
return false
} else if(!isValidPassword(passwordTextField.text!)) {
displayErrorAlertMessage("Password must contain at least 1 capital letter and 1 number, be longer than 6 characters and cannot be more than 15 characters in length");
return false
} else {
keychain.set(passwordTextField.text!, forKey: "userPassword")
}
}
return true
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
} | mit | 2eaa1d81057123b3a2c9aec92e1bd626 | 43.908745 | 182 | 0.670957 | 5.631855 | false | false | false | false |
L-Zephyr/Drafter | Sources/Drafter/Parser/TokenParser/TokenParser.swift | 1 | 4675 | //
// ConcreteParserType.swift
// drafterPackageDescription
//
// Created by LZephyr on 2017/10/31.
//
import Foundation
import SwiftyParse
// MARK: - TokenParser
typealias Tokens = [Token]
typealias TokenParser<T> = Parser<T, Tokens>
// MARK: - TokenParser Extensions
extension Parser where Stream == Tokens {
/// 执行parser,只返回结果
func run(_ tokens: Tokens) -> Result? {
switch self.parse(tokens) {
case .success(let (result, _)):
return result
case .failure(let error):
#if DEBUG
print("\(error)")
#endif
return nil
}
}
/// 连续执行该Parser直到输入耗尽为止,将所有的结果放在数组中返回,不会返回错误
var continuous: TokenParser<[Result]> {
return TokenParser<[Result]> { (tokens) -> ParseResult<([Result], Tokens)> in
var result = [Result]()
var remainder = tokens
while remainder.count != 0 {
switch self.parse(remainder) {
case .success(let (t, rest)):
result.append(t)
remainder = rest
case .failure(let error):
#if DEBUG
print("fail: \(error), continuous to next")
#endif
remainder = Array(remainder.dropFirst())
continue
}
}
return .success((result, remainder))
}
}
}
/// 创建一个始终返回指定值的的算子,不消耗输入
func pure<T>(_ t: T) -> TokenParser<T> {
return TokenParser<T>.result(t)
}
// MARK: - 这些都要去掉
/// 创建一个始终返回错误的parser
func error<T>(_ err: ParseError = .unkown) -> TokenParser<T> {
return TokenParser<T>.error(err)
}
/// 解析单个token并消耗输入, 失败时不消耗输入
func token(_ t: TokenType) -> TokenParser<Token> {
return Parser(parse: { (tokens) -> ParseResult<(Token, Tokens)> in
guard let first = tokens.first, first.type == t else {
let msg = "Expected type: \(t), found: \(tokens.first?.description ?? "empty")"
return .failure(.notMatch(msg))
}
#if DEBUG
print("match token: \(first)")
#endif
return .success((first, Array(tokens.dropFirst())))
})
}
// MARK: - Any Tokens
/// 匹配任意一个Token
var anyToken: TokenParser<Token> {
return Parser { (tokens) -> ParseResult<(Token, Tokens)> in
guard let first = tokens.first else {
return .failure(.custom("tokens empty"))
}
return .success((first, Array(tokens.dropFirst())))
}
}
/// 获取任意Token知道p成功为止, p不会消耗输入,该方法不会返回错误
func anyTokens(until p: TokenParser<Token>) -> TokenParser<[Token]> {
return (p.not *> anyToken).many
}
/// 匹配在l和r之间的任意Token,l和r也会被消耗掉并出现在结果中,lr匹配失败时会返回错误
func anyTokens(encloseBy l: TokenParser<Token>, and r: TokenParser<Token>) -> TokenParser<[Token]> {
let content = l.lookahead *> lazy(anyTokens(encloseBy: l, and: r)) // 递归匹配
<|> ({ [$0] } <^> (r.not *> anyToken)) // 匹配任意token直到碰到r
return curry({ [$0] + Array($1.joined()) + [$2] })
<^> l
<*> content.many
<*> r
}
/// 匹配在l和r之间的任意Token,l和r会被消耗掉,但不会出现在结果中,lr匹配失败时会返回错误
func anyTokens(inside l: TokenParser<Token>, and r: TokenParser<Token>) -> TokenParser<[Token]> {
return anyTokens(encloseBy: l, and: r).map {
Array($0.dropFirst().dropLast()) // 去掉首尾的元素
}
}
/// 任意被包围在{}、[]、()或<>中的符号
var anyEnclosedTokens: TokenParser<[Token]> {
return anyTokens(encloseBy: token(.leftBrace), and: token(.rightBrace)) // {..}
<|> anyTokens(encloseBy: token(.leftSquare), and: token(.rightSquare)) // [..]
<|> anyTokens(encloseBy: token(.leftParen), and: token(.rightParen)) // (..)
<|> anyTokens(encloseBy: token(.leftAngle), and: token(.rightAngle)) // <..>
}
/// 匹配任意字符直到p失败为止,p只有在不被{}、[]、()或<>包围时进行判断
func anyOpenTokens(until p: TokenParser<Token>) -> TokenParser<[Token]> {
return { $0.flatMap {$0} }
<^> (p.not *> (anyEnclosedTokens <|> anyToken.map { [$0] })).many
}
// MARK: - lazy
///
func lazy<T>(_ parser: @autoclosure @escaping () -> TokenParser<T>) -> TokenParser<T> {
return TokenParser<T> { parser().parse($0) }
}
| mit | bce3082e0597903ea3a6cb3bd4e1734c | 29.313869 | 100 | 0.575247 | 3.525467 | false | false | false | false |
cprovatas/PPProfileManager | PPProfileManager/PPDetailViewController.swift | 1 | 9954 | //
// PPDetailViewController.swift
// PPProfileManager
//
// Created by Charlton Provatas on 5/28/17.
// Copyright © 2017 Charlton Provatas. All rights reserved.
//
import Foundation
import UIKit
final class PPDetailViewController : UIViewController {
///#MARK - IBOutlets
@IBOutlet private weak var profileImageView: UIImageView! {
didSet {
profileImageView.layer.borderColor = UIColor.white.cgColor
profileImageView.getFIRImage(id: currentUser.id)
profileImageView.shadowed()
}
}
@IBOutlet private weak var backgroundProfileImageView: UIImageView! {
didSet {
backgroundProfileImageView.getFIRImage(id: currentUser.id)
}
}
@IBOutlet private weak var hobbyDeleteButton: UIButton! {
didSet {
hobbyDeleteButton.setImage(#imageLiteral(resourceName: "trash").colored(PPGlobals.defaultGreen), for: .normal)
}
}
@IBOutlet private weak var hobbyAddButton: UIButton! {
didSet {
hobbyAddButton.setImage(#imageLiteral(resourceName: "plus").colored(PPGlobals.defaultGreen), for: .normal)
}
}
@IBOutlet private weak var tableViewHeaderView: UIView! {
didSet {
tableViewHeaderView.layer.borderColor = PPGlobals.defaultGreen.cgColor
}
}
@IBOutlet fileprivate weak var backgroundView: UIView! {
didSet {
/// if no background color was explicitly set, user the gender color
backgroundView.backgroundColor = (currentUser.backgroundColor ?? currentUser.gender.color).withAlphaComponent(0.7)
}
}
@IBOutlet private weak var nameLabel: UILabel! {
didSet {
nameLabel.text = currentUser.name
}
}
@IBOutlet private weak var ageLabel: UILabel! {
didSet {
ageLabel.text = currentUser.ageFormattedString
}
}
@IBOutlet private weak var genderLabel: UILabel! {
didSet {
genderLabel.text = currentUser.gender.string
}
}
/// placeholder for when table is empty
@IBOutlet fileprivate weak var placeholderLabel: UILabel!
@IBOutlet private weak var tableView: UITableView!
/// model that represents the detail view
public var currentUser : PPUser!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = currentUser.name
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
profileImageView.layer.cornerRadius = profileImageView.frame.height / 2 // frame returned will not be correct in 'viewDidLoad'
}
/// #MARK - IBActions
@IBAction private func gearTapped(_ sender: UIBarButtonItem) {
let alrt = UIAlertController(title: "Select An Action", message: nil, preferredStyle: .actionSheet)
alrt.addAction(UIAlertAction(title: "Change Background Color", style: .default, handler: { (_) in
self.presentColorSelectorViewController()
}))
alrt.addAction(UIAlertAction(title: "Remove Profile", style: .destructive, handler: { (_) in
self.removeProfile()
}))
alrt.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alrt, animated: true)
}
@IBAction private func deleteHobbyTapped() {
tableView.setEditing(!tableView.isEditing, animated: true)
}
@IBAction private func addHobbyTapped() {
let msg = "Please type the hobby that you would like to add below."
let alrt = UIAlertController(title: msg, message: nil, preferredStyle: .alert)
alrt.addTextField()
alrt.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in
let txt = alrt.textFields![0].text! //the text will never be nil at this point
if txt.characters.count < 3 || txt.characters.count > 50 { /// present error if hobby is invalid length
alrt.title = "Invalid Hobby. Please try again"
self.present(alrt, animated: true)
}else {
alrt.title = msg
self.addHobby(withText: txt)
}
}))
alrt.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alrt, animated: true)
}
// #MARK - private instance functions
/// Updates model and table view with new hobby
private func addHobby(withText text: String) {
currentUser.hobbies.append(text)
FIR.child(currentUser.id).child("hobbies").setValue(currentUser.hobbies) { (error, _) in
if error != nil {
UIAlertView(title: error!.localizedDescription, message: nil, delegate: nil, cancelButtonTitle: "OK").show()
}else {
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(row: self.tableView.numberOfRows(inSection: 0), section: 0)], with: .right)
self.tableView.endUpdates()
}
}
}
/// Displays confirmation alert and removes profile
private func removeProfile() {
let alrt = UIAlertController(title: "Are you sure you would like to remove this profile?", message: "This action cannot be undone", preferredStyle: .alert)
alrt.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in
self.deleteUser()
}))
alrt.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alrt, animated: true)
}
/// presents color selector view controller vc to update background color for profile
private func presentColorSelectorViewController() {
guard let vc = UIStoryboard(name: "PPColorSelectorViewController", bundle: nil).instantiateInitialViewController() as? PPColorSelectorViewController else {
/// we shouldn't get here unless IB was modified
fatalError("\(self.self) Error Function: '\(#function)' Line \(#line). VC was not implemented with that identifier. Check IB")
}
vc.delegate = self
/// view controller must be embedded in a navigation controller in order to display the navigation bar properly
let navCon = UINavigationController(rootViewController: vc)
navCon.navigationBar.barStyle = .blackOpaque
navCon.navigationBar.barTintColor = PPGlobals.defaultGreen
present(navCon, animated: true)
}
/// Summary: Delete current user from database and profile image associated with the user
private func deleteUser() {
FIR.child(self.currentUser.id).removeValue(completionBlock: { (error, ref) in
if error != nil {
UIAlertView(title: error!.localizedDescription, message: nil, delegate: nil, cancelButtonTitle: "OK").show()
}else {
self.navigationController!.popViewController(animated: true)
}
})
FIRStorage.child(currentUser.id).delete()
}
}
/// #MARK - Color selector delegate for background color change
extension PPDetailViewController : PPColorSelectorViewControllerDelegate {
func colorSelectorViewController(_ viewController: PPColorSelectorViewController, didDismissWithColor color: UIColor?) {
if color != nil {
// update database with new color
FIR.child(currentUser.id).child("backgroundColor").setValue(color!.hexString, withCompletionBlock: { (error, ref) in
if error != nil {
UIAlertView(title: error!.localizedDescription, message: "", delegate: nil, cancelButtonTitle: "OK").show()
}else {
self.currentUser.backgroundColor = color!
self.backgroundView.backgroundColor = color!.withAlphaComponent(0.7)
}
})
}
}
}
/// #MARK - UITableViewDelegate - hobby table view
extension PPDetailViewController : UITableViewDelegate {}
/// #MARK - UITableViewDatasource - hobby table view
extension PPDetailViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "PPDetailTableViewCell") else {
/// we shouldn't get here unless IB was modified
fatalError("\(self.self) Error Function: '\(#function)' Line \(#line). cell was not implemented with that identifier. Check IB")
}
/// set up default text label
cell.textLabel!.font = UIFont(name: PPGlobals.defaultFontName, size: 18)
cell.textLabel!.textColor = PPGlobals.defaultGreen
cell.textLabel!.textAlignment = .center
cell.textLabel!.text = currentUser.hobbies[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let count = currentUser.hobbies.count
placeholderLabel.isHidden = count > 0
return count
}
/// Delete hobby and do swipe animation
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
currentUser.hobbies.remove(at: indexPath.row)
/// update model with hobbies
FIR.child(currentUser.id).child("hobbies").setValue(currentUser.hobbies) { (error, _) in
if error != nil {
UIAlertView(title: error!.localizedDescription, message: nil, delegate: nil, cancelButtonTitle: "OK").show()
}else {
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .left)
tableView.endUpdates()
}
}
}
}
}
| mit | e1fe905c4ed2f9a3cf6fdc3d9e4795d4 | 40.644351 | 163 | 0.637195 | 4.9765 | false | false | false | false |
jameslinjl/SHPJavaGrader | Sources/App/Models/GradingResult.swift | 1 | 1107 | import Vapor
import Fluent
final class GradingResult: Model {
var id: Node?
var username: String
var assignmentId: String
var status: String
var content: String
var exists: Bool = false
init(username: String, assignmentId: String, status: String, content: String) {
self.username = username
self.assignmentId = assignmentId
self.status = status
self.content = content
}
init(node: Node, in context: Context) throws {
id = try node.extract("_id")
username = try node.extract("username")
assignmentId = try node.extract("assignmentId")
status = try node.extract("status")
content = try node.extract("content")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"_id": id,
"username": username,
"assignmentId": assignmentId,
"status": status,
"content": content
])
}
static func prepare(_ database: Database) throws {}
static func revert(_ database: Database) throws {}
}
| mit | ec6a6242049b7e2322b003594bb2bc96 | 26.675 | 83 | 0.599819 | 4.5 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/SwiftApp/RxSwift/Demo1/Protocol/Operators.swift | 1 | 3327 | //
// Operators.swift
// SwiftApp
//
// Created by wuyp on 2017/7/6.
// Copyright © 2017年 raymond. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
infix operator <->: DefaultPrecedence
func nonMarkedText(_ textInput: UITextInput) -> String? {
let start = textInput.beginningOfDocument
let end = textInput.endOfDocument
guard let rangeAll = textInput.textRange(from: start, to: end),
let text = textInput.text(in: rangeAll) else {
return nil
}
guard let markedTextRange = textInput.markedTextRange else {
return text
}
guard let startRange = textInput.textRange(from: start, to: markedTextRange.start),
let endRange = textInput.textRange(from: markedTextRange.end, to: end) else {
return text
}
return (textInput.text(in: startRange) ?? "") + (textInput.text(in: endRange) ?? "")
}
func <-> <Base: UITextInput>(textInput: TextInput<Base>, variable: Variable<String>) -> Disposable {
let bindToUIDisposable = variable.asObservable().bind(to: textInput.text)
let bindToVariable = textInput.text
.subscribe(onNext: { [weak base = textInput.base] n in
guard let base = base else {
return
}
let nonMarkedTextValue = nonMarkedText(base)
/**
In some cases `textInput.textRangeFromPosition(start, toPosition: end)` will return nil even though the underlying
value is not nil. This appears to be an Apple bug. If it's not, and we are doing something wrong, please let us know.
The can be reproed easily if replace bottom code with
if nonMarkedTextValue != variable.value {
variable.value = nonMarkedTextValue ?? ""
}
and you hit "Done" button on keyboard.
*/
if let nonMarkedTextValue = nonMarkedTextValue, nonMarkedTextValue != variable.value {
variable.value = nonMarkedTextValue
}
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
func <-> <T>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable {
if T.self == String.self {
#if DEBUG
fatalError("It is ok to delete this message, but this is here to warn that you are maybe trying to bind to some `rx.text` property directly to variable.\n" +
"That will usually work ok, but for some languages that use IME, that simplistic method could cause unexpected issues because it will return intermediate results while text is being inputed.\n" +
"REMEDY: Just use `textField <-> variable` instead of `textField.rx.text <-> variable`.\n" +
"Find out more here: https://github.com/ReactiveX/RxSwift/issues/649\n"
)
#endif
}
let bindToUIDisposable = variable.asObservable()
.bindTo(property)
let bindToVariable = property
.subscribe(onNext: { n in
variable.value = n
}, onCompleted: {
bindToUIDisposable.dispose()
})
return Disposables.create(bindToUIDisposable, bindToVariable)
}
| apache-2.0 | b6fd31a028af71ba39698434756e6e16 | 36.772727 | 211 | 0.620337 | 4.755365 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/Common/Nodes/Generators/Physical Models/Plucked String/AKPluckedString.swift | 1 | 5541 | //
// AKPluckedString.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// Karplus-Strong plucked string instrument.
///
/// - parameter frequency: Variable frequency. Values less than the initial frequency will be doubled until it is greater than that.
/// - parameter amplitude: Amplitude
/// - parameter lowestFrequency: This frequency is used to allocate all the buffers needed for the delay. This should be the lowest frequency you plan on using.
///
public class AKPluckedString: AKVoice {
// MARK: - Properties
internal var internalAU: AKPluckedStringAudioUnit?
internal var token: AUParameterObserverToken?
private var frequencyParameter: AUParameter?
private var amplitudeParameter: AUParameter?
private var lowestFrequency: Double
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet(newValue) {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Variable frequency. Values less than the initial frequency will be doubled until it is greater than that.
public var frequency: Double = 110 {
willSet(newValue) {
if frequency != newValue {
frequencyParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Amplitude
public var amplitude: Double = 0.5 {
willSet(newValue) {
if amplitude != newValue {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
override public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize the pluck with defaults
convenience override init() {
self.init(frequency: 110)
}
/// Initialize this pluck node
///
/// - parameter frequency: Variable frequency. Values less than the initial frequency will be doubled until it is greater than that.
/// - parameter amplitude: Amplitude
/// - parameter lowestFrequency: This frequency is used to allocate all the buffers needed for the delay. This should be the lowest frequency you plan on using.
///
public init(
frequency: Double,
amplitude: Double = 0.5,
lowestFrequency: Double = 110) {
self.frequency = frequency
self.amplitude = amplitude
self.lowestFrequency = lowestFrequency
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x706c756b /*'pluk'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKPluckedStringAudioUnit.self,
asComponentDescription: description,
name: "Local AKPluckedString",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKPluckedStringAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
}
guard let tree = internalAU?.parameterTree else { return }
frequencyParameter = tree.valueForKey("frequency") as? AUParameter
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.frequencyParameter!.address {
self.frequency = Double(value)
} else if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
}
}
}
internalAU?.frequency = Float(frequency)
internalAU?.amplitude = Float(amplitude)
}
/// Function create an identical new node for use in creating polyphonic instruments
public override func duplicate() -> AKVoice {
let copy = AKPluckedString(frequency: self.frequency, amplitude: self.amplitude, lowestFrequency: self.lowestFrequency)
return copy
}
/// Trigger the sound with an optional set of parameters
/// - parameter frequency: Frequency in Hz
/// - amplitude amplitude: Volume
///
public func trigger(frequency frequency: Double, amplitude: Double = 1) {
self.frequency = frequency
self.amplitude = amplitude
self.internalAU!.start()
self.internalAU!.triggerFrequency(Float(frequency), amplitude: Float(amplitude))
}
/// Function to start, play, or activate the node, all do the same thing
public override func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public override func stop() {
self.internalAU!.stop()
}
}
| apache-2.0 | df50f77badb43856652c02cf8542335b | 34.519231 | 164 | 0.645551 | 5.405854 | false | false | false | false |
pfvernon2/swiftlets | iOSX/iOS/UIAlertController+Utilities.swift | 1 | 1938 | //
// UIAlertController+Utilities.swift
// swiftlets
//
// Created by Frank Vernon on 5/6/16.
// Copyright © 2016 Frank Vernon. All rights reserved.
//
import Foundation
import UIKit
public extension UIAlertController {
/**
Creates and returns a UIAlertController with optional OK and Cancel buttons. If handlers are not supplied for the OK or Cancel buttons then the associated actions will not be added to the alert.
The titles for the OK and Cancel buttons are defined as NSLocalizedStrings for ease of localization.
- parameters title: title of the alert
- parameters message: message of the alert
- parameters preferredStyle: style of the alert
- parameters okHandler: completion block for the OK action. If not supplied then no OK button will be added to the alert.
- parameters cancelHandler: completion block for the Cancel action. If not supplied then no OK button will be added to the alert.
- returns: A UIAlertController
*/
class func alertControllerOKCancel(title:String?, message:String?, preferredStyle:UIAlertController.Style = .alert, okHandler: ((UIAlertAction) -> Void)?, cancelHandler: ((UIAlertAction) -> Void)?) -> UIAlertController{
let result = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)
if let okHandler = okHandler {
let okAction = UIAlertAction(title: NSLocalizedString("OK", comment: "UIAlertController OK control"), style: .default, handler: okHandler)
result.addAction(okAction)
}
if let cancelHandler = cancelHandler {
let cancelAction:UIAlertAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "UIAlertController Cancel control"), style: .cancel, handler: cancelHandler)
result.addAction(cancelAction)
}
return result
}
}
| apache-2.0 | e2d622d5c654d5ed0e92902a8184c446 | 42.044444 | 223 | 0.695922 | 5.350829 | false | false | false | false |
dbahat/conventions-ios | Conventions/Conventions/extentions/UIViewExtentions.swift | 1 | 933 | //
// UIViewExtentions.swift
// Conventions
//
// Created by David Bahat on 18/09/2017.
// Copyright © 2017 Amai. All rights reserved.
//
import Foundation
extension UIView {
// Inflates the nib file into the custom view as a subview.
func inflateNib<T>(_ type: T) {
let view = Bundle.main.loadNibNamed(String(describing: type), owner: self, options: nil)![0] as! UIView
view.frame = self.bounds
addSubview(view)
}
func startRotate() {
let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = NSNumber(value: Double.pi * 2)
rotation.duration = 2
rotation.isCumulative = true
rotation.repeatCount = .greatestFiniteMagnitude
layer.add(rotation, forKey: "rotationAnimation")
}
func stopRotate() {
layer.removeAnimation(forKey: "rotationAnimation")
}
}
| apache-2.0 | 9fdd204c7f3ca15054ff00c2794c88c9 | 28.125 | 111 | 0.645923 | 4.142222 | false | false | false | false |
eduardourso/EUActivityView | Pod/Classes/EUActivityView.swift | 1 | 4212 | //
// EUActivityView.swift
// Pods
//
// Created by EduardoUrso on 1/27/16.
//
//
import UIKit
public enum EUActivityIndicatorStyle {
/**
Pulse.
- returns: Instance of EUActivityIndicatorAnimationPulse.
*/
case Pulse
/**
SoundScale.
- returns: Instance of EUActivityIndicatorAnimationSoundScale.
*/
case SoundScale
private func animation() -> EUActivityViewAnimationDelegate {
switch self {
case .Pulse:
return EUActivityIndicatorAnimationPulse()
case .SoundScale:
return EUActivityIndicatorAnimationSoundScale()
}
}
}
public class EUActivityView: UIView {
lazy var activityIndicator:UIActivityIndicatorView = {
var activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .White)
activityIndicator.layer.backgroundColor = self.customBackgroundColor.CGColor
activityIndicator.frame = self.customBackgroundFrame
activityIndicator.layer.cornerRadius = 5.0
activityIndicator.startAnimating()
return activityIndicator
} ()
lazy var backgroundView:UIView = {
var backgroundView = UIView(frame: self.customBackgroundFrame)
backgroundView.layer.backgroundColor = self.customBackgroundColor.CGColor
backgroundView.layer.cornerRadius = 5.0
return backgroundView
}()
private var superView:UIView?
private var customSize = CGSize(width: 50, height: 50)
private var customBackgroundFrame:CGRect = CGRectMake(0, 0, 100, 100)
public var type: EUActivityIndicatorStyle
public var customBackgroundColor: UIColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 0.7)
public var customActivityIndicatorColor: UIColor = UIColor.whiteColor()
public override init(frame: CGRect) {
self.type = EUActivityIndicatorStyle.Pulse
self.customSize = CGSize(width: frame.width/2, height: frame.height/2)
self.customBackgroundFrame = frame
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func showDefaultActivityView(superView:UIView) {
// TODO: check what can be removed from the main queue
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.superView = superView
if let center = self.superView?.center {
self.center = center
self.activityIndicator.center = center
}
superView.addSubview(self.activityIndicator)
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
}
}
public func showCustomActivityView(superView:UIView, type:EUActivityIndicatorStyle) {
// TODO: check what can be removed from the main queue
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.superView = superView
if let center = self.superView?.center {
self.center = center
self.backgroundView.center = center
}
self.type = type
let animation: protocol<EUActivityViewAnimationDelegate> = self.type.animation()
self.layer.sublayers = nil
animation.setUpAnimationInLayer(self.backgroundView.layer, size: self.customSize, color: self.customActivityIndicatorColor)
self.backgroundView.addSubview(self)
superView.addSubview(self.backgroundView)
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
}
}
public func hideLoadingView() {
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.activityIndicator.stopAnimating()
self.backgroundView.removeFromSuperview()
if UIApplication.sharedApplication().isIgnoringInteractionEvents() {
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}
}
}
}
| mit | 333078dd5728e8e6baa937a60afa67df | 31.4 | 135 | 0.635565 | 5.393086 | false | false | false | false |
awind/Pixel | Pixel/Dictionary+Extension.swift | 1 | 1627 | //
// Dictionary.swift
// Pixel
//
// Created by SongFei on 15/12/6.
// Copyright © 2015年 SongFei. All rights reserved.
//
import UIKit
extension Dictionary {
func filter(predicate: Element -> Bool) -> Dictionary {
var filteredDictionary = Dictionary()
for (key, value) in self {
if predicate(key, value) {
filteredDictionary[key] = value
}
}
return filteredDictionary
}
func queryStringWithEncoding() -> String {
var parts = [String]()
for (key, value) in self {
let keyString: String = "\(key)"
let valueString: String = "\(value)"
let query: String = "\(keyString)=\(valueString)"
parts.append(query)
}
return parts.joinWithSeparator("&")
}
func urlEncodedQueryStringWithEncoding(encoding: NSStringEncoding) -> String {
var parts = [String]()
for (key, value) in self {
let keyString: String = "\(key)".urlEncodedStringWithEncoding(encoding)
let valueString: String = "\(value)".urlEncodedStringWithEncoding(encoding)
let query: String = "\(keyString)=\(valueString)"
parts.append(query)
}
return parts.joinWithSeparator("&")
}
}
infix operator +| {}
func +| <K,V>(left: Dictionary<K,V>, right: Dictionary<K,V>) -> Dictionary<K,V> {
var map = Dictionary<K,V>()
for (k, v) in left {
map[k] = v
}
for (k, v) in right {
map[k] = v
}
return map
}
| apache-2.0 | 9b91602c0113af38956391cd1951498e | 24.375 | 87 | 0.538177 | 4.54902 | false | false | false | false |
animalsBeef/CF-TestDYZ | DYZB/DYZB/Classes/Tools/NetworkTools.swift | 1 | 934 | //
// NetworkTools.swift
// Alamofire的测试
//
// Created by 1 on 16/9/19.
// Copyright © 2016年 小码哥. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case get
case post
}
class NetworkTools {
class func requestData(type : MethodType, URLString : String, parameters : [String : NSString]? = nil, finishedCallback : (result : AnyObject) -> ()) {
// 1.获取类型
let method = type == .get ? Method.GET : Method.POST
// 2.发送网络请求
Alamofire.request(method, URLString, parameters: parameters).responseJSON { (response) in
// 3.获取结果
guard let result = response.result.value else {
print(response.result.error)
return
}
// 4.将结果回调出去
finishedCallback(result : result)
}
}
}
| mit | 695e51832d01374037b781729149420d | 23.361111 | 155 | 0.555302 | 4.363184 | false | false | false | false |
taotao361/swift | FirstSwiftDemo/others/ViewController.swift | 1 | 173932 | //
// ViewController.swift
// FirstSwiftDemo
//
// Created by yangxutao on 2017/5/4.
// Copyright © 2017年 yangxutao. All rights reserved.
//
import UIKit
//typealias NNNNN = String //别名
protocol ViewControllerDelegate {
}
extension ViewController : ViewControllerDelegate {
}
extension String {
}
extension Double {
var km : Double { return self * 1000.0 }
var m : Double { return self }
var cm : Double { return self / 100.0 }
var mm : Double {return self / 1000.0 }
var ft : Double { return self / 3.28084 }
}
extension Int {
func repeatCount(task : ()->Void) -> Void {
for _ in 1..<self {
task()
}
}
}
extension Int {
mutating func square () {
self = self * self
}
}
extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 0..<digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
//枚举名大写开头,成员小写开头
enum MoveMent {
case Right
case Left
case Up
case Down
}
enum Direct : String {
case north,east,west,sorth
}
//原始值 原始类型为Int
// 映射到整型
enum Movement: Int {
case Left = 0
case Right = 1
case Top = 2
case Bottom = 3
}
// 同样你可以与字符串一一对应
enum House: String {
case Baratheon = "Ours is the Fury"
case Greyjoy = "We Do Not Sow"
case Martell = "Unbowed, Unbent, Unbroken"
case Stark = "Winter is Coming"
case Tully = "Family, Duty, Honor"
case Tyrell = "Growing Strong"
}
// 或者float double都可以(同时注意枚举中的花式unicode)
enum Constants: Double {
case π = 3.14159
case e = 2.71828
case φ = 1.61803398874
case λ = 1.30357
}
//关联值
//“定义一个名为Barcode的枚举类型,它的一个成员值是具有(Int,Int,Int,Int)类型关联值的upc,另一个成员值是具有String类型关联值的qrCode。”
enum Barcode {
case upc(Int,Int,Int,Int)
case qr(String)
}
//递归枚举
enum Expression {
case number(Int)
indirect case add(Expression,Expression)
indirect case multiply(Expression,Expression)
}
/*
疑问:
1、带原始值的枚举类型的可失败构造器
2、闭包使用
3、自动引用计数
4、
5、
*/
extension String {
func description () {
print(self)
}
mutating func add (a : String) {
self = self + a
}
}
// MARK: -
//该例子为 Int 添加了嵌套枚举。这个名为 Kind 的枚举表示特定整数的类型。具体来说,就是表示整数是正数、零或者负数。
//这个例子还为 Int 添加了一个计算型实例属性,即 kind,用来根据整数返回适当的 Kind 枚举成员。
// MARK: - 嵌套类型
extension Int {
enum Kind { //嵌套枚举
case Negative,Zero,Positive
}
// class Des { //嵌套类
// func descriptionClass() {
// print("\(self) 是嵌套在整型类型的 类 的方法")
// }
// }
// struct AnotherStruct { //嵌套结构体
// func discriptionStruct() {
// print("\(self) 是嵌套在整形类型 的 结构体 的 方法")
// }
// }
var kind : Kind {
switch self {
case 0:
return .Zero
case let x where x > 0 :
return .Positive
default:
return .Negative
}
}
}
extension A {
func appenName (last : String) {
let name = firstName + last
print("名字为 \(name) ")
}
// class B {
// func bName() {
// print("bName")
// }
// }
}
class A {
var firstName = ""
func getName () {
print("A 的 firstName 是 \(firstName)")
}
}
struct BlackjackCard {
//嵌套枚举
enum Suit : Character {
case Spades = "♠️",Hearts = "♥️",Diamonds = "♦️",Clubs = "♣️"
}
//
enum Rank : Int {
case Two = 2,Three,Four,FIve,Six,Seven,Eight,Nine,Ten
case Jack, Queen, King, Ace
struct Values {
let first : Int,second : Int?
}
var values : Values {
switch self {
case .Ace:
return Values.init(first: 1, second: 11)
case .Jack,.Queen,.King:
return Values.init(first: 10, second: nil)
default:
return Values.init(first: self.rawValue, second: nil)
}
}
}
//BlackjackCard 属性 和 方法
let rank : Rank,suit : Suit
var description : String {
var output = "suit is \(suit.rawValue)"
output += "value is \(rank.values.first)"
if let second = rank.values.second {
output += "or \(second)"
}
return output
}
}
//协议
//只含有一个实例属性要求的协议
//FullyNamed 协议除了要求遵循协议的类型提供 fullName 属性外,并没有其他特别的要求。这个协议表示,任何遵循 FullyNamed 的类型,都必须有一个可读的 String 类型的实例属性 fullName。
protocol FullyNamed {
var fullName: String { get }
}
protocol Togglable {
mutating func toggle()
}
//构造器协议
protocol GeneratorProtocol {
init(name : String)
}
protocol PeopleProtocol {
init()
}
//委托模式
//骰子游戏
protocol DiceGame {
var dice : Dice {get}
func play()
}
protocol DiceGameDelegate {
func gameDidStart(_ game : DiceGame)
func game(_ game : DiceGame,didStartNewTurnWithRoll diceRoll : Int)
func gameDidEnd(_ game : DiceGame)
}
protocol RandomNumberGenerator {
func random() -> Double
}
class LinearCongruentialGenerator: RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0
let a = 3877.0
let c = 29573.0
func random() -> Double {
lastRandom = ((lastRandom * a + c).truncatingRemainder(dividingBy:m))
return lastRandom / m
}
}
class Dice {
let sides : Int
let generator : RandomNumberGenerator
init(sides : Int,generator : RandomNumberGenerator) {
self.sides = sides
self.generator = generator
}
func roll () -> Int {
return Int(generator.random() * Double(sides)) + 1 //类型转换 Int()
}
}
class SnakesAndLadders : DiceGame {
let finalSquare = 25
let dice = Dice.init(sides: 6, generator: LinearCongruentialGenerator())
var square = 0
var board : [Int]
init() {
board = [Int].init(repeating: 0, count: finalSquare + 1)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
}
var delegate : DiceGameDelegate?
func play() {
square = 0
delegate?.gameDidStart(self)
gameLoop : while square != finalSquare {
let diceRoll = dice.roll()
delegate?.game(self, didStartNewTurnWithRoll: diceRoll)
switch square + diceRoll {
case finalSquare:
break gameLoop
case let newSquare where newSquare > finalSquare:
continue gameLoop
default:
square += diceRoll
square += board[square]
}
}
delegate?.gameDidEnd(self)
}
}
class DiceGameTracker: DiceGameDelegate {
var numberOfTurns = 0
func gameDidStart(_ game: DiceGame) {
numberOfTurns = 0
if game is SnakesAndLadders {
print("Started a new game of Snakes and Ladders")
}
print("The game is using a \(game.dice.sides)-sided dice")
}
func game(_ game: DiceGame, didStartNewTurnWithRoll diceRoll: Int) {
numberOfTurns += 1
print("Rolled a \(diceRoll)")
}
func gameDidEnd(_ game: DiceGame) {
print("The game lasted for \(numberOfTurns) turns")
}
}
//类类型专属协议
protocol PrivateProtocol : class {
}
//类类型的协议不能被结构体 枚举遵循
//struct PPPPPP : PrivateProtocol {
// var name : String
//}
protocol GroupProtocol {
func test()
}
class BBB: GroupProtocol {
func test() {
print("BBB test")
}
}
class CCC: GroupProtocol {
func test() {
print("CCC test")
}
}
class DDD: GroupProtocol {
func test() {
print("DDD test")
}
}
//泛型
struct Type<Element> {
var items = [Element]()
mutating func push(_ a : Element) {
items.append(a)
}
mutating func pop() -> Element {
return items.removeLast()
}
}
extension Type {
var topItem : Element? {
return items.isEmpty ? nil : items[items.count - 1]
}
}
//关联类型
protocol Container {
associatedtype itemType
var count : Int { get }
mutating func appending(_ item : itemType)
subscript(i : Int) -> itemType { get }
}
struct Stack<Element> : Container {
var items = [Element].init()
mutating func push (_ item : Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
//协议实现
typealias itemType = Element
var count: Int {
return items.count
}
mutating func appending(_ item: Element) {
self.push(item)
}
subscript (i : Int) -> Element {
return items[i]
}
}
//具有where字句的扩展
extension Stack where Element : Equatable {
func isTop(_ item : Element) -> Bool {
guard let topItem = items.last else {
return false
}
return topItem == item
}
}
//你可以使用泛型 where 子句去扩展一个协议
//itemType 为 关联类型
extension Container where itemType : Equatable {
func startWith(_ item : itemType) -> Bool {
return count >= 1 && self[0] == item
}
}
//一个泛型 where 子句去要求 Item 为特定类型
extension Container where itemType == Double {
}
//访问等级
struct TrackedString {
private(set) var numberOfEdits = 0
var value : String = "" {
didSet {
numberOfEdits += 1
}
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// let vv : YTTestView = YTTestView.init(frame: CGRect.init(x: 0, y: 20, width: 320, height: 568-20))
// view.addSubview(vv)
}
//访问控制 access control
func accessControl () {
// fileprivate
// open
// public
// private
// internal 默认
let car = Car.init()
let name = car.name
print(name,car.price)
/*元组类型
元组的访问级别将由元组中访问级别最严格的类型来决定。例如,如果你构建了一个包含两种不同类型的元组,其中一个类型为内部访问级别,另一个类型为私有访问级别,那么这个元组的访问级别为私有访问级别。
注意
元组不同于类、结构体、枚举、函数那样有单独的定义。元组的访问级别是在它被使用时自动推断出的,而无法明确指定。
*/
//枚举类型
//枚举成员的访问级别和该枚举类型相同,你不能为枚举成员单独指定不同的访问级别。
//原始值和关联值
//枚举定义中的任何原始值或关联值的类型的访问级别至少不能低于枚举类型的访问级别。例如,你不能在一个 internal 访问级别的枚举中定义 private 级别的原始值类型。
//嵌套类型
//如果在 private 级别的类型中定义嵌套类型,那么该嵌套类型就自动拥有 private 访问级别。如果在 public 或者 internal 级别的类型中定义嵌套类型,那么该嵌套类型自动拥有 internal 访问级别。如果想让嵌套类型拥有 public 访问级别,那么需要明确指定该嵌套类型的访问级别。
//子类
//子类的访问级别不能高于父类,例如,父类的访问级别是 internal,子类的访问级别就不能是 public。
//此外,你可以在符合当前访问级别的条件下重写任意类成员(方法、属性、构造器、下标等)。
//可以通过重写为继承来的类成员提供更高的访问级别。下面的例子中,类 A 的访问级别是 public,它包含一个方法 someMethod(),访问级别为 private。类 B 继承自类 A,访问级别为 internal,但是在类 B 中重写了类 A 中访问级别为 private 的方法 someMethod(),并重新指定为 internal 级别。通过这种方式,我们就可以将某类中 private 级别的类成员重新指定为更高的访问级别,以便其他人使用
//常量、变量、属性、下标
//常量、变量、属性不能拥有比它们的类型更高的访问级别。例如,你不能定义一个 public 级别的属性,但是它的类型却是 private 级别的。同样,下标也不能拥有比索引类型或返回类型更高的访问级别。
//如果常量、变量、属性、下标的类型是 private 级别的,那么它们必须明确指定访问级别为 private:
//Getter 和 Setter
//常量、变量、属性、下标的 Getters 和 Setters 的访问级别和它们所属类型的访问级别相同。
//Setter 的访问级别可以低于对应的 Getter 的访问级别,这样就可以控制变量、属性或下标的读写权限。在 var 或 subscript 关键字之前,你可以通过 fileprivate(set),private(set) 或 internal(set) 为它们的写入权限指定更低的访问级别。
//这个规则同时适用于存储型属性和计算型属性。即使你不明确指定存储型属性的 Getter 和 Setter,Swift 也会隐式地为其创建 Getter 和 Setter,用于访问该属性的后备存储。使用 fileprivate(set),private(set) 和 internal(set) 可以改变 Setter 的访问级别,这对计算型属性也同样适用。
//构造器
//自定义构造器的访问级别可以低于或等于其所属类型的访问级别。唯一的例外是必要构造器,它的访问级别必须和所属类型的访问级别相同。
//如同函数或方法的参数,构造器参数的访问级别也不能低于构造器本身的访问级别。
//结构体默认的成员逐一构造器
//如果结构体中任意存储型属性的访问级别为 private,那么该结构体默认的成员逐一构造器的访问级别就是 private。否则,这种构造器的访问级别依然是 internal。
//协议继承
//如果定义了一个继承自其他协议的新协议,那么新协议拥有的访问级别最高也只能和被继承协议的访问级别相同。例如,你不能将继承自 internal 协议的新协议定义为 public 协议。
//扩展
//你可以在访问级别允许的情况下对类、结构体、枚举进行扩展。扩展成员具有和原始类型成员一致的访问级别。例如,你扩展了一个 public 或者 internal 类型,扩展中的成员具有默认的 internal 访问级别,和原始类型中的成员一致 。如果你扩展了一个 private 类型,扩展成员则拥有默认的 private 访问级别。
func add(_ a : Int...) -> Int {
var temp : Int = 0
for item in a {
temp += item
}
return temp
}
let a = add(2,3,4,5,6)
print(a)
print(#function) //打印方法名
let digitNames = [
0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16, 58, 510]
let strings = numbers.map {
(number) -> String in
var number = number
var output = ""
repeat {
output = digitNames[number % 10]! + output
number /= 10
} while number > 0
return output
}
print(strings)
}
//泛型
func generics() {
func swapTwoValue(_ a: inout Int,_ b: inout Int) {
let temp = a
a = b
b = temp
}
func swapValue<T>(_ a: inout T,_ b: inout T) {
let temp = a
a = b
b = temp
}
var firstName = "lll"
var lastName = "ppp"
swapValue(&firstName, &lastName)
print(firstName,lastName)
//类型参数 <T>
//命名类型参数
//请始终使用大写字母开头的驼峰命名法(例如 T 和 MyTypeParameter)来为类型参数命名,以表明它们是占位类型,而不是一个值。
//在大多数情况下,类型参数具有一个描述性名字,例如 Dictionary<Key, Value> 中的 Key 和 Value,以及 Array<Element> 中的 Element,这可以告诉阅读代码的人这些类型参数和泛型函数之间的关系。然而,当它们之间没有有意义的关系时,通常使用单个字母来命名,例如 T、U、V,正如上面演示的 swapTwoValues(_:_:) 函数中的 T 一样。
//泛型类型
struct intType {
var items = [Int].init()
mutating func push(_ a : Int) {
items.append(a)
}
mutating func pop () -> Int {
return items.removeLast()
}
}
//泛型版本
//Element为待提供的类型提供了一个占位符,只是用站位类型 Element 代替了真实类型Int,
//Element 在如下三个地方被用作占位符:
//创建 items 属性,使用 Element 类型的空数组对其进行初始化。
//指定 push(_:) 方法的唯一参数 item 的类型必须是 Element 类型。
//指定 pop() 方法的返回值类型必须是 Element 类型。
var stringType = Type<String>.init()
stringType.push("33")
stringType.push("44")
stringType.pop()
print(stringType.items)
//扩展一个泛型类型
//扩展泛型的时候,泛型原始类型中的属性列表可以直接使用
//类型约束
//类型约束可以指定一个类型参数必须继承自指定类,或者符合一个特定的协议或协议组合。
//Swift 的 Dictionary 类型对字典的键的类型做了些限制。在字典的描述中,字典的键的类型必须是可哈希(hashable)的。也就是说,必须有一种方法能够唯一地表示它。Dictionary 的键之所以要是可哈希的,是为了便于检查字典是否已经包含某个特定键的值。若没有这个要求,Dictionary 将无法判断是否可以插入或者替换某个指定键的值,也不能查找到已经存储在字典中的指定键的值。
// func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
// // 这里是泛型函数的函数体部分
// }
//这里有个名为 findIndex(ofString:in:) 的非泛型函数,该函数的功能是在一个 String 数组中查找给定 String 值的索引。若查找到匹配的字符串,findIndex(ofString:in:) 函数返回该字符串在数组中的索引值,否则返回 nil:
func findIndex(aString : String,in array: [String]) -> Int? {
for (index,value) in array.enumerated() {
if value == aString {
return index
}
}
return nil
}
let index = findIndex(aString: "hh", in: ["hh","pp","ll"])
if let ind = index {
print(ind)
}
// 如果只能查找字符串在数组中的索引,用处不是很大。不过,你可以用占位类型 T 替换 String 类型来写出具有相同功能的泛型函数 findIndex(_:_:)。
func findValue<T : Equatable>(valueToFind : T, in array : [T]) -> Int? {
for (index,value) in array.enumerated() {
if value == valueToFind {
return index
}
}
return nil
}
let aa = findValue(valueToFind: 9, in: [1,2,3,8,9,89])
if let b = aa {
print(b)
}
//关联类型
//定义一个协议时,有的时候声明一个或多个关联类型作为协议定义的一部分将会非常有用。关联类型为协议中的某个类型提供了一个占位名(或者说别名),其代表的实际类型在协议被采纳时才会被指定。你可以通过 associatedtype 关键字来指定关联类型。
struct IntStack : Container {
var items = [Int].init()
mutating func push (_ item : Int) {
items.append(item)
}
mutating func pop() -> Int {
return items.removeLast()
}
//Container 实现部分
typealias itemType = Int //这行代码可以省略
mutating func appending(_ item: Int) {
self.push(item)
}
subscript(i : Int) -> Int {
return items[i]
}
var count: Int {
return items.count
}
}
//结构体泛型
struct Stack<Element> : Container {
var items = [Element].init()
mutating func push (_ item : Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
//协议实现
typealias itemType = Element
var count: Int {
return items.count
}
mutating func appending(_ item: Element) {
self.push(item)
}
subscript (i : Int) -> Element {
return items[i]
}
}
//通过扩展一个存在的类型来制定关联类型
//泛型where语句
var stack = Stack<String>.init()
stack.push("aa")
stack.push("bb")
stack.push("cc")
//具有泛型 where 字句的扩展
}
///协议
func testProtocol () {
//协议
//类、结构体或枚举都可以遵循协议
//可以对协议进行扩展
//协议语法
//协议的定义方式与类、结构体和枚举的定义非常相似:
// protocol SomeProtocol {
// // 这里是协议的定义部分
// }
// struct SomeStructure: FirstProtocol, AnotherProtocol {
// // 这里是结构体的定义部分
// }
// 拥有父类的类在遵循协议时,应该将父类名放在协议名之前,以逗号分隔
// class SomeClass: SomeSuperClass, FirstProtocol, AnotherProtocol {
// // 这里是类的定义部分
// }
//属性要求
// 协议不指定属性是存储型属性还是计算型属性,它只指定属性的名称和类型。此外,协议还指定属性是可读的还是可读可写的
// 协议总是用 var 关键字来声明变量属性,在类型声明后加上 { set get } 来表示属性是可读可写的,可读属性则用 { get } 来表示:
// protocol SomeProtocol {
// var mustBeSettable: Int { get set }
// var doesNotNeedToBeSettable: Int { get }
// }
// 在协议中定义类型属性时,总是使用 static 关键字作为前缀。当类类型遵循协议时,除了 static 关键字,还可以使用 class 关键字来声明类型属性:
// protocol AnotherProtocol {
// static var someTypeProperty: Int { get set }
// }
struct Person : FullyNamed {
var fullName: String
}
//Starship 类把 fullName 属性实现为只读的计算型属性。每一个 Starship 类的实例都有一个名为 name 的非可选属性和一个名为 prefix 的可选属性。 当 prefix 存在时,计算型属性 fullName 会将 prefix 插入到 name 之前,从而为星际飞船构建一个全名。
class StarShip : FullyNamed {
var prefix : String
var name : String
init(name : String,prefix : String? = nil) {
self.name = name
self.prefix = prefix!
}
var fullName: String {
return (prefix != nil ? prefix + "" : "") + name
}
}
//方法要求
//协议可以要求遵循协议的类型实现某些指定的实例方法或类方法。这些方法作为协议的一部分,像普通方法一样放在协议的定义中,但是不需要大括号和方法体。可以在协议中定义具有可变参数的方法,和普通方法的定义方式相同。但是,不支持为协议中的方法的参数提供默认值。
//正如属性要求中所述,在协议中定义类方法的时候,总是使用 static 关键字作为前缀。当类类型遵循协议时,除了 static 关键字,还可以使用 class 关键字作为前缀:
//Mutating 方法要求
//有时需要在方法中改变方法所属的实例。例如,在值类型(即结构体和枚举)的实例方法中,将 mutating 关键字作为方法的前缀,写在 func 关键字之前,表示可以在该方法中修改它所属的实例以及实例的任意属性的值。这一过程在在实例方法中修改值类型章节中有详细描述。
//如果你在协议中定义了一个实例方法,该方法会改变遵循该协议的类型的实例,那么在定义协议时需要在方法前加 mutating 关键字。这使得结构体和枚举能够遵循此协议并满足此方法要求。
//实现协议中的 mutating 方法时,若是类类型,则不用写 mutating 关键字。而对于结构体和枚举,则必须写 mutating 关键字
enum OnOffSwitch : Togglable {
case on,off
mutating func toggle() {
switch self {
case .on:
self = .off
case.off:
self = .on
}
}
}
var light = OnOffSwitch.off
light.toggle()
//构造器要求
//协议可以要求遵循协议的类型实现指定的构造器。你可以像编写普通构造器那样,在协议的定义里写下构造器的声明,但不需要写花括号和构造器的实体:
//你可以在遵循协议的类中实现构造器,无论是作为指定构造器,还是作为便利构造器。无论哪种情况,你都必须为构造器实现标上 required 修饰符:
//使用 required 修饰符可以确保所有子类也必须提供此构造器实现,从而也能符合协议。
//如果类已经被标记为 final,那么不需要在协议构造器的实现中使用 required 修饰符,因为 final 类不能有子类。关于 final 修饰符的更多内容,请参见防止重写。在类前边 加上 final 关键字,表明类不能被继承
class Zero : GeneratorProtocol {
var name : String
required init(name: String) {
self.name = name
}
}
//如果一个子类重写了父类的指定构造器,并且该构造器满足了某个协议的要求,那么该构造器的实现要同事标注 required 和 override 修饰符
class People {
init() {
}
}
class Man : People ,PeopleProtocol {
// 因为遵循协议,需要加上 required
// 因为继承自父类,需要加上 override
required override init() {
}
}
//可失败构造器要求
//协议还可以为遵循协议的类型定义可失败构造器要求,详见可失败构造器。
//遵循协议的类型可以通过可失败构造器(init?)或非可失败构造器(init)来满足协议中定义的可失败构造器要求。协议中定义的非可失败构造器要求可以通过非可失败构造器(init)或隐式解包可失败构造器(init!)来满足。
//协议作为类型
//尽管协议本身并未实现任何功能,但是协议可以被当做一个成熟的类型类使用
/*
协议可以像其他普通类型一样使用,使用场景如下:
作为函数、方法或构造器中的参数类型或返回值类型
作为常量、变量或属性的类型
作为数组、字典或其他容器中的元素类型
协议是一种类型,因此协议类型的名称应与其他类型(例如 Int,Double,String)的写法相同,使用大写字母开头的驼峰式写法,例如(FullyNamed 和 RandomNumberGenerator)。
*/
//委托模式
//委托是一种设计模式,它允许类或结构体将一些需要它们负责的功能委托给其他类型的实例。委托模式的实现很简单:定义协议来封装那些需要被委托的功能,这样就能确保遵循协议的类型能提供这些功能。委托模式可以用来响应特定的动作,或者接收外部数据源提供的数据,而无需关心外部数据源的类型。
let tracker = DiceGameTracker.init()
let game = SnakesAndLadders.init()
game.delegate = tracker
game.play()
//类类型专属协议 通过添加 class 关键字来限制协议只能被类类型遵循,而结构体或枚举不能遵循该协议。class 关键字必须第一个出现在协议的继承列表中,在其他继承的协议之前:
//协议类型集合
//协议类型可以在数组或者字典这样的集合中使用,在协议类型提到了这样的用法。下面的例子创建了一个元素类型为 TextRepresentable 的数组:
let bbb = BBB.init()
let ccc = CCC.init()
let ddd = DDD.init()
let groups : [GroupProtocol] = [bbb,ccc,ddd]
for thing in groups {
thing.test()
}
}
/// 错误处理
func test15() {
//错误处理
enum VendingMachineError : Error {
case invalidSelection
case insufficientFunds(coinsNeed : Int)
case outOfStock
}
//抛出一个错误可以让你表明有意外情况发生,导致正常的执行流程无法继续执行。抛出错误使用throw关键字。例如,下面的代码抛出一个错误,提示贩卖机还需要5个硬币:
// throw VendingMachineError.insufficientFunds(coinsNeed: 5)
//用 throwing 函数传递错误
//为了表示一个函数、方法或构造器可以抛出错误,在函数声明的参数列表之后加上throws关键字。一个标有throws关键字的函数被称作throwing 函数。如果这个函数指明了返回值类型,throws关键词需要写在箭头(->)的前面。
//用 throws 函数传递错误
//为了表示一个函数、方法或构造器可以抛出错误,在函数声明的参数列表之后加上throws关键字。一个标有throws关键字的函数被称作throwing 函数。如果这个函数指明了返回值类型,throws关键词需要写在箭头(->)的前面。
// func canThrowError () throws -> String {}
// func canThrows () throws {}
struct Item {
var price : Int
var count : Int
}
class VendingMachine {
var inventory = [
"a" : Item(price : 12,count : 4),
"b": Item(price : 13,count : 5),
"c" : Item(price : 15,count : 6)
]
var coinsDeposited = 0
func dispenseSnack(snack : String) {
print("dispence \(snack)")
}
func vend(itemNamed name : String) throws {
guard let item = inventory[name] else { //没有这个item项
throw VendingMachineError.invalidSelection
}
guard item.count > 0 else { //存货不够
throw VendingMachineError.outOfStock
}
guard item.price <= coinsDeposited else { //钱不够
throw VendingMachineError.insufficientFunds(coinsNeed: item.price - coinsDeposited)
}
coinsDeposited -= item.price
var newItem = item
newItem.count -= 1
inventory[name] = newItem
print("dispensing \(name)")
}
}
//在vend(itemNamed:)方法的实现中使用了guard语句来提前退出方法,确保在购买某个物品所需的条件中,有任一条件不满足时,能提前退出方法并抛出相应的错误。由于throw语句会立即退出方法,所以物品只有在所有条件都满足时才会被售出。
//因为vend(itemNamed:)方法会传递出它抛出的任何错误,在你的代码中调用此方法的地方,必须要么直接处理这些错误——使用do-catch语句,try?或try!;要么继续将这些错误传递下去。例如下面例子中,buyFavoriteSnack(_:vendingMachine:)同样是一个 throwing 函数,任何由vend(itemNamed:)方法抛出的错误会一直被传递到buyFavoriteSnack(person:vendingMachine:)函数被调用的地方。
let favouriteItem = [
"xiaohong":"a",
"xiaoming":"b",
"xiaogang":"c"
]
func buyFavouriteSnack(person : String,vendingMachine : VendingMachine) throws {
let snackName = favouriteItem[person] ?? "xiaoyun"
try vendingMachine.vend(itemNamed: snackName)
}
//用 Do-Catch 处理错误
//可以使用一个do-catch语句运行一段闭包代码来处理错误。如果在do子句中的代码抛出了一个错误,这个错误会与catch子句做匹配,从而决定哪条子句能处理它。
// do {
// try expression
// statements
// } catch pattern 1 {
// statements
// } catch pattern 2 where condition {
// statements
// } catch {
// statements
// }
//在catch后面写一个匹配模式来表明这个子句能处理什么样的错误。如果一条catch子句没有指定匹配模式,那么这条子句可以匹配任何错误,并且把错误绑定到一个名字为error的局部常量。关于模式匹配的更多信息请参考 模式。
//catch子句不必将do子句中的代码所抛出的每一个可能的错误都作处理。如果所有catch子句都未处理错误,错误就会传递到周围的作用域。然而,错误还是必须要被某个周围的作用域处理的——要么是一个外围的do-catch错误处理语句,要么是一个 throwing 函数的内部。举例来说,下面的代码处理了VendingMachineError枚举类型的全部枚举值,但是所有其它的错误就必须由它周围的作用域处理:
let vendingMachine = VendingMachine.init()
vendingMachine.coinsDeposited = 20
do {
try buyFavouriteSnack(person: "xiaoming", vendingMachine: vendingMachine)
print("买到啦")
} catch VendingMachineError.invalidSelection {
print("invalid selection")
} catch VendingMachineError.insufficientFunds(coinsNeed: let coinsNeed) {
print("need coins \(coinsNeed)")
} catch VendingMachineError.outOfStock {
print("no have stock")
} catch { //加个空的catch ,不然会报错 Errors thrown from here are not handled because the enclosing catch is not exhaustive
}
//将错误转换成可选值
//可以使用try?通过将错误转换成一个可选值来处理错误。如果在评估try?表达式时一个错误被抛出,那么表达式的值就是nil。例如,在下面的代码中,x和y有着相同的数值和等价的含义:
//如果你想对所有的错误都采用同样的方式来处理,用try?就可以让你写出简洁的错误处理代码。例如,下面的代码用几种方式来获取数据,如果所有方式都失败了则返回nil:
//禁用错误传递
//指定清理工作
//可以使用defer语句在即将离开当前代码块时执行一系列语句。该语句让你能执行一些必要的清理工作,不管是以何种方式离开当前代码块的——无论是由于抛出错误而离开,还是由于诸如return或者break的语句。例如,你可以用defer语句来确保文件描述符得以关闭,以及手动分配的内存得以释放。
//defer语句将代码的执行延迟到当前的作用域退出之前。该语句由defer关键字和要被延迟执行的语句组成。延迟执行的语句不能包含任何控制转移语句,例如break或是return语句,或是抛出一个错误。延迟执行的操作会按照它们被指定时的顺序的相反顺序执行——也就是说,第一条defer语句中的代码会在第二条defer语句中的代码被执行之后才执行,以此类推。
// func processFile(filename: String) throws {
// if exists(filename) {
// let file = open(filename)
// defer {
// close(file)
// }
// while let line = try file.readline() {
// // 处理文件。
// }
// // close(file) 会在这里被调用,即作用域的最后。
// }
// }
}
/// 类型转换
func test14() {
//类型转换
//类型转换 可以判断实例的类型,也可以将实例看做是其父类或者子类的实例。
//类型转换在 Swift 中使用 is 和 as 操作符实现。这两个操作符提供了一种简单达意的方式去检查值的类型或者转换它的类型。
class Library {
let name : String
init(name : String) {
self.name = name
}
}
class Movie : Library {
var director : String
init(name: String,director : String) {
self.director = director
super.init(name: name)
}
}
class Song : Library {
var artist : String
init(name : String,artist : String) {
self.artist = artist
super.init(name: name)
}
}
let group = [
Movie.init(name: "a", director: "AA"),
Movie.init(name: "b", director: "BB"),
Song.init(name: "c", artist: "CC"),
Song.init(name: "d", artist: "DD"),
]
//类型检查,用 类型检查操作符(is)来检查一个实例是否属于特定子类型。若实例属于那个子类型,类型检查操作符返回 true,否则返回 false。<# is 是检查 子类是不是 ,某类的 特定子类型 类似于isKindOfClass#>
var songCount = 0,movieCount = 0
for item in group {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
//向下转型
//某类型的一个常量或变量可能在幕后实际上属于一个子类。当确定是这种情况时,你可以尝试向下转到它的子类型,用类型转换操作符(as? 或 as!)。as? as!
/*
因为向下转型可能会失败,类型转型操作符带有两种不同形式。条件形式as? 返回一个你试图向下转成的类型的可选值。强制形式 as! 把试图向下转型和强制解包(转换结果结合为一个操作。
当你不确定向下转型可以成功时,用类型转换的条件形式(as?)。条件形式的类型转换总是返回一个可选值,并且若下转是不可能的,可选值将是 nil。这使你能够检查向下转型是否成功。
只有你可以确定向下转型一定会成功时,才使用强制形式(as!)。当你试图向下转型为一个不正确的类型时,强制形式的类型转换会触发一个运行时错误。
下面的例子,迭代了 library 里的每一个 MediaItem,并打印出适当的描述。要这样做,item 需要真正作为 Movie 或 Song 的类型来使用,而不仅仅是作为 MediaItem。为了能够在描述中使用 Movie 或 Song 的 director 或 artist 属性,这是必要的。
在这个示例中,数组中的每一个 item 可能是 Movie 或 Song。事前你不知道每个 item 的真实类型,所以这里使用条件形式的类型转换(as?)去检查循环里的每次下转:
*/
for item in group {
if let movie = item as? Movie { //返回的是可选值,可能是?Movie,?Song 所以使用可选绑定
print("movie name = \(movie.name) director = \(movie.director)")
} else if let song = item as? Song {
print("song name = \(song.name) artist = \(song.artist)")
}
}
//Any AnyObject 的类型转换
//Swift 为不确定类型提供了两种特殊的类型别名
//Any 可以表示任何类型,包括函数类型。
//AnyObject 可以表示任何类类型的实例。
var things = [Any].init()
things.append(0)
things.append(0.0)
things.append(42)
things.append(3.13)
things.append("hello world")
things.append((3,5))
things.append(Movie.init(name: "pp", director: "kk"))
things.append({(name : String) -> String in "hello \(name)" })
things.append((404,"badnet"))
for thing in things {
switch thing {
case 0 as Int:
print("zero int")
case 0 as Double:
print("zero double")
case let someInt as Int:
print(someInt)
case is Double:
print("double \(thing)")
case let someString as String:
print(someString)
case let (x,y) as (Int,String):
print("tuple is \(x) \(y)")
case let movie as Movie:
print(movie.name,movie.director)
case let stringConverter as (String) -> String:
print(stringConverter("haha"))
default:
print("other")
}
}
}
//可选链
func test13 () {
/*
1、使用可选链式调用代替强制展开
2、为可选链式调用定义模型类
3、通过可选链式调用访问属性
4、通过链式调用调用方法
5、通过链式调用 访问下标
6、连接多层可选链式调用
7、在方法的可选返回值上进行可选链式调用
*/
//可选链式调用是一种可以在当前值可能为nil的可选值上请求和调用属性、方法及下标的方法。如果可选值有值,那么调用就会成功;如果可选值是nil,那么调用将返回nil。多个调用可以连接在一起形成一个调用链,如果其中任何一个节点为nil,整个调用链都会失败,即返回nil。
//1、使用可选链是调用代替强制展开
//可用链式调用?和强制展开!的区别是:?调用只会失败并不会发生运行时错误,但是!如果可选没有值,就会发生运行时错误;
//可选链式调用 返回值 为可选值;
// class Person {
// var residence : Residence?
// }
// class Residence {
// var numberOfRooms = 1
// }
//
// let john = Person.init()
// let residence = Residence.init()
// john.residence = residence
//// let roomCount = john.residence!.numberOfRooms //如果residence没有值,会发生运行时错误
//
// //下边写法 可选链式调用提供了另一种访问numberOfRooms的方式,使用问号(?)来替代原来的叹号(!)
// if let number = john.residence?.numberOfRooms {
// print("roomCount = \(number)")
// } else {
// print("nil")
// }
//为可选链式调用定义模型类
//通过使用可选链式调用可以调用多层属性、方法和下标。这样可以在复杂的模型中向下访问各种子属性,并且判断能否访问子属性的属性、方法或下标。
class Room {
let name : String
init(name : String) {
self.name = name
}
}
class Address {
var buildName : String?
var buildNumber : String?
var street : String?
func buildIdentifier () -> String? {
if buildName != nil {
return buildName
} else if buildNumber != nil && street != nil {
return "\(buildNumber!) \(street!)"
} else {
return nil
}
}
}
class Person {
var residence : Residence?
}
class Residence {
var rooms = [Room].init()
var numberOfRooms : Int {
return rooms.count
}
subscript(i : Int) -> Room {
get {
return rooms[i]
}
set {
rooms[i] = newValue
}
}
func printNumberOfRooms () {
print("number of rooms is \(numberOfRooms)")
}
var address : Address?
}
let john = Person.init()
if let roomCount = john.residence?.numberOfRooms {
print("rooms have \(roomCount)")
} else {
print("no have ")
}
let residence = Residence.init()
john.residence = residence
let address = Address.init()
address.buildNumber = "90"
address.buildName = "ppp"
address.street = "45 street"
john.residence?.address = address
if let name = john.residence?.address?.buildName {
print("build name = \(name)")
} else {
print("build name = nil")
}
//通过判断函数的返回值是否为 nil 来判断 调用是否成功
if john.residence?.printNumberOfRooms() != nil {
print("create success")
} else {
print("create false")
}
//这个方法没有返回值。然而,没有返回值的方法具有隐式的返回类型Void,如无返回值函数中所述。这意味着没有返回值的方法也会返回(),或者说空的元组。
//如果在可选值上通过可选链式调用来调用这个方法,该方法的返回类型会是Void?,而不是Void,因为通过可选链式调用得到的返回值都是可选的。这样我们就可以使用if语句来判断能否成功调用printNumberOfRooms()方法,即使方法本身没有定义返回值。通过判断返回值是否为nil可以判断调用是否成功:
//访问下标
//通过可选链式调用访问可选值的下标时,应该将问号放在下标方括号的前面而不是后面。可选链式调用的问号一般直接跟在可选表达式的后面。
//问号直接放在john.residence的后面,并且在方括号的前面,因为john.residence是可选值。
//类似的,可以通过下标,用可选链式调用来赋值:
// john.residence?[0] = Room.init(name: "FIRST")
// let johnHouse = Residence.init()
residence.rooms.append(Room.init(name: "111"))
residence.rooms.append(Room.init(name: "222"))
residence.rooms.append(Room.init(name: "333"))
residence.rooms.append(Room.init(name: "444"))
if let firstRoomName = john.residence?[0].name {
print("the first room name is \(firstRoomName)")
} else {
print("the first room name is nil")
}
if let roomName = john.residence?[0].name {
print("name = \(roomName)")
} else {
print("name = nil")
}
//访问可选类型的下标
//如果下标返回可选类型值,比如 Swift 中Dictionary类型的键的下标,可以在下标的结尾括号后面放一个问号来在其可选返回值上进行可选链式调用:
// var testDic : Dictionary = ["first":[2,3,4,56],"sec":[65,78,6]]
// testDic["sec"]?[1] = 888
// print(testDic["sec"]?[1])
//连接多层可选链式调用
//如果你访问的值不是可选的,可选链式调用将会返回可选值。
//如果你访问的值就是可选的,可选链式调用不会让可选返回值变得“更可选”。
//通过可选链式调用访问一个Int值,将会返回Int?,无论使用了多少层可选链式调用。
//类似的,通过可选链式调用访问Int?值,依旧会返回Int?值,并不会返回Int??。
if let streetName = john.residence?.address?.street {
print("street name = \(streetName)")
} else {
print("street name = nil")
}
//在方法的可选返回值上进行可选链式调用
if let identifier = john.residence?.address?.buildIdentifier() {
print("identifier = \(identifier)")
} else {
print("identifier = nil")
}
if let beginWith = john.residence?.address?.buildIdentifier()?.hasPrefix("p") {
if beginWith {
print("YES")
} else {
print("NO")
}
}
//在上面的例子中,在方法的圆括号后面加上问号是因为你要在buildingIdentifier()方法的可选返回值上进行可选链式调用,而不是方法本身。
}
/// 嵌套类型
func test12() {
let li = A.init()
li.firstName = "li"
li.appenName(last: " ming")
let black = BlackjackCard.init(rank: .Jack, suit: .Hearts)
print(black.description)
//引用嵌套类型
print(black.suit.rawValue)
print(black.rank.values.first)
print(BlackjackCard.Suit.Diamonds.rawValue)
}
//enumerate
func testEnum() {
//枚举
var move = MoveMent.Left
//switch 使用
switch move {
case .Left:
print("left")
// default:
// print("none")
}
//判断使用
move = .Down
if move == .Left {
print("left")
}
//明确case 使用
if case .Left = move {
print("left")
}
//使用默认构造方法来初始化
let moveMent = Movement.init(rawValue: 3)
print(moveMent!)
let code = Barcode.qr("haha")
var code1 = Barcode.qr("ll")
code1 = .qr("kk")
print(code,code1)
//枚举类型的 原始值的隐式赋值
//,Plant.mercury的显式原始值为1,Planet.venus的隐式原始值为2,依次类推。
//当原始类型为字符串时,每个枚举成员的隐式原始值为该枚举成员的名称
//使用 rawValue 可以访问成员的原始值
var direct = Direct.east
direct = .west
print(direct)
print(direct.rawValue)
print(Direct.east.rawValue)
// let dd = Direct.init(rawValue: "weat")
// print(dd ?? "")
// print(dd!.rawValue)
//递归枚举
//递归枚举是一种枚举类型,它有一个或多个枚举成员使用该枚举类型的实例作为关联值
func evaluate (_ expression : Expression) -> Int {
switch expression {
case let .number(value):
return value
case let .add(left,right) :
return evaluate(left) + evaluate(right)
case let .multiply(left,right) :
return evaluate(left) * evaluate(right)
}
}
let number1 = Expression.number(4)
let number2 = Expression.number(5)
let add = Expression.add(number1, number2)
let multiply = Expression.multiply(number2, number1)
print(evaluate(multiply))
print(evaluate(add))
}
//扩展
func test11 () {
/*
使用关键字 extension 来声明扩展:
extension SomeType {
// 为 SomeType 添加的新功能写到这里
}
可以通过扩展来扩展一个已有类型,使其采纳一个或多个协议。在这种情况下,无论是类还是结构体,协议名字的书写方式完全一样:
extension SomeType: SomeProtocol, AnotherProctocol {
// 协议实现写到这里
}
*/
//计算型属性
//扩展可以为已有的类型添加计算型实例属性 和 计算型类型属性
let oneInch = 25.4.mm
print("one inch is \(oneInch) meters")
//扩展可以添加新的计算型属性,但是不可以添加存储型属性,也不可以为已有属性添加属性观察器。
//添加构造器
//添加实例方法 类型方法
3.repeatCount {
print("hello world !")
}
//可变实例方法
//通过扩展添加的实例方法也可以修改该实例本身。结构体和枚举类型中修改 self 或其属性的方法必须将该实例方法标注为 mutating,正如来自原始实现的可变方法一样。
var count = 3
print(count.square())
//下标
//扩展可以为已有类型添加新下标
//扩展
/*
添加计算型属性和计算型类型属性
定义实例方法和类型方法
提供新的构造器
定义下标
定义和使用新的嵌套类型
使一个已有类型符合某个协议
扩展可以为一个类型增加新的功能,但是不能重写已有功能
扩展可以为已有类型添加新的实例方法和类型方法。
通过扩展添加的实例方法也可以修改该实例本身。结构体和枚举类型中修改 self 或其属性的方法必须将该实例方法标注为 mutating,正如来自原始实现的可变方法一样。
*/
//计算型属性 扩展可以为已有类型添加计算型实例属性 和 计算型类型数形
let a = "haha"
a.description()
//嵌套类型 扩展可以为已有的类 结构体 枚举 添加新的嵌套类型
let arrayInt = [1,2,3,-4,0]
for a in arrayInt {
switch a.kind {
case .Negative:
print("-")
case .Positive:
print("+")
default:
print("0")
}
}
//下标
//扩展可以为已有类型添加新下标
}
//自动引用计数
func test10 () {
class Person {
let name : String
init(name : String) {
self.name = name
print("\(name) is initial")
}
deinit {
print("\(name) is being deinitialized")
}
}
var person = Person.init(name: "xiao")
var reference1 : Person?
var reference2 : Person?
var reference3 : Person?
reference1 = person
reference2 = reference1
reference3 = reference1
reference2 = nil
reference3 = nil
reference1 = nil
// class Person {
// let name: String
// init(name: String) { self.name = name }
// var apartment: Apartment?
// deinit { print("\(name) is being deinitialized") }
// }
//
// class Apartment {
// let unit: String
// init(unit: String) { self.unit = unit }
// weak var tenant: Person? weak弱引用
// deinit { print("Apartment \(unit) is being deinitialized") }
// }
//弱引用
// 弱引用不会对其引用的实例保持强引用,因而不会阻止 ARC 销毁被引用的实例。这个特性阻止了引用变为循环强引用。声明属性或者变量时,在前面加上weak关键字表明这是一个弱引用。
//因为弱引用不会保持所引用的实例,即使引用存在,实例也有可能被销毁。因此,ARC 会在引用的实例被销毁后自动将其赋值为nil。并且因为弱引用可以允许它们的值在运行时被赋值为nil,所以它们会被定义为可选类型变量,而不是常量。
//你可以像其他可选值一样,检查弱引用的值是否存在,你将永远不会访问已销毁的实例的引用。
//无主引用
//Person和Apartment的例子展示了两个属性的值都允许为nil,并会潜在的产生循环强引用。这种场景最适合用弱引用来解决。
//Customer和CreditCard的例子展示了一个属性的值允许为nil,而另一个属性的值不允许为nil,这也可能会产生循环强引用。这种场景最适合通过无主引用来解决。
//无主引用以及隐式解析可选属性
}
//析构过程
func test9() {
//析构过程
//析构器只适用于类类型,当一个类的实例被释放之前,析构器会被立即调用。析构器用关键字deinit来标示,类似于构造器要用init来标示。
// 析构过程原理
//Swift 会自动释放不再需要的实例以释放资源。如自动引用计数章节中所讲述,Swift 通过自动引用计数(ARC)处理实例的内存管理。通常当你的实例被释放时不需要手动地去清理。但是,当使用自己的资源时,你可能需要进行一些额外的清理。例如,如果创建了一个自定义的类来打开一个文件,并写入一些数据,你可能需要在类实例被释放之前手动去关闭该文件。
//在类的定义中,每个类最多只能有一个析构器,而且析构器不带任何参数,如下所示:
// deinit {
//
// }
class Bank {
static var coinsInBank = 10000
static func distribute(coins numberCoinsRequired : Int) -> Int {
let numberOfCoin = min(numberCoinsRequired, coinsInBank)
coinsInBank -= numberOfCoin
return numberOfCoin
}
static func receive (coins : Int) {
coinsInBank += coins
}
}
class Player {
var coinsInPurse : Int
init(coins : Int) {
coinsInPurse = Bank.distribute(coins: coins)
}
func win(coins : Int) {
coinsInPurse += Bank.distribute(coins: coins)
}
deinit { //对象时放就会调用 类似于OC中的 dealloc
Bank.receive(coins: coinsInPurse)
}
}
var playerOne : Player? = Player.init(coins: 100)
print("a new player has joined the game with \(playerOne!.coinsInPurse) coins") //因为playerOne是可选的,所以访问其coinsInPurse属性来打印钱包中的硬币数量时,使用感叹号(!)来解包:
playerOne?.win(coins: 1000)
playerOne!.win(coins: 1000)
print("------- \(playerOne!.coinsInPurse)")
playerOne = nil
print(" ------ bank.coins = \(Bank.coinsInBank)")
}
//构造器
func test8() {
//构造器 init关键字
//Swift 的构造器无需返回值
//类和结构体在创建实例时,必须为所有存储型属性设置合适的初始值 存储型属性的值不能处于一个未知的状态。
//可以在构造器中为存储型属性赋初值,也可以在定义属性时为其设置默认值
//当你为存储型属性设置默认值或者在构造器中为其赋值时,它们的值是被直接设置的,不会触发任何属性观察者。
// init () {
// //处理构造过程
// }
struct Fahrenheit {
var temperature : Double
init() {
temperature = 32.0
}
}
let f = Fahrenheit()
print(f.temperature)
//默认属性值
//如前所述,你可以在构造器中为存储型属性设置初始值。同样,你也可以在属性声明时为其设置默认值。
//如果一个属性总是使用相同的初始值,那么为其设置一个默认值比每次都在构造器中赋值要好。两种方法的效果是一样的,只不过使用默认值让属性的初始化和声明结合得更紧密。使用默认值能让你的构造器更简洁、更清晰,且能通过默认值自动推导出属性的类型;同时,它也能让你充分利用默认构造器、构造器继承等特性,后续章节将讲到。
//自定义构造过程
//构造参数
struct Celsius {
var temperatureInCelsius : Double
init(fromFahrenheit fahrenheit : Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}
init(fromKelvin kelvin : Double) {
temperatureInCelsius = kelvin - 273.15
}
}
let celsius = Celsius.init(fromFahrenheit: 32.0)
print(celsius.temperatureInCelsius)
// let celsius1 = Celsius()
// print(celsius.temperatureInCelsius)
struct People {
var age : Int
var name : String
init(name : String,age : Int) {
self.name = name
self.age = age
}
}
let people = People(name: "haha",age : 19)
print(people.name,people.age)
//参数的内部名称 和 外部名称
//跟函数和方法参数相同,构造参数也拥有一个在构造器内部使用的参数名字和一个在调用构造器时使用的外部参数名字。
//然而,构造器并不像函数和方法那样在括号前有一个可辨别的名字。因此在调用构造器时,主要通过构造器中的参数名和类型来确定应该被调用的构造器。正因为参数如此重要,如果你在定义构造器时没有提供参数的外部名字,Swift 会为构造器的每个参数自动生成一个跟内部名字相同的外部名。
struct Color {
let green,red,white : Double
init(green : Double,red : Double,white : Double) {
self.red = red
self.white = white
self.green = green
}
// init(all : Double) {
// self.red = all
// self.white = all
// self.green = all
// }
init(_ all : Double) {
red = all
green = all
white = all
}
}
//注意,如果不通过外部参数名字传值,你是没法调用这个构造器的。只要构造器定义了某个外部参数名,你就必须使用它,忽略它将导致编译错误:
//不带外部名的构造器参数
//如果你不希望为构造器的某个参数提供外部名字,你可以使用下划线(_)来显式描述它的外部名,以此重写上面所说的默认行为
// let color = Color(23.0)
//可选属性类型
class ServeyQuestion {
var text : String
var response : String?
init(text : String) {
self.text = text
}
func ask() -> Void {
print(text)
}
}
let question = ServeyQuestion.init(text: "have a question")
// let q = ServeyQuestion(text: "ll")
question.ask()
print(question.response ?? "可选默认值")
//构造过程中常量的修改
//你可以在构造过程中的任意时间点给常量属性指定一个值,只要在构造过程结束时是一个确定的值。一旦常量属性被赋值,它将永远不可更改。
//注意
//对于类的实例来说,它的常量属性只能在定义它的类的构造过程中修改;不能在子类中修改。
//你可以修改上面的SurveyQuestion示例,用常量属性替代变量属性text,表示问题内容text在SurveyQuestion的实例被创建之后不会再被修改。尽管text属性现在是常量,我们仍然可以在类的构造器中设置它的值
//默认构造器
class ShoppingListItem {
var name : String?
var price : Double?
var quantity = 1
}
let shoppingListItem = ShoppingListItem()//默认构造器
//由于ShoppingListItem类中的所有属性都有默认值,且它是没有父类的基类,它将自动获得一个可以为所有属性设置默认值的默认构造器(尽管代码中没有显式为name属性设置默认值,但由于name是可选字符串类型,它将默认设置为nil)。上面例子中使用默认构造器创造了一个ShoppingListItem类的实例(使用ShoppingListItem()形式的构造器语法),并将其赋值给变量item
print(shoppingListItem.name ?? "no name",shoppingListItem.price ?? "250",shoppingListItem.quantity)
//结构体的逐一成员构造器
//除了上面提到的默认构造器,如果结构体没有提供自定义的构造器,它们将自动获得一个逐一成员构造器,即使结构体的存储型属性没有默认值。
struct Size {
var width : Double = 0.0
var height : Double = 0.0
}
let size = Size(width : 90,height : 90)
print(size.width,size.height)
var size1 = Size()
size1.width = 80.0
size1.height = 80.0
print(size1)
//值类型的构造器代理
//对于值类型,你可以使用self.init在自定义的构造器中引用相同类型中的其它构造器。并且你只能在构造器内部调用self.init。
//如果你为某个值类型定义了一个自定义的构造器,你将无法访问到默认构造器(如果是结构体,还将无法访问逐一成员构造器)。这种限制可以防止你为值类型增加了一个额外的且十分复杂的构造器之后,仍然有人错误的使用自动生成的构造器
//注意
//假如你希望默认构造器、逐一成员构造器以及你自己的自定义构造器都能用来创建实例,可以将自定义的构造器写到扩展(extension)中,而不是写在值类型的原始定义中。想查看更多内容,请查看扩展章节。
struct Size2 {
var width = 0.0
var height = 0.0
}
struct Point {
var x = 0.0
var y = 0.0
}
struct Rect {
var origin = Point()
var size = Size2()
init() {}
init(origin : Point,size : Size2) {
self.origin = origin
self.size = size
}
init(center : Point,size : Size2) {
let originX = center.x - (size.width/2)
let originY = center.y - size.height/2
self.init(origin: Point(x : originX,y : originY), size: size)
}
}
let rect1 = Rect.init()
//第一个Rect构造器init(),在功能上跟没有自定义构造器时自动获得的默认构造器是一样的。这个构造器是一个空函数,使用一对大括号{}来表示,它没有执行任何构造过程。调用这个构造器将返回一个Rect实例,它的origin和size属性都使用定义时的默认值Point(x: 0.0, y: 0.0)和Size(width: 0.0, height: 0.0):
let rect2 = Rect.init(origin: Point.init(x: 2.0, y: 2.0), size: Size2.init(width: 5.0, height: 5.0))
//第二个Rect构造器init(origin:size:),在功能上跟结构体在没有自定义构造器时获得的逐一成员构造器是一样的。这个构造器只是简单地将origin和size的参数值赋给对应的存储型属性
let rect3 = Rect.init(center: Point.init(x: 6.0, y: 6.0), size: Size2.init(width: 5.0, height: 5.0))
print("----\n\(rect1) -----\n\(rect2) --------\n\(rect3)")
//第三个Rect构造器init(center:size:)稍微复杂一点。它先通过center和size的值计算出origin的坐标,然后再调用(或者说代理给)init(origin:size:)构造器来将新的origin和size值赋值到对应的属性中:
//类的继承和构造过程
//类里面的所有存储行属性,包括所有继承自父类的属性,都必须在构造过程中设置初始值
/*
指定构造器和便利构造器的语法
类的指定构造器的写法跟值类型简单构造器一样:
init(parameters) {
}
便利构造器也采用相同样式的写法,但需要在init关键字之前放置convenience关键字,并使用空格将它们俩分开:
convenience init(parameters) {
}
类的构造器代理规则
规则1:指定构造器必须调用其直接父类的指定构造器
规则2:便利构造器必须调用同类中定义的其他构造器
规则3:便利构造器必须最终导致一个指定构造器被调用
记忆方法:
1、指定构造器必须总是向上代理
2、便利构造器必须总是横向代理
*/
class Tree {
var height : Double
var age : Int
init(_ height : Double,_ age : Int) { //指定构造器
self.height = height
self.age = age
}
convenience init(_ h : Double) { //便利构造器
self.init(h, 3)
}
convenience init(_ a : Int) { //便利构造器
// self.init(10.0, 2)
self.init(20.0)
self.absorbSun()
self.absorbWater()
}
final func absorbSun() -> Void { //子类不能重写
print("吸收阳光")
}
func absorbWater() {
print("吸收水分")
}
}
//每一个类必须拥有至少一个指定构造器,在某种情况下,许多类通过继承父类的指定构造器而满足了这一条件,遍历构造器在类中是比较次要的辅助性构造器,便利构造器必须调用一个类中的指定构造器,并未参数提供默认值
let tree = Tree.init(3.0, 3)
print(tree.height,tree.age)
class SmallTree : Tree {
var weight = 10.0 //第一阶段
// override init(_ height: Double, _ age: Int) {
// super.init(height, age)
// }
init(weight : Double) { //第二阶段
super.init(20.0, 4)
self.weight = weight
}
override func absorbWater() { //重写父类方法
print("smallTree 吸收水分")
}
}
let smallTree = SmallTree.init(weight: 30.8)
smallTree.age = 40
smallTree.height = 90.0
smallTree.weight = 80.0
smallTree.absorbWater()
print("smallTree weight\(smallTree.weight) height\(smallTree.height) age\(smallTree.age)")
//这些规则则不会影响类的实例如何创建,任何上图中展示的构造器都可以用来创建完全初始化的实例,这些规则只影响类定义如何实现;
//两段式构造过程
//Swift 中类的构造过程包含两个阶段。第一个阶段,每个存储型属性被引入它们的类指定一个初始值。当每个存储型属性的初始值被确定后,第二阶段开始,它给每个类一次机会,在新实例准备使用之前进一步定制它们的存储型属性。
//两段式构造过程的使用让构造过程更安全,同时在整个类层级结构中给予了每个类完全的灵活性。两段式构造过程可以防止属性值在初始化之前被访问,也可以防止属性被另外一个构造器意外地赋予不同的值。
//Swift 的两段式构造过程跟 Objective-C 中的构造过程类似。最主要的区别在于阶段 1,Objective-C 给每一个属性赋值0或空值(比如说0或nil)。Swift 的构造流程则更加灵活,它允许你设置定制的初始值,并自如应对某些属性不能以0或nil作为合法默认值的情况。
/*
swift编译器执行4种安全检查,以确保两段式构造过程正确的完成
1、指定构造器必须保证它所在类引入的所有属性都必须先初始化完成,之后才能将其它构造任务向上代理给父类中的构造器。
如上所述,一个对象的内存只有在其所有存储型属性确定之后才能完全初始化。为了满足这一规则,指定构造器必须保证它所在类引入的属性在它往上代理之前先完成初始化。
2、指定构造器必须先向上代理调用父类构造器,然后再为继承的属性设置新值。如果没这么做,指定构造器赋予的新值将被父类中的构造器所覆盖。
3、便利构造器必须先代理调用同一类中的其它构造器,然后再为任意属性赋新值。如果没这么做,便利构造器赋予的新值将被同一类中其它指定构造器所覆盖。
4、构造器在第一阶段构造完成之前,不能调用任何实例方法,不能读取任何实例属性的值,不能引用self作为一个值。
类实例在第一阶段结束以前并不是完全有效的。只有第一阶段完成后,该实例才会成为有效实例,才能访问属性和调用方法。
阶段1:
某个指定构造器或便利构造器被调用。
完成新实例内存的分配,但此时内存还没有被初始化。
指定构造器确保其所在类引入的所有存储型属性都已赋初值。存储型属性所属的内存完成初始化。
指定构造器将调用父类的构造器,完成父类属性的初始化。
这个调用父类构造器的过程沿着构造器链一直往上执行,直到到达构造器链的最顶部。
当到达了构造器链最顶部,且已确保所有实例包含的存储型属性都已经赋值,这个实例的内存被认为已经完全初始化。此时阶段 1 完成
阶段2:
从顶部构造器链一直往下,每个构造器链中类的指定构造器都有机会进一步定制实例。构造器此时可以访问self、修改它的属性并调用实例方法等等。
最终,任意构造器链中的便利构造器可以有机会定制实例和使用self。
*/
//构造器的继承和重写
//跟 Objective-C 中的子类不同,Swift 中的子类默认情况下不会继承父类的构造器。Swift 的这种机制可以防止一个父类的简单构造器被一个更精细的子类继承,并被错误地用来创建子类的实例。
//重写 父类的指定构造器 关键字 overide;重写便利构造器不需要加上关键字 override
class HighTree : Tree {
convenience init(_ h : Double) { //no have override
self.init(3.0, 3)
}
override init(_ height: Double, _ age: Int) { //have override
super.init(height, age)
self.height = height + 10.0
self.age = age + 1
}
}
let highTree = HighTree.init(30.0)
print(highTree.height,highTree.age)
//构造器的自动继承
//假如你为新引入的属性都提供了默认值;
//规则1、如果子类没有定义任何指定构造器,那么它将自动继承所有父类的指定构造器
//规则2、如果子类提供了所有父类指定构造器的实现——无论是通过规则 1 继承过来的,还是提供了自定义实现——它将自动继承所有父类的便利构造器。
class MediumTree : Tree {
var branch = 10
}
let mediumTree = MediumTree.init(20.0, 3)
print(mediumTree.age)
//子类的便利构造器 可以 复写父类的指定构造器
class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[Unnamed]")
}
}
class RecipeIngredient: Food {
var quantity: Int
init(name: String, quantity: Int) {
self.quantity = quantity
super.init(name: name)
}
override convenience init(name: String) {
self.init(name: name, quantity: 1)
}
}
//RecipeIngredient的便利构造器init(name: String)使用了跟Food中指定构造器init(name: String)相同的参数。由于这个便利构造器重写了父类的指定构造器init(name: String),因此必须在前面使用override修饰符
//可失败构造器
//如果一个类、结构体或枚举类型的对象,在构造过程中有可能失败,则为其定义一个可失败构造器。这里所指的“失败”是指,如给构造器传入无效的参数值,或缺少某种所需的外部资源,又或是不满足某种必要的条件等。
//为了妥善处理这种构造过程中可能会失败的情况。你可以在一个类,结构体或是枚举类型的定义中,添加一个或多个可失败构造器。其语法为在init关键字后面添加问号(init?)。
//<#可失败构造器的参数名和参数类型,不能与其它非可失败构造器的参数名,及其参数类型相同。#>
//可失败构造器会创建一个类型为自身类型的可选类型的对象。你通过return nil语句来表明可失败构造器在何种情况下应该“失败”。
//注意
//严格来说,构造器都不支持返回值。因为构造器本身的作用,只是为了确保对象能被正确构造。因此你只是用return nil表明可失败构造器构造失败,而不要用关键字return来表明构造成功。
struct Animal {
let species : String
init? (species : String) {
if species.isEmpty {return nil }
self.species = species
}
init(sp : String) {
self.species = sp
}
}
let animal = Animal.init(species: "monkey") //animal的类型是Animal?
if let someAnimal = animal {
print("An animal was initialized with a species of \(someAnimal.species)")
}
let anyAnimal = Animal.init(species: "")
if anyAnimal == nil {
print("animal = nil")
}
//枚举类型的可失败构造器
enum TemperatureUnit {
case Kelvin,Celsius,Fahrenheit
init ? (symbal : Character) {
switch symbal {
case "K":
self = .Kelvin
case "C":
self = .Celsius
case "F":
self = .Fahrenheit
default:
return nil
}
}
}
let temp = TemperatureUnit.init(symbal: "F")
if temp != nil {
print("initial success")
}
let temp1 = TemperatureUnit.init(symbal: "C")
if temp1 == nil {
print("initial false")
}
//带原始值的枚举类型的可失败构造器
//带原始值的枚举类型会自带一个可失败构造器init?(rawValue:),该可失败构造器有一个名为rawValue的参数,其类型和枚举类型的原始值类型一致,如果该参数的值能够和某个枚举成员的原始值匹配,则该构造器会构造相应的枚举成员,否则构造失败。
enum Temperature : Character {
case Kelvin = "K",Celsius = "C",Fahrenheit = "F"
}
let t = Temperature.init(rawValue: "D")
let t1 = Temperature.init(rawValue: "C")
if t == nil {
print("false")
}
if t1 != nil {
print("success")
}
//构造失败的传递
//类,结构体,枚举的可失败构造器可以横向代理到类型中的其他可失败构造器。类似的,子类的可失败构造器也能向上代理到父类的可失败构造器。
//无论是向上代理还是横向代理,如果你代理到的其他可失败构造器触发构造失败,整个构造过程将立即终止,接下来的任何构造代码不会再被执行。
//注意
//可失败构造器也可以代理到其它的非可失败构造器。通过这种方式,你可以增加一个可能的失败状态到现有的构造过程中。
class Product {
let name : String
init ? (name : String) {
if name.isEmpty {return nil}
self.name = name
}
}
class CartItem : Product {
let quantity : Int
init ? (quantity : Int,name : String) {
if quantity < 1 {return nil}
self.quantity = quantity
super.init(name: name)
}
}
//重写可失败构造器
class Document {
var name : String?
init() { }
init ? (name : String) {
self.name = name
}
}
class Adocument : Document {
override init() {
super.init()
self.name = "[Untitled]"
}
override init(name: String) {
super.init()
if name.isEmpty {
self.name = "[Untitled]"
} else {
self.name = name
}
}
}
//你可以在子类的非可失败构造器中使用强制解包来调用父类的可失败构造器。比如,下面的UntitledDocument子类的name属性的值总是"[Untitled]",它在构造过程中使用了父类的可失败构造器init?(name:):
class UntitledDocument : Document {
override init() {
super.init(name: "[Untitled]")! //抢劫报
}
}
//可失败构造器 init!
//通常来说我们通过在init关键字后添加问号的方式(init?)来定义一个可失败构造器,但你也可以通过在init后面添加惊叹号的方式来定义一个可失败构造器(init!),该可失败构造器将会构建一个对应类型的隐式解包可选类型的对象。
//你可以在init?中代理到init!,反之亦然。你也可以用init?重写init!,反之亦然。你还可以用init代理到init!,不过,一旦init!构造失败,则会触发一个断言。
//必要构造器
//在类的构造器前添加 required 修饰符表明所有该类的子类都必须实现该构造器:
//在子类重写父类的必要构造器时,必须在子类的构造器前也添加required修饰符,表明该构造器要求也应用于继承链后面的子类。在重写父类中必要的指定构造器时,不需要添加override修饰符:
class Class {
var name : String
required init(name : String){
self.name = name
print("构造器实现----\(name)")
}
}
class SubClass : Class {
required init(name: String) {
super.init(name: name)
}
}
let c = Class.init(name: "yang")
let c1 = SubClass.init(name: "tao")
print(c.name,c1.name)
//通过闭包或者函数来设置属性的默认值
/*
如果某个存储型属性的默认值需要一些定制或设置,你可以使用闭包或全局函数为其提供定制的默认值。每当某个属性所在类型的新实例被创建时,对应的闭包或函数会被调用,而它们的返回值会当做默认值赋值给这个属性。
这种类型的闭包或函数通常会创建一个跟属性类型相同的临时变量,然后修改它的值以满足预期的初始状态,最后返回这个临时变量,作为属性的默认值。
下面介绍了如何用闭包为属性提供默认值:
*/
// class SomeClass {
// let someProperty: SomeType = {
// // 在这个闭包中给 someProperty 创建一个默认值
// // someValue 必须和 SomeType 类型相同
// return someValue
// }()
// }
//注意闭包结尾的大括号后面接了一对空的小括号。这用来告诉 Swift 立即执行此闭包。如果你忽略了这对括号,相当于将闭包本身作为值赋值给了属性,而不是将闭包的返回值赋值给属性。
//注意
//如果你使用闭包来初始化属性,请记住在闭包执行时,实例的其它部分都还没有初始化。这意味着你不能在闭包里访问其它属性,即使这些属性有默认值。同样,你也不能使用隐式的self属性,或者调用任何实例方法。
struct Checkerboard {
let boardColors: [Bool] = {
var temporaryBoard = [Bool]()
var isBlack = false
for i in 1...8 {
for j in 1...8 {
temporaryBoard.append(isBlack)
isBlack = !isBlack
}
isBlack = !isBlack
}
return temporaryBoard
}()
func squareIsBlackAtRow(row: Int, column: Int) -> Bool {
return boardColors[(row * 8) + column]
}
}
let board = Checkerboard()
print(board.boardColors)
}
//继承
func test7 () {
//继承
/*
一个类可以继承另一个类的方法,属性和其它特性。当一个类继承其它类时,继承类叫子类,被继承类叫超类(或父类)。在 Swift 中,继承是区分「类」与其它类型的一个基本特征。
在 Swift 中,类可以调用和访问超类的方法,属性和下标,并且可以重写这些方法,属性和下标来优化或修改它们的行为。Swift 会检查你的重写定义在超类中是否有匹配的定义,以此确保你的重写行为是正确的。
可以为类中继承来的属性添加属性观察器,这样一来,当属性值改变时,类就会被通知到。可以为任何属性添加属性观察器,无论它原本被定义为存储型属性还是计算型属性。
注意
Swift 中的类并不是从一个通用的基类继承而来。如果你不为你定义的类指定一个超类的话,这个类就自动成为基类。
*/
//定义一个基类 不继承于其他类的类称为基类
class Vehicle {
var currentSpeed = 0.0
var description : String { //只读计算属性description
return "traveling at \(currentSpeed) miles per hour"
}
func makeNoise() {
//什么都不做 子类处理
}
}
//子类生成
//子类生成指的是在一个已有类的基础上创建一个新的类。子类继承超类的特性,并且可以进一步完善。你还可以为子类添加新的特性。
//为了指明某个类的超类,将超类名写在子类名的后面,用冒号分隔:
class SomeClass : Vehicle {
//子类继承Vehicle
}
//新的Bicycle类自动获得Vehicle类的所有特性,比如currentSpeed和description属性,还有它的makeNoise()方法。
class Bike : Vehicle {
var hasBasket = true
}
let bike = Bike()
bike.hasBasket = false
bike.currentSpeed = 9.0
print(bike.description)
//子类还可以继续被其它类继承,下面的示例为Bicycle创建了一个名为Tandem(双人自行车)的子类:
class Tandem : Bike {
var numberPerson = 2
}
//重写
/*
子类可以为继承来的实例方法,类方法,实例属性,或下标提供自己定制的实现。我们把这种行为叫重写。
如果要重写某个特性,你需要在重写定义的前面加上override关键字。这么做,你就表明了你是想提供一个重写版本,而非错误地提供了一个相同的定义。意外的重写行为可能会导致不可预知的错误,任何缺少override关键字的重写都会在编译时被诊断为错误。
override关键字会提醒 Swift 编译器去检查该类的超类(或其中一个父类)是否有匹配重写版本的声明。这个检查可以确保你的重写定义是正确的。
当你在子类中重写超类的方法,属性或下标时,有时在你的重写版本中使用已经存在的超类实现会大有裨益。比如,你可以完善已有实现的行为,或在一个继承来的变量中存储一个修改过的值。
在合适的地方,你可以通过使用super前缀来访问超类版本的方法,属性或下标:
在方法someMethod()的重写实现中,可以通过super.someMethod()来调用超类版本的someMethod()方法。
在属性someProperty的 getter 或 setter 的重写实现中,可以通过super.someProperty来访问超类版本的someProperty属性。
在下标的重写实现中,可以通过super[someIndex]来访问超类版本中的相同下标。
*/
class Train : Vehicle {
override func makeNoise() {
print("火车声")
}
}
let train = Train()
train.makeNoise()
//重写属性
//你可以提供定制的 getter(或 setter)来重写任意继承来的属性,无论继承来的属性是存储型的还是计算型的属性。子类并不知道继承来的属性是存储型的还是计算型的,它只知道继承来的属性会有一个名字和类型。你在重写一个属性时,必需将它的名字和类型都写出来。这样才能使编译器去检查你重写的属性是与超类中同名同类型的属性相匹配的。
//你可以将一个继承来的只读属性重写为一个读写属性,只需要在重写版本的属性里提供 getter 和 setter 即可。但是,你不可以将一个继承来的读写属性重写为一个只读属性
//注意
//如果你在重写属性中提供了 setter,那么你也一定要提供 getter。如果你不想在重写版本中的 getter 里修改继承来的属性值,你可以直接通过super.someProperty来返回继承来的值,其中someProperty是你要重写的属性的名字。
class Car : Vehicle {
var gear = 1
override var description: String {
return super.description + "in gear \(gear)"
}
}
let car = Car()
car.currentSpeed = 90.0
print(car.description)
//从写属性观察器
//注意
//你不可以为继承来的常量存储型属性或继承来的只读计算型属性添加属性观察器。这些属性的值是不可以被设置的,所以,为它们提供willSet或didSet实现是不恰当。
//此外还要注意,你不可以同时提供重写的 setter 和重写的属性观察器。如果你想观察属性值的变化,并且你已经为那个属性提供了定制的 setter,那么你在 setter 中就可以观察到任何值变化了。
class AutoCar : Car {
override var currentSpeed: Double {
didSet {
gear = Int(currentSpeed/10.0) + 1
}
}
}
let autoCar = AutoCar()
autoCar.currentSpeed = 90.0
print("aotoCar gear is \(autoCar.gear)")
//防止重写
/*
你可以通过把方法,属性或下标标记为final来防止它们被重写,只需要在声明关键字前加上final修饰符即可(例如:final var,final func,final class func,以及final subscript)。
如果你重写了带有final标记的方法,属性或下标,在编译时会报错。在类扩展中的方法,属性或下标也可以在扩展的定义里标记为 final 的。
你可以通过在关键字class前添加final修饰符(final class)来将整个类标记为 final 的。这样的类是不可被继承的,试图继承这样的类会导致编译报错。
*/
class People {
final var weight = 34.0
var job = "coder"
func goToWork() -> Void {
print("go to work")
}
}
// class Man : People {
// override var weight = 90.0
//
// }
}
//下标
func test6() {
//下标
//下标可以定义在类、结构体和枚举中,是访问集合,列表或序列中元素的快捷方式。可以使用下标的索引,设置和获取值,而不需要再调用对应的存取方法。举例来说,用下标访问一个Array实例中的元素可以写作someArray[index],访问Dictionary实例中的元素可以写作someDictionary[key]。
//一个类型可以定义多个下标,通过不同索引类型进行重载。下标不限于一维,你可以定义具有多个入参的下标满足自定义类型的需求。
//下表语法
// subscript (index : Int) -> Int {
// get {
// return 4
// }
// set(newValue) {
// //执行赋值操作
// }
// }
//如同只读计算型属性,可以省略只读下标的get关键字:
// subscript(index : Int) -> Int {
// return 5
// }
struct TimeTable {
let multipier : Int
subscript(index : Int) -> Int {
return multipier * index
}
}
let threeTimeTable = TimeTable(multipier : 3)
print(threeTimeTable[6])
//在上例中,创建了一个TimesTable实例,用来表示整数3的乘法表。数值3被传递给结构体的构造函数,作为实例成员multiplier的值。
//你可以通过下标访问threeTimesTable实例,例如上面演示的threeTimesTable[6]。这条语句查询了3的乘法表中的第六个元素,返回3的6倍即18。
//下表用法
// 例如,Swift 的Dictionary类型实现下标用于对其实例中储存的值进行存取操作。为字典设值时,在下标中使用和字典的键类型相同的键,并把一个和字典的值类型相同的值赋给这个下标:
//
// var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
// numberOfLegs["bird"] = 2
// 上例定义一个名为numberOfLegs的变量,并用一个包含三对键值的字典字面量初始化它。numberOfLegs字典的类型被推断为[String: Int]。字典创建完成后,该例子通过下标将String类型的键bird和Int类型的值2添加到字典中。
//
//下标选项
//标可以接受任意数量的入参,并且这些入参可以是任意类型。下标的返回值也可以是任意类型。下标可以使用变量参数和可变参数,但不能使用输入输出参数,也不能给参数设置默认值。
//一个类或结构体可以根据自身需要提供多个下标实现,使用下标时将通过入参的数量和类型进行区分,自动匹配合适的下标,这就是下标的重载。
struct Matrix {
let rows : Int,columns : Int
var grid : [Double]
init(rows : Int,columns : Int) {
self.rows = rows
self.columns = columns
grid = Array(repeatElement(0.0, count: 3))
}
func indexIsValidForRow(row : Int,column : Int) -> Bool {
return row >= 0 && row < rows && column < columns && column >= 0
}
subscript(row : Int,column : Int) -> Double {
get {
assert(indexIsValidForRow(row: row, column: column), "index out of range")
return grid[(row * column) + column]
}
set {
assert(indexIsValidForRow(row: row, column: column),"index out of range")
grid[(row * column) + column] = newValue
}
}
}
//Matrix提供了一个接受两个入参的构造方法,入参分别是rows和columns,创建了一个足够容纳rows * columns个Double类型的值的数组。通过传入数组长度和初始值0.0到数组的构造器,将矩阵中每个位置的值初始化为0.0。关于数组的这种构造方法请参考创建一个空数组。
//你可以通过传入合适的row和column的数量来构造一个新的Matrix实例:
var matrix = Matrix(rows : 2,columns : 2)
//将row 和 column 的值传入下标来为矩阵设置值,下标的入参使用逗号分隔
matrix[0,1] = 1.5
matrix[1,0] = 3.2
//上面两条语句分别调用下标的 setter 将矩阵右上角位置(即row为0、column为1的位置)的值设置为1.5,将矩阵左下角位置(即row为1、column为0的位置)的值设置为3.2:
//Matrix下标的 getter 和 setter 中都含有断言,用来检查下标入参row和column的值是否有效。为了方便进行断言,Matrix包含了一个名为indexIsValidForRow(_:column:)的便利方法,用来检查入参row和column的值是否在矩阵范围内
// //下标
// struct GetName {
// var name : String
// subscript(firstName : String) -> String {
// get {
// return firstName + name
// }
//// set {
////
//// }
// }
// }
//
// let getName = GetName.init(name: "ming")
// print(getName["xiao"])
}
//实例方法 和 类方法
func test5() -> Void {
//方法
//实例方法
//结构体和枚举能够定义方法是 Swift 与 C/Objective-C 的主要区别之一。在 Objective-C 中,类是唯一能定义方法的类型。但在 Swift 中,你不仅能选择是否要定义一个类/结构体/枚举,还能灵活地在你创建的类型(类/结构体/枚举)上定义方法。
class Counter {
var count = 0
func increment() -> Void {
count += 1
}
func increment(by aCount : Int) {
count += aCount
}
func reset () {
count = 0
}
}
/*
Counter类定义了三个实例方法:
increment让计数器按一递增;
increment(by: Int)让计数器按一个指定的整数值递增;
reset将计数器重置为0。
Counter这个类还声明了一个可变属性count,用它来保持对当前计数器值的追踪。
*/
let counter = Counter()
counter.increment()
counter.increment(by: 10)
counter.reset()
counter.increment(by: 20)
print(counter.count)
//函数参数可以同时有一个局部名称(在函数体内部使用)和一个外部名称(在调用函数时使用),详情参见指定外部参数名。方法参数也一样,因为方法就是函数,只是这个函数与某个类型相关联了。
//self属性 类型的每一个实例都有一个隐含属性叫做self,self完全等同于该实例本身。你可以在一个实例的实例方法中使用这个隐含的self属性来引用当前实例。
//上面例子中的increment方法还可以这样写:
// func increment() {
// self.count += 1
// }
//使用这条规则的主要场景是实例方法的某个参数名称与实例的某个属性名称相同的时候。在这种情况下,参数名称享有优先权,并且在引用属性时必须使用一种更严格的方式。这时你可以使用self属性来区分参数名称和属性名称。
struct Point {
var x = 0.0,y = 0.0
func theRightX(x : Double) -> Bool {
return self.x > x
}
}
let somePoint = Point(x : 4.0,y : 5.0)
let isBig = somePoint.theRightX(x: 3.0)
if isBig {
print("big")
}
//在实例方法中修改值类型
//结构体和枚举是值类型,默认情况下,值类型的属性不能在它的实例方法中被修改;
//但是,如果你确实需要在某个特定的方法中修改结构体或者枚举的属性,你可以为这个方法选择可变(mutating)行为,然后就可以从其方法内部改变它的属性;并且这个方法做的任何改变都会在方法执行结束时写回到原始结构中。方法还可以给它隐含的self属性赋予一个全新的实例,这个新实例在方法结束时会替换现存实例。
// 要使用可变方法,将关键字mutating 放到方法的func关键字之前就可以了:
struct MutablePoint {
var x = 0.0,y = 0.0
mutating func moveByX(deltaX:Double,deltaY:Double) {
x += deltaX
y += deltaY
}
}
var mutablePoint = MutablePoint(x:2.0,y:3.0)
mutablePoint.moveByX(deltaX: 3.0, deltaY: 4.0)
print("the point noew is \(mutablePoint.x) \(mutablePoint.y)")
//上面的Point结构体定义了一个可变方法 moveByX(_:y:) 来移动Point实例到给定的位置。该方法被调用时修改了这个点,而不是返回一个新的点。方法定义时加上了mutating关键字,从而允许修改属性。注意,不能在结构体类型的常量(a constant of structure type)上调用可变方法,因为其属性不能被改变,即使属性是变量属性
//在可变方法中给属性赋值
struct MutablePoint1 {
var x = 0.0,y = 0.0
mutating func moveBy (x deltaX : Double,y deltaY : Double) {
self = MutablePoint1(x : x + deltaX,y : y + deltaY)
}
}
//枚举的可变方法可以把self设置为同一枚举类型中不同的成员:
enum Switch {
case Off,High,Low
mutating func next() {
switch self {
case .Off:
self = .Low
case .Low:
self = .High
default:
self = .High
}
}
}
//类型方法 类方法
//实例方法是被某个类型的实例调用的方法。你也可以定义在类型本身上调用的方法,这种方法就叫做类型方法。在方法的func关键字之前加上关键字class,来指定类型方法。类还可以用关键字class来允许子类重写父类的方法实现。
// 类 在方法 func 的前边加上 <#class#> 关键字,来制定类型方法,类还可以使用关键字 class 来允许子类重写父类的方法实现
// 在OC中,你只能为类添加类方法,在swift中,你可以为所有的嘞、结构体。、枚举添加类方法,使用关键字<#static#> 每一个类型方法都被他所支持的类型所包含
// 使用点语法调用
class SomeClass {
class func someMethod() {
print("这是一个类方法")
}
}
SomeClass.someMethod()
struct LevelTracker {
static var highUnlockedLevel = 1
var currentLevel = 1
static func unlock(_ level : Int) {
if level > highUnlockedLevel {
highUnlockedLevel = level
}
}
static func isUnlocked(_ level : Int) -> Bool {
return level < highUnlockedLevel
}
@discardableResult
mutating func advance(to level : Int) -> Bool {
if LevelTracker.isUnlocked(level) {
currentLevel = level
return true
} else {
return false
}
}
}
class Player {
var tracker = LevelTracker()
let playerName : String
func complete(level : Int) {
LevelTracker.unlock(level + 1)
tracker.advance(to: level + 1)
}
init(name : String) {
playerName = name
}
}
var playerOne = Player(name : "xiaohong")
playerOne.complete(level: 1)
print("highest unlocked level is now \(LevelTracker.highUnlockedLevel)")
playerOne = Player(name : "hehe")
if playerOne.tracker.advance(to: 6) {
print("noe level is 6")
} else {
print("unLock")
}
}
//属性
func test4() {
//属性
//存储属性
struct FixedLengthRange {
var firstValue : Int
let length : Int
}
var rangeOfThreeItem = FixedLengthRange(firstValue : 6,length : 4)
rangeOfThreeItem.firstValue = 10;
print(rangeOfThreeItem.firstValue,rangeOfThreeItem.length)
//解释:FixedLengthRange 的实例包含一个名为 firstValue 的变量存储属性和一个名为 length 的常量存储属性。在上面的例子中,length 在创建实例的时候被初始化,因为它是一个常量存储属性,所以之后无法修改它的值。
//常量结构体的存储属性
//如果创建了一个结构体的实例并将其赋值给一个常量,则无法修改该实例的任何属性,即使有属性被声明为变量也不行:
// let constRange = FixedLengthRange(firstValue : 10,length : 5)
// constRange.firstValue = 20
// print(constRange.firstValue)
//因为 rangeOfFourItems 被声明成了常量(用 let 关键字),即使 firstValue 是一个变量属性,也无法再修改它了。
//这种行为是由于结构体(struct)属于值类型。当值类型的实例被声明为常量的时候,它的所有属性也就成了常量。但是引用类型 class就不一样,把一个引用类型的实例赋值给一个常量后,还是可以改变该常量的变量属性
//延迟存储属性
//延迟存储属性是指当第一次被调用的时候才会计算其初始值的属性。在属性声明前使用 lazy 来标示一个延迟存储属性。
//注意
//必须将延迟存储属性声明成变量(使用 var 关键字),因为属性的初始值可能在实例构造完成之后才会得到。而常量属性在构造过程完成之前必须要有初始值,因此无法声明成延迟属性。
//注意
//如果一个被标记为 lazy 的属性在没有初始化时就同时被多个线程访问,则无法保证该属性只会被初始化一次。
//存储属性 实例变量
//如果您有过 Objective-C 经验,应该知道 Objective-C 为类实例存储值和引用提供两种方法。除了属性之外,还可以使用实例变量作为属性值的后端存储。
//Swift 编程语言中把这些理论统一用属性来实现。Swift 中的属性没有对应的实例变量,属性的后端存储也无法直接访问。这就避免了不同场景下访问方式的困扰,同时也将属性的定义简化成一个语句。属性的全部信息——包括命名、类型和内存管理特征——都在唯一一个地方(类型定义中)定义。
//计算属性
struct Point {
var x = 0.0,y = 0.0
}
struct Size {
var width = 0.0,height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center : Point {
get {
let centerX = origin.x - (size.width/2)
let centerY = origin.y - (size.height/2)
return Point(x: centerX,y : centerY)
}
set(newPoint) {
origin.x = newPoint.x - (size.width/2)
origin.y = newPoint.y - (size.height/2)
}
}
}
var square = Rect(origin : Point(x:0.0,y:0.0),size : Size(width : 10.0,height : 10.0))
let initialCenter = square.center
square.center = Point(x:15.0,y:15.0)
print(square.origin.x,square.origin.y)
//简化set声明 如果计算属性的 setter 没有定义表示新值的参数名,则可以使用默认名称 newValue。下面是使用了简化 setter 声明的
// set {
// origin.x = newValue.x - (size.width/2)
// origin.y = newValue.y - (size.height/2)
// }
//只读计算属性
//只有 getter 没有 setter 的计算属性就是只读计算属性。只读计算属性总是返回一个值,可以通过点运算符访问,但不能设置新的值。
//注意
//必须使用 var 关键字定义计算属性,包括只读计算属性,因为它们的值不是固定的。let 关键字只用来声明常量属性,表示初始化后再也无法修改的值。
//只读计算属性的声明可以去掉 get 关键字和花括号:
struct cuboid {
var width = 0.0,height = 0.0,depth = 0.0
var volume : Double {
return width * height * depth
}
}
//这个例子定义了一个名为 Cuboid 的结构体,表示三维空间的立方体,包含 width、height 和 depth 属性。结构体还有一个名为 volume 的只读计算属性用来返回立方体的体积。为 volume 提供 setter 毫无意义,因为无法确定如何修改 width、height 和 depth 三者的值来匹配新的 volume。然而,Cuboid 提供一个只读计算属性来让外部用户直接获取体积是很有用的。
//属性观察器
//willSet 在新的值被设置之前调用
//didSet 在新的值被设置之后立即调用
class StepCounter {
var totalStep : Int = 0 {
willSet(newTotalSteps){
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalStep > oldValue {
print("Added \(totalStep - oldValue) steps")
}
}
}
}
let stepConter = StepCounter()
stepConter.totalStep = 200
stepConter.totalStep = 360
stepConter.totalStep = 500
//集合 set, Swift 中的Set类型被写为Set<Element>,这里的Element表示Set中允许存储的类型,和数组不同的是,集合没有等价的简化形式。
var letters = Set<Character>()
letters.insert("C")
letters = [] //赋值空集合
var favourite : Set<String> = ["play soccer","play basketball","swimming"]
//一个Set类型不能从数组字面量中被单独推断出来,因此Set类型必须显式声明。然而,由于 Swift 的类型推断功能,如果你想使用一个数组字面量构造一个Set并且该数组字面量中的所有元素类型相同,那么你无须写出Set的具体类型。favoriteGenres的构造形式可以采用简化的方式代替
var fav : Set = ["haha","hehe"]
print(fav,favourite)
fav.insert("lala")
favourite.insert("play pingpang")
if fav.isEmpty {
print("empty")
} else {
print("not empty")
}
fav.insert("gogo")
let haha = fav.remove("haha")
print(haha ?? "optional xxx") //返回可选类型
if fav.contains("hehe") {
print("contain")
} else {
print("not contain")
}
//Swift 的Set类型没有确定的顺序,为了按照特定顺序来遍历一个Set中的值可以使用sorted()方法,它将返回一个有序数组,这个数组的元素排列顺序由操作符'<'对元素进行比较的结果来确定.
for item in fav.sorted() {
print(item)
}
//集合操作
//你可以高效地完成Set的一些基本操作,比如把两个集合组合到一起,判断两个集合共有元素,或者判断两个集合是否全包含,部分包含或者不相交。
let a : Set = [1,2,3,4,5]
let b : Set = [2,4,6,8,10]
let c = a.intersection(b)
let d = a.symmetricDifference(b)
let f = a.union(b)
let g = a.subtracting(b)
print("\(c)\n\(d)\n\(f)\n\(g)\n")
//使用intersection(_:)方法根据两个集合中都包含的值创建的一个新的集合。
//使用symmetricDifference(_:)方法根据在一个集合中但不在两个集合中的值创建一个新的集合。
//使用union(_:)方法根据两个集合的值创建一个新的集合。
//使用subtracting(_:)方法根据不在该集合中的值创建一个新的集合。
/*集合成员关系和相等
1、使用是否相等运算符 == 来判断两个及合是否包含全部相同的值
2、使用isSubset(of:)方法来判断一个集合的值是否也被包含在另外一个集合中
3、使用isSuperset(of:)方法来判断一个集合中包含另一个集合中所有的值。
4、使用isStrictSubset(of:)或者isStrictSuperset(of:)方法来判断一个集合是否是另外一个集合的子集合或者父集合并且两个集合并不相等。
5、使用isDisjoint(with:)方法来判断两个集合是否不含有相同的值(是否没有交集)。
*/
let set1 : Set = [1,2,3,4,5,6]
let set2 : Set = [2,3,4]
let set3 : Set = [4,90]
let isSub = set1.isSubset(of: set2)
let isSuper = set1.isSubset(of: set2)
let isJoint = set1.isDisjoint(with: set3)
print(isSub,isSuper,isJoint)
//字典
var numberOfInterger = [Int : String]() //创建一个 [Int : String] 类型空字典
numberOfInterger[16] = "sixteen"
numberOfInterger[3] = "three"
numberOfInterger = [:]//如果上下文已经提供了类型信息,我们可以使用空字典字面量来创建一个空字典,记作[:](中括号中放一个冒号):
//使用字典字面量创建字典
var numberOfString : [String : String] = ["hh":"haha","ll":"lala"]
numberOfString["pp"] = "papa"
print(numberOfInterger,numberOfString)
//和数组一样,我们在用字典字面量构造字典时,如果它的键和值都有各自一致的类型,那么就不必写出字典的类型。
var airports = ["hh":"haha","pp":"papa"]
print(airports)
print(airports.count)
if airports.isEmpty {
print("empty")
}
airports["hh"] = "hehe"
print(airports)
airports.updateValue("kaka", forKey: "hh")
if let oldValue = airports["pp"] {
print(oldValue)
}
//我们还可以使用下标语法来通过给某个键的对应值赋值为nil来从字典里移除一个键值对:
airports["beijing"] = "peking airport"
airports["beiijing"] = nil
//使用remove移除
airports["beijing"] = "peking airport"
let value = airports.removeValue(forKey: "beijing")
print(value ?? "可选没有值")
//字典遍历
for (a,b) in airports {
print(a,b)
}
//通过访问keys或者values属性,我们也可以遍历字典的键或者值:
for key in airports.keys {
print(key)
}
for value in airports.values {
print(value)
}
//如果我们只是需要使用某个字典的键集合或者值集合来作为某个接受Array实例的 API 的参数,可以直接使用keys或者values属性构造一个新数组:
let newArray = [String](airports.keys)
let newArray1 = [String](airports.values)
print(newArray,newArray1)
//创建空数组
let voidArray = [String]()
let voidArray1 = [Int]()
var array1 = [Int]()
var array2 : [String] = ["aa"]//
array2.append("bb")
array1.append(90)
print(voidArray,voidArray1,array1)
}
//类 结构体
func test3() {
//类和结构体
/* 共同点
定义属性用于存储值
定义方法用于提供功能
定义下表操作使得可以通过下表语法来访问实例所包含的值
定义构造器用于生成初始化值
通过扩展以增加默认实现的功能
实现协议已提供某种标准功能
类还有如下附加功能
1、继承 允许一个类继承另一个类的特征
2、类型转换允许在运行时检查和解释一个类实例的类型
3、析构器允许一个类实例释放任何其所被分配的资源
4、引用计数允许对一个类的多次引用
注意
结构体总是通过被复制的方式在代码中传递,不使用引用计数
*/
//定义 class struct 注意
//在你每次定义一个新类或者结构体的时候,实际上你是定义了一个新的 Swift 类型。因此请使用UpperCamelCase这种方式来命名(如SomeClass和SomeStructure等),以便符合标准 Swift 类型的大写命名风格(如String,Int和Bool)。相反的,请使用lowerCamelCase这种方式为属性和方法命名(如framerate和incrementCount),以便和类型名区分。
struct SomeStruct {
var width = 0
var height = 0
}
class SomeClass {
var someStruct = SomeStruct()
var a = false
var name : String?
}
//类的实例 结构体实例
//结构体和类都使用构造器语法来生成新的实例。构造器语法的最简单形式是在结构体或者类的类型名称后跟随 <#一对空括号#>,通过这种方式所创建的类或者结构体实例,其属性均会被初始化为默认值。构造过程章节会对类和结构体的初始化进行更详细的讨论。
let someC = SomeClass()
var someS = SomeStruct()
someC.name = "haha"
someS.width = 33
someC.someStruct.height = 30
print(someC.someStruct.height)
//结构体类型的成员逐一构造器
//所有结构体都有一个自动生成的成员逐一构造器,用于初始化新结构体实例中成员的属性。新实例中各个属性的初始值可以通过属性的名称传递到成员逐一构造器之中:
let bStruct = SomeStruct(width : 30,height : 90)
//与结构体不同,类实例没有默认的成员逐一构造器
//结构体和枚举是值类型
//值类型被赋予给一个变量、常量或者被传递给一个函数的时候,其值会被拷贝。
//在之前的章节中,我们已经大量使用了值类型。实际上,在 Swift 中,所有的基本类型:整数(Integer)、浮点数(floating-point)、布尔值(Boolean)、字符串(string)、数组(array)和字典(dictionary),都是值类型,并且在底层都是以结构体的形式所实现。
//在 Swift 中,所有的结构体和枚举类型都是值类型。这意味着它们的实例,以及实例中所包含的任何值类型属性,在代码中传递的时候都会被复制。
//类是引用类型 结构体 枚举是值类型
//与值类型不同,引用类型在被赋予到一个变量、常量或者被传递到一个函数时,其值不会被拷贝。因此,引用的是已存在的实例本身而不是其拷贝。
//恒等运算符
//因为类是引用类型,有可能有多个常量和变量在幕后同时引用同一个类实例。(对于结构体和枚举来说,这并不成立。因为它们作为值类型,在被赋予到常量、变量或者传递到函数时,其值总是会被拷贝。)
//等价于(===)
//不等价于(!==)
//请注意,“等价于”(用三个等号表示,===)与“等于”(用两个等号表示,==)的不同:
//“等价于”表示两个类类型(class type)的常量或者变量引用同一个类实例。
// “等于”表示两个实例的值“相等”或“相同”,判定时要遵照设计者定义的评判标准,因此相对于“相等”来说,这是一种更加合适的叫法。
//类和结构体的选择
/*
按照通用的准则,当符合一条或多条以下条件时,请考虑构建结构体:
该数据结构的主要目的是用来封装少量相关简单数据值。
有理由预计该数据结构的实例在被赋值或传递时,封装的数据将会被拷贝而不是被引用。
该数据结构中储存的值类型属性,也应该被拷贝,而不是被引用。
该数据结构不需要去继承另一个既有类型的属性或者行为。
举例来说,以下情境中适合使用结构体:
几何形状的大小,封装一个width属性和height属性,两者均为Double类型。
一定范围内的路径,封装一个start属性和length属性,两者均为Int类型。
三维坐标系内一点,封装x,y和z属性,三者均为Double类型。
在所有其它案例中,定义一个类,生成一个它的实例,并通过引用来管理和传递。实际中,这意味着绝大部分的自定义数据构造都应该是类,而非结构体。
*/
}
//闭包 枚举
func test2() {
//闭包
//一般形式
// { (<#parameters#>) -> <#return type#> in
// <#statements#>
// }
//例
let plus : (Int,Int) ->Int = {
(a : Int,b : Int) -> Int in
return a + b
}
print(plus(2,3))
//swift可以根据上下文判断变量类型,可以省略Int类型
let plus1 : (Int,Int) -> Int = {
(a,b) -> Int in //变量的括号也可省略
return a + b
}
print(plus1(2,3))
let plus2 : (Int,Int) -> Int = {
a,b in
return a + b
}
print(plus2(2,3))
//单表达式可以隐式返回,可以省略return
let plus3 : (Int,Int) -> Int = {
a,b in a + b
}
print(plus3(2,3))
//如果闭包没有参数,则可以省略in
let plus4 : () -> Int = {
return 100 + 200
}
print(plus4())
//既没有参数也没有返回值 return in 都省略
let plus5 : () -> Void = {
print("啥都没有")
}
print(plus5())
//总结:闭包类型是由参数类型和返回值类型决定的,跟函数一样,第一个闭包类型是(Int,Int)->Int,plus4的类型为()->Int,plus5的类型为()->Void;这里的plus类型就是闭包类型,意思是声明一个plusX变量,变量右边是具体实现,左边是变量值;右边给左边赋值;
//给闭包起别名
typealias aliasClosure = (String,String)->String
let addString : aliasClosure = {
(aString,bString) in
return aString + bString
}
print(addString("hello","world"))
//尾随闭包
//若函数参数的最后一个是闭包类型,则可以省略参数标签,然后可以将闭包表达式写在函数调用括号后边;
func funcClosure(voidClosure : () -> Void) {
voidClosure()
}
//正常写法
funcClosure(voidClosure:{
print("haha")
})
//尾随闭包写法
funcClosure() {
print("haha")
}
//也可以把括号省略
funcClosure {
print("haha")
}
//值捕获
//闭包可以在其被定义的上下文捕获变量或者常量;
//akeIncrementer(forIncrement:) 有一个 Int 类型的参数,其外部参数名为 forIncrement,内部参数名为 amount,该参数表示每次 incrementer 被调用时 runningTotal 将要增加的量。makeIncrementer 函数还定义了一个嵌套函数 incrementer,用来执行实际的增加操作。该函数简单地使 runningTotal 增加 amount,并将其返回。
func makeIncrementer(forIncrement count:Int) ->()->Int {
var total = 0
func incream()->Int {
total += count
return total
}
return incream
}
let addCount = makeIncrementer(forIncrement: 10)
print(addCount)
//逃逸闭包
//自动闭包
//枚举
//关联值
enum Barcode {
case upc(Int,Int,Int,Int)
case qrCode(String)
}
//以上代码可以这么理解:定义一个名为Barcode的枚举类型,它的成员值具有(Int,Int,Int,Int) 类型的关联值ups,另一个成员是具有string类型关联值得qrCode,这个定义不提供任何Int或String类型的关联值,它只是定义了,当Barcode常量和变量等于Barcode.upc或Barcode.qrCode时,可以存储的关联值的类型。
var product = Barcode.upc(23, 34, 4443, 544)
// 上面的例子创建了一个名为productBarcode的变量,并将Barcode.upc赋值给它,关联的元组值为(23, 34, 4443, 544)。
product = .qrCode("wwwwwwwwwww")
//这时,原始的Barcode.upc和其整数关联值被新的Barcode.qrCode和其字符串关联值所替代。Barcode类型的常量和变量可以存储一个.upc或者一个.qrCode(连同它们的关联值),但是在同一时间只能存储这两个值中的一个。
switch product {
case .upc(let numer, let manu, let pro, let check):
print("\(pro) \(numer)")
default:
print("")
}
//原始值
enum controlCharactor : Character {
case tab = "\t"
case linefeed = "\n"
case cReturn = "\r"
}
//原始值的隐士赋值
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
//在上面的例子中,Plant.mercury的显式原始值为1,Planet.venus的隐式原始值为2,依次类推。
// 当使用字符串作为枚举类型的原始值时,每个枚举成员的隐式原始值为该枚举成员的名称。
enum PlanetDirect : String {
case north,south,east,west
}
//上面的例子中 PlanetDirect.north 的原始值为 north,以此类推
//使用枚举成员的rawValle属性可以访问该枚举成员的原始值
let earth = Planet.earth.rawValue //原始值为3
let sunsetDirect = PlanetDirect.west.rawValue //原始值为west
//使用原始值初始化枚举实例
let possiblPlanet = Planet(rawValue : 7)
// possiblePlanet 类型为 Planet? 值为 Planet.uranus
print(earth,sunsetDirect,possiblPlanet)
//递归枚举
}
func test1() {
//变量
let π = 3.14159
let 你好 = "你好世界"
let 🐶🐮 = "dogcow"
print(π,你好,🐶🐮)
//整数与浮点型转换
//整数与浮点型转换必须显示指定类型
//如果不转换类型,则无法相加
let a : Int = 3
let b : Double = 0.23233
let c = Double(a) + b
print(c)
//浮点型转化为整形
//当用这种方式来初始化一个新的整数值时,浮点值会被截断。也就是说 4.75 会变成 4,-3.9 会变成 -3。不是四舍五入,是直接去掉小数部分
let d = Int(b)
print(d)
//类型别名 把String类型取名为 NSString
typealias NSString = String
let ss : NSString = "wwww"
print(ss)
//布尔值
//Bool 布尔值只有true false
//不需要将变量或者常量声明为某个特定的类型,因为swift会根据上下文类型判断来得知
// var hasSuccess = false
// hasSuccess = true
//元组 tuple
//元组把多个值组合成一个值,元组内可以是任意类型
let internetError = (404,"Not Found")
print(internetError)
//变量internetError的类型是 (Int,String),值是 (404,"Not Found") 一个元组把一个Int类型和一个String类型组合起来;
//你可以把任意顺序的类型组合成一个元组,这个元组可以包含所有类型。只要你想,你可以创建一个类型为 (Int, Int, Int) 或者 (String, Bool) 或者其他任何你想要的组合的元组。
//可以将一个元组的内容拆解开,然后使用,例如
let (tupleFirst,tupleSec) = internetError
print("元组第一个元素是 \(tupleFirst) 第二个元素是 \(tupleSec)")
//如果只需要元组的一部分数据,你可使用下划线 _ 来标记
let (tupleFir,_) = internetError //使用下划线来忽略不想要的数据
print(tupleFir)
//你还可以使用下标来访问元组的数据,下标从0开始
print(internetError.0,internetError.1)
//你还可以在定义元组的时候给元素命名,例如
let internetSuccess = (stateCode : 200,description : "OK")
//通过元素名字来获取元素的值
print(internetSuccess.stateCode,internetSuccess.description)
//作为函数返回值时,元组非常有用。一个用来获取网页的函数可能会返回一个 (Int, String) 元组来描述是否获取成功。和只能返回一个类型的值比较起来,一个包含两个不同类型值的元组可以让函数的返回信息更有用
//注意:
//元组在临时组织值的时候很有用,但是并不适合创建复杂的数据结构。如果你的数据结构并不是临时使用,请使用类或者结构体而不是元组
//可选类型 optional 用来处理值可能缺失的时候 可选类型表示 (1、有值,或值等于x 2、没有值)、
//注意:
//C 和 OC 并没有可选类型概念,最接近的就是OC的一个特性,要么返回一个对象或者值,要么返回nil,nil表示缺少一个合法的对象或者值;然而 Swift 的可选类型可以让你暗示任意类型的值缺失,并不需要一个特殊值。
//举例
// let optionalInt = "123"
//let convertString = Int(optionalInt)
// convertedNumber 被推测为类型 "Int?", 或者类型 "optional Int"
//print(convertString) //打印为 Optional(123)
//所以它返回一个可选类型(optional)Int,而不是一个 Int。一个可选的 Int 被写作 Int? 而不是 Int。问号暗示包含的值是可选类型,也就是说可能包含 Int 值也可能不包含值。(不能包含其他任何值比如 Bool 值或者 String 值。只能是 Int 或者什么都没有。)
//可以为可选值 赋值为nil,表示没有值
//haveValue 表示一个可选的 Int 值,404
// var haveValue : Int? = 404
// haveValue = nil
//print(haveValue)
//注意:
//nil不能用于非可选的常量和变量。如果你的代码中有常量或者变量需要处理值缺失的情况,请把它们声明成对应的可选类型
//如果你声明了一个可选的变量或者常量,编译器会自动赋值nil
var surveyAnswer: String?
surveyAnswer = "uuuuu"
// surveyAnswer 被自动设置为 nil
//声明可选变量没有赋值,会自动赋值nil
// let hahaha : Double?
// hahaha = 33.14
//print(surveyAnswer,hahaha)
//注意:
//Swift 的 nil 和 Objective-C 中的 nil 并不一样。在 Objective-C 中,nil 是一个指向不存在对象的指针。在 Swift 中,nil 不是指针——它是一个确定的值,用来表示值缺失。任何类型的可选状态都可以被设置为 nil,不只是对象类型。
//强制解析 !
//当你确定可选类型确实包含值之后,你可以在可选的名字后面加一个感叹号(!)来获取值。这个惊叹号表示“我知道这个可选有值,请使用它。”这被称为可选值的强制解析(forced unwrapping):
//注意:
//使用 ! 来获取一个不存在的可选值会导致运行时错误。使用 ! 来强制解析值之前,一定要确定可选包含一个非 nil 的值
//可选绑定
//使用可选绑定来判断可选类型是否有值,如果有值就赋值给一个变量或者常量,可选绑定可以用在if 语句 和 while语句中,这条语句不仅可以判断可选类型是否有值,还可以将可选类型中的值赋值给变量或者常量;
let someOptional : String? = "haha"
if let a = someOptional {
print(a)
}
//这段代码解释为:如果someOptional返回的可选String有值,创建一个 名叫a的常量并把值付给他;
//你可以包含多个可选绑定或多个布尔条件在一个 if 语句中,只要使用逗号分开就行。只要有任意一个可选绑定的值为nil,或者任意一个布尔条件为false,则整个if条件判断为false,这时你就需要使用嵌套 if 条件语句来处理,如下所示:
if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
// 输出 "4 < 42 < 100"
if let firstNumber = Int("4") {
if let secondNumber = Int("42") {
if firstNumber < secondNumber && secondNumber < 100 {
print("\(firstNumber) < \(secondNumber) < 100")
}
}
}
// 输出 "4 < 42 < 100"
//隐式解析可选类型
//有时候可选类型在第一次赋值时就知道它一定有值,这种情况每次都判断可选类型有没有值是非常低效的,这种类型的可选状态称为隐士解析可选类型,把想要用作可选类型的后边问好?改成!即可,(String?----->String!)来声明一个可选类型;
//
let aString : String? = "astring"
let bString = aString!//需要叹号来获取值
print(bString)
let cString : String! = "cString"
let dString : String = cString//不需要叹号
print(dString)
//错误处理
//断言
//断言函数
let age = 4
assert(age > 0, "age can not less than zero")
//需要使用断言的环境
//整数类型的下标索引被传入一个自定义下标实现,但是下标索引值可能太小或者太大。
//需要给函数传入一个值,但是非法的值可能导致函数不能正常执行。
//一个可选值现在是 nil,但是后面的代码运行需要一个非 nil 值。
//术语
//运算符
//赋值运算符 =
//组合赋值运算符 += -+
//比较运算符 > < >= <=
//逻辑运算符 && || !
//算术运算符 + - * / %
//三目运算符 ? :
//区间运算符 闭区间运算符:a...b 比如for循环 半开区间运算符 a...<b
//空合运算符 a ?? b 将a进行空判断,如果a包含一个值就进行解封,没有值就默认为b,a类型必须是可选类型,默认值b必须和a的值类型相同;
//空合运算符是对一下代码精简的表述
// a != nil ? a! : b 上述代码使用了三目运算符。当可选类型 a 的值不为空时,进行强制解封(a!),访问 a 中的值;反之返回默认值 b。无疑空合运算符(??)提供了一种更为优雅的方式去封装条件判断和解封两种行为,显得简洁以及更具可读性。
let defaultColorName = "red"
var userDefinedColorName: String? //默认值为 nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName 的值为空,所以 colorNameToUse 的值为 "red"
//字符串 和 字符
let hello : String = "hello world"
print(hello)
print(hello.endIndex)
print(hello[hello.startIndex])
print(hello[hello.index(after: hello.startIndex)])
print(hello[hello.index(before: hello.endIndex)])
let index = hello.index(hello.startIndex, offsetBy: 4)
print(hello[index])
//比较字符串相等 == !=
}
func test() -> Void {
// var myString = "hello world"
// myString = "hahha"
// print(myString)
//
// let yourString = "hello your world";
// print(yourString);
let name = "xiaoming";print(name)//在一行内书写多条语句时,要加上 分号,只=只有一条语句加不加都可以,swift没有要求
// let a= 2 + 3 运算符不能直接挨着变量名,要使用空格间隔开,不然会报错;
// let distance : NNNNN = "200"
// print(distance)
// var xiao : Float //声明变量
// xiao = 3.88
// print(xiao)
//
// var name1 : String //声明字符串变量
// name1 = "llllllllllll";
// print(name1)
//
//
// let 好 = "kkk"
// print(好)
/*
// \(变量名) 可用此方式插入字符串
var name2 = "她"
var email = "[email protected]"
print("\(name2) 的email为 \(email)")
var varibleOptional : String?
var optionalType: Optional<String>
varibleOptional = "bnoashioilahusias"
print(varibleOptional)
//如果一个可选类型的实例只包含一个值,那么就可以使用 后缀操作符 ! 来访问这个值;
optionalType = "jshklahjskjlha"
print(optionalType!)
// var myString : String? = nil
// myString = "hsjkghjbaskjhjks"
//
// if myString != nil {
// print(myString)
// } else {
// print("myString = nil")
// }
//强制解析
var string : String?
string = "hsklhkjlhkljlk"
if string != nil {
print(string!)//强制解析可选值,使用感叹号 ❗️ 打印为 Optional("hsklhkjlhkljlk!")
} else {//使用 !来获取一个不存在的值会导致报错,在强制解析之前要确定可选包含一个非 nil 的值;
print("string = nil")
}
//自动解析
//在声明可选变量时可用 ! 替换 ?,这样在使用可选变量时就不用使用 !来获取它的值,会自动解析;
var secString : String!
secString = "opopopopopo"
if secString != nil {
print(secString)
} else {
print("secString = nil")
}
//可选绑定
//使用可选绑定来来判断可选类型是否包含值,如果包含,就把这个值赋值给一个临时常量或者变量,可选绑定可以用到if 和 while语句中,来对可选值进行判断包含不包含值,
var bindString : String?
bindString = "binding string"
if let aString = bindString {
print(bindString)
} else {
print("没有可选值")
}
//常量 一旦设置为常量,在应用程序中就无法更改 这和OC一致;
//常量可以是任意数据类型,整形 字符串 浮点型 枚举类型常量
//常量类似于变量,区别在于常量的值一旦设定就不能改变,而变量的值可以随意更改。
//常量是用 let 修饰;变量使用var修饰
//类型标注
//当你声明常量或者变量的时候可以加上类型标注(type annotation),说明常量或者变量中要存储的值的类型。如果要添加类型标注,需要在常量或者变量名后面加上一个冒号和空格,然后加上类型名称 var constantName:<data type> = <optional initial value>
var myInt : Int = 33;
myInt = 44
var myStr : String = "jlijlijklk"
myStr = "808909890"
let myStrings : String = "gklghkj"
print(myInt)
print(myStr,myStrings)
//常量命名
// 常量命名可以由 字母 下划线 数字组成;常量需要以字母或者下划线开头 swift区分大小写
//swift 字面量 :能够直截了指出变量的类型并为变量赋值的值;
let aNumber = 3 //整型字面量
let aString = "Hello" //字符串字面量
let aBool = true //布尔值字面量
//整形字面量
//整型字面量可以是一个十进制,二进制,八进制或十六进制常量。 二进制前缀为 0b,八进制前缀为 0o,十六进制前缀为 0x,十进制没有前缀:
let decimalInteger = 17 // 17 - 十进制表示
let binaryInteger = 0b10001 // 17 - 二进制表示
let octalInteger = 0o21 // 17 - 八进制表示
let hexadecimalInteger = 0x11 // 17 - 十六进制表示
print(hexadecimalInteger,decimalInteger,binaryInteger,octalInteger)
let octalValue = 0o22
print(octalValue) //18
//十进制浮点型字面量由十进制数字串后跟小数部分或指数部分(或两者皆有)组成。十进制小数部分由小数点 . 后跟十进制数字串组成。指数部分由大写或小写字母 e 为前缀后跟十进制数字串组成,这串数字表示 e 之前的数量乘以 10 的几次方。例如:1.25e2 表示 1.25 ⨉ 10^2,也就是 125.0;同样,1.25e-2 表示 1.25 ⨉ 10^-2,也就是 0.0125。
//十六进制浮点型字面量由前缀 0x 后跟可选的十六进制小数部分以及十六进制指数部分组成。十六进制小数部分由小数点后跟十六进制数字串组成。指数部分由大写或小写字母 p 为前缀后跟十进制数字串组成,这串数字表示 p 之前的数量乘以 2 的几次方。例如:0xFp2 表示 15 ⨉ 2^2,也就是 60;同样,0xFp-2 表示 15 ⨉ 2^-2,也就是 3.75。
//负的浮点型字面量由一元运算符减号 - 和浮点型字面量组成,例如 -42.5。
//浮点型字面量允许使用下划线 _ 来增强数字的可读性,下划线会被系统忽略,因此不会影响字面量的值。同样地,也可以在数字前加 0,并不会影响字面量的值。
let decimalDouble = 12.1875 //十进制浮点型字面量
let exponentDouble = 1.21875e1 //十进制浮点型字面量
let hexadecimalDouble = 0xC.3p0 //十六进制浮点型字面量
//字符串字面量 "" 双引号包含
//字符串型字面量中不能包含未转义的双引号 (")、未转义的反斜线(\)、回车符或换行符。
let yourString : String
yourString = "hklhkjhkljhklj\nuhiouhuhkj\rssasasasa\"ewewewew\t\""
print(yourString)
/*
\0 空字符
\\ 反斜线 \
\b 退格(BS) ,将当前位置移到前一列
\f 换页(FF),将当前位置移到下页开头
\n 换行符
\r 回车符
\t 水平制表符
\v 垂直制表符
\' 单引号
\" 双引号
\000 1到3位八进制数所代表的任意字符
\xhh... 1到2位十六进制所代表的任意字符
*/
/*
布尔型字面量
布尔型字面量的默认类型是 Bool。
布尔值字面量有三个值,它们是 Swift 的保留关键字:
true 表示真。
false 表示假。
nil 表示没有值。
*/
var isEmpty : Bool = false;
isEmpty = true
print(isEmpty)
//运算符 运算符是一个符号,用来告诉编译器来执行一个数学运算或逻辑运算
//swift 有一下几种运算符
//算术运算符 + - * / % ++ --
//逻辑运算符 && || ! 与或非
//赋值运算符 =
//比较运算符 == > < != >= <=
//位运算符 位运算符用来对二进制位进行操作,~,&,|,^,分别为取反,按位与与,按位与或,按位与异或运算
//区间运算符
//其他运算符
let A : Int = 10
let B : Int = 30
print("A + B = \(A + B)")
print("A != B === \(A != B)")
//repeat...while 循环 首先会执行一次表达式,如果表达式为true,则继续执行,知道表达式为false;
var LL : Int = 30
repeat {
LL = LL + 1
print(LL)
} while LL < 35
//fallthrough 语句
//在大多数语言中,switch 语句块中,case 要紧跟 break,否则 case 之后的语句会顺序运行,而在 Swift 语言中,默认是不会执行下去的,switch 也会终止。如果你想在 Swift 中让 case 之后的语句会按顺序继续运行,则需要使用 fallthrough 语句。
//默认不继续往下进行,直到遇到fallthrough语句才会往下执行;
var index = 20
switch index {
case 10:
print(index)
case 20:
print("hahahahahaha")
fallthrough
case 30:
print("30")
fallthrough
case 40:
print("40")
case 50:
print("30")
case 60:
print("30")
default:
print("default")
}
//for in循环
var someString : [String] = ["www","errrr","ytrtrtrt"]
someString .append("yyyyy")
someString.insert("ooooooo", at: 2)
for aString in someString {
print(aString)
}
//字符串
let bString = String("pppppp")
// bString?.insert("M", at: bString?.3)
var cString = String.init()
cString = "mmmmmm"
print(cString)
//空字符串
var dString = ""
dString = dString + "yiuyiouyio"
dString += "YYYYY"
print(dString)
let fString = String()
if fString.isEmpty {
print("是空串")
} else {
print("不是空串")
}
//字符串插入值
//字符串插值是一种构建新字符串的方式,可以在其中包含常量、变量、字面量和表达式。 您插入的字符串字面量的每一项都在以反斜线为前缀的圆括号中:
var varA = 20
let constA = 100
var varC:Float = 20.0
var stringA = "\(varA) 乘于 \(constA) 等于 \(varC * 100)"
print( stringA )
//字符串连接
//字符串可以用➕来连接
var varD = "D";
var varF = "F"
varD = varD + "D"
print("====== \(varD + varF)")
//字符串长度
print("字符串长度为 = \(varD.lengthOfBytes(using: String.Encoding.utf8))")
print("字符串长度 = \(varD.characters.count)")
//字符串比较 使用 == 比较字符串
print("两个字符串是否相等 \(varD == varF)")
// Unicode 字符串
//字符 character Swift 的字符是一个单一的字符字符串字面量,数据类型为 Character。
//swift不能创建空字符变量
let char1 : Character = "W";
let char2 : Character = "E";
print(char1,char2)
//遍历字符串中的字符
for char in varD.characters {
print(char)
}
//字符串追加字符 字符串
varD.append("p")
varF.append(varD)
//字典
/* Swift 字典用来存储无序的相同类型数据的集合,Swift 字典会强制检测元素的类型,如果类型不同则会报错。
Swift 字典每个值(value)都关联唯一的键(key),键作为字典中的这个值数据的标识符。
和数组中的数据项不同,字典中的数据项并没有具体顺序。我们在需要通过标识符(键)访问数据的时候使用字典,这种方法很大程度上和我们在现实世界中使用字典查字义的方法一样。
Swift 字典的key没有类型限制可以是整型或字符串,但必须是唯一的。
如果创建一个字典,并赋值给一个变量,则创建的字典就是可以修改的。这意味着在创建字典后,可以通过添加、删除、修改的方式改变字典里的项目。如果将一个字典赋值给常量,字典就不可修改,并且字典的大小和内容都不可以修改。
*/
//创建字典
//var someDict = [KeyType: ValueType]()
//var someDict = [Int: String]()
//var dic1 = [String:String]()
var dic : [Int:String] = [2:"eeee",3:"rrrr",4:"tttt"];
var dic1 : [String:String] = ["222":"aaa"]
let var2 = dic[2]
let var4 = dic[4]
let var3 = dic[3]
print(var2,var3,var4)
//修改字典的值 两种方法
dic.updateValue("TTTT", forKey: 4)
dic[3] = "RRRR";
print(dic)
//移除键值对
dic.removeValue(forKey: 2)
print(dic)
//也可以通过指定键的值为 nil 来移除 key-value(键-值)对
dic[3] = nil
dic[5] = "YYY"
print(dic)
//遍历字典
for (key,value) in dic {
print("key = \(key),value = \(value)")
}
//我们也可以使用enumerate()方法来进行字典遍历,返回的是字典的索引及 (key, value) 对
for (key,value) in dic.enumerated(){
print("字典 key \(key) - 字典 (key, value) 对 \(value)")
}
//字典转换为数组
let keys = [Int](dic.keys)
let values = [String] (dic.values)
print(keys,values,"键值对数目 = \(dic.count)")
//count属性 isEmpty属性
/*数组 可以有相同的值,但是必须是在不同的位置上,数组中值的类型必须是一致的;
Swift 数组使用有序列表存储同一类型的多个值。相同的值可以多次出现在一个数组的不同位置中。
Swift 数组会强制检测元素的类型,如果类型不同则会报错,Swift 数组应该遵循像Array<Element>这样的形式,其中Element是这个数组中唯一允许存在的数据类型。
如果创建一个数组,并赋值给一个变量,则创建的集合就是可以修改的。这意味着在创建数组后,可以通过添加、删除、修改的方式改变数组里的项目。如果将一个数组赋值给常量,数组就不可更改,并且数组的大小和内容都不可以修改。
*/
var someArray : [String] = ["wwww","rrrr","uuuuu"]
//根据下表来获取数组内的值
let firstValue = someArray[2]
//修改数组
someArray.append("00000")
someArray.insert("KKK", at: 2)
someArray[2] = "jjjj"
print(someArray)
//遍历数组
var nameString = [String]()
nameString.append("haha")
nameString.append("heihei")
nameString.insert("nihao", at: 1)
for name in nameString {
print(name)
}
for (index,name) in nameString.enumerated() {
print(index,name)
}
//合并数组 使用➕
let mergeArray = someArray + nameString
print(mergeArray)
//count属性 isEmpty属性
*/
/*
//函数
self.thirdFunc()
let aR = self.firstfunc()
let aResult = self.secFunc(paras: "ni", paras1: 4, paras2: "hao")
print(aResult,aR)
let arrayInt : [Int] = [2,3,5,-200,3000,900]
let result = self.minMax(array: arrayInt)
print(result.minmum,result.max)
//需要注意的是,元组的成员不需要在元组从函数中返回时命名,因为它们的名字已经在函数返回类型中指定了
let rrr = self.minMaxFunc(array: []) //传进去的是空数组
print(rrr ?? "为空")//默认值 ??
//函数 参数标签 和 参数名称 默认情况下函数的参数名作为函数的参数标签;
func someFunction(firstParameterName: Int, secondParameterName: Int) {
// 在函数体内,firstParameterName 和 secondParameterName 代表参数中的第一个和第二个参数值
}
someFunction(firstParameterName: 1, secondParameterName: 2)
//指定参数标签 funcLabel参数标签 你可以在函数名称前指定它的参数标签,中间以空格分隔
func func2(funcLabel argument : [Int]) ->() {
print(argument)
}
func2(funcLabel: [1,2,3])
//函数没有返回值可以不写 ->()
func func3(argument : String) {
print(argument)
}
func3(argument: "hahha")
//忽略参数标签 如果不想为某函数添加一个标签,可以使用 _ (下划线)来替代参数标签
func noLabel(_ argument1 : String,_ argument2 : Int) {
print(argument1,argument2.description)
}
noLabel("kkkkkk", 3)
//默认参数值 你可以在函数体中通过给参数赋值来为任意一个参数定义默认值(Deafult Value)。当默认值被定义后,调用这个函数时可以忽略这个参数。
//可以看出使用默认值参数 可以忽略也可以不忽略,调用方法的 时候会出现两种提示;一种是忽略一种是不忽略的方法;
func defaultArgument(withoutDefault : Int,defaultArgument : Int = 4) {
print(withoutDefault,defaultArgument)
}
defaultArgument(withoutDefault: 3, defaultArgument: 5)
func defaultStringArgument(withoutDefault : String,defaultArgument : Int = 20) {
print(withoutDefault,defaultArgument)
}
defaultStringArgument(withoutDefault: "kkkk", defaultArgument: 3)
defaultStringArgument(withoutDefault: "llll")
//可变参数 参数后边加上 ... 表示参数是可变的,numbers表示 float类型的一个数组
//注意:一个函数只能拥有一个可变参数
func mutableArgumentFunc(numbers : Float...) -> Float {
var number : Float = 0.0
for value in numbers {
number += value
}
return Float(number)
}
print(mutableArgumentFunc(numbers: 3.9,4.9,4.7))
//输入输出参数 inout关键字
//函数参数默认是常量。试图在函数体中更改参数值将会导致编译错误(compile-time error)。这意味着你不能错误地更改参数值。如果你想要一个函数可以修改参数的值,并且想要在这些修改在函数调用结束后仍然存在,那么就应该把这个参数定义为输入输出参数(In-Out Parameters)。
//定义一个输入输出参数时,在参数定义前加 inout 关键字。一个输入输出参数有传入函数的值,这个值被函数修改,然后被传出函数,替换原来的值。想获取更多的关于输入输出参数的细节和相关的编译器优化,请查看输入输出参数一节。你只能传递变量给输入输出参数。你不能传入常量或者字面量,因为这些量是不能被修改的。当传入的参数作为输入输出参数时,需要在参数名前加 & 符,表示这个值可以被函数修改。
//输入输出函数是对函数体外产生呢过影响的一种方式;
func inoutArgument(_ a : inout Int,b : inout Int) {
let temp = a;
a = b;
b = temp;
print(a,b)
}
var a = 4
var b = 90
inoutArgument(&a, b: &b)
//函数类型
//每个函数都有特定的类型,类型是由参数类型和返回值类型组成;
func addFunc( a : Int,b : Int) -> Int {
return a+b
}
func multiplyFunc(_ a : Int,_ b : Int) ->Int {
return a*b
}
//上边两个函数可以说是(Int,Int)-> Int类型,可以解读为有两个Int类型的参数,返回一个Int类型的值;
//下边函数 ()->void 可以解读为没有参数 返回类型为void类型的函数
func fun5(){
}
//使用函数类型
//在swift中,函数也是一种类型,你可以使用函数像其他类型一样,你可以定义一个类型为函数的变量或常量,并适当的赋值给它
//例
var funcTypeVarible : (Int,Int)->Int = addFunc(a:b:)
//这句代码可以解读为: 变量funcTypeVarible是 一个参数由两个Int类型 返回值类型为 Int的函数 类型变量
print(funcTypeVarible(2,4))
//有相同匹配类型的不同函数可以被赋值给同一个变量,就像非函数类型的变量一样
funcTypeVarible = multiplyFunc(_:_:)
print(funcTypeVarible(2,4))
//函数类型作为参数类型
//例
func func6(argument1 : (Int,Int)->Int,argument2 : Int,argument3 : Int) {
print(argument1(argument2,argument3))
}
func6(argument1: funcTypeVarible, argument2: 4, argument3: 5)
// 不想看到参数标签,函数参数名前 加 _,并使用空格分开即可
func func7(_ argument1 : (Int,Int)->Int,_ argument2 : Int,_ argument3 : Int) {
print(argument1(argument2,argument3))
}
func7(funcTypeVarible, 3, 4)
//函数类型作为返回值类型
//你可以用函数类型作为另一个函数的返回类型。你需要做的是在返回箭头(->)后写一个完整的函数类型。
//例 两个函数类型都为 (Int)->Int
func forword(_ a : Int) -> Int {
return a+1
}
func backword(_ b : Int) -> Int {
return b - 1
}
func funcReturnFunc(isBool : Bool) -> (Int)->Int {
return isBool ? backword : forword
}
//嵌套函数 在函数内部定义函数称为嵌套函数,函数外部定义函数称之为全局函数,全局函数的作用域是整个类,函数内部的函数作用域在函数内部;
//nested functions 嵌套函数
//global functions 全局函数
//enclosing function 外围函数
//上边的函数都在viewDidLoad函数内部定义,都称之为嵌套函数
*/
/*
//闭包 block -oc
//闭包是自包含的代码块
//闭包是自包含的函数代码块,可以在代码中被传递和使用。Swift 中的闭包与 C 和 Objective-C 中的代码块(blocks)以及其他一些编程语言中的匿名函数比较相似。闭包可以捕获和存储其所在上下文中任意常量和变量的引用。被称为包裹常量和变量。 Swift 会为你管理在捕获过程中涉及到的所有内存操作
//闭包表达式语法
// { (<#parameters#>) -> <#return type#> in
// <#statements#>
// }
let names = ["asjk","nkk","opop","vvvn"]
func cccloseure(_ s1 : String,_ s2 : String) -> Bool {
return s1 > s2
}
var result = names.sorted(by: cccloseure)
print(result)
result = names.sorted(by: { (s1 : String,s2 : String) -> Bool in
return s1 > s2
})
//返回值箭头 -> 和围绕在参数的括号也可以被省略
//如下
result = names.sorted(by: {s1,s2 in return s1 > s2})
//单表达式闭包 单行表达式闭包可以通过省略 return 关键字来隐式返回单行表达式的结果
//如下
result = names.sorted(by: {s1,s2 in s1 > s2})
//参数名称缩写
//Swift 自动为内联闭包提供了参数名称缩写功能,你可以直接通过 $0,$1,$2 来顺序调用闭包的参数,以此类推。
//如下 在这个例子中,$0和$1表示闭包中第一个和第二个 String 类型的参数。
result = names.sorted(by: {$0 > $1})
//运算符方法
// 实际上还有一种更简短的方式来编写上面例子中的闭包表达式。Swift 的 String 类型定义了关于大于号(>)的字符串实现,其作为一个函数接受两个 String 类型的参数并返回 Bool 类型的值。而这正好与 sorted(by:) 方法的参数需要的函数类型相符合。因此,你可以简单地传递一个大于号,Swift 可以自动推断出你想使用大于号的字符串函数实现:
result = names.sorted(by: >)
//尾随闭包
func someFunctionThatTakesAClosure (closure : () -> Void) {
// 函数体部分
}
// 以下是不使用尾随闭包进行函数调用
someFunctionThatTakesAClosure(closure: {
// 闭包主体部分
})
// 以下是使用尾随闭包进行函数调用
someFunctionThatTakesAClosure() {
// 闭包主体部分
}
// 在闭包表达式语法一节中作为 sorted(by:) 方法参数的字符串排序闭包可以改写为:
result = names.sorted() { $0 > $1 }
// 如果闭包表达式是函数或方法的唯一参数,则当你使用尾随闭包时,你甚至可以把 () 省略掉:
result = names.sorted { $0 > $1 }
//参数为两个int类型 返回值也为int类型的闭包
let add = { (a : Int,b : Int) -> Int in
a + b
}
print(add(2,3))
//没有参数没有返回值的闭包
let sentence = { print("没有参数没有返回值的闭包")
}
print(sentence)
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//无参有返回值函数
func firstfunc() -> String {
return "nihao"
}
//有参有返回值函数
func secFunc(paras : String,paras1 : Int,paras2 : String) ->String {
let pp = paras + paras2 + paras1.description
return pp
}
//无参无返回值函数
func thirdFunc() ->(){
print("无参无返回值")
}
//多重返回值函数 返回元组tuple
func minMax(array : [Int]) -> (minmum : Int,max : Int) {
var currentMin = array[0]
var currentMax = array[0]
for value in array {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin,currentMax)
}
//可选元组返回类型 返回值后边加一个❓
//上边的例子为例
func minMaxFunc(array : [Int]) -> (minmum : Int,max : Int)? {
if array.isEmpty { return nil } //加入传入的数组为空,就返回nil,这就是返回可选元组
var currentMin = array[0]
var currentMax = array[0]
for value in array {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin,currentMax)
}
}
| mit | 927ab7eab9ed22b61c4ddb5349e8940b | 29.762708 | 252 | 0.527508 | 3.442406 | false | false | false | false |
anthonycastelli/Thunder | Sources/Thunder/TaskCommand.swift | 1 | 930 | //
// TaskCommand.swift
// Flock
//
// Created by Jake Heiser on 12/28/15.
// Copyright © 2015 jakeheis. All rights reserved.
//
import SwiftCLI
class TaskCommand: Command {
let name: String
let task: Task
let dryRun = Flag("-n", "--none")
let environment = Key<String>("-e", "--enviornment")
init(task: Task) {
self.name = task.fullName
self.task = task
}
func execute() throws {
Thunder.configure(for: (environment.value ?? "production"))
TaskExecutor.mode = dryRun.value ? .dryRun : .execute
do {
try TaskExecutor.run(task: task)
} catch TaskError.commandFailed {
throw CLI.Error(message: "A command failed.".red)
} catch TaskError.error(let string) {
throw CLI.Error(message: string.red)
} catch let error {
throw error
}
}
}
| mit | fe68f53cabbab83b3d3a2b651a4d447c | 22.225 | 67 | 0.557589 | 4.00431 | false | false | false | false |
Harley-xk/SimpleDataKit | Example/Pods/Comet/Comet/Extensions/Numbers+Comet.swift | 1 | 1974 | //
// Numbers+Comet.swift
// Comet
//
// Created by Harley.xk on 2017/8/18.
//
import Foundation
// Convert String to Numbers
public extension String {
// convert string to int
// returns 0 if failed
public var intValue: Int {
return Int(self) ?? 0
}
// convert string to double
// returns 0 if failed
public var doubleValue: Double {
return Double(self) ?? 0
}
// convert string to float
// returns 0 if failed
public var floatValue: Float {
return Float(self) ?? 0
}
}
// Convert Float to String
public extension Float {
// 返回指定小数位数的字符串
public func string(decimals: Int = 0) -> String {
return String(format: "%.\(decimals)f", self)
}
// 返回指定格式的字符串
public func string(format: String?) -> String {
if let format = format {
return String(format: format, self)
} else {
return string(decimals: 0)
}
}
}
// Convert Double to String
public extension Double {
// 返回指定小数位数的字符串
public func string(decimals: Int = 0) -> String {
return String(format: "%.\(decimals)f", self)
}
// 返回指定格式的字符串
public func string(format: String?) -> String {
if let format = format {
return String(format: format, self)
} else {
return string(decimals: 0)
}
}
}
extension Int {
// 返回指定格式的字符串
public func string(format: String? = nil) -> String {
if let format = format {
return String(format: format, self)
} else {
return "\(self)"
}
}
// random number from min to max
static public func random(min: Int = 0, max: Int) -> Int {
let random = Int(arc4random())
let number = random % (max + 1 - min) + min
return number
}
}
| mit | 8b9ee82501461b223017db90bf55d846 | 21.481928 | 62 | 0.554126 | 4.065359 | false | false | false | false |
keepcalmandcodecodecode/SweetSpinners | Pod/Classes/CircleView.swift | 1 | 785 | //
// CircleView.swift
// Pods
//
// Created by macmini1 on 28.01.16.
//
//
import Foundation
import UIKit
class CircleView:UIView{
var fillColor:UIColor = UIColor.grayColor()
override init(frame: CGRect) {
super.init(frame:frame)
self.backgroundColor = UIColor.clearColor()
}
func useFillColor(color:UIColor)->CircleView{
self.fillColor = color
return self
}
func useBackgroundColor(color:UIColor)->CircleView{
self.backgroundColor = color
return self
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func drawRect(rect: CGRect) {
let ovalPath = UIBezierPath(ovalInRect: rect)
self.fillColor.setFill()
ovalPath.fill()
}
} | mit | 91fb8390aec2acb32c40da706e4ce273 | 22.117647 | 55 | 0.63949 | 4.22043 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.